context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Authorization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
public static partial class RoleAssignmentsOperationsExtensions
{
/// <summary>
/// Gets role assignments of the resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<RoleAssignment> ListForResource(this IRoleAssignmentsOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>))
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).ListForResourceAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments of the resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='resourceProviderNamespace'>
/// Resource identity.
/// </param>
/// <param name='parentResourcePath'>
/// Resource identity.
/// </param>
/// <param name='resourceType'>
/// Resource identity.
/// </param>
/// <param name='resourceName'>
/// Resource identity.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForResourceAsync( this IRoleAssignmentsOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceWithHttpMessagesAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments of the resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Resource group name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<RoleAssignment> ListForResourceGroup(this IRoleAssignmentsOperations operations, string resourceGroupName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>))
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).ListForResourceGroupAsync(resourceGroupName, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments of the resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Resource group name.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForResourceGroupAsync( this IRoleAssignmentsOperations operations, string resourceGroupName, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceGroupWithHttpMessagesAsync(resourceGroupName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// Scope.
/// </param>
/// <param name='roleAssignmentName'>
/// Role assignment name.
/// </param>
public static RoleAssignment Delete(this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName)
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).DeleteAsync(scope, roleAssignmentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// Scope.
/// </param>
/// <param name='roleAssignmentName'>
/// Role assignment name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> DeleteAsync( this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(scope, roleAssignmentName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// Scope.
/// </param>
/// <param name='roleAssignmentName'>
/// Role assignment name.
/// </param>
/// <param name='properties'>
/// Gets or sets role assignment properties.
/// </param>
public static RoleAssignment Create(this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName, RoleAssignmentProperties properties = default(RoleAssignmentProperties))
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).CreateAsync(scope, roleAssignmentName, properties), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// Scope.
/// </param>
/// <param name='roleAssignmentName'>
/// Role assignment name.
/// </param>
/// <param name='properties'>
/// Gets or sets role assignment properties.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> CreateAsync( this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName, RoleAssignmentProperties properties = default(RoleAssignmentProperties), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(scope, roleAssignmentName, properties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get single role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// Scope.
/// </param>
/// <param name='roleAssignmentName'>
/// Role assignment name.
/// </param>
public static RoleAssignment Get(this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName)
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).GetAsync(scope, roleAssignmentName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get single role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// Scope.
/// </param>
/// <param name='roleAssignmentName'>
/// Role assignment name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> GetAsync( this IRoleAssignmentsOperations operations, string scope, string roleAssignmentName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(scope, roleAssignmentName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// Role assignment Id
/// </param>
public static RoleAssignment DeleteById(this IRoleAssignmentsOperations operations, string roleAssignmentId)
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).DeleteByIdAsync(roleAssignmentId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// Role assignment Id
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> DeleteByIdAsync( this IRoleAssignmentsOperations operations, string roleAssignmentId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.DeleteByIdWithHttpMessagesAsync(roleAssignmentId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Create role assignment by Id.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// Role assignment Id
/// </param>
/// <param name='properties'>
/// Gets or sets role assignment properties.
/// </param>
public static RoleAssignment CreateById(this IRoleAssignmentsOperations operations, string roleAssignmentId, RoleAssignmentProperties properties = default(RoleAssignmentProperties))
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).CreateByIdAsync(roleAssignmentId, properties), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create role assignment by Id.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// Role assignment Id
/// </param>
/// <param name='properties'>
/// Gets or sets role assignment properties.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> CreateByIdAsync( this IRoleAssignmentsOperations operations, string roleAssignmentId, RoleAssignmentProperties properties = default(RoleAssignmentProperties), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateByIdWithHttpMessagesAsync(roleAssignmentId, properties, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get single role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// Role assignment Id
/// </param>
public static RoleAssignment GetById(this IRoleAssignmentsOperations operations, string roleAssignmentId)
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).GetByIdAsync(roleAssignmentId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get single role assignment.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='roleAssignmentId'>
/// Role assignment Id
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RoleAssignment> GetByIdAsync( this IRoleAssignmentsOperations operations, string roleAssignmentId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByIdWithHttpMessagesAsync(roleAssignmentId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments of the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<RoleAssignment> List(this IRoleAssignmentsOperations operations, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>))
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).ListAsync(odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments of the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListAsync( this IRoleAssignmentsOperations operations, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments of the scope.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// Scope.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<RoleAssignment> ListForScope(this IRoleAssignmentsOperations operations, string scope, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>))
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).ListForScopeAsync(scope, odataQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments of the scope.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='scope'>
/// Scope.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForScopeAsync( this IRoleAssignmentsOperations operations, string scope, ODataQuery<RoleAssignmentFilter> odataQuery = default(ODataQuery<RoleAssignmentFilter>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForScopeWithHttpMessagesAsync(scope, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments of the resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RoleAssignment> ListForResourceNext(this IRoleAssignmentsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).ListForResourceNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments of the resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForResourceNextAsync( this IRoleAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments of the resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RoleAssignment> ListForResourceGroupNext(this IRoleAssignmentsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).ListForResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments of the resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForResourceGroupNextAsync( this IRoleAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments of the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RoleAssignment> ListNext(this IRoleAssignmentsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments of the subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListNextAsync( this IRoleAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets role assignments of the scope.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RoleAssignment> ListForScopeNext(this IRoleAssignmentsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRoleAssignmentsOperations)s).ListForScopeNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets role assignments of the scope.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RoleAssignment>> ListForScopeNextAsync( this IRoleAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListForScopeNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Orleans;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.TestingHost;
using TestExtensions;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
using Xunit;
using Orleans.Hosting;
using Orleans.Serialization;
namespace UnitTests.General
{
[TestCategory("BVT"), TestCategory("GrainCallFilter")]
public class GrainCallFilterTests : OrleansTestingBase, IClassFixture<GrainCallFilterTests.Fixture>
{
public class Fixture : BaseTestClusterFixture
{
protected override void ConfigureTestCluster(TestClusterBuilder builder)
{
builder.ConfigureHostConfiguration(TestDefaultConfiguration.ConfigureHostConfiguration);
builder.AddSiloBuilderConfigurator<SiloInvokerTestSiloBuilderConfigurator>();
builder.AddClientBuilderConfigurator<ClientConfigurator>();
}
private class SiloInvokerTestSiloBuilderConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder
.AddIncomingGrainCallFilter(context =>
{
if (string.Equals(context.InterfaceMethod.Name, nameof(IGrainCallFilterTestGrain.GetRequestContext)))
{
if (RequestContext.Get(GrainCallFilterTestConstants.Key) != null) throw new InvalidOperationException();
RequestContext.Set(GrainCallFilterTestConstants.Key, "1");
}
return context.Invoke();
})
.AddIncomingGrainCallFilter<GrainCallFilterWithDependencies>()
.AddOutgoingGrainCallFilter(async ctx =>
{
if (ctx.InterfaceMethod?.Name == "Echo")
{
// Concatenate the input to itself.
var orig = (string) ctx.Arguments[0];
ctx.Arguments[0] = orig + orig;
}
await ctx.Invoke();
})
.AddSimpleMessageStreamProvider("SMSProvider")
.AddMemoryGrainStorageAsDefault()
.AddMemoryGrainStorage("PubSubStore");
}
}
private class ClientConfigurator : IClientBuilderConfigurator
{
public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
{
clientBuilder.AddOutgoingGrainCallFilter(async ctx =>
{
if (ctx.InterfaceMethod?.DeclaringType == typeof(IOutgoingMethodInterceptionGrain))
{
ctx.Arguments[1] = ((string) ctx.Arguments[1]).ToUpperInvariant();
}
await ctx.Invoke();
if (ctx.InterfaceMethod?.DeclaringType == typeof(IOutgoingMethodInterceptionGrain))
{
var result = (Dictionary<string, object>) ctx.Result;
result["orig"] = result["result"];
result["result"] = "intercepted!";
}
})
.AddSimpleMessageStreamProvider("SMSProvider");
}
}
}
[SuppressMessage("ReSharper", "NotAccessedField.Local")]
public class GrainCallFilterWithDependencies : IIncomingGrainCallFilter
{
private readonly SerializationManager serializationManager;
private readonly Silo silo;
private readonly IGrainFactory grainFactory;
public GrainCallFilterWithDependencies(SerializationManager serializationManager, Silo silo, IGrainFactory grainFactory)
{
this.serializationManager = serializationManager;
this.silo = silo;
this.grainFactory = grainFactory;
}
public Task Invoke(IIncomingGrainCallContext context)
{
if (string.Equals(context.ImplementationMethod.Name, nameof(IGrainCallFilterTestGrain.GetRequestContext)))
{
if (RequestContext.Get(GrainCallFilterTestConstants.Key) is string value)
{
RequestContext.Set(GrainCallFilterTestConstants.Key, value + '2');
}
}
return context.Invoke();
}
}
private readonly Fixture fixture;
public GrainCallFilterTests(Fixture fixture)
{
this.fixture = fixture;
}
/// <summary>
/// Ensures that grain call filters are invoked around method calls in the correct order.
/// </summary>
/// <returns>A <see cref="Task"/> representing the work performed.</returns>
[Fact]
public async Task GrainCallFilter_Outgoing_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IOutgoingMethodInterceptionGrain>(random.Next());
var grain2 = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next());
// This grain method reads the context and returns it
var result = await grain.EchoViaOtherGrain(grain2, "ab");
// Original arg should have been:
// 1. Converted to upper case on the way out of the client: ab -> AB.
// 2. Doubled on the way out of grain1: AB -> ABAB.
// 3. Reversed on the wya in to grain2: ABAB -> BABA.
Assert.Equal("BABA", result["orig"] as string);
Assert.NotNull(result["result"]);
Assert.Equal("intercepted!", result["result"]);
}
/// <summary>
/// Ensures that grain call filters are invoked around method calls in the correct order.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_Order_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IGrainCallFilterTestGrain>(random.Next());
// This grain method reads the context and returns it
var context = await grain.GetRequestContext();
Assert.NotNull(context);
Assert.Equal("1234", context);
}
/// <summary>
/// Ensures that the invocation interceptor is invoked for stream subscribers.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_Stream_Test()
{
var streamProvider = this.fixture.Client.GetStreamProvider("SMSProvider");
var id = Guid.NewGuid();
var stream = streamProvider.GetStream<int>(id, "InterceptedStream");
var grain = this.fixture.GrainFactory.GetGrain<IStreamInterceptionGrain>(id);
// The intercepted grain should double the value passed to the stream.
const int testValue = 43;
await stream.OnNextAsync(testValue);
var actual = await grain.GetLastStreamValue();
Assert.Equal(testValue * 2, actual);
}
/// <summary>
/// Tests that some invalid usages of invoker interceptors are denied.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_InvalidOrder_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IGrainCallFilterTestGrain>(0);
var result = await grain.CallWithBadInterceptors(false, false, false);
Assert.Equal("I will not misbehave!", result);
await Assert.ThrowsAsync<InvalidOperationException>(() => grain.CallWithBadInterceptors(true, false, false));
await Assert.ThrowsAsync<InvalidOperationException>(() => grain.CallWithBadInterceptors(false, false, true));
await Assert.ThrowsAsync<InvalidOperationException>(() => grain.CallWithBadInterceptors(false, true, false));
}
/// <summary>
/// Tests filters on just the grain level.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_GrainLevel_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(0);
var result = await grain.One();
Assert.Equal("intercepted one with no args", result);
result = await grain.Echo("stao erom tae");
Assert.Equal("eat more oats", result);// Grain interceptors should receive the MethodInfo of the implementation, not the interface.
result = await grain.NotIntercepted();
Assert.Equal("not intercepted", result);
result = await grain.SayHello();
Assert.Equal("Hello", result);
}
/// <summary>
/// Tests filters on generic grains.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_GenericGrain_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IGenericMethodInterceptionGrain<int>>(0);
var result = await grain.GetInputAsString(679);
Assert.Contains("Hah!", result);
Assert.Contains("679", result);
result = await grain.SayHello();
Assert.Equal("Hello", result);
}
/// <summary>
/// Tests filters on grains which implement multiple of the same generic interface.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_ConstructedGenericInheritance_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<ITrickyMethodInterceptionGrain>(0);
var result = await grain.GetInputAsString("2014-12-19T14:32:50Z");
Assert.Contains("Hah!", result);
Assert.Contains("2014-12-19T14:32:50Z", result);
result = await grain.SayHello();
Assert.Equal("Hello", result);
var bestNumber = await grain.GetBestNumber();
Assert.Equal(38, bestNumber);
result = await grain.GetInputAsString(true);
Assert.Contains(true.ToString(CultureInfo.InvariantCulture), result);
}
/// <summary>
/// Tests that grain call filters can handle exceptions.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_ExceptionHandling_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next());
// This grain method throws, but the exception should be handled by one of the filters and converted
// into a specific message.
var result = await grain.Throw();
Assert.NotNull(result);
Assert.Equal("EXCEPTION! Oi!", result);
}
/// <summary>
/// Tests that grain call filters can throw exceptions.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_FilterThrows_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next());
var exception = await Assert.ThrowsAsync<MethodInterceptionGrain.MyDomainSpecificException>(() => grain.FilterThrows());
Assert.NotNull(exception);
Assert.Equal("Filter THROW!", exception.Message);
}
/// <summary>
/// Tests that if a grain call filter sets an incorrect result type for <see cref="Orleans.IGrainCallContext.Result"/>,
/// an exception is thrown on the caller.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_SetIncorrectResultType_Test()
{
var grain = this.fixture.GrainFactory.GetGrain<IMethodInterceptionGrain>(random.Next());
// This grain method throws, but the exception should be handled by one of the filters and converted
// into a specific message.
await Assert.ThrowsAsync<InvalidCastException>(() => grain.IncorrectResultType());
}
/// <summary>
/// Tests that <see cref="IIncomingGrainCallContext.ImplementationMethod"/> and <see cref="IGrainCallContext.InterfaceMethod"/> are non-null
/// for a call made to a grain and that they match the correct methods.
/// </summary>
[Fact]
public async Task GrainCallFilter_Incoming_GenericInterface_ConcreteGrain_Test()
{
var id = random.Next();
var hungry = this.fixture.GrainFactory.GetGrain<IHungryGrain<Apple>>(id);
var caterpillar = this.fixture.GrainFactory.GetGrain<ICaterpillarGrain>(id);
var omnivore = this.fixture.GrainFactory.GetGrain<IOmnivoreGrain>(id);
RequestContext.Set("tag", "hungry-eat");
await hungry.Eat(new Apple());
await ((IHungryGrain<Apple>)caterpillar).Eat(new Apple());
RequestContext.Set("tag", "omnivore-eat");
await omnivore.Eat("string");
await ((IOmnivoreGrain)caterpillar).Eat("string");
RequestContext.Set("tag", "caterpillar-eat");
await caterpillar.Eat("string");
RequestContext.Set("tag", "hungry-eatwith");
await caterpillar.EatWith(new Apple(), "butter");
await hungry.EatWith(new Apple(), "butter");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.Implementation.Workspaces;
using Microsoft.CodeAnalysis.Host;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
public class ProjectCacheHostServiceFactoryTests
{
private void Test(Action<IProjectCacheHostService, ProjectId, ICachedObjectOwner, ObjectReference> action)
{
// Putting cacheService.CreateStrongReference in a using statement
// creates a temporary local that isn't collected in Debug builds
// Wrapping it in a lambda allows it to get collected.
var cacheService = new ProjectCacheService(null, int.MaxValue);
var projectId = ProjectId.CreateNewId();
var owner = new Owner();
var instance = new ObjectReference();
action(cacheService, projectId, owner, instance);
}
[Fact]
public void TestCacheKeepsObjectAlive1()
{
Test((cacheService, projectId, owner, instance) =>
{
((Action)(() =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, instance.Strong);
instance.Strong = null;
CollectGarbage();
Assert.True(instance.Weak.IsAlive);
}
})).Invoke();
CollectGarbage();
Assert.False(instance.Weak.IsAlive);
GC.KeepAlive(owner);
});
}
[Fact]
public void TestCacheKeepsObjectAlive2()
{
Test((cacheService, projectId, owner, instance) =>
{
((Action)(() =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, instance.Strong);
instance.Strong = null;
CollectGarbage();
Assert.True(instance.Weak.IsAlive);
}
})).Invoke();
CollectGarbage();
Assert.False(instance.Weak.IsAlive);
GC.KeepAlive(owner);
});
}
[Fact]
public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected1()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, (object)owner, instance);
owner = null;
instance.Strong = null;
CollectGarbage();
Assert.False(instance.Weak.IsAlive);
}
});
}
[Fact]
public void TestCacheDoesNotKeepObjectsAliveAfterOwnerIsCollected2()
{
Test((cacheService, projectId, owner, instance) =>
{
using (cacheService.EnableCaching(projectId))
{
cacheService.CacheObjectIfCachingEnabledForKey(projectId, owner, instance);
owner = null;
instance.Strong = null;
CollectGarbage();
Assert.False(instance.Weak.IsAlive);
}
});
}
[Fact]
public void TestImplicitCacheKeepsObjectAlive1()
{
var cacheService = new ProjectCacheService(null, int.MaxValue);
var instance = new object();
var weak = new WeakReference(instance);
cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, instance);
instance = null;
CollectGarbage();
Assert.True(weak.IsAlive);
GC.KeepAlive(cacheService);
}
[Fact]
public void TestImplicitCacheMonitoring()
{
var cacheService = new ProjectCacheService(null, 10, forceCleanup: true);
var weak = PutObjectInImplicitCache(cacheService);
var timeout = TimeSpan.FromSeconds(10);
var current = DateTime.UtcNow;
do
{
Thread.Sleep(100);
CollectGarbage();
if (DateTime.UtcNow - current > timeout)
{
break;
}
}
while (weak.IsAlive);
Assert.False(weak.IsAlive);
GC.KeepAlive(cacheService);
}
private static WeakReference PutObjectInImplicitCache(ProjectCacheService cacheService)
{
var instance = new object();
var weak = new WeakReference(instance);
cacheService.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, instance);
instance = null;
return weak;
}
[Fact]
public void TestP2PReference()
{
var workspace = new AdhocWorkspace();
var project1 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj1", "proj1", LanguageNames.CSharp);
var project2 = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "proj2", "proj2", LanguageNames.CSharp, projectReferences: SpecializedCollections.SingletonEnumerable(new ProjectReference(project1.Id)));
var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default, projects: new ProjectInfo[] { project1, project2 });
var solution = workspace.AddSolution(solutionInfo);
var instance = new object();
var weak = new WeakReference(instance);
var cacheService = new ProjectCacheService(workspace, int.MaxValue);
using (var cache = cacheService.EnableCaching(project2.Id))
{
cacheService.CacheObjectIfCachingEnabledForKey(project1.Id, (object)null, instance);
instance = null;
solution = null;
workspace.OnProjectRemoved(project1.Id);
workspace.OnProjectRemoved(project2.Id);
}
// make sure p2p reference doesn't go to implicit cache
CollectGarbage();
Assert.False(weak.IsAlive);
}
[Fact]
public void TestEjectFromImplicitCache()
{
List<Compilation> compilations = new List<Compilation>();
for (int i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++)
{
compilations.Add(CSharpCompilation.Create(i.ToString()));
}
var weakFirst = new WeakReference(compilations[0]);
var weakLast = new WeakReference(compilations[compilations.Count - 1]);
var cache = new ProjectCacheService(null, int.MaxValue);
for (int i = 0; i < ProjectCacheService.ImplicitCacheSize + 1; i++)
{
cache.CacheObjectIfCachingEnabledForKey(ProjectId.CreateNewId(), (object)null, compilations[i]);
}
compilations = null;
CollectGarbage();
Assert.False(weakFirst.IsAlive);
Assert.True(weakLast.IsAlive);
GC.KeepAlive(cache);
}
[Fact]
public void TestCacheCompilationTwice()
{
var comp1 = CSharpCompilation.Create("1");
var comp2 = CSharpCompilation.Create("2");
var comp3 = CSharpCompilation.Create("3");
var weak3 = new WeakReference(comp3);
var weak1 = new WeakReference(comp1);
var cache = new ProjectCacheService(null, int.MaxValue);
var key = ProjectId.CreateNewId();
var owner = new object();
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp1);
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp2);
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3);
// When we cache 3 again, 1 should stay in the cache
cache.CacheObjectIfCachingEnabledForKey(key, owner, comp3);
comp1 = null;
comp2 = null;
comp3 = null;
CollectGarbage();
Assert.True(weak1.IsAlive);
Assert.True(weak3.IsAlive);
GC.KeepAlive(cache);
}
private class Owner : ICachedObjectOwner
{
object ICachedObjectOwner.CachedObject { get; set; }
}
private static void CollectGarbage()
{
for (var i = 0; i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.GenerateType
{
[ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared]
internal class CSharpGenerateTypeService :
AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax>
{
private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
protected override string DefaultFileExtension => ".cs";
protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName)
{
return simpleName.GetLeftSideOfDot();
}
protected override bool IsInCatchDeclaration(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.CatchDeclaration);
}
protected override bool IsArrayElementType(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.ArrayType) &&
expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression);
}
protected override bool IsInValueTypeConstraintContext(
SemanticModel semanticModel,
ExpressionSyntax expression,
CancellationToken cancellationToken)
{
if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList))
{
var typeArgumentList = (TypeArgumentListSyntax)expression.Parent;
var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken);
var symbol = symbolInfo.GetAnySymbol();
if (symbol.IsConstructor())
{
symbol = symbol.ContainingType;
}
var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression);
var type = symbol as INamedTypeSymbol;
if (type != null)
{
type = type.OriginalDefinition;
var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
var method = symbol as IMethodSymbol;
if (method != null)
{
method = method.OriginalDefinition;
var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
}
return false;
}
protected override bool IsInInterfaceList(ExpressionSyntax expression)
{
if (expression is TypeSyntax &&
expression.Parent is BaseTypeSyntax &&
expression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)expression.Parent).Type == expression)
{
var baseList = (BaseListSyntax)expression.Parent.Parent;
// If it's after the first item, then it's definitely an interface.
if (baseList.Types[0] != expression.Parent)
{
return true;
}
// If it's in the base list of an interface or struct, then it's definitely an
// interface.
return
baseList.IsParentKind(SyntaxKind.InterfaceDeclaration) ||
baseList.IsParentKind(SyntaxKind.StructDeclaration);
}
if (expression is TypeSyntax &&
expression.IsParentKind(SyntaxKind.TypeConstraint) &&
expression.Parent.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
{
var typeConstraint = (TypeConstraintSyntax)expression.Parent;
var constraintClause = (TypeParameterConstraintClauseSyntax)typeConstraint.Parent;
var index = constraintClause.Constraints.IndexOf(typeConstraint);
// If it's after the first item, then it's definitely an interface.
return index > 0;
}
return false;
}
protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts)
{
nameParts = new List<string>();
return expression.TryGetNameParts(out nameParts);
}
protected override bool TryInitializeState(
SemanticDocument document,
SimpleNameSyntax simpleName,
CancellationToken cancellationToken,
out GenerateTypeServiceStateOptions generateTypeServiceStateOptions)
{
generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions();
if (simpleName.IsVar)
{
return false;
}
if (SyntaxFacts.IsAliasQualifier(simpleName))
{
return false;
}
// Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly
// unlikely that this would be a location where a user would be wanting to generate
// something. They're really just trying to reference something that exists but
// isn't available for some reason (i.e. a missing reference).
var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>();
if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword)
{
return false;
}
ExpressionSyntax nameOrMemberAccessExpression = null;
if (simpleName.IsRightSideOfDot())
{
// This simplename comes from the cref
if (simpleName.IsParentKind(SyntaxKind.NameMemberCref))
{
return false;
}
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent;
// If we're on the right side of a dot, then the left side better be a name (and
// not an arbitrary expression).
var leftSideExpression = simpleName.GetLeftSideOfDot();
if (!leftSideExpression.IsKind(
SyntaxKind.QualifiedName,
SyntaxKind.IdentifierName,
SyntaxKind.AliasQualifiedName,
SyntaxKind.GenericName,
SyntaxKind.SimpleMemberAccessExpression))
{
return false;
}
}
else
{
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName;
}
// BUG(5712): Don't offer generate type in an enum's base list.
if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax &&
nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression &&
nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration))
{
return false;
}
// If we can guarantee it's a type only context, great. Otherwise, we may not want to
// provide this here.
var semanticModel = document.SemanticModel;
if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
// Don't offer Generate Type in an expression context *unless* we're on the left
// side of a dot. In that case the user might be making a type that they're
// accessing a static off of.
var syntaxTree = semanticModel.SyntaxTree;
var start = nameOrMemberAccessExpression.SpanStart;
var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken);
var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel);
var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken);
var isExpressionOrStatementContext = isExpressionContext || isStatementContext;
// Delegate Type Creation is not allowed in Non Type Namespace Context
generateTypeServiceStateOptions.IsDelegateAllowed = false;
if (!isExpressionOrStatementContext)
{
return false;
}
if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOf())
{
if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot())
{
return false;
}
var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol;
var token = simpleName.GetLastToken().GetNextToken();
// We let only the Namespace to be left of the Dot
if (leftSymbol == null ||
!leftSymbol.IsKind(SymbolKind.Namespace) ||
!token.IsKind(SyntaxKind.DotToken))
{
return false;
}
else
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
// Global Namespace
if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess &&
!SyntaxFacts.IsInNamespaceOrTypeContext(simpleName))
{
var token = simpleName.GetLastToken().GetNextToken();
if (token.IsKind(SyntaxKind.DotToken) &&
simpleName.Parent == token.Parent)
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
}
var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>();
if (fieldDeclaration != null &&
fieldDeclaration.Parent is CompilationUnitSyntax &&
document.Document.SourceCodeKind == SourceCodeKind.Regular)
{
return false;
}
// Check to see if Module could be an option in the Type Generation in Cross Language Generation
var nextToken = simpleName.GetLastToken().GetNextToken();
if (simpleName.IsLeftSideOfDot() ||
nextToken.IsKind(SyntaxKind.DotToken))
{
if (simpleName.IsRightSideOfDot())
{
var parent = simpleName.Parent as QualifiedNameSyntax;
if (parent != null)
{
var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol;
if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace))
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
}
}
}
if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
if (nextToken.IsKind(SyntaxKind.DotToken))
{
// In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName
generateTypeServiceStateOptions.IsDelegateAllowed = false;
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
// case: class Foo<T> where T: MyType
if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any())
{
generateTypeServiceStateOptions.IsClassInterfaceTypes = true;
return true;
}
// Events
if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() ||
nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any())
{
// Case : event foo name11
// Only Delegate
if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax))
{
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
// Case : event SomeSymbol.foo name11
if (nameOrMemberAccessExpression is QualifiedNameSyntax)
{
// Only Namespace, Class, Struct and Module are allowed to contain Delegate
// Case : event Something.Mytype.<Delegate> Identifier
if (nextToken.IsKind(SyntaxKind.DotToken))
{
if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax)
{
return true;
}
else
{
Contract.Fail("Cannot reach this point");
}
}
else
{
// Case : event Something.<Delegate> Identifier
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
}
}
}
else
{
// MemberAccessExpression
if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)))
&& nameOrMemberAccessExpression.IsLeftSideOfDot())
{
// Check to see if the expression is part of Invocation Expression
ExpressionSyntax outerMostMemberAccessExpression = null;
if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
outerMostMemberAccessExpression = nameOrMemberAccessExpression;
}
else
{
Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression));
outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent;
}
outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile((n) => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault();
if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax)
{
generateTypeServiceStateOptions.IsEnumNotAllowed = true;
}
}
}
// Cases:
// // 1 - Function Address
// var s2 = new MyD2(foo);
// // 2 - Delegate
// MyD1 d = null;
// var s1 = new MyD2(d);
// // 3 - Action
// Action action1 = null;
// var s3 = new MyD2(action1);
// // 4 - Func
// Func<int> lambda = () => { return 0; };
// var s4 = new MyD3(lambda);
if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax)
{
var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent;
// Enum and Interface not Allowed in Object Creation Expression
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
if (objectCreationExpressionOpt.ArgumentList != null)
{
if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing)
{
return false;
}
// Get the Method symbol for the Delegate to be created
if (generateTypeServiceStateOptions.IsDelegateAllowed &&
objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken);
}
else
{
generateTypeServiceStateOptions.IsDelegateAllowed = false;
}
}
if (objectCreationExpressionOpt.Initializer != null)
{
foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions)
{
var simpleAssignmentExpression = expression as AssignmentExpressionSyntax;
if (simpleAssignmentExpression == null)
{
continue;
}
var name = simpleAssignmentExpression.Left as SimpleNameSyntax;
if (name == null)
{
continue;
}
generateTypeServiceStateOptions.PropertiesToGenerate.Add(name);
}
}
}
if (generateTypeServiceStateOptions.IsDelegateAllowed)
{
// MyD1 z1 = foo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration))
{
var variableDeclaration = (VariableDeclarationSyntax)nameOrMemberAccessExpression.Parent;
if (variableDeclaration.Variables.Count != 0)
{
var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null);
if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken);
}
}
}
// var w1 = (MyD1)foo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression))
{
var castExpression = (CastExpressionSyntax)nameOrMemberAccessExpression.Parent;
if (castExpression.Expression != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken);
}
}
}
return true;
}
private IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
{
if (expression == null)
{
return null;
}
var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken);
if (memberGroup.Length != 0)
{
return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null;
}
var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
if (expressionType.IsDelegateType())
{
return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod;
}
var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol;
if (expressionSymbol.IsKind(SymbolKind.Method))
{
return (IMethodSymbol)expressionSymbol;
}
return null;
}
private Accessibility DetermineAccessibilityConstraint(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return semanticModel.DetermineAccessibilityConstraint(
state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken);
}
protected override IList<ITypeParameterSymbol> GetTypeParameters(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (state.SimpleName is GenericNameSyntax)
{
var genericName = (GenericNameSyntax)state.SimpleName;
var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count
? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList()
: Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity);
return this.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken);
}
return SpecializedCollections.EmptyList<ITypeParameterSymbol>();
}
protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList)
{
if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null)
{
argumentList = objectCreationExpression.ArgumentList.Arguments.ToList();
return true;
}
argumentList = null;
return false;
}
protected override IList<string> GenerateParameterNames(
SemanticModel semanticModel, IList<ArgumentSyntax> arguments)
{
return semanticModel.GenerateParameterNames(arguments);
}
public override string GetRootNamespace(CompilationOptions options)
{
return string.Empty;
}
protected override bool IsInVariableTypeContext(ExpressionSyntax expression)
{
return false;
}
protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken);
}
protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken)
{
var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken);
if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess)
{
var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken);
if (accessibilityConstraint == Accessibility.Public ||
accessibilityConstraint == Accessibility.Internal)
{
accessibility = accessibilityConstraint;
}
}
return accessibility;
}
protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
{
return argument.DetermineParameterType(semanticModel, cancellationToken);
}
protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
{
return compilation.ClassifyConversion(sourceType, targetType).IsImplicit;
}
public override async Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbolAsync(
INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken)
{
var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot;
var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (containers.Length != 0)
{
// Search the NS declaration in the root
var containerList = new List<string>(containers);
var enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit);
if (enclosingNamespace != null)
{
var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken);
if (enclosingNamespaceSymbol.Symbol != null)
{
return Tuple.Create((INamespaceSymbol)enclosingNamespaceSymbol.Symbol,
(INamespaceOrTypeSymbol)namedTypeSymbol,
enclosingNamespace.CloseBraceToken.GetLocation());
}
}
}
var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken);
var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers);
var lastMember = compilationUnit.Members.LastOrDefault();
Location afterThisLocation = null;
if (lastMember != null)
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0));
}
else
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan());
}
return Tuple.Create(globalNamespace,
rootNamespaceOrType,
afterThisLocation);
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, CompilationUnitSyntax compilationUnit)
{
foreach (var member in compilationUnit.Members)
{
var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member);
if (namespaceDeclaration != null)
{
return namespaceDeclaration;
}
}
return null;
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot)
{
var namespaceDecl = localRoot as NamespaceDeclarationSyntax;
if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax)
{
return null;
}
List<string> namespaceContainers = new List<string>();
GetNamespaceContainers(namespaceDecl.Name, namespaceContainers);
if (namespaceContainers.Count + indexDone > containers.Count ||
!IdentifierMatches(indexDone, namespaceContainers, containers))
{
return null;
}
indexDone = indexDone + namespaceContainers.Count;
if (indexDone == containers.Count)
{
return namespaceDecl;
}
foreach (var member in namespaceDecl.Members)
{
var resultant = GetDeclaringNamespace(containers, indexDone, member);
if (resultant != null)
{
return resultant;
}
}
return null;
}
private bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers)
{
for (int i = 0; i < namespaceContainers.Count; ++i)
{
if (namespaceContainers[i] != containers[indexDone + i])
{
return false;
}
}
return true;
}
private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers)
{
if (name is QualifiedNameSyntax)
{
GetNamespaceContainers(((QualifiedNameSyntax)name).Left, namespaceContainers);
namespaceContainers.Add(((QualifiedNameSyntax)name).Right.Identifier.ValueText);
}
else
{
Debug.Assert(name is SimpleNameSyntax);
namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText);
}
}
internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue)
{
typeKindValue = TypeKindOptions.AllOptions;
if (expression == null)
{
return false;
}
var node = expression as SyntaxNode;
while (node != null)
{
if (node is BaseListSyntax)
{
if (node.Parent != null && (node.Parent is InterfaceDeclarationSyntax || node.Parent is StructDeclarationSyntax))
{
typeKindValue = TypeKindOptions.Interface;
return true;
}
typeKindValue = TypeKindOptions.BaseList;
return true;
}
node = node.Parent;
}
return false;
}
internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project)
{
if (expression == null)
{
return false;
}
if (GeneratedTypesMustBePublic(project))
{
return true;
}
var node = expression as SyntaxNode;
SyntaxNode previousNode = null;
while (node != null)
{
// Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type
if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
var typeDecl = node.Parent as TypeDeclarationSyntax;
if (typeDecl != null)
{
if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return IsAllContainingTypeDeclsPublic(typeDecl);
}
else
{
// The Type Decl which contains the BaseList does not contain Public
return false;
}
}
Contract.Fail("Cannot reach this point");
}
if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
// Make sure the GFU is not inside the Accessors
if (previousNode != null && previousNode is AccessorListSyntax)
{
return false;
}
// Make sure that Event Declaration themselves are Public in the first place
if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return false;
}
return IsAllContainingTypeDeclsPublic(node);
}
previousNode = node;
node = node.Parent;
}
return false;
}
private bool IsAllContainingTypeDeclsPublic(SyntaxNode node)
{
// Make sure that all the containing Type Declarations are also Public
var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>();
if (containingTypeDeclarations.Count() == 0)
{
return true;
}
else
{
return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword));
}
}
internal override bool IsGenericName(SimpleNameSyntax simpleName)
{
if (simpleName == null)
{
return false;
}
var genericName = simpleName as GenericNameSyntax;
return genericName != null;
}
internal override bool IsSimpleName(ExpressionSyntax expression)
{
return expression is SimpleNameSyntax;
}
internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken)
{
// Nothing to include
if (string.IsNullOrWhiteSpace(includeUsingsOrImports))
{
return updatedSolution;
}
SyntaxNode root = null;
if (modifiedRoot == null)
{
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
else
{
root = modifiedRoot;
}
if (root is CompilationUnitSyntax)
{
var compilationRoot = (CompilationUnitSyntax)root;
var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports));
// Check if the usings is already present
if (compilationRoot.Usings.Where(n => n != null && n.Alias == null)
.Select(n => n.Name.ToString())
.Any(n => n.Equals(includeUsingsOrImports)))
{
return updatedSolution;
}
// Check if the GFU is triggered from the namespace same as the usings namespace
if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false))
{
return updatedSolution;
}
var placeSystemNamespaceFirst = document.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst);
var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation);
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity);
}
return updatedSolution;
}
private ITypeSymbol GetPropertyType(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken)
{
var parentAssignment = propertyName.Parent as AssignmentExpressionSyntax;
if (parentAssignment != null)
{
return typeInference.InferType(
semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken);
}
var isPatternExpression = propertyName.Parent as IsPatternExpressionSyntax;
if (isPatternExpression != null)
{
return typeInference.InferType(
semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken);
}
return null;
}
private IPropertySymbol CreatePropertySymbol(
SimpleNameSyntax propertyName, ITypeSymbol propertyType)
{
return CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: SpecializedCollections.EmptyList<AttributeData>(),
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(),
explicitInterfaceSymbol: null,
name: propertyName.Identifier.ValueText,
type: propertyType,
parameters: null,
getMethod: s_accessor,
setMethod: s_accessor,
isIndexer: false);
}
private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: null,
accessibility: Accessibility.Public,
statements: null);
internal override bool TryGenerateProperty(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken,
out IPropertySymbol property)
{
property = null;
var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken);
if (propertyType == null || propertyType is IErrorTypeSymbol)
{
property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType);
return property != null;
}
property = CreatePropertySymbol(propertyName, propertyType);
return property != null;
}
internal override IMethodSymbol GetDelegatingConstructor(
SemanticDocument document,
ObjectCreationExpressionSyntax objectCreation,
INamedTypeSymbol namedType,
ISet<IMethodSymbol> candidates,
CancellationToken cancellationToken)
{
var model = document.SemanticModel;
var oldNode = objectCreation
.AncestorsAndSelf(ascendOutOfTrivia: false)
.Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node))
.LastOrDefault();
var typeNameToReplace = objectCreation.Type;
var newTypeName = namedType.GenerateTypeSyntax();
var newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation);
var newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation);
var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model);
if (speculativeModel != null)
{
newObjectCreation = (ObjectCreationExpressionSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
var symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken);
var parameterTypes = newObjectCreation.ArgumentList.Arguments.Select(
a => speculativeModel.GetTypeInfo(a.Expression, cancellationToken).ConvertedType).ToList();
return GenerateConstructorHelpers.GetDelegatingConstructor(
document, symbolInfo, candidates, namedType, parameterTypes);
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ViewComponents
{
public class DefaultViewComponentSelectorTest
{
private static readonly string Namespace = typeof(DefaultViewComponentSelectorTest).Namespace;
[Fact]
public void SelectComponent_ByShortNameWithSuffix()
{
// Arrange
var selector = CreateSelector();
// Act
var result = selector.SelectComponent("Suffix");
// Assert
Assert.Same(typeof(ViewComponentContainer.SuffixViewComponent).GetTypeInfo(), result.TypeInfo);
}
[Fact]
public void SelectComponent_ByLongNameWithSuffix()
{
// Arrange
var selector = CreateSelector();
// Act
var result = selector.SelectComponent($"{Namespace}.Suffix");
// Assert
Assert.Same(typeof(ViewComponentContainer.SuffixViewComponent).GetTypeInfo(), result.TypeInfo);
}
[Fact]
public void SelectComponent_ByShortNameWithoutSuffix()
{
// Arrange
var selector = CreateSelector();
// Act
var result = selector.SelectComponent("WithoutSuffix");
// Assert
Assert.Same(typeof(ViewComponentContainer.WithoutSuffix).GetTypeInfo(), result.TypeInfo);
}
[Fact]
public void SelectComponent_ByLongNameWithoutSuffix()
{
// Arrange
var selector = CreateSelector();
// Act
var result = selector.SelectComponent($"{Namespace}.WithoutSuffix");
// Assert
Assert.Same(typeof(ViewComponentContainer.WithoutSuffix).GetTypeInfo(), result.TypeInfo);
}
[Fact]
public void SelectComponent_ByAttribute()
{
// Arrange
var selector = CreateSelector();
// Act
var result = selector.SelectComponent("ByAttribute");
// Assert
Assert.Same(typeof(ViewComponentContainer.ByAttribute).GetTypeInfo(), result.TypeInfo);
}
[Fact]
public void SelectComponent_ByNamingConvention()
{
// Arrange
var selector = CreateSelector();
// Act
var result = selector.SelectComponent("ByNamingConvention");
// Assert
Assert.Same(typeof(ViewComponentContainer.ByNamingConventionViewComponent).GetTypeInfo(), result.TypeInfo);
}
[Fact]
public void SelectComponent_Ambiguity()
{
// Arrange
var selector = CreateSelector();
var expected =
"The view component name 'Ambiguous' matched multiple types:" + Environment.NewLine +
$"Type: '{typeof(ViewComponentContainer.Ambiguous1)}' - " +
"Name: 'Namespace1.Ambiguous'" + Environment.NewLine +
$"Type: '{typeof(ViewComponentContainer.Ambiguous2)}' - " +
"Name: 'Namespace2.Ambiguous'";
// Act
var ex = Assert.Throws<InvalidOperationException>(() => selector.SelectComponent("Ambiguous"));
// Assert
Assert.Equal(expected, ex.Message);
}
[Theory]
[InlineData("Name")]
[InlineData("Ambiguous.Name")]
public void SelectComponent_AmbiguityDueToDerivation(string name)
{
// Arrange
var selector = CreateSelector();
var expected =
$"The view component name '{name}' matched multiple types:" + Environment.NewLine +
$"Type: '{typeof(ViewComponentContainer.AmbiguousBase)}' - " +
"Name: 'Ambiguous.Name'" + Environment.NewLine +
$"Type: '{typeof(ViewComponentContainer.DerivedAmbiguous)}' - " +
"Name: 'Ambiguous.Name'";
// Act
var ex = Assert.Throws<InvalidOperationException>(() => selector.SelectComponent(name));
// Assert
Assert.Equal(expected, ex.Message);
}
[Fact]
public void SelectComponent_FullNameToAvoidAmbiguity()
{
// Arrange
var selector = CreateSelector();
// Act
var result = selector.SelectComponent("Namespace1.Ambiguous");
// Assert
Assert.Same(typeof(ViewComponentContainer.Ambiguous1).GetTypeInfo(), result.TypeInfo);
}
[Fact]
public void SelectComponent_OverrideNameToAvoidAmbiguity()
{
// Arrange
var selector = CreateSelector();
// Act
var result = selector.SelectComponent("NonAmbiguousName");
// Assert
Assert.Same(typeof(ViewComponentContainer.DerivedAmbiguousWithOverriddenName).GetTypeInfo(), result.TypeInfo);
}
[Theory]
[InlineData("FullNameInAttribute")]
[InlineData("CoolNameSpace.FullNameInAttribute")]
public void SelectComponent_FullNameInAttribute(string name)
{
// Arrange
var selector = CreateSelector();
// Act
var result = selector.SelectComponent(name);
// Assert
Assert.Same(typeof(ViewComponentContainer.FullNameInAttribute).GetTypeInfo(), result.TypeInfo);
}
private IViewComponentSelector CreateSelector()
{
var provider = new DefaultViewComponentDescriptorCollectionProvider(
new FilteredViewComponentDescriptorProvider());
return new DefaultViewComponentSelector(provider);
}
private class ViewComponentContainer
{
public class SuffixViewComponent : ViewComponent
{
public string Invoke() => "Hello";
}
public class WithoutSuffix : ViewComponent
{
public string Invoke() => "Hello";
}
public class ByNamingConventionViewComponent
{
public string Invoke() => "Hello";
}
[ViewComponent]
public class ByAttribute
{
public string Invoke() => "Hello";
}
[ViewComponent(Name = "Namespace1.Ambiguous")]
public class Ambiguous1
{
public string Invoke() => "Hello";
}
[ViewComponent(Name = "Namespace2.Ambiguous")]
public class Ambiguous2
{
public string Invoke() => "Hello";
}
[ViewComponent(Name = "CoolNameSpace.FullNameInAttribute")]
public class FullNameInAttribute
{
public string Invoke() => "Hello";
}
[ViewComponent(Name = "Ambiguous.Name")]
public class AmbiguousBase
{
public string Invoke() => "Hello";
}
public class DerivedAmbiguous : AmbiguousBase
{
}
[ViewComponent(Name = "NonAmbiguousName")]
public class DerivedAmbiguousWithOverriddenName : AmbiguousBase
{
}
}
// This will only consider types nested inside this class as ViewComponent classes
private class FilteredViewComponentDescriptorProvider : DefaultViewComponentDescriptorProvider
{
public FilteredViewComponentDescriptorProvider()
: this(typeof(ViewComponentContainer).GetNestedTypes(bindingAttr: BindingFlags.Public))
{
}
// For error messages in tests above, ensure the TestApplicationPart returns types in a consistent order.
public FilteredViewComponentDescriptorProvider(params Type[] allowedTypes)
: base(GetApplicationPartManager(allowedTypes.OrderBy(type => type.Name, StringComparer.Ordinal)))
{
}
private static ApplicationPartManager GetApplicationPartManager(IEnumerable<Type> types)
{
var manager = new ApplicationPartManager();
manager.ApplicationParts.Add(new TestApplicationPart(types));
manager.FeatureProviders.Add(new TestFeatureProvider());
return manager;
}
private class TestFeatureProvider : IApplicationFeatureProvider<ViewComponentFeature>
{
public void PopulateFeature(IEnumerable<ApplicationPart> parts, ViewComponentFeature feature)
{
foreach (var type in parts.OfType<IApplicationPartTypeProvider>().SelectMany(p => p.Types))
{
feature.ViewComponents.Add(type);
}
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="IndexingFilter.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// IFilter interop definitions.
//
// These structures and constants are managed equivalents to COM structures
// constants required by the IFilter interface.
//
// History:
// 01/26/2004: BruceMac: Initial implementation.
// 08/26/2004: JohnLarc: Moved to internal namespace MS.Internal.Interop.
// 06/24/2005: LGolding: Split the definitions of PROPSPEC and PROPVARIANT
// out into Base\MS\Internal\Interop\OlePropertyStructs.cs,
// because they are now needed by both the IFilter code in
// PresentationFramework and the EncryptedPackageCoreProperties
// class in WindowsBase.
// 03/24/2006: RukeH: Redefined the standard managed COM interface IPersistFile.
//
//-----------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using MS.Internal.IO.Packaging;
namespace MS.Internal.Interop
{
#region COM structs and enums
/// <summary>
/// The IFilter error codes as defined in file filterr.h of the Windows SDK.
/// </summary>
internal enum FilterErrorCode : int
{
/// <summary>
/// No more chunks of text available in object.
/// </summary>
FILTER_E_END_OF_CHUNKS = unchecked((int)0x80041700),
/// <summary>
/// No more text available in chunk.
/// </summary>
FILTER_E_NO_MORE_TEXT = unchecked((int)0x80041701),
/// <summary>
/// No more property values available in chunk.
/// </summary>
FILTER_E_NO_MORE_VALUES = unchecked((int)0x80041702),
/// <summary>
/// Unable to access object.
/// </summary>
FILTER_E_ACCESS = unchecked((int)0x80041703),
/// <summary>
/// Moniker doesn't cover entire region.
/// </summary>
FILTER_W_MONIKER_CLIPPED = unchecked((int)0x00041704),
/// <summary>
/// No text in current chunk.
/// </summary>
FILTER_E_NO_TEXT = unchecked((int)0x80041705),
/// <summary>
/// No values in current chunk.
/// </summary>
FILTER_E_NO_VALUES = unchecked((int)0x80041706),
/// <summary>
/// Unable to bind IFilter for embedded object.
/// </summary>
FILTER_E_EMBEDDING_UNAVAILABLE = unchecked((int)0x80041707),
/// <summary>
/// Unable to bind IFilter for linked object.
/// </summary>
FILTER_E_LINK_UNAVAILABLE = unchecked((int)0x80041708),
/// <summary>
/// This is the last text in the current chunk.
/// </summary>
FILTER_S_LAST_TEXT = unchecked((int)0x00041709),
/// <summary>
/// This is the last value in the current chunk.
/// </summary>
FILTER_S_LAST_VALUES = unchecked((int)0x0004170A),
/// <summary>
/// File was not filtered due to password protection.
/// </summary>
FILTER_E_PASSWORD = unchecked((int)0x8004170B),
/// <summary>
/// The document format is not recognized by the filter.
/// </summary>
FILTER_E_UNKNOWNFORMAT = unchecked((int)0x8004170C),
}
/// <summary>
/// The mode/access/sharing flags that are passed to IPersistXXX.Load.
/// </summary>
[Flags]
internal enum STGM_FLAGS
{
//
// Mode
//
/// <summary>
/// Create. Subsumes Create, CreateNew and OpenOrCreate.
/// </summary>
CREATE = 0x00001000,
/// <summary>
/// Select the mode bit.
/// </summary>
MODE = 0x00001000, // mask
//
// Access
//
/// <summary>
/// Read access.
/// </summary>
READ = 0x00000000,
/// <summary>
/// Write access.
/// </summary>
WRITE = 0x00000001,
/// <summary>
/// Read-write access.
/// </summary>
READWRITE = 0x00000002,
/// <summary>
/// Flag to zero in on the access bits.
/// </summary>
ACCESS = 0x00000003, // mask
//
// Sharing
//
/// <summary>
/// ReadWrite
/// </summary>
SHARE_DENY_NONE = 0x00000040,
/// <summary>
/// Write
/// </summary>
SHARE_DENY_READ = 0x00000030,
/// <summary>
/// Read
/// </summary>
SHARE_DENY_WRITE = 0x00000020,
/// <summary>
/// None
/// </summary>
SHARE_EXCLUSIVE = 0x00000010,
/// <summary>
/// Flag to select the Share bits.
/// </summary>
SHARING = 0x00000070, // mask
}
/// <summary>
/// Property ID's for PSGUID_STORAGE
/// </summary>
internal enum PID_STG : int
{
/// <summary>
/// The directory in which a file is located. Default type is VT_LPWSTR
/// </summary>
DIRECTORY = 0x02,
/// <summary>
/// CLID of a file. Default type is VT_CLSID.
/// </summary>
CLASSID = 0x03,
/// <summary>
/// Storage type for this file
/// </summary>
STORAGETYPE = 0x04,
/// <summary>
/// Volume ID of the disk
/// </summary>
VOLUME_ID = 0x05,
/// <summary>
/// Internal work ID for the parent or folder for this file.
/// </summary>
PARENT_WORKID = 0x06,
/// <summary>
/// Whether the file has been placed in secondary storage.
/// </summary>
SECONDARYSTORE = 0x07,
/// <summary>
/// Internal file index for this file.
/// </summary>
FILEINDEX = 0x08,
/// <summary>
/// Last change Update Sequence Number (USN) for this file.
/// </summary>
LASTCHANGEUSN = 0x09,
/// <summary>
/// The name of the file. Default type is VT_LPWSTR.
/// </summary>
NAME = 0x0a,
/// <summary>
/// The complete path for a file. Default type is VT_LPWSTR.
/// </summary>
PATH = 0x0b,
/// <summary>
/// The size of a file. Default type is VT_I8.
/// </summary>
SIZE = 0x0c,
/// <summary>
/// The attribute flags for a file. Default type is VT_UI4.
/// </summary>
ATTRIBUTES = 0x0d,
/// <summary>
/// The date and time of the last write to the file. Default type is VT_FILETIME.
/// </summary>
WRITETIME = 0x0e,
/// <summary>
/// The date and time the file was created. Default type is VT_FILETIME.
/// </summary>
CREATETIME = 0x0f,
/// <summary>
/// The time of the last access to the file. Default type is VT_FILETIME.
/// </summary>
ACCESSTIME = 0x10,
/// <summary>
/// The time of the last change to a file in an NTFS file system, including changes in the main data stream and secondary streams.
/// </summary>
CHANGETIME = 0x11,
/// <summary>
/// File allocation size.
/// </summary>
ALLOCSIZE = 0x12,
/// <summary>
/// The contents of the file. This property is for query restrictions only; it cannot be retrieved in a query result. Default type is VT_LPWSTR.
/// </summary>
CONTENTS = 0x13,
/// <summary>
/// The short (8.3) file name for the file. Default type is VT_LPWSTR.
/// </summary>
SHORTNAME = 0x14
}
/// <summary>
/// FULLPROPSPEC
/// </summary>
/// <remarks>
/// typedef struct tagFULLPROPSPEC
/// {
/// GUID guidPropSet;
/// PROPSPEC psProperty;
/// } FULLPROPSPEC;
/// </remarks>
[StructLayout(LayoutKind.Sequential, Pack = 0)]
internal struct FULLPROPSPEC
{
/// <summary>
/// The globally unique identifier (GUID) that identifies the property set.
/// </summary>
internal Guid guid;
/// <summary>
/// Pointer to the PROPSPEC structure that specifies a property either by its property
/// identifier or by the associated string name.
/// </summary>
internal PROPSPEC property;
};
/// <summary>
/// Init flags
/// </summary>
[Flags]
internal enum IFILTER_INIT : int
{
/// <summary>
/// Paragraph breaks should be marked with the Unicode PARAGRAPH SEPARATOR (0x2029)
/// </summary>
IFILTER_INIT_CANON_PARAGRAPHS = 0x01,
/// <summary>
/// Soft returns, such as the newline character in Word,
/// should be replaced by hard returnsLINE SEPARATOR (0x2028)
/// </summary>
IFILTER_INIT_HARD_LINE_BREAKS = 0x02,
/// <summary>
/// Various word-processing programs have forms of hyphens that are not represented
/// in the host character set, such as optional hyphens (appearing only at the end of a line)
/// and nonbreaking hyphens. This flag indicates that optional hyphens are to be converted
/// to nulls, and non-breaking hyphens are to be converted to normal hyphens (0x2010), or
/// HYPHEN-MINUSES (0x002D).
/// </summary>
IFILTER_INIT_CANON_HYPHENS = 0x04,
/// <summary>
/// Just as the IFILTER_INIT_CANON_HYPHENS flag standardizes hyphens, this one standardizes spaces.
/// All special space characters, such as nonbreaking spaces, are converted to the standard space
/// character (0x0020).
/// </summary>
IFILTER_INIT_CANON_SPACES = 0x08,
/// <summary>
/// Indicates that the client wants text split into chunks representing internal value-type properties.
/// </summary>
IFILTER_INIT_APPLY_INDEX_ATTRIBUTES = 0x10,
/// <summary>
/// Any properties not covered by the IFILTER_INIT_APPLY_INDEX_ATTRIBUTES and
/// IFILTER_INIT_APPLY_CRAWL_ATTRIBUTES flags should be emitted.
/// </summary>
IFILTER_INIT_APPLY_OTHER_ATTRIBUTES = 0x20,
/// <summary>
/// Optimizes IFilter for indexing because the client calls the IFilter::Init method only once and does
/// not call IFilter::BindRegion. This eliminates the possibility of accessing a chunk both before and
/// after accessing another chunk.
/// </summary>
IFILTER_INIT_INDEXING_ONLY = 0x40,
/// <summary>
/// The text extraction process must recursively search all linked objects within the document. If a link
/// is unavailable, the IFilter::GetChunk call that would have obtained the first chunk of the link should
/// return FILTER_E_LINK_UNAVAILABLE.
/// </summary>
IFILTER_INIT_SEARCH_LINKS = 0x80,
/// <summary>
/// Indicates that the client wants text split into chunks representing properties determined
/// during the indexing process.
/// </summary>
IFILTER_INIT_APPLY_CRAWL_ATTRIBUTES = 0x100,
/// <summary>
/// The content indexing process can return property values set by the filter
/// </summary>
IFILTER_INIT_FILTER_OWNED_VALUE_OK = 0x200
};
/// <summary>
/// more flags
/// </summary>
/// <remarks>
/// typedef enum tagIFILTER_FLAGS
/// {
/// IFILTER_FLAGS_OLE_PROPERTIES = 1
/// } IFILTER_FLAGS;
/// </remarks>
[Flags]
internal enum IFILTER_FLAGS : int
{
/// <summary>
/// Zero
/// </summary>
IFILTER_FLAGS_NONE = 0,
/// <summary>
/// This filter returns OLE properties
/// </summary>
IFILTER_FLAGS_OLE_PROPERTIES = 1
};
/// <summary>
/// Break Type
/// </summary>
internal enum CHUNK_BREAKTYPE : int
{
/// <summary>
/// No break is placed between the current chunk and the previous chunk. The chunks are glued together.
/// </summary>
CHUNK_NO_BREAK = 0,
/// <summary>
/// A word break is placed between this chunk and the previous chunk that had the same attribute. Use
/// of CHUNK_EOW should be minimized because the choice of word breaks is language-dependent, so
/// determining word breaks is best left to the search engine.
/// </summary>
CHUNK_EOW = 1,
/// <summary>
/// A sentence break is placed between this chunk and the previous chunk that had the same attribute.
/// </summary>
CHUNK_EOS = 2,
/// <summary>
/// A paragraph break is placed between this chunk and the previous chunk that had the same attribute.
/// </summary>
CHUNK_EOP = 3,
/// <summary>
/// A chapter break is placed between this chunk and the previous chunk that had the same attribute.
/// </summary>
CHUNK_EOC = 4
}
/// <summary>
/// Chunk State
/// </summary>
[Flags]
internal enum CHUNKSTATE
{
/// <summary>
/// The current chunk is a text-type property
/// </summary>
CHUNK_TEXT = 0x1,
/// <summary>
/// The current chunk is a value-type property
/// </summary>
CHUNK_VALUE = 0x2,
/// <summary>
/// Reserved
/// </summary>
CHUNK_FILTER_OWNED_VALUE = 0x4
}
/// <summary>
/// Stat Chunk
/// </summary>
/// <remarks>
/// typedef struct tagSTAT_CHUNK
/// {
/// ULONG idChunk;
/// CHUNK_BREAKTYPE breakType;
/// CHUNKSTATE flags;
/// LCID locale;
/// FULLPROPSPEC attribute;
/// ULONG idChunkSource;
/// ULONG cwcStartSource;
/// ULONG cwcLenSource;
/// } STAT_CHUNK;
/// </remarks>
[StructLayout(LayoutKind.Sequential, Pack = 0)]
internal struct STAT_CHUNK
{
/// <summary>
/// The chunk identifier.
/// Chunk identifiers must be unique for the current instance of the IFilter interface.
/// Chunk identifiers must be in ascending order. The order in which chunks are numbered should correspond
/// to the order in which they appear in the source document. Some search engines can take advantage of the
/// proximity of chunks of various properties. If so, the order in which chunks with different properties
/// are emitted will be important to the search engine.
/// </summary>
internal uint idChunk;
/// <summary>
/// The type of break that separates the previous chunk from the current chunk.
/// </summary>
internal CHUNK_BREAKTYPE breakType;
/// <summary>
/// Flags indicate whether this chunk contains a text-type or a value-type property
/// </summary>
internal CHUNKSTATE flags;
/// <summary>
/// The language and sublanguage associated with a chunk of text
/// </summary>
/// <remarks>
/// The managed equivalent to LCID is CultureInfo which takes an int constructor (the LCID) and
/// offers a read-only LCID property.
///
/// COM definition:
/// typedef DWORD LCID;
/// </remarks>
internal uint locale;
/// <summary>
/// The property to be applied to the chunk
/// </summary>
internal FULLPROPSPEC attribute;
/// <summary>
/// The ID of the source of a chunk
/// </summary>
internal uint idChunkSource;
/// <summary>
/// The offset from which the source text for a derived chunk starts in the source chunk
/// </summary>
internal uint cwcStartSource;
/// <summary>
/// The length in characters of the source text from which the current chunk was derived
/// </summary>
internal uint cwcLenSource;
};
/// <summary>
/// Unused but required for function signature on IFilter
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 0)]
internal struct FILTERREGION
{
/// <summary>
/// Chunk ID
/// </summary>
uint idChunk;
/// <summary>
/// Beginning of the region, specified as an offset from the beginning of the chunk
/// </summary>
uint cwcStart;
/// <summary>
/// Extent of the region, specified as a number of Unicode characters
/// </summary>
uint cwcExtent;
};
#endregion
#region IFilter Interface
/// <summary>
/// Managed equivalent for IFilter indexing interface
/// </summary>
[ComImport, ComVisible(true)]
[Guid("89BCB740-6119-101A-BCB7-00DD010655AF")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFilter
{
/// <summary>
/// Init
/// </summary>
/// <param name="grfFlags">usage flags</param>
/// <param name="cAttributes">number of items in aAttributes</param>
/// <param name="aAttributes">array of FULLPROPSPEC structs</param>
/// <returns></returns>
IFILTER_FLAGS Init(
[In] IFILTER_INIT grfFlags, // IFILTER_INIT value
[In] uint cAttributes, // number of items in aAttributes
[In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]
FULLPROPSPEC[] aAttributes); // restrict responses to the specified attributes
/// <summary>
/// GetChunk
/// </summary>
/// <returns></returns>
STAT_CHUNK GetChunk();
/// <summary>
/// GetText
/// </summary>
/// <param name="pcwcBuffer">buffer size in characters before and after we write to it</param>
/// <param name="pBuffer">preallocated buffer to write into</param>
/// <returns></returns>
void GetText([In, Out] ref uint pcwcBuffer, [In] IntPtr pBuffer);
/// <summary>
/// GetValue - unsafe code because marshaller cannot handle the complex argument
/// </summary>
/// <returns>PROPVARIANT object</returns>
IntPtr GetValue();
/// <summary>
/// BindRegion - do not implement - unused
/// </summary>
/// <param name="origPos"></param>
/// <param name="riid"></param>
/// <returns></returns>
IntPtr BindRegion([In] FILTERREGION origPos, [In] ref Guid riid);
}
#endregion IFilter Interface
#region IPersistStream Interface
/// <summary>
/// Managed definition of IPersistStream.
/// </summary>
/// <remarks>
/// The declaration order strictly follows that in objidl.h, otherwise
/// the vtbl would not be correctly accessed when invoking a COM object!
/// </remarks>
[ComImport, ComVisible(true)]
[Guid("00000109-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IPersistStream
{
/// <summary>
/// Retrieves the ClassID of this object. It returns
/// S_OK if successful, E_FAIL if not.
///
/// original interface:
/// HRESULT GetClassID(CLSID * pClassID);
///
/// </summary>
/// <remarks>
/// Strictly speaking, this method is inherited from IPersist, but since
/// IPersist is the only super-interface of IPersistStream, all we care about
/// is for its method to be declared first (since we do not need IPersist per se).
/// </remarks>
void GetClassID(out Guid pClassID);
/// <summary>
/// Determines if the object has changed since the last
/// save. S_OK means the file is clean. S_FALSE the file
/// has changed.
///
/// original interface:
/// HRESULT IsDirty(void);
///
/// </summary>
[PreserveSig()]
int IsDirty();
/// <summary>
/// Points the component to the specified stream.
/// </summary>
/// <remarks>
/// Uses our own managed definition of IStream in order to allow marshaling
/// the result of pointer arithmetic in Read.
/// </remarks>
void Load(IStream pstm);
/// <summary>
/// This is used when saving an object to a stream.
/// </summary>
/// <remarks>
/// In the case of an indexing filter, this function is not supported.
/// </remarks>
void Save(IStream pstm, [MarshalAs(UnmanagedType.Bool)] bool fRemember);
/// <summary>
/// Return the size in bytes of the stream needed to save the object.
/// </summary>
/// <param name="pcbSize">Points to a 64-bit unsigned integer value indicating the size in bytes of the stream needed to save this object.</param>
/// <remarks>
/// This is meaningful only when the interface is implemented in such a way
/// as to define a persistent object that is backed against the stream.
/// </remarks>
void GetSizeMax([Out] out Int64 pcbSize);
}
#endregion IPersistStream Interface
#region IStream
/// <summary>
/// Managed definition of IStream.
/// </summary>
/// <remarks>
/// The InteropServices provide a standard definition for this interface, but it is redefined
/// here to allow Read and Write to pass pointers rather than arrays, allowing them to optimize
/// the handling of the offset parameter.
/// The hard core of this definition consists of the Guid attribute and the order in which methods are declared.
/// This will map to an IStream vtbl, just like the standard definition.
/// So, the only difference with the standard definition is in the way the buffer parameter to Read and Write
/// will be marshaled.
/// </remarks>
[ComImport, ComVisible(true)]
[Guid("0000000C-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IStream
{
/// <summary>
/// Read no more than sizeInBytes bytes into the byte array located at bufferBase.
/// Return the result at the address refToNumBytesRead.
/// </summary>
/// <remarks>
/// Strictly speaking, Read and Write are part of ISequentialStream, which is inherited by IStream. Placing
/// them at the head of the list of methods reflects vtbl layout in COM C++.
///
/// IntPtr gets marshaled as ELEMENT_TYPE_I, which is defined in CorHdr.h as the "native integer size".
/// For all practical purposes, this is the size of an address, for there's no architecture we support whose
/// data bus and address bus have different widths.
/// </remarks>
void Read(IntPtr bufferBase, int sizeInBytes, IntPtr refToNumBytesRead);
/// <summary>
/// Write at most sizeInBytes bytes into the byte array located at buffer base.
/// Return the number of bytes effectively written at the address refToNumBytesWritten.
/// </summary>
void Write(IntPtr bufferBase, int sizeInBytes, IntPtr refToNumBytesWritten);
/// <summary>
/// Move the position to 'offset' with respect to 'origin' (one of STREAM_SEEK_SET, STREAM_SEEK_CUR,
/// and STREAM_SEEK_END).
/// The new position is returned at address refToNewOffsetNullAllowed unless this param is set to null.
/// </summary>
void Seek(long offset, int origin, IntPtr refToNewOffsetNullAllowed);
/// <summary>
/// Set the stream size.
/// </summary>
void SetSize(long newSize);
/// <summary>
/// Copy bytesToCopy bytes from the current position into targetStream.
/// </summary>
void CopyTo(
MS.Internal.Interop.IStream targetStream,
long bytesToCopy,
IntPtr refToNumBytesRead,
IntPtr refToNumBytesWritten);
/// <summary>
/// Flush or, in transacted mode, commit. The commitFlags parameter is a member of the STGC enumeration.
/// The most commonly used value is STGC_DEFAULT, i.e. 0.
/// </summary>
void Commit(int commitFlags);
/// <summary>
/// Discards all changes that have been made to a transacted stream since the last call to IStream::Commit.
/// </summary>
void Revert();
/// <summary>
/// Restricts access to a specified range of bytes in the stream.
/// Supporting this functionality is optional since some file systems do not provide it.
/// </summary>
void LockRegion(long offset, long sizeInBytes, int lockType);
/// <summary>
/// Removes the access restriction on a range of bytes previously restricted with IStream::LockRegion.
/// </summary>
void UnlockRegion(long offset, long sizeInBytes, int lockType);
/// <summary>
/// Retrieves the STATSTG structure for this stream.
/// </summary>
void Stat(out System.Runtime.InteropServices.ComTypes.STATSTG statStructure, int statFlag);
/// <summary>
/// Creates a new stream object that references the same bytes as the original stream but provides a separate
/// seek pointer to those bytes.
/// </summary>
void Clone(out MS.Internal.Interop.IStream newStream);
}
#endregion IStream
#region IPersistStreamWithArrays Interface
/// <summary>
/// Managed definition of IPersistStream.
/// </summary>
/// <remarks>
/// This particular version uses the standard managed definition of IStream,
/// which marshals arrays rather than buffer pointers. It is destined to be used
/// with the class ManagedIStream, which implements IStream in managed code.
///
/// The declaration order strictly follows that in objidl.h, otherwise
/// the vtbl would not be correctly accessed when invoking a COM object!
/// </remarks>
[ComImport, ComVisible(true)]
[Guid("00000109-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IPersistStreamWithArrays
{
/// <summary>
/// Retrieves the ClassID of this object. It returns
/// S_OK if successful, E_FAIL if not.
///
/// original interface:
/// HRESULT GetClassID(CLSID * pClassID);
///
/// </summary>
/// <remarks>
/// Strictly speaking, this method is inherited from IPersist, but since
/// IPersist is the only super-interface of IPersistStreamWithArrays, all we care about
/// is for its method to be declared first (since we do not need IPersist per se).
/// </remarks>
void GetClassID(out Guid pClassID);
/// <summary>
/// Determines if the object has changed since the last
/// save. S_OK means the file is clean. S_FALSE the file
/// has changed.
///
/// original interface:
/// HRESULT IsDirty(void);
///
/// </summary>
[PreserveSig()]
int IsDirty();
/// <summary>
/// Points the component to the specified stream.
/// </summary>
/// <remarks>
/// Uses the standard array-based definition of IStream.
/// </remarks>
void Load(System.Runtime.InteropServices.ComTypes.IStream pstm);
/// <summary>
/// This is used when saving an object to a stream.
/// </summary>
/// <remarks>
/// In the case of an indexing filter, this function is not supported.
/// </remarks>
void Save(System.Runtime.InteropServices.ComTypes.IStream pstm, [MarshalAs(UnmanagedType.Bool)] bool fRemember);
/// <summary>
/// Return the size in bytes of the stream needed to save the object.
/// </summary>
/// <param name="pcbSize">Points to a 64-bit unsigned integer value indicating the size in bytes of the stream needed to save this object.</param>
/// <remarks>
/// This is meaningful only when the interface is implemented in such a way
/// as to define a persistent object that is backed against the stream.
/// </remarks>
void GetSizeMax([Out] out Int64 pcbSize);
}
#endregion IPersistStreamWithArrays Interface
#region IPersistFile Interface
/// <summary>
/// Managed definition of IPersistFile.
/// </summary>
/// <remarks>
/// The System.Runtime.InteropServices.ComTypes namespace provides a standard definition for
/// this interface, but it is redefined here to allow IPersistFile.GetCurFile() to have
/// two successful return values S_OK and S_FALSE. In order to return S_FALSE and still
/// keep the output parameter ppszFileName valid, we cannot return by throwing COMExceptions.
/// Instead, IPersistFile.GetCurFile() needs to be marked [PreserveSig] and explicitly
/// return S_OK or S_FALSE.
/// </remarks>
[ComImport, ComVisible(true)]
[Guid("0000010b-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IPersistFile
{
/// <summary>
/// Retrieves the class identifier (CLSID) of an object.
/// </summary>
/// <param name="pClassID">When this method returns, contains a reference to the CLSID.
/// This parameter is passed uninitialized.
/// </param>
void GetClassID(out Guid pClassID);
/// <summary>
/// Checks an object for changes since it was last saved to its current file.
/// </summary>
/// <returns>
/// S_OK if the file has changed since it was last saved; S_FALSE if the file
/// has not changed since it was last saved.
/// </returns>
[PreserveSig]
int IsDirty();
/// <summary>
/// Opens the specified file and initializes an object from the file contents.
/// </summary>
/// <param name="pszFileName">A zero-terminated string containing the absolute path of the file to open.</param>
/// <param name="dwMode">
/// A combination of values from the STGM enumeration to indicate the access
/// mode in which to open pszFileName.
/// </param>
void Load([MarshalAs(UnmanagedType.LPWStr)] string pszFileName, int dwMode);
/// <summary>
/// Saves a copy of the object into the specified file.
/// </summary>
/// <param name="pszFileName">
/// A zero-terminated string containing the absolute path of the file to which
/// the object is saved.
/// </param>
/// <param name="fRemember">
/// true to used the pszFileName parameter as the current working file; otherwise false.
/// </param>
void Save([MarshalAs(UnmanagedType.LPWStr)] string pszFileName,
[MarshalAs(UnmanagedType.Bool)] bool fRemember);
/// <summary>
/// Notifies the object that it can write to its file.
/// </summary>
/// <param name="pszFileName">The absolute path of the file where the object was previously saved.</param>
void SaveCompleted([MarshalAs(UnmanagedType.LPWStr)] string pszFileName);
/// <summary>
/// Retrieves either the absolute path to the current working file of the object
/// or, if there is no current working file, the default file name prompt of
/// the object.
/// </summary>
/// <param name="ppszFileName">
/// When this method returns, contains the address of a pointer to a zero-terminated
/// string containing the path for the current file, or the default file name
/// prompt (such as *.txt). This parameter is passed uninitialized.
/// </param>
[PreserveSig]
int GetCurFile([MarshalAs(UnmanagedType.LPWStr)] out string ppszFileName);
}
#endregion IPersistFile Interface
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class CamelCasePropertyNamesContractResolverTests : TestFixtureBase
{
[Test]
public void JsonConvertSerializerSettings()
{
Person person = new Person();
person.BirthDate = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.LastModified = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.Name = "Name!";
string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""name"": ""Name!"",
""birthDate"": ""2000-11-20T23:55:44Z"",
""lastModified"": ""2000-11-20T23:55:44Z""
}", json);
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(person.BirthDate, deserializedPerson.BirthDate);
Assert.AreEqual(person.LastModified, deserializedPerson.LastModified);
Assert.AreEqual(person.Name, deserializedPerson.Name);
json = JsonConvert.SerializeObject(person, Formatting.Indented);
StringAssert.AreEqual(@"{
""Name"": ""Name!"",
""BirthDate"": ""2000-11-20T23:55:44Z"",
""LastModified"": ""2000-11-20T23:55:44Z""
}", json);
}
[Test]
public void JTokenWriter()
{
JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
ignoreAttributeOnClassTestClass.Field = int.MinValue;
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
JTokenWriter writer = new JTokenWriter();
serializer.Serialize(writer, ignoreAttributeOnClassTestClass);
JObject o = (JObject)writer.Token;
JProperty p = o.Property("theField");
Assert.IsNotNull(p);
Assert.AreEqual(int.MinValue, (int)p.Value);
string json = o.ToString();
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
#pragma warning disable 618
[Test]
public void MemberSearchFlags()
{
PrivateMembersClass privateMembersClass = new PrivateMembersClass("PrivateString!", "InternalString!");
string json = JsonConvert.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
StringAssert.AreEqual(@"{
""_privateString"": ""PrivateString!"",
""i"": 0,
""_internalString"": ""InternalString!""
}", json);
PrivateMembersClass deserializedPrivateMembersClass = JsonConvert.DeserializeObject<PrivateMembersClass>(@"{
""_privateString"": ""Private!"",
""i"": -2,
""_internalString"": ""Internal!""
}", new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual("Private!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_privateString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
Assert.AreEqual("Internal!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_internalString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
// readonly
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
}
#pragma warning restore 618
#endif
[Test]
public void BlogPostExample()
{
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json =
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
//{
// "name": "Widget",
// "expiryDate": "\/Date(1292868060000)\/",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
StringAssert.AreEqual(@"{
""name"": ""Widget"",
""expiryDate"": ""2010-12-20T18:01:00Z"",
""price"": 9.99,
""sizes"": [
""Small"",
""Medium"",
""Large""
]
}", json);
}
#if !(NET35 || NET20 || PORTABLE40)
[Test]
public void DynamicCamelCasePropertyNames()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
string json = JsonConvert.SerializeObject(o, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""explicit"": false,
""text"": ""Text!"",
""integer"": 2147483647,
""int"": 0,
""childObject"": null
}", json);
}
#endif
[Test]
public void DictionaryCamelCasePropertyNames()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "First", "Value1!" },
{ "Second", "Value2!" }
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""first"": ""Value1!"",
""second"": ""Value2!""
}", json);
}
}
}
| |
//
// HttpClient.cs
//
// Authors:
// Marek Safar <[email protected]>
//
// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.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.Threading;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.IO;
using HttpClientLibrary;
namespace System.Net.Http
{
public class HttpClient : HttpMessageInvoker
{
static readonly TimeSpan TimeoutDefault = TimeSpan.FromSeconds(100);
Uri base_address;
CancellationTokenSource cts;
bool disposed;
HttpRequestHeaders headers;
long buffer_size;
TimeSpan timeout;
public HttpClient()
: this(new HttpClientHandler(), true)
{
}
public HttpClient(HttpMessageHandler handler)
: this(handler, true)
{
}
public HttpClient(HttpMessageHandler handler, bool disposeHandler)
: base(handler, disposeHandler)
{
buffer_size = int.MaxValue;
timeout = TimeoutDefault;
cts = new CancellationTokenSource();
}
public Uri BaseAddress
{
get
{
return base_address;
}
set
{
base_address = value;
}
}
public HttpRequestHeaders DefaultRequestHeaders
{
get
{
return headers ?? (headers = new HttpRequestHeaders());
}
}
public long MaxResponseContentBufferSize
{
get
{
return buffer_size;
}
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException();
buffer_size = value;
}
}
public TimeSpan Timeout
{
get
{
return timeout;
}
set
{
if (value != TimeSpan.FromMilliseconds(System.Threading.Timeout.Infinite) && value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException();
timeout = value;
}
}
public void CancelPendingRequests()
{
// Cancel only any already running requests not any new request after this cancellation
// NOTE: can't call dispose due to a bug in the .NET 3.5 implementation of CancellationTokenRegistration.Dispose
var c = Interlocked.Exchange(ref cts, new CancellationTokenSource());
c.Cancel();
}
protected override void Dispose(bool disposing)
{
if (disposing && !disposed)
{
disposed = true;
cts.Dispose();
}
base.Dispose(disposing);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri));
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri));
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(string requestUri)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri));
}
public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri));
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content });
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content }, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content });
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content }, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Put, requestUri) { Content = content });
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Put, requestUri) { Content = content }, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Put, requestUri) { Content = content });
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Put, requestUri) { Content = content }, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
{
return SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
{
return SendAsync(request, completionOption, CancellationToken.None);
}
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
if (request == null)
throw new ArgumentNullException("request");
if (request.SetIsUsed())
throw new InvalidOperationException("Cannot send the same request message multiple times");
if (request.RequestUri == null)
{
if (base_address == null)
throw new InvalidOperationException("The request URI must either be an absolute URI or BaseAddress must be set");
request.RequestUri = base_address;
}
else if (!request.RequestUri.IsAbsoluteUri)
{
if (base_address == null)
throw new InvalidOperationException("The request URI must either be an absolute URI or BaseAddress must be set");
request.RequestUri = new Uri(base_address, request.RequestUri);
}
if (headers != null)
{
request.Headers.AddHeaders(headers);
}
return SendAsyncWorker(request, completionOption, cancellationToken);
}
Task<HttpResponseMessage> SendAsyncWorker(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
{
var currentSource = this.cts;
Func<Task<CancellationTokenSource>> acquireResource = () => CompletedTask.FromResult(CancellationTokenSource.CreateLinkedTokenSource(currentSource.Token, cancellationToken));
Func<Task<CancellationTokenSource>, Task<HttpResponseMessage>> body =
resourceTask =>
{
var lcts = resourceTask.Result;
lcts.CancelAfter(timeout);
var task = base.SendAsync(request, lcts.Token);
if (task == null)
throw new InvalidOperationException("Handler failed to return a value");
return task.Then(
responseTask =>
{
var response = responseTask.Result;
if (response == null)
throw new InvalidOperationException("Handler failed to return a response");
//
// Read the content when default HttpCompletionOption.ResponseContentRead is set
//
if (response.Content != null && (completionOption & HttpCompletionOption.ResponseHeadersRead) == 0)
{
return response.Content.LoadIntoBufferAsync(MaxResponseContentBufferSize)
.Select(_ => response);
}
return CompletedTask.FromResult(response);
})
.Finally(_ => GC.KeepAlive(currentSource));
};
return TaskBlocks.Using(acquireResource, body);
}
public Task<byte[]> GetByteArrayAsync(string requestUri)
{
Func<Task<HttpResponseMessage>> resource = () => GetAsync(requestUri, HttpCompletionOption.ResponseContentRead);
Func<Task<HttpResponseMessage>, Task<byte[]>> body =
respTask =>
{
var resp = respTask.Result;
resp.EnsureSuccessStatusCode();
return resp.Content.ReadAsByteArrayAsync();
};
return TaskBlocks.Using(resource, body);
}
public Task<byte[]> GetByteArrayAsync(Uri requestUri)
{
Func<Task<HttpResponseMessage>> resource = () => GetAsync(requestUri, HttpCompletionOption.ResponseContentRead);
Func<Task<HttpResponseMessage>, Task<byte[]>> body =
respTask =>
{
var resp = respTask.Result;
resp.EnsureSuccessStatusCode();
return resp.Content.ReadAsByteArrayAsync();
};
return TaskBlocks.Using(resource, body);
}
public Task<Stream> GetStreamAsync(string requestUri)
{
return GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).Then(
respTask =>
{
var resp = respTask.Result;
resp.EnsureSuccessStatusCode();
return resp.Content.ReadAsStreamAsync();
});
}
public Task<Stream> GetStreamAsync(Uri requestUri)
{
return GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).Then(
respTask =>
{
var resp = respTask.Result;
resp.EnsureSuccessStatusCode();
return resp.Content.ReadAsStreamAsync();
});
}
public Task<string> GetStringAsync(string requestUri)
{
Func<Task<HttpResponseMessage>> resource = () => GetAsync(requestUri, HttpCompletionOption.ResponseContentRead);
Func<Task<HttpResponseMessage>, Task<string>> body =
respTask =>
{
var resp = respTask.Result;
resp.EnsureSuccessStatusCode();
return resp.Content.ReadAsStringAsync();
};
return TaskBlocks.Using(resource, body);
}
public Task<string> GetStringAsync(Uri requestUri)
{
Func<Task<HttpResponseMessage>> resource = () => GetAsync(requestUri, HttpCompletionOption.ResponseContentRead);
Func<Task<HttpResponseMessage>, Task<string>> body =
respTask =>
{
var resp = respTask.Result;
resp.EnsureSuccessStatusCode();
return resp.Content.ReadAsStringAsync();
};
return TaskBlocks.Using(resource, body);
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria.ID;
namespace Terraria.ModLoader
{
/// <summary>
/// This serves as the central class from which buff-related functions are supported and carried out.
/// </summary>
public static class BuffLoader
{
private static int nextBuff = BuffID.Count;
internal static readonly IList<ModBuff> buffs = new List<ModBuff>();
internal static readonly IList<GlobalBuff> globalBuffs = new List<GlobalBuff>();
private static readonly bool[] vanillaLongerExpertDebuff = new bool[BuffID.Count];
private static readonly bool[] vanillaCanBeCleared = new bool[BuffID.Count];
private delegate void DelegateUpdatePlayer(int type, Player player, ref int buffIndex);
private static DelegateUpdatePlayer[] HookUpdatePlayer;
private delegate void DelegateUpdateNPC(int type, NPC npc, ref int buffIndex);
private static DelegateUpdateNPC[] HookUpdateNPC;
private static Func<int, Player, int, int, bool>[] HookReApplyPlayer;
private static Func<int, NPC, int, int, bool>[] HookReApplyNPC;
private delegate void DelegateModifyBuffTip(int type, ref string tip, ref int rare);
private static DelegateModifyBuffTip[] HookModifyBuffTip;
private static Action<string, List<Vector2>>[] HookCustomBuffTipSize;
private static Action<string, SpriteBatch, int, int>[] HookDrawCustomBuffTip;
static BuffLoader()
{
for (int k = 0; k < BuffID.Count; k++)
{
vanillaCanBeCleared[k] = true;
}
vanillaLongerExpertDebuff[BuffID.Poisoned] = true;
vanillaLongerExpertDebuff[BuffID.Darkness] = true;
vanillaLongerExpertDebuff[BuffID.Cursed] = true;
vanillaLongerExpertDebuff[BuffID.OnFire] = true;
vanillaLongerExpertDebuff[BuffID.Bleeding] = true;
vanillaLongerExpertDebuff[BuffID.Confused] = true;
vanillaLongerExpertDebuff[BuffID.Slow] = true;
vanillaLongerExpertDebuff[BuffID.Weak] = true;
vanillaLongerExpertDebuff[BuffID.Silenced] = true;
vanillaLongerExpertDebuff[BuffID.BrokenArmor] = true;
vanillaLongerExpertDebuff[BuffID.CursedInferno] = true;
vanillaLongerExpertDebuff[BuffID.Frostburn] = true;
vanillaLongerExpertDebuff[BuffID.Chilled] = true;
vanillaLongerExpertDebuff[BuffID.Frozen] = true;
vanillaLongerExpertDebuff[BuffID.Ichor] = true;
vanillaLongerExpertDebuff[BuffID.Venom] = true;
vanillaLongerExpertDebuff[BuffID.Blackout] = true;
vanillaCanBeCleared[BuffID.PotionSickness] = false;
vanillaCanBeCleared[BuffID.Werewolf] = false;
vanillaCanBeCleared[BuffID.Merfolk] = false;
vanillaCanBeCleared[BuffID.WaterCandle] = false;
vanillaCanBeCleared[BuffID.Campfire] = false;
vanillaCanBeCleared[BuffID.HeartLamp] = false;
vanillaCanBeCleared[BuffID.NoBuilding] = false;
}
internal static int ReserveBuffID()
{
if (ModNet.AllowVanillaClients) throw new Exception("Adding buffs breaks vanilla client compatiblity");
int reserveID = nextBuff;
nextBuff++;
return reserveID;
}
internal static int BuffCount => nextBuff;
/// <summary>
/// Gets the ModBuff instance with the given type. If no ModBuff with the given type exists, returns null.
/// </summary>
public static ModBuff GetBuff(int type)
{
return type >= BuffID.Count && type < BuffCount ? buffs[type - BuffID.Count] : null;
}
internal static void ResizeArrays()
{
Array.Resize(ref Main.pvpBuff, nextBuff);
Array.Resize(ref Main.persistentBuff, nextBuff);
Array.Resize(ref Main.vanityPet, nextBuff);
Array.Resize(ref Main.lightPet, nextBuff);
Array.Resize(ref Main.meleeBuff, nextBuff);
Array.Resize(ref Main.debuff, nextBuff);
Array.Resize(ref Main.buffName, nextBuff);
Array.Resize(ref Main.buffTip, nextBuff);
Array.Resize(ref Main.buffNoSave, nextBuff);
Array.Resize(ref Main.buffNoTimeDisplay, nextBuff);
Array.Resize(ref Main.buffDoubleApply, nextBuff);
Array.Resize(ref Main.buffAlpha, nextBuff);
Array.Resize(ref Main.buffTexture, nextBuff);
ModLoader.BuildGlobalHook(ref HookUpdatePlayer, globalBuffs, g => g.Update);
ModLoader.BuildGlobalHook(ref HookUpdateNPC, globalBuffs, g => g.Update);
ModLoader.BuildGlobalHook(ref HookReApplyPlayer, globalBuffs, g => g.ReApply);
ModLoader.BuildGlobalHook(ref HookReApplyNPC, globalBuffs, g => g.ReApply);
ModLoader.BuildGlobalHook(ref HookModifyBuffTip, globalBuffs, g => g.ModifyBuffTip);
ModLoader.BuildGlobalHook(ref HookCustomBuffTipSize, globalBuffs, g => g.CustomBuffTipSize);
ModLoader.BuildGlobalHook(ref HookDrawCustomBuffTip, globalBuffs, g => g.DrawCustomBuffTip);
}
internal static void Unload()
{
buffs.Clear();
nextBuff = BuffID.Count;
globalBuffs.Clear();
}
internal static bool IsModBuff(int type)
{
return type >= BuffID.Count;
}
//in Terraria.Player.UpdateBuffs at end of if else chain add BuffLoader.Update(this.buffType[k], this, ref k);
public static void Update(int buff, Player player, ref int buffIndex)
{
int originalIndex = buffIndex;
if (IsModBuff(buff))
{
GetBuff(buff).Update(player, ref buffIndex);
}
foreach (var hook in HookUpdatePlayer)
{
if (buffIndex != originalIndex)
{
break;
}
hook(buff, player, ref buffIndex);
}
}
public static void Update(int buff, NPC npc, ref int buffIndex)
{
if (IsModBuff(buff))
{
GetBuff(buff).Update(npc, ref buffIndex);
}
foreach (var hook in HookUpdateNPC)
{
hook(buff, npc, ref buffIndex);
}
}
public static bool ReApply(int buff, Player player, int time, int buffIndex)
{
foreach (var hook in HookReApplyPlayer)
{
if (hook(buff, player, time, buffIndex))
{
return true;
}
}
if (IsModBuff(buff))
{
return GetBuff(buff).ReApply(player, time, buffIndex);
}
return false;
}
public static bool ReApply(int buff, NPC npc, int time, int buffIndex)
{
foreach (var hook in HookReApplyNPC)
{
if (hook(buff, npc, time, buffIndex))
{
return true;
}
}
if (IsModBuff(buff))
{
return GetBuff(buff).ReApply(npc, time, buffIndex);
}
return false;
}
public static bool LongerExpertDebuff(int buff)
{
return GetBuff(buff)?.longerExpertDebuff ?? vanillaLongerExpertDebuff[buff];
}
public static bool CanBeCleared(int buff)
{
return GetBuff(buff)?.canBeCleared ?? vanillaCanBeCleared[buff];
}
public static void ModifyBuffTip(int buff, ref string tip, ref int rare)
{
if (IsModBuff(buff))
{
GetBuff(buff).ModifyBuffTip(ref tip, ref rare);
}
foreach (var hook in HookModifyBuffTip)
{
hook(buff, ref tip, ref rare);
}
}
public static void CustomBuffTipSize(string buffTip, List<Vector2> sizes)
{
foreach (var hook in HookCustomBuffTipSize)
{
hook(buffTip, sizes);
}
}
public static void DrawCustomBuffTip(string buffTip, SpriteBatch spriteBatch, int originX, int originY)
{
foreach (var hook in HookDrawCustomBuffTip)
{
hook(buffTip, spriteBatch, originX, originY);
}
}
}
}
| |
// 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;
/// <summary>
/// Compare(System.DateTime,System.DateTime)
/// </summary>
public class DateTimeCompare
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Compare a datetime instance with itself");
try
{
DateTime t1 = new DateTime(2006, 9, 21, 10, 54, 56, 888);
if (DateTime.Compare(t1, t1) != 0)
{
TestLibrary.TestFramework.LogError("001.1", "Compare a datetime instance with itself does not return 0");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Compare a datetime instance with a datetime instance less than it");
try
{
DateTime t1 = new DateTime(2006, 9, 21, 10, 54, 56, 888);
DateTime t2 = new DateTime(2006, 9, 21, 10, 54, 56, 887);
if (DateTime.Compare(t1, t2) <= 0)
{
TestLibrary.TestFramework.LogError("002.1", "Compare a datetime instance with a datetime instance less than it does not greater than 0");
retVal = false;
}
t2 = new DateTime(2006, 9, 21, 10, 54, 55, 888);
if (DateTime.Compare(t1, t2) <= 0)
{
TestLibrary.TestFramework.LogError("002.2", "Compare a datetime instance with a datetime instance less than it does not greater than 0");
retVal = false;
}
t2 = new DateTime(2006, 9, 21, 10, 53, 56, 888);
if (DateTime.Compare(t1, t2) <= 0)
{
TestLibrary.TestFramework.LogError("002.3", "Compare a datetime instance with a datetime instance less than it does not greater than 0");
retVal = false;
}
t2 = new DateTime(2006, 9, 21, 9, 54, 56, 888);
if (DateTime.Compare(t1, t2) <= 0)
{
TestLibrary.TestFramework.LogError("002.4", "Compare a datetime instance with a datetime instance less than it does not greater than 0");
retVal = false;
}
t2 = new DateTime(2006, 9, 20, 10, 54, 56, 888);
if (DateTime.Compare(t1, t2) <= 0)
{
TestLibrary.TestFramework.LogError("002.5", "Compare a datetime instance with a datetime instance less than it does not greater than 0");
retVal = false;
}
t2 = new DateTime(2006, 8, 21, 10, 54, 56, 888);
if (DateTime.Compare(t1, t2) <= 0)
{
TestLibrary.TestFramework.LogError("002.6", "Compare a datetime instance with a datetime instance less than it does not greater than 0");
retVal = false;
}
t2 = new DateTime(2005, 9, 21, 10, 54, 56, 888);
if (DateTime.Compare(t1, t2) <= 0)
{
TestLibrary.TestFramework.LogError("002.7", "Compare a datetime instance with a datetime instance less than it does not greater than 0");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Compare a datetime instance equal to it");
try
{
DateTime t1 = new DateTime(2006, 9, 21, 10, 54, 56, 888);
DateTime t2 = new DateTime(2006, 9, 21, 10, 54, 56, 888);
if (DateTime.Compare(t1, t2) != 0)
{
TestLibrary.TestFramework.LogError("003.1", "Compare a datetime instance equal to it does not return 0");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Compare a datetime instance with a datetime instance greater than it");
try
{
DateTime t1 = new DateTime(2006, 9, 21, 10, 54, 56, 888);
DateTime t2 = new DateTime(2006, 9, 21, 10, 54, 56, 889);
if (DateTime.Compare(t1, t2) >= 0)
{
TestLibrary.TestFramework.LogError("004.1", "Compare a datetime instance with a datetime instance greater than it does not less than 0");
retVal = false;
}
t2 = new DateTime(2006, 9, 21, 10, 54, 57, 888);
if (DateTime.Compare(t1, t2) >= 0)
{
TestLibrary.TestFramework.LogError("004.1", "Compare a datetime instance with a datetime instance greater than it does not less than 0");
retVal = false;
}
t2 = new DateTime(2006, 9, 21, 10, 55, 56, 888);
if (DateTime.Compare(t1, t2) >= 0)
{
TestLibrary.TestFramework.LogError("004.1", "Compare a datetime instance with a datetime instance greater than it does not less than 0");
retVal = false;
}
t2 = new DateTime(2006, 9, 21, 11, 54, 56, 888);
if (DateTime.Compare(t1, t2) >= 0)
{
TestLibrary.TestFramework.LogError("004.1", "Compare a datetime instance with a datetime instance greater than it does not less than 0");
retVal = false;
}
t2 = new DateTime(2006, 9, 22, 10, 54, 56, 888);
if (DateTime.Compare(t1, t2) >= 0)
{
TestLibrary.TestFramework.LogError("004.1", "Compare a datetime instance with a datetime instance greater than it does not less than 0");
retVal = false;
}
t2 = new DateTime(2006, 10, 21, 10, 54, 56, 888);
if (DateTime.Compare(t1, t2) >= 0)
{
TestLibrary.TestFramework.LogError("004.1", "Compare a datetime instance with a datetime instance greater than it does not less than 0");
retVal = false;
}
t2 = new DateTime(2007, 9, 21, 10, 54, 56, 888);
if (DateTime.Compare(t1, t2) >= 0)
{
TestLibrary.TestFramework.LogError("004.1", "Compare a datetime instance with a datetime instance greater than it does not less than 0");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
DateTimeCompare test = new DateTimeCompare();
TestLibrary.TestFramework.BeginTestCase("DateTimeCompare");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Printing;
using System.Linq;
using bv.model.BLToolkit;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
using eidss.model.Reports;
using eidss.model.Reports.AZ;
using eidss.model.Reports.Common;
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.Parameterized.Human.AJ.DataSets;
namespace EIDSS.Reports.Parameterized.Human.AJ.Reports
{
[CanWorkWithArchive]
[NullableAdapters]
public sealed partial class VetLabReport : BaseReport
{
private const string TestNamePrefix = "strTestName_";
private const string TestCountPrefix = "intTest_";
private const string TempPrefix = "TEMP_";
private bool m_IsFirstRow = true;
private bool m_IsPrintGroup = true;
private int m_DiagnosisCounter;
public VetLabReport()
{
InitializeComponent();
}
public void SetParameters(VetLabSurrogateModel model, DbManagerProxy manager, DbManagerProxy archiveManager)
{
SetLanguage(model, manager);
DateCell.Text = ReportRebinder.ToDateTimeString(DateTime.Now);
ForDateCell.Text = model.Header;
string location = AddressModel.GetLocation(model.Language,
m_BaseDataSet.sprepGetBaseParameters[0].CountryName,
model.RegionId, model.RegionName,
model.RayonId, model.RayonName);
if (string.IsNullOrEmpty(model.OrganizationEnteredByName))
{
SentByCell.Text = location;
}
else
{
SentByCell.Text = model.RegionId.HasValue
? string.Format("{0} ({1})", model.OrganizationEnteredByName, location)
: model.OrganizationEnteredByName;
}
m_DiagnosisCounter = 1;
Action<SqlConnection, SqlTransaction> action = ((connection, transaction) =>
{
m_DataAdapter.Connection = connection;
m_DataAdapter.Transaction = transaction;
m_DataAdapter.CommandTimeout = CommandTimeout;
m_DataSet.EnforceConstraints = false;
m_DataAdapter.Fill(m_DataSet.spRepVetLabReportAZ, model.Language,
model.StartDate.ToString("s"), model.EndDate.ToString("s"),
model.RegionId, model.RayonId, model.OrganizationEnteredById, model.UserId);
});
FillDataTableWithArchive(action, BeforeMergeWithArchive,
manager, archiveManager,
m_DataSet.spRepVetLabReportAZ,
model.Mode,
new[] {"strDiagnosisSpeciesKey", "strOIECode"},
new string[0]);
m_DataSet.spRepVetLabReportAZ.DefaultView.Sort = "DiagniosisOrder, strDiagnosisName, SpeciesOrder, strSpecies";
IEnumerable<DataColumn> columns = m_DataSet.spRepVetLabReportAZ.Columns.Cast<DataColumn>();
int testCount = columns.Count(c => c.ColumnName.Contains(TestCountPrefix));
AddCells(testCount - 1);
if (m_DataSet.spRepVetLabReportAZ.FirstOrDefault(r => r.idfsDiagnosis < 0) == null)
{
RowNumberCell.Text = 1.ToString();
}
}
private void BeforeMergeWithArchive(DataTable sourceData, DataTable archiveData)
{
RemoveTestColumnsIfEmpty(sourceData);
RemoveTestColumnsIfEmpty(archiveData);
List<string> sourceCaptions = ReportArchiveHelper.GetCaptionsAndAssignToColumns(sourceData, TestNamePrefix);
List<string> archiveCaptions = ReportArchiveHelper.GetCaptionsAndAssignToColumns(archiveData, TestNamePrefix);
MergeCaptions(sourceCaptions, archiveCaptions);
AddMissingColumns(sourceData, sourceCaptions);
AddMissingColumns(archiveData, sourceCaptions);
RemoveEmptyRowsIfRealDataExists(archiveData, sourceData);
}
internal static void RemoveTestColumnsIfEmpty(DataTable data)
{
if (data.Rows.Count == 0)
{
List<DataColumn> testColumns = data.Columns
.Cast<DataColumn>()
.Where(c => c.ColumnName.Contains(TestNamePrefix) || c.ColumnName.Contains(TestCountPrefix))
.ToList();
foreach (DataColumn column in testColumns)
{
data.Columns.Remove(column);
}
}
}
private static void MergeCaptions(List<string> sourceCaptions, IEnumerable<string> archiveCaptions)
{
foreach (string caption in archiveCaptions)
{
if (!sourceCaptions.Contains(caption))
{
sourceCaptions.Add(caption);
}
}
sourceCaptions.Sort();
}
internal static void AddMissingColumns(DataTable data, List<string> sourceCaptions)
{
var columnList = new List<DataColumn>();
for (int i = 0; i < sourceCaptions.Count; i++)
{
string caption = sourceCaptions[i];
DataColumn testNameColumn = data.Columns
.Cast<DataColumn>()
.FirstOrDefault(c => c.Caption == caption);
string tempTestColumnName = TempPrefix + TestNamePrefix + (i + 1);
string tempCountColumnName = TempPrefix + TestCountPrefix + (i + 1);
DataColumn testCountColumn;
if (testNameColumn != null)
{
string oldCountColumnName = testNameColumn.ColumnName.Replace(TestNamePrefix, TestCountPrefix);
testCountColumn = data.Columns[oldCountColumnName];
testNameColumn.ColumnName = tempTestColumnName;
testCountColumn.ColumnName = tempCountColumnName;
}
else
{
testNameColumn = data.Columns.Add(tempTestColumnName, typeof (String));
testNameColumn.Caption = caption;
testCountColumn = data.Columns.Add(tempCountColumnName, typeof (Int32));
foreach (DataRow row in data.Rows)
{
row[testNameColumn] = caption;
}
}
columnList.Add(testNameColumn);
columnList.Add(testCountColumn);
}
for (int i = columnList.Count - 1; i >= 0; i--)
{
DataColumn column = columnList[i];
column.ColumnName = column.ColumnName.Replace(TempPrefix, string.Empty);
column.SetOrdinal(data.Columns.Count - columnList.Count + i);
}
}
private void RemoveEmptyRowsIfRealDataExists(DataTable archiveData, DataTable sourceData)
{
VetLabReportDataSet.spRepVetLabReportAZRow archiveRow =
archiveData.Rows.Cast<VetLabReportDataSet.spRepVetLabReportAZRow>().FirstOrDefault(r => r.strDiagnosisSpeciesKey == "1_1");
VetLabReportDataSet.spRepVetLabReportAZRow sourceRow =
sourceData.Rows.Cast<VetLabReportDataSet.spRepVetLabReportAZRow>().FirstOrDefault(r => r.strDiagnosisSpeciesKey == "1_1");
if (archiveRow == null && sourceRow != null)
{
sourceData.Rows.Remove(sourceRow);
}
if (archiveRow != null && sourceRow == null)
{
archiveData.Rows.Remove(archiveRow);
}
}
private void AddCells(int testCount)
{
if (testCount <= 0)
{
return;
}
try
{
((ISupportInitialize) (DetailsDataTable)).BeginInit();
((ISupportInitialize) (HeaderDataTable)).BeginInit();
((ISupportInitialize) (FooterDataTable)).BeginInit();
var resources = new ComponentResourceManager(typeof (VetLabReport));
float cellWidth = TestCountCell_1.WidthF * (float) Math.Pow(14.0 / 15, testCount - 1) / 2;
TestCountCell_1.WidthF = cellWidth;
TestCountCell_1.DataBindings.Clear();
TestCountCell_1.DataBindings.Add(CreateTestCountBinding(testCount + 1));
TestCountTotalCell_1.WidthF = cellWidth;
TestCountTotalCell_1.DataBindings.Clear();
TestCountTotalCell_1.DataBindings.Add(CreateTestCountBinding(testCount + 1));
TestCountTotalCell_1.Summary.Running = SummaryRunning.Report;
TestNameHeaderCell_1.WidthF = cellWidth;
TestNameHeaderCell_1.DataBindings.Clear();
TestNameHeaderCell_1.DataBindings.Add(CreateTestNameBinding(testCount + 1));
TestsConductedHeaderCell.WidthF = cellWidth * (testCount + 1);
for (int i = 0; i < testCount; i++)
{
int columnIndex = i + 1;
var testCountCell = new XRTableCell();
DetailsDataRow.InsertCell(testCountCell, DetailsDataRow.Cells.Count - 2);
resources.ApplyResources(testCountCell, TestCountCell_1.Name);
testCountCell.WidthF = cellWidth;
testCountCell.DataBindings.Add(CreateTestCountBinding(columnIndex));
var testCountTotalCell = new XRTableCell();
FooterDataRow.InsertCell(testCountTotalCell, FooterDataRow.Cells.Count - 2);
// testCountTotalCell.Text = columnIndex.ToString();
resources.ApplyResources(testCountTotalCell, TestCountTotalCell_1.Name);
testCountTotalCell.WidthF = cellWidth;
testCountTotalCell.DataBindings.Add(CreateTestCountBinding(columnIndex));
testCountTotalCell.Summary.Running = SummaryRunning.Report;
var testNameCell = new XRTableCell();
HeaderDataRow2.InsertCell(testNameCell, HeaderDataRow2.Cells.Count - 2);
resources.ApplyResources(testNameCell, TestCountCell_1.Name);
testNameCell.WidthF = cellWidth;
testNameCell.Angle = 90;
testNameCell.DataBindings.Add(CreateTestNameBinding(columnIndex));
}
}
finally
{
((ISupportInitialize) (FooterDataTable)).EndInit();
((ISupportInitialize) (HeaderDataTable)).EndInit();
((ISupportInitialize) (DetailsDataTable)).EndInit();
}
}
private static XRBinding CreateTestCountBinding(int columnIndex)
{
return new XRBinding("Text", null, "spRepVetLabReportAZ." + TestCountPrefix + columnIndex);
}
private static XRBinding CreateTestNameBinding(int columnIndex)
{
return new XRBinding("Text", null, "spRepVetLabReportAZ." + TestNamePrefix + columnIndex);
}
private void GroupFooterDiagnosis_BeforePrint(object sender, PrintEventArgs e)
{
m_IsPrintGroup = true;
m_DiagnosisCounter++;
RowNumberCell.Text = m_DiagnosisCounter.ToString();
}
private void RowNumberCell_BeforePrint(object sender, PrintEventArgs e)
{
AjustGroupBorders(RowNumberCell, m_IsPrintGroup);
AjustGroupBorders(DiseaseCell, m_IsPrintGroup);
AjustGroupBorders(OIECell, m_IsPrintGroup);
m_IsPrintGroup = false;
AjustNonGroupBorders(SpeciesCell);
}
private void AjustNonGroupBorders(XRTableCell firstNonGroupCell)
{
if (!m_IsFirstRow)
{
XRTableCellCollection cells = firstNonGroupCell.Row.Cells;
for (int i = cells.IndexOf(firstNonGroupCell); i < cells.Count; i++)
{
cells[i].Borders = BorderSide.Left | BorderSide.Top | BorderSide.Right;
}
}
m_IsFirstRow = false;
}
private void AjustGroupBorders(XRTableCell cell, bool isPrinted)
{
if (!isPrinted)
{
cell.Text = string.Empty;
cell.Borders = BorderSide.Left | BorderSide.Right;
}
else
{
cell.Borders = m_DiagnosisCounter > 1
? BorderSide.Left | BorderSide.Top | BorderSide.Right
: BorderSide.Left | BorderSide.Right;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CoreGraphics;
using Foundation;
using Mitten.Mobile.ViewModels;
using UIKit;
namespace Mitten.Mobile.iOS.ViewControllers
{
/// <summary>
/// Base class for a view controller that is associated with a specified view model.
/// </summary>
public abstract class UIViewController<TViewModel> : UIViewController
where TViewModel : ViewModel
{
private static class Constants
{
public const int PaddingWhenKeyboardVisible = 8;
}
private List<NSObject> notificationObservers;
private UIViewControllerFactory viewControllerFactory;
private UIScrollView scrollView;
private UIEdgeInsets? originalContentInsets;
private bool ensureNavigationBarVisible;
private bool ensureNavigationBarHidden;
/// <summary>
/// Initializes a new instance of the UIViewController class.
/// </summary>
protected UIViewController()
{
}
/// <summary>
/// Initializes a new instance of the UIViewController class.
/// </summary>
/// <param name="handle">Object handle used by the runtime.</param>
protected UIViewController(IntPtr handle)
: base(handle)
{
}
/// <summary>
/// Gets the view model for this controller.
/// </summary>
public TViewModel ViewModel { get; private set; }
/// <summary>
/// Gets whether or not the current view controller is a child to another view controller.
/// </summary>
public bool IsChild { get; private set; }
/// <summary>
/// Gets whether or not the view for this view controller has appeared.
/// </summary>
protected bool HasViewAppeared
{
get { return this.View.Superview != null; }
}
/// <summary>
/// Occurs when the view has been loaded.
/// </summary>
public override async void ViewDidLoad()
{
// If there is a navigation bar and it is set to opaque, the main view for this view controller
// will automatically get pushed down below the navigation bar. However, if the navigation
// bar is translucent, the view will not get pushed down. Setting this to true prevents the
// view from getting pushed down when opaque. This way, we can layout our
// views and not be concerned whether or not there will be a navigation bar.
this.ExtendedLayoutIncludesOpaqueBars = true;
base.ViewDidLoad();
await this.HandleViewDidLoad();
this.ViewModel.ViewFinishedLoading();
}
/// <summary>
/// Notifies the view controller that its view is about to be added to a view hierarchy.
/// </summary>
/// <param name="animated">If true, the appearance of the view is being animated.</param>
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
this.AddNotificationObserver(
NSNotificationCenter.DefaultCenter.AddObserver(
UIApplication.ContentSizeCategoryChangedNotification,
_ => this.HandleContentSizeCategoryChanged()));
this.RegisterNotificationHooks();
if (this.ensureNavigationBarVisible)
{
this.SetNavigationBarHidden(false, animated);
}
if (this.ensureNavigationBarHidden)
{
this.SetNavigationBarHidden(true, animated);
}
}
/// <summary>
/// Occurs when the view is about to be removed from the view hierarchy.
/// </summary>
/// <param name="animated">If true, the disappearance of the view is being animated.</param>
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
this.RemoveNotificationObservers();
}
/// <summary>
/// Binds the user interface to the view model.
/// </summary>
protected abstract void Bind();
/// <summary>
/// Gets a loading overlay to show when awaiting for any background loading tasks to complete when the view is first loaded.
/// </summary>
/// <returns>A loading overlay.</returns>
protected abstract ILoadingOverlay GetBackgroundLoadingOverlay();
/// <summary>
/// Handles the view did load event as an async operation.
/// </summary>
/// <returns>The task.</returns>
protected virtual async Task HandleViewDidLoad()
{
if (!this.IsChild)
{
this.InitializeNavigationBar();
}
if (this.ViewModel.IsLoading)
{
UIView transitionView = this.GetTransitionView(this.View.Frame);
this.View.AddSubview(transitionView);
this.View.BringSubviewToFront(transitionView);
await this.ViewModel.AwaitBackgroundLoading(this.GetBackgroundLoadingOverlay());
transitionView.RemoveFromSuperview();
this.InitializeViewAndBind();
}
else
{
this.InitializeViewAndBind();
}
}
/// <summary>
/// Initializes and updates any visual appearances for the views owned by this controller.
/// </summary>
protected virtual void InitializeViews()
{
this.StartIntroAnimations();
}
/// <summary>
/// Starts any animations that are meant to be played when the view is first shown to the user.
/// </summary>
protected virtual void StartIntroAnimations()
{
}
/// <summary>
/// The view controller should register any notification hooks or events.
/// </summary>
protected virtual void RegisterNotificationHooks()
{
}
/// <summary>
/// Gets a view to display while transitioning from a new screen into the current screen
/// and a background loading task is still running. The current view does not get
/// binded and initialized until after the loading task so the transition view gets
/// shown while the user waits.
/// </summary>
/// <param name="frame">The frame for the view.</param>
/// <returns>A transition view.</returns>
/// <remarks>
/// This is different from the loading overlay in that the loading overlay is intended
/// to cover the entire screen and is not shown during the transition between views.
/// Whereas the transition view is added as a subview to the current view and is intended
/// to cover any pre-initialized views until after the background loading has finished.
/// </remarks>
protected virtual UIView GetTransitionView(CGRect frame)
{
UIView view = new UIView(frame);
view.BackgroundColor = UIColor.White;
return view;
}
/// <summary>
/// Creates a new view controller that is intended to represent a child view to be shown inside the current view controller.
/// A child view controller will be allowed to or modify decorator type views such as the navigation bar or status bar.
/// </summary>
/// <param name="parameter">An optional parameter that is passed to the view model.</param>
/// <returns>A new view controller.</returns>
protected UIViewController<TChildViewModel> CreateChildViewController<TChildViewModel>(object parameter)
where TChildViewModel : ViewModel
{
UIViewController<TChildViewModel> child = this.viewControllerFactory.InstantiateViewController<TChildViewModel>(parameter);
child.IsChild = true;
return child;
}
/// <summary>
/// Registers a scroll view with the current controller to handle adjusting the view
/// when a keyboard is shown to prevent edit fields from being hidden by the keyboard.
/// </summary>
/// <param name="scrollView">A scroll view.</param>
protected void RegisterKeyboardHooksForScrollView(UIScrollView scrollView)
{
if (this.scrollView != null)
{
throw new InvalidOperationException("A scroll view has already been registered.");
}
// TODO: what if keyboard is already shown?
this.scrollView = scrollView;
this.RegisterKeyboardDidShow(e =>
{
this.originalContentInsets = this.scrollView.ContentInset;
NSValue keyboardFrame = (NSValue)e.Notification.UserInfo.ObjectForKey(UIKeyboard.FrameBeginUserInfoKey);
nfloat keyboardHeight = keyboardFrame.CGRectValue.Height;
UIEdgeInsets contentInsets = new UIEdgeInsets(this.originalContentInsets.Value.Top, 0, keyboardHeight, 0);
this.scrollView.ContentInset = contentInsets;
this.scrollView.ScrollIndicatorInsets = contentInsets;
UIView firstResponder = this.FindFirstResponder(this.scrollView);
if (firstResponder != null)
{
CGRect visibleRect =
new CGRect(
this.View.Frame.X,
this.View.Frame.Y,
this.View.Frame.Width,
this.View.Frame.Height - keyboardHeight);
CGPoint locationInScrollView = this.scrollView.ConvertPointFromView(firstResponder.Frame.Location, firstResponder);
if (!visibleRect.Contains(locationInScrollView))
{
this.scrollView.ScrollRectToVisible(new CGRect(locationInScrollView, firstResponder.Frame.Size), false);
}
}
});
this.RegisterKeyboardWillBeHidden(e =>
{
// If the current view controller does not have the keyboard visible and then pushes another
// view controller onto the stack, this delegate (on the parent) will get invoked if the child
// view controller has the keyboard visible when navigating back to the parent view controller.
if (this.originalContentInsets.HasValue)
{
this.scrollView.ContentInset = this.originalContentInsets.Value;
this.scrollView.ScrollIndicatorInsets = this.originalContentInsets.Value;
}
this.originalContentInsets = null;
});
}
/// <summary>
/// Handles when the dynamic type for the current view has changed. This occurs when the
/// user changes the content size in the device's settings while the app is in the background.
/// This won't get invoked until the user brings it back into the foreground.
/// </summary>
protected virtual void HandleContentSizeCategoryChanged()
{
}
/// <summary>
/// Occurs when the controller is being disposed.
/// </summary>
/// <param name="disposing">True if the controller was explicilty disposed.</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
this.RemoveNotificationObservers();
}
/// <summary>
/// Registers a delegate to listen for when the application has become active from the background.
/// </summary>
/// <param name="becameActive">Gets invoked when the application has become active.</param>
protected void RegisterDidBecomeActive(Action becameActive)
{
this.AddNotificationObserver(
NSNotificationCenter.DefaultCenter.AddObserver(
UIApplication.DidBecomeActiveNotification,
_ => becameActive()));
}
/// <summary>
/// Indicates that the navigation bar for the current view should be visible whenever the view is shown to the user.
/// </summary>
protected void EnsureNavigationBarVisible()
{
if (this.IsChild)
{
throw new InvalidOperationException("The current view controller is a child.");
}
this.ensureNavigationBarVisible = true;
}
/// <summary>
/// Indicates that the navigation bar for the current view should be hidden whenever the view is shown to the user.
/// </summary>
protected void EnsureNavigationBarHidden()
{
if (this.IsChild)
{
throw new InvalidOperationException("The current view controller is a child.");
}
this.ensureNavigationBarHidden = true;
}
/// <summary>
/// Registers a series of input fields to form a 'chain' as the user moves from field-to-field.
/// There is a little bit of work that needs to be setup in the controller's storyboard and
/// this logic will handle moving from the first field in the chain to the next field when the user
/// hits the Next (Return) button on the keyboard and the last field in the chain will instead trigger
/// the supplied Action.
/// </summary>
/// <param name="action">The action to invoke when the user hits the Go (Return) button while in the last field.</param>
/// <param name="textFields">A list of fields used to form a chain.</param>
protected void RegisterInputChain(Action action, params UITextField[] textFields)
{
if (textFields.Length < 1)
{
throw new ArgumentException("You must specify at least 1 field in order to form a chain.", nameof(textFields));
}
if (textFields.Length > 1)
{
for (int i = 0; i < textFields.Length - 1; i++)
{
this.RegisterNextField(textFields[i], textFields[i + 1]);
}
}
UITextField lastField = textFields.Last();
this.RegisterGo(lastField, action);
}
/// <summary>
/// Registers a delegate with the specified focused field that will handle moving the
/// input focus to the next field when the Next (Return) button on the keyboard is pressed.
/// </summary>
/// <param name="focusField">The field that is expected to have input focus.</param>
/// <param name="nextField">The field to give the input focus to.</param>
protected void RegisterNextField(UITextField focusField, UITextField nextField)
{
focusField.ReturnKeyType = UIReturnKeyType.Next;
focusField.ShouldReturn += field =>
{
nextField.BecomeFirstResponder();
return true;
};
}
/// <summary>
/// Registers a delegate with the specified focused field that will invoke the
/// given action when the Go (Return) button on the keyboard is pressed.
/// </summary>
/// <param name="focusField">The field that is expected to have input focus.</param>
/// <param name="action">The action to invoke.</param>
protected void RegisterGo(UITextField focusField, Action action)
{
focusField.ReturnKeyType = UIReturnKeyType.Go;
focusField.ShouldReturn += field =>
{
action();
return true;
};
}
/// <summary>
/// Creates a view for the navigation bar that displays the app's logo.
/// </summary>
/// <returns>A new UIView.</returns>
protected virtual UIView CreateNavigationLogoView()
{
return new UIView();
}
/// <summary>
/// Updates the navigation title based on the current controller's view model.
/// </summary>
protected void UpdateNavigationTitle()
{
NavigationBarTitle title = this.ViewModel.GetNavigationBarTitle();
if (title.TitleType == NavigationBarTitle.NavigationBarTitleType.Logo)
{
this.NavigationItem.TitleView = this.CreateNavigationLogoView();
}
else
{
this.NavigationItem.Title = title.Text ?? string.Empty;
}
}
/// <summary>
/// Initializes the navigation bar.
/// </summary>
internal protected virtual void InitializeNavigationBar()
{
this.UpdateNavigationTitle();
this.InitializeNavigationBackButton();
}
/// <summary>
/// Initializes this controller and sets the view model.
/// </summary>
/// <param name="viewControllerFactory">The view controller factory for the app.</param>
/// <param name="viewModel">View model for the controller.</param>
internal void Initialize(UIViewControllerFactory viewControllerFactory, TViewModel viewModel)
{
if (this.ViewModel != null)
{
throw new InvalidOperationException("The view controller has already been initialized.");
}
this.ViewModel = viewModel;
this.viewControllerFactory = viewControllerFactory;
}
/// <summary>
/// Registers a delegate to listen for the keyboard will be shown event.
/// </summary>
/// <param name="keyboardShown">Gets invoked when the keyboard is about to be shown.</param>
internal void RegisterKeyboardWillBeShown(Action<UIKeyboardEventArgs> keyboardShown)
{
this.AddNotificationObserver(
NSNotificationCenter.DefaultCenter.AddObserver(
UIKeyboard.WillShowNotification,
notification => keyboardShown(new UIKeyboardEventArgs(notification))));
}
/// <summary>
/// Registers a delegate to listen for the keyboard did show event.
/// </summary>
/// <param name="keyboardShown">Gets invoked when the keyboard has been shown.</param>
internal void RegisterKeyboardDidShow(Action<UIKeyboardEventArgs> keyboardShown)
{
this.AddNotificationObserver(
NSNotificationCenter.DefaultCenter.AddObserver(
UIKeyboard.DidShowNotification,
notification => keyboardShown(new UIKeyboardEventArgs(notification))));
}
/// <summary>
/// Registers a delegate to listen for the keyboard will be hidden event.
/// </summary>
/// <param name="keyboardHidden">Gets invoked when the keyboard is about to be hidden.</param>
internal void RegisterKeyboardWillBeHidden(Action<UIKeyboardEventArgs> keyboardHidden)
{
this.AddNotificationObserver(
NSNotificationCenter.DefaultCenter.AddObserver(
UIKeyboard.WillHideNotification,
notification => keyboardHidden(new UIKeyboardEventArgs(notification))));
}
private void InitializeViewAndBind()
{
this.InitializeViews();
this.Bind();
}
private void InitializeNavigationBackButton()
{
if (this.NavigationItem.BackBarButtonItem == null)
{
// remove text from the back button, by default it would be the text of the previos screen's title
this.NavigationItem.BackBarButtonItem = new UIBarButtonItem(string.Empty, UIBarButtonItemStyle.Plain, null);
}
}
private void SetNavigationBarHidden(bool hide, bool animated)
{
this.NavigationController.SetNavigationBarHidden(hide, animated);
}
private void AddNotificationObserver(NSObject observer)
{
if (this.notificationObservers == null)
{
this.notificationObservers = new List<NSObject>();
}
this.notificationObservers.Add(observer);
}
private void RemoveNotificationObservers()
{
if (this.notificationObservers != null)
{
foreach (NSObject observer in this.notificationObservers)
{
NSNotificationCenter.DefaultCenter.RemoveObserver(observer);
}
this.notificationObservers.Clear();
this.scrollView = null;
}
}
private UIView FindFirstResponder(UIView superview)
{
UIView firstResponder = null;
foreach (UIView view in superview.Subviews)
{
firstResponder =
view.IsFirstResponder
? view
: this.FindFirstResponder(view);
if (firstResponder != null)
{
break;
}
}
return firstResponder;
}
}
}
| |
using System;
using System.Collections;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
using System.Collections.Generic;
using System.Threading;
using System.Text;
namespace Logging
{
/// <summary>
/// This class is used to Log Infos, and Exceptions.
/// This could be used to trace the application on production
/// Logs are stored as csv file.
/// </summary>
public sealed class LogHelper
{
private static volatile LogHelper _instance;
private static object _lock = new Object();
private string _trace = "false";
private int _level = 2;
private int _depth = 1;
private string _path = string.Empty;
private string _logIn = string.Empty;
private string _AppName = string.Empty;
private EventLog _eventLog;
#region Public Static Method
/// <summary>
/// Singleton Constructor
/// </summary>
private LogHelper()
{
if (ConfigurationManager.AppSettings.HasKeys())
{
_trace = ConfigurationManager.AppSettings["Trace"] ?? "false";
_path = ConfigurationManager.AppSettings["LogPath"] ?? AppDomain.CurrentDomain.BaseDirectory;
_logIn = ConfigurationManager.AppSettings["LogIn"] ?? "Windows";
_AppName = ConfigurationManager.AppSettings["EventSource"] ?? Process.GetCurrentProcess().MainModule.FileName;
}
if (_logIn.Trim().ToLower() == "windows" || _logIn.Trim().ToLower() == "both")
{
SetupWindowsEvent();
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Level"]))
{
if (!int.TryParse(ConfigurationManager.AppSettings["Level"].ToString(), out _level))
{
_level = 1;
}
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Depth"]))
{
if (!int.TryParse(ConfigurationManager.AppSettings["Depth"].ToString(), out _depth))
{
_depth = 1;
}
}
}
/// <summary>
/// Set Windows event, to log infos in event viewer
/// </summary>
private void SetupWindowsEvent()
{
if (!EventLog.SourceExists(_AppName))
EventLog.CreateEventSource(_AppName, "Application");
_eventLog = new EventLog();
_eventLog.Source = _AppName;
}
/// <summary>
/// Properties to get the singleton object
/// </summary>
public static LogHelper Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new LogHelper();
}
}
}
return _instance;
}
}
#endregion
#region Public Write Method
/// <summary>
/// Write info of the called method.
/// </summary>
public void WriteLog(string username, int AppDepth)
{
if (!CheckConfig()) return;
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string log = methodBase.DeclaringType.FullName + ":" + methodBase.Name;
WriteLog(LogType.Information, username, AppDepth, log, null);
}
/// <summary>
/// Write info of the called method with generic parameter
/// </summary>
public void WriteGenericLog<T>(T request, string username, int AppDepth)
{
if (!CheckConfig()) return;
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string message = methodBase.DeclaringType.FullName + ":" + methodBase.Name;
Dictionary<string, string> data = null;
Type t = typeof(T);
if (t != typeof(string) && t != typeof(object) && !t.IsValueType && !t.IsPrimitive)
{
data = new Dictionary<string, string>();
if (request is IEnumerable)
{
int idx = 0;
var collection = request as IEnumerable;
if (collection != null)
{
foreach (object obj in collection)
{
Type objType = obj.GetType();
data = AddDataLog(username, objType, objType.Name, obj, data, "#" + idx.ToString());
idx++;
}
}
}
else
{
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo pi in properties)
{
try
{
data = AddDataLog(username, pi.PropertyType, pi.Name, request == null ? null : pi.GetValue(request, null), data, string.Empty);
}
catch (Exception ex)
{
WriteException(ex, username);
continue;
}
}
}
}
else
{
message += ":" + Convert.ToString(request);
}
WriteLog(LogType.Information, username, AppDepth, message, data);
}
/// <summary>
/// Dictionary constructor, to get all properties of the generic parameter
/// </summary>
private Dictionary<string, string> AddDataLog(string username, Type t, string key, object value, Dictionary<string, string> dataLog, string index)
{
if (t != typeof(string) && t != typeof(object) && !t.IsValueType && !t.IsPrimitive && value != null)
{
if (value is IEnumerable)
{
int idx = 0;
var collection = value as IEnumerable;
if (collection != null)
{
foreach (object obj in collection)
{
Type objType = obj.GetType();
dataLog = AddDataLog(username, objType, key + "#" + index + "_" + objType.Name, obj, dataLog, "#" + idx.ToString());
idx++;
}
}
}
else
{
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo pi in properties)
{
try
{
dataLog = AddDataLog(username, pi.PropertyType, key + "#" + index + "_" + pi.Name, pi.GetValue(value, null), dataLog, index);
}
catch (Exception ex)
{
WriteException(ex, username);
continue;
}
}
}
}
else
{
dataLog.Add(key + "#" + index, Convert.ToString(value));
}
return dataLog;
}
/// <summary>
/// Write info of the called method with specified data
/// </summary>
public void WriteLog(IDictionary data, string username, int AppDepth)
{
if (!CheckConfig()) return;
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string message = methodBase.DeclaringType.FullName + ":" + methodBase.Name;
WriteLog(LogType.Information, username, AppDepth, message, data);
}
/// <summary>
/// Write info of the called method with message
/// </summary>
/// <param name="message">message to log</param>
public void WriteLog(string message, string username, int AppDepth)
{
if (!CheckConfig()) return;
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string log = methodBase.DeclaringType.FullName + ":" + methodBase.Name + ":" + message;
WriteLog(LogType.Information, username, AppDepth, log, null);
}
/// <summary>
/// Write warning in the called method with warning message
/// </summary>
/// <param name="message">warning message to log</param>
public void WriteWarningLog(string message, string username, int AppDepth)
{
if (!CheckConfig()) return;
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string log = methodBase.DeclaringType.FullName + ":" + methodBase.Name + ":" + message;
WriteLog(LogType.Warning, username, AppDepth, log, null);
}
/// <summary>
/// Write error of the called method with error message
/// </summary>
/// <param name="message">error message to log</param>
public void WriteErrorLog(string message, string username, int AppDepth)
{
if (!CheckConfig()) return;
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string log = methodBase.DeclaringType.FullName + ":" + methodBase.Name + ":" + message;
WriteLog(LogType.Error, username, AppDepth, log, null);
}
/// <summary>
/// Write warning in the called method with warning message
/// </summary>
/// <param name="message">warning message to log</param>
public void WriteDebugLog(string message, string username, int AppDepth)
{
if (!CheckConfig()) return;
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string log = methodBase.DeclaringType.FullName + ":" + methodBase.Name + ":" + message;
WriteLog(LogType.Debug, username, AppDepth, log, null);
}
/// <summary>
/// Write success message at the end of called method to indcate method doesn't return error
/// </summary>
public void WriteSuccessLog(string username, int AppDepth)
{
if (!CheckConfig()) return;
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string log = methodBase.DeclaringType.FullName + ":" + methodBase.Name + ":" + "Command Succeeded";
WriteLog(LogType.Information, username, AppDepth, log, null);
}
/// <summary>
/// Write info of th called method with message and specified data
/// </summary>
/// <param name="message">message to log</param>
/// <param name="data">data to log</param>
public void WriteLog(string message, string username, int AppDepth, IDictionary data)
{
if (!CheckConfig()) return;
StackTrace stackTrace = new StackTrace();
StackFrame stackFrame = stackTrace.GetFrame(1);
MethodBase methodBase = stackFrame.GetMethod();
string log = methodBase.DeclaringType.FullName + ":" + methodBase.Name + ":" + message;
WriteLog(LogType.Information, username, AppDepth, log, data);
}
/// <summary>
/// Write logs to file/windows event
/// </summary>
/// <param name="logType">info, warning, error</param>
/// <param name="message">message to log</param>
/// <param name="data">data to log</param>
private void WriteLog(LogType logType, string username, int AppDepth, string message, IDictionary data)
{
string day = DateTime.Today.ToString("yyyy-MM-dd");
int threadID = Thread.CurrentThread.ManagedThreadId;
string logFileName = _path + "\\" + username + "\\" + day + "-" + threadID + ".log";
try
{
if (_logIn.ToLower().Trim() == "file" || _logIn.ToLower().Trim() == "both")
{
if (!System.IO.File.Exists(logFileName))
{
if (!System.IO.Directory.Exists(_path))
{
System.IO.Directory.CreateDirectory(_path);
}
if (!System.IO.Directory.Exists(_path + "\\" + username))
{
System.IO.Directory.CreateDirectory(_path + "\\" + username);
}
System.IO.File.Create(logFileName).Close();
}
if (((int)logType <= _level) && (AppDepth <=_depth))
{
using (System.IO.StreamWriter w = System.IO.File.AppendText(logFileName))
{
w.Write("Time-{0},", DateTime.Now);
w.Write("Type-{0},", logType.ToString());
if (data != null)
{
w.Write("Message-{0},", message);
w.Write("\"Details-");
foreach (DictionaryEntry de in data)
{
w.WriteLine("{0}:{1}", de.Key, de.Value);
}
w.WriteLine("\"");
}
else
{
w.WriteLine("Message-{0}", message);
}
w.Flush();
w.Close();
}
}
if (_logIn.ToLower().Trim() == "windows" || _logIn.ToLower().Trim() == "both")
{
if (_eventLog == null)
SetupWindowsEvent();
switch (logType)
{
case LogType.Critical:
case LogType.Error:
_eventLog.WriteEntry(message, EventLogEntryType.Error);
break;
case LogType.Warning:
_eventLog.WriteEntry(message, EventLogEntryType.Warning);
break;
default:
_eventLog.WriteEntry(message, EventLogEntryType.Information);
break;
}
}
}
}
catch (Exception e)
{
WriteException(e, username);
}
}
/// <summary>
/// write exception to file/windows event
/// </summary>
/// <param name="ex">exception to log</param>
public void WriteException(Exception ex, string username)
{
string day = DateTime.Today.ToString("yyyy-MM-dd");
int threadID = Thread.CurrentThread.ManagedThreadId;
string logFileName = _path + "\\" + username + "\\" + day + "-" + threadID + ".log";
if (!System.IO.File.Exists(logFileName))
{
if (!System.IO.Directory.Exists(_path))
{
System.IO.Directory.CreateDirectory(_path);
}
if (!System.IO.Directory.Exists(_path + "\\" + username))
{
System.IO.Directory.CreateDirectory(_path + "\\" + username);
}
System.IO.File.Create(logFileName).Close();
}
Exception innerException = null;
using (System.IO.StreamWriter w = System.IO.File.AppendText(logFileName))
{
w.Write("Time-{0},", DateTime.Now);
w.Write("Type-{0},", LogType.Critical.ToString());
w.Write("Message-{0},", ex.Message);
w.WriteLine("\"Details-");
foreach (DictionaryEntry de in ex.Data)
{
w.WriteLine("{0}:{1}", de.Key, de.Value);
}
w.WriteLine();
w.Write("HelpLink-{0};", ex.HelpLink);
w.Write("Source-{0};", ex.Source);
w.WriteLine("StackTrace-\r\n{0}", ex.StackTrace);
innerException = ex.InnerException;
if (innerException != null)
{
w.WriteLine("TargetSite-{0}", innerException.TargetSite);
while (innerException != null)
{
w.WriteLine("Inner Exception-");
w.Write("Message-{0},", innerException.Message);
w.WriteLine("Details-");
foreach (DictionaryEntry de in innerException.Data)
{
w.WriteLine("{0}:{1};", de.Key, de.Value);
}
w.Write("HelpLink-{0};", innerException.HelpLink);
w.Write("Source-{0};", innerException.Source);
w.WriteLine("StackTrace-\r\n{0}", innerException.StackTrace);
w.WriteLine("TargetSite-{0}", innerException.TargetSite);
innerException = innerException.InnerException;
}
}
else
{
w.WriteLine("TargetSite-{0}\"", ex.TargetSite);
}
w.Flush();
w.Close();
}
if (_eventLog == null)
SetupWindowsEvent();
StringBuilder eventMessage = new StringBuilder();
eventMessage.AppendFormat("Message-{0}\r\n", ex.Message);
eventMessage.AppendFormat("Source-{0}\r\n", ex.Source);
foreach (DictionaryEntry de in ex.Data)
{
eventMessage.AppendFormat("Data-{0}:{1}\r\n", de.Key, de.Value);
}
eventMessage.AppendFormat("TargetSite-{0}\r\n", ex.TargetSite);
eventMessage.AppendFormat("StackTrace-{0}\r\n", ex.StackTrace);
eventMessage.AppendFormat("HelpLink-{0}\r\n;", ex.HelpLink);
innerException = ex.InnerException;
while (innerException != null)
{
eventMessage.AppendFormat("Message-{0}\r\n", innerException.Message);
eventMessage.AppendFormat("Source-{0}\r\n", innerException.Source);
foreach (DictionaryEntry de in innerException.Data)
{
eventMessage.AppendFormat("Data-{0}:{1}\r\n", de.Key, de.Value);
}
eventMessage.AppendFormat("TargetSite-{0}\r\n", innerException.TargetSite);
eventMessage.AppendFormat("StackTrace-{0}\r\n", innerException.StackTrace);
eventMessage.AppendFormat("HelpLink-{0}\r\n;", innerException.HelpLink);
innerException = innerException.InnerException;
}
_eventLog.WriteEntry(eventMessage.ToString(), EventLogEntryType.Error);
}
/// <summary>
/// check if the config has been set, trace == true means logging is enabled.
/// </summary>
/// <returns></returns>
private bool CheckConfig()
{
return (_trace.ToLower() == "true");
}
public enum LogType
{
Critical,
Information,
Error,
Warning,
Debug
}
public enum LoggingLevel
{
CriticalOnly = 0,
InfoOnly = 1,
ErrorOnly = 2,
WarningOnly = 3,
AllInfo = 4
}
#endregion
}
}
| |
using DevExpress.Mvvm.UI.Interactivity;
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Linq;
using System.Collections.Generic;
using DevExpress.Mvvm.Native;
namespace DevExpress.Mvvm.UI {
[TargetTypeAttribute(typeof(UserControl))]
[TargetTypeAttribute(typeof(Window))]
public class DXSplashScreenService : ViewServiceBase, ISplashScreenService {
public static readonly DependencyProperty SplashScreenTypeProperty =
DependencyProperty.Register("SplashScreenType", typeof(Type), typeof(DXSplashScreenService),
new PropertyMetadata(null));
public static readonly DependencyProperty SplashScreenWindowStyleProperty =
DependencyProperty.Register("SplashScreenWindowStyle", typeof(Style), typeof(DXSplashScreenService),
new PropertyMetadata(null, (d, e) => ((DXSplashScreenService)d).OnSplashScreenWindowStyleChanged((Style)e.OldValue, (Style)e.NewValue)));
public static readonly DependencyProperty SplashScreenStartupLocationProperty =
DependencyProperty.Register("SplashScreenStartupLocation", typeof(WindowStartupLocation), typeof(DXSplashScreenService),
new PropertyMetadata(WindowStartupLocation.CenterScreen));
public static readonly DependencyProperty ShowSplashScreenOnLoadingProperty =
DependencyProperty.Register("ShowSplashScreenOnLoading", typeof(bool), typeof(DXSplashScreenService), new PropertyMetadata(false));
public static readonly DependencyProperty ProgressProperty =
DependencyProperty.Register("Progress", typeof(double), typeof(DXSplashScreenService),
new PropertyMetadata(SplashScreenViewModel.ProgressDefaultValue, (d, e) => ((DXSplashScreenService)d).OnProgressChanged()));
public static readonly DependencyProperty MaxProgressProperty =
DependencyProperty.Register("MaxProgress", typeof(double), typeof(DXSplashScreenService),
new PropertyMetadata(SplashScreenViewModel.MaxProgressDefaultValue, (d, e) => ((DXSplashScreenService)d).OnMaxProgressChanged()));
public static readonly DependencyProperty StateProperty =
DependencyProperty.Register("State", typeof(object), typeof(DXSplashScreenService),
new PropertyMetadata(SplashScreenViewModel.StateDefaultValue, (d, e) => ((DXSplashScreenService)d).OnStateChanged()));
public static readonly DependencyProperty SplashScreenOwnerProperty =
DependencyProperty.Register("SplashScreenOwner", typeof(FrameworkElement), typeof(DXSplashScreenService));
public static readonly DependencyProperty SplashScreenClosingModeProperty =
DependencyProperty.Register("SplashScreenClosingMode", typeof(SplashScreenClosingMode), typeof(DXSplashScreenService), new PropertyMetadata(SplashScreenClosingMode.OnParentClosed));
public static readonly DependencyProperty OwnerSearchModeProperty =
DependencyProperty.Register("OwnerSearchMode", typeof(SplashScreenOwnerSearchMode), typeof(DXSplashScreenService), new PropertyMetadata(SplashScreenOwnerSearchMode.Full));
public static readonly DependencyProperty FadeInDurationProperty =
DependencyProperty.Register("FadeInDuration", typeof(TimeSpan), typeof(DXSplashScreenService), new PropertyMetadata(TimeSpan.FromSeconds(0.2)));
public static readonly DependencyProperty FadeOutDurationProperty =
DependencyProperty.Register("FadeOutDuration", typeof(TimeSpan), typeof(DXSplashScreenService), new PropertyMetadata(TimeSpan.FromSeconds(0.2)));
public static readonly DependencyProperty UseIndependentWindowProperty =
DependencyProperty.Register("UseIndependentWindow", typeof(bool), typeof(DXSplashScreenService),
new PropertyMetadata(false, (d, e) => ((DXSplashScreenService)d).OnUseIndependentWindowChanged()));
public Type SplashScreenType {
get { return (Type)GetValue(SplashScreenTypeProperty); }
set { SetValue(SplashScreenTypeProperty, value); }
}
public Style SplashScreenWindowStyle {
get { return (Style)GetValue(SplashScreenWindowStyleProperty); }
set { SetValue(SplashScreenWindowStyleProperty, value); }
}
public WindowStartupLocation SplashScreenStartupLocation {
get { return (WindowStartupLocation)GetValue(SplashScreenStartupLocationProperty); }
set { SetValue(SplashScreenStartupLocationProperty, value); }
}
public bool ShowSplashScreenOnLoading {
get { return (bool)GetValue(ShowSplashScreenOnLoadingProperty); }
set { SetValue(ShowSplashScreenOnLoadingProperty, value); }
}
public double Progress {
get { return (double)GetValue(ProgressProperty); }
set { SetValue(ProgressProperty, value); }
}
public double MaxProgress {
get { return (double)GetValue(MaxProgressProperty); }
set { SetValue(MaxProgressProperty, value); }
}
public object State {
get { return (object)GetValue(StateProperty); }
set { SetValue(StateProperty, value); }
}
public FrameworkElement SplashScreenOwner {
get { return (FrameworkElement)GetValue(SplashScreenOwnerProperty); }
set { SetValue(SplashScreenOwnerProperty, value); }
}
public SplashScreenClosingMode SplashScreenClosingMode {
get { return (SplashScreenClosingMode)GetValue(SplashScreenClosingModeProperty); }
set { SetValue(SplashScreenClosingModeProperty, value); }
}
public SplashScreenOwnerSearchMode OwnerSearchMode {
get { return (SplashScreenOwnerSearchMode)GetValue(OwnerSearchModeProperty); }
set { SetValue(OwnerSearchModeProperty, value); }
}
public TimeSpan FadeInDuration {
get { return (TimeSpan)GetValue(FadeInDurationProperty); }
set { SetValue(FadeInDurationProperty, value); }
}
public TimeSpan FadeOutDuration {
get { return (TimeSpan)GetValue(FadeOutDurationProperty); }
set { SetValue(FadeOutDurationProperty, value); }
}
public bool UseIndependentWindow {
get { return (bool)GetValue(UseIndependentWindowProperty); }
set { SetValue(UseIndependentWindowProperty, value); }
}
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new DataTemplateSelector ViewTemplateSelector { get { return null; } set { OnViewTemplateSelectorChanged(null, null); } }
DependencyObject Owner {
get {
if(SplashScreenOwner != null)
return SplashScreenOwner;
if(OwnerSearchMode == SplashScreenOwnerSearchMode.Full)
return AssociatedObject ?? SplashScreenHelper.GetApplicationActiveWindow(true);
else if(OwnerSearchMode == SplashScreenOwnerSearchMode.IgnoreAssociatedObject)
return SplashScreenHelper.GetApplicationActiveWindow(true);
return null;
}
}
bool IsSplashScreenActive { get { return (splashContainer != null && splashContainer.IsActive) || (!UseIndependentWindow && DXSplashScreen.IsActive); } }
bool ISplashScreenService.IsSplashScreenActive { get { return IsSplashScreenActive; } }
bool SplashScreenIsShownOnLoading = false;
bool isSplashScreenShown = false;
DXSplashScreen.SplashScreenContainer splashContainer = null;
internal DXSplashScreen.SplashScreenContainer GetSplashContainer(bool ensureInstance) {
if(splashContainer == null && ensureInstance)
splashContainer = new DXSplashScreen.SplashScreenContainer();
return splashContainer;
}
protected override void OnViewTemplateSelectorChanged(DataTemplateSelector oldValue, DataTemplateSelector newValue) {
throw new InvalidOperationException("ViewTemplateSelector is not supported by DXSplashScreenService");
}
protected override void OnViewTemplateChanged(DataTemplate oldValue, DataTemplate newValue) {
base.OnViewTemplateChanged(oldValue, newValue);
if(newValue != null)
newValue.Seal();
}
void OnSplashScreenWindowStyleChanged(Style oldValue, Style newValue) {
if(newValue != null)
newValue.Seal();
}
protected override void OnAttached() {
base.OnAttached();
if(ShowSplashScreenOnLoading && !AssociatedObject.IsLoaded && !IsSplashScreenActive) {
AssociatedObject.Loaded += OnAssociatedObjectLoaded;
SplashScreenIsShownOnLoading = true;
((ISplashScreenService)this).ShowSplashScreen();
}
}
protected override void OnDetaching() {
HideSplashScreenOnAssociatedObjectLoaded();
base.OnDetaching();
}
void OnAssociatedObjectLoaded(object sender, RoutedEventArgs e) {
HideSplashScreenOnAssociatedObjectLoaded();
}
void HideSplashScreenOnAssociatedObjectLoaded() {
if(SplashScreenIsShownOnLoading) {
AssociatedObject.Loaded -= OnAssociatedObjectLoaded;
SplashScreenIsShownOnLoading = false;
((ISplashScreenService)this).HideSplashScreen();
}
}
void OnProgressChanged() {
if(isSplashScreenShown)
((ISplashScreenService)this).SetSplashScreenProgress(Progress, MaxProgress);
}
void OnMaxProgressChanged() {
if(isSplashScreenShown)
((ISplashScreenService)this).SetSplashScreenProgress(Progress, MaxProgress);
}
void OnStateChanged() {
if(isSplashScreenShown)
((ISplashScreenService)this).SetSplashScreenState(State);
}
void OnUseIndependentWindowChanged() {
if(isSplashScreenShown)
throw new InvalidOperationException("The property value cannot be changed while the DXSplashScreenService is active.");
}
void ISplashScreenService.ShowSplashScreen(string documentType) {
if(SplashScreenType != null && (!string.IsNullOrEmpty(documentType) || ViewTemplate != null || ViewLocator != null))
throw new InvalidOperationException(DXSplashScreenExceptions.ServiceException1);
if(IsSplashScreenActive)
return;
Func<object, object> contentCreator = null;
object contentCreatorParams = null;
IList<object> windowCreatorParams = new List<object>() { SplashScreenWindowStyle, SplashScreenStartupLocation, Owner.With(x => new SplashScreenOwner(x)),
SplashScreenClosingMode, FadeInDuration, FadeOutDuration };
if(SplashScreenType == null) {
contentCreator = CreateSplashScreen;
contentCreatorParams = new object[] { documentType, ViewLocator, ViewTemplate };
} else {
DXSplashScreen.CheckSplashScreenType(SplashScreenType);
if(typeof(Window).IsAssignableFrom(SplashScreenType))
windowCreatorParams.Add(SplashScreenType);
else if(typeof(FrameworkElement).IsAssignableFrom(SplashScreenType)) {
contentCreator = DXSplashScreen.DefaultSplashScreenContentCreator;
contentCreatorParams = SplashScreenType;
}
}
if(UseIndependentWindow)
GetSplashContainer(true).Show(CreateSplashScreenWindow, contentCreator, windowCreatorParams.ToArray(), contentCreatorParams);
else
DXSplashScreen.Show(CreateSplashScreenWindow, contentCreator, windowCreatorParams.ToArray(), contentCreatorParams);
isSplashScreenShown = UseIndependentWindow || DXSplashScreen.IsActive;
if(Math.Abs(Progress - SplashScreenViewModel.ProgressDefaultValue) > 0.0001)
OnProgressChanged();
if(Math.Abs(MaxProgress - SplashScreenViewModel.MaxProgressDefaultValue) > 0.0001)
OnMaxProgressChanged();
if(!object.Equals(State, SplashScreenViewModel.StateDefaultValue))
OnStateChanged();
}
void ISplashScreenService.HideSplashScreen() {
if(!IsSplashScreenActive) {
isSplashScreenShown = false;
return;
}
if(UseIndependentWindow && splashContainer.IsActive) {
GetSplashContainer(true).Close();
isSplashScreenShown = false;
} else {
DXSplashScreen.Close();
isSplashScreenShown = DXSplashScreen.IsActive;
}
}
void ISplashScreenService.SetSplashScreenProgress(double progress, double maxProgress) {
if(!IsSplashScreenActive) return;
if(UseIndependentWindow)
GetSplashContainer(false).Progress(progress, maxProgress);
else
DXSplashScreen.Progress(progress, maxProgress);
}
void ISplashScreenService.SetSplashScreenState(object state) {
if(!IsSplashScreenActive) return;
if(UseIndependentWindow)
GetSplashContainer(false).SetState(state);
else
DXSplashScreen.SetState(state);
}
static Window CreateSplashScreenWindow(object parameter) {
Type windowType = SplashScreenHelper.FindParameter<Type>(parameter);
Style windowStyle = SplashScreenHelper.FindParameter<Style>(parameter);
IList<TimeSpan> fadeDurations = SplashScreenHelper.FindParameters<TimeSpan>(parameter);
Window res;
if(windowType != null)
res = (Window)Activator.CreateInstance(windowType);
else if(windowStyle != null)
res = new DXSplashScreen.SplashScreenWindow();
else
res = DXSplashScreen.DefaultSplashScreenWindowCreator(parameter);
res.WindowStartupLocation = SplashScreenHelper.FindParameter<WindowStartupLocation>(parameter, WindowStartupLocation.CenterScreen);
if(windowStyle != null)
res.Style = windowStyle;
if(fadeDurations.Any(x => x.TotalMilliseconds > 0) && !Interaction.GetBehaviors(res).Any(x => x is WindowFadeAnimationBehavior))
Interaction.GetBehaviors(res).Add(new WindowFadeAnimationBehavior() { FadeInDuration = fadeDurations[0], FadeOutDuration = fadeDurations[1] });
return res;
}
static object CreateSplashScreen(object parameter) {
object[] parameters = (object[])parameter;
string documentType = parameters[0] as string;
IViewLocator viewLocator = parameters[1] as IViewLocator;
DataTemplate viewTemplate = parameters[2] as DataTemplate;
var SplashScreenViewModel = new SplashScreenViewModel();
return ViewHelper.CreateAndInitializeView(viewLocator, documentType, SplashScreenViewModel, null, null, viewTemplate, null);
}
}
public enum SplashScreenOwnerSearchMode {
Full,
IgnoreAssociatedObject,
OwnerOnly
}
}
| |
using System;
using Csla;
using Csla.Data;
using Csla.Serialization;
using System.ComponentModel.DataAnnotations;
using BusinessObjects.Properties;
using System.Linq;
using BusinessObjects.CoreBusinessClasses;
using DalEf;
using System.Collections.Generic;
namespace BusinessObjects.Documents
{
[Serializable]
public partial class cDocuments_TravelOrder_OtherExpenses: CoreBusinessChildClass<cDocuments_TravelOrder_OtherExpenses>
{
public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty);
#if !SILVERLIGHT
[System.ComponentModel.DataObjectField(true, true)]
#endif
public System.Int32 Id
{
get { return GetProperty(IdProperty); }
internal set { SetProperty(IdProperty, value); }
}
private static readonly PropertyInfo< System.Int32 > documents_TravelOrderIdProperty = RegisterProperty<System.Int32>(p => p.Documents_TravelOrderId, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Int32 Documents_TravelOrderId
{
get { return GetProperty(documents_TravelOrderIdProperty); }
set { SetProperty(documents_TravelOrderIdProperty, value); }
}
private static readonly PropertyInfo<System.Int32> ordinalProperty = RegisterProperty<System.Int32>(p => p.Ordinal, string.Empty);
[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))]
public System.Int32 Ordinal
{
get { return GetProperty(ordinalProperty); }
set { SetProperty(ordinalProperty, value); }
}
private static readonly PropertyInfo< System.String > descriptionProperty = RegisterProperty<System.String>(p => p.Description, string.Empty, (System.String)null);
public System.String Description
{
get { return GetProperty(descriptionProperty); }
set { SetProperty(descriptionProperty, (value ?? "").Trim()); }
}
private static readonly PropertyInfo< System.Decimal? > ammountProperty = RegisterProperty<System.Decimal?>(p => p.Ammount, string.Empty, (System.Decimal?)null);
public System.Decimal? Ammount
{
get { return GetProperty(ammountProperty); }
set { SetProperty(ammountProperty, value); }
}
private static readonly PropertyInfo< bool? > admitedProperty = RegisterProperty<bool?>(p => p.Admited, string.Empty,(bool?)null);
public bool? Admited
{
get { return GetProperty(admitedProperty); }
set { SetProperty(admitedProperty, value); }
}
/// <summary>
/// Used for optimistic concurrency.
/// </summary>
[NotUndoable]
internal System.Byte[] LastChanged = new System.Byte[8];
internal static cDocuments_TravelOrder_OtherExpenses NewDocuments_TravelOrder_OtherExpenses()
{
return DataPortal.CreateChild<cDocuments_TravelOrder_OtherExpenses>();
}
public static cDocuments_TravelOrder_OtherExpenses GetDocuments_TravelOrder_OtherExpenses(Documents_TravelOrder_OtherExpensesCol data)
{
return DataPortal.FetchChild<cDocuments_TravelOrder_OtherExpenses>(data);
}
#region Data Access
[RunLocal]
protected override void Child_Create()
{
BusinessRules.CheckRules();
}
private void Child_Fetch(Documents_TravelOrder_OtherExpensesCol data)
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LoadProperty<int>(documents_TravelOrderIdProperty, data.Documents_TravelOrderId);
LoadProperty<int>(ordinalProperty, data.Ordinal);
LoadProperty<string>(descriptionProperty, data.Description);
LoadProperty<decimal?>(ammountProperty, data.Ammount);
LoadProperty<bool?>(admitedProperty, data.Admited);
LastChanged = data.LastChanged;
BusinessRules.CheckRules();
}
private void Child_Insert(Documents_TravelOrder parent)
{
using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities"))
{
var data = new Documents_TravelOrder_OtherExpensesCol();
data.Documents_TravelOrder = parent;
data.Ordinal = ReadProperty<int>(ordinalProperty);
data.Description = ReadProperty<string>(descriptionProperty);
data.Ammount = ReadProperty<decimal?>(ammountProperty);
data.Admited = ReadProperty<bool?>(admitedProperty);
ctx.ObjectContext.AddToDocuments_TravelOrder_OtherExpensesCol(data);
data.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "Id")
{
LoadProperty<int>(IdProperty, data.Id);
LoadProperty<int>(documents_TravelOrderIdProperty, data.Documents_TravelOrderId);
LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey));
LastChanged = data.LastChanged;
}
};
}
}
private void Child_Update()
{
using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities"))
{
var data = new Documents_TravelOrder_OtherExpensesCol();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
ctx.ObjectContext.Attach(data);
data.Ordinal = ReadProperty<int>(ordinalProperty);
data.Description = ReadProperty<string>(descriptionProperty);
data.Ammount = ReadProperty<decimal?>(ammountProperty);
data.Admited = ReadProperty<bool?>(admitedProperty);
data.PropertyChanged += (o, e) =>
{
if (e.PropertyName == "LastChanged")
LastChanged = data.LastChanged;
};
}
}
private void Child_DeleteSelf()
{
using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities"))
{
var data = new Documents_TravelOrder_OtherExpensesCol();
data.Id = ReadProperty<int>(IdProperty);
data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey;
//data.SubjectId = parent.Id;
ctx.ObjectContext.Attach(data);
ctx.ObjectContext.DeleteObject(data);
}
}
#endregion
}
[Serializable]
public partial class cDocuments_TravelOrder_OtherExpensesCol : BusinessListBase<cDocuments_TravelOrder_OtherExpensesCol,cDocuments_TravelOrder_OtherExpenses>
{
internal static cDocuments_TravelOrder_OtherExpensesCol NewDocuments_TravelOrder_OtherExpensesCol()
{
return DataPortal.CreateChild<cDocuments_TravelOrder_OtherExpensesCol>();
}
public static cDocuments_TravelOrder_OtherExpensesCol GetDocuments_TravelOrder_OtherExpensesCol(IEnumerable<Documents_TravelOrder_OtherExpensesCol> dataSet)
{
var childList = new cDocuments_TravelOrder_OtherExpensesCol();
childList.Fetch(dataSet);
return childList;
}
#region Data Access
private void Fetch(IEnumerable<Documents_TravelOrder_OtherExpensesCol> dataSet)
{
RaiseListChangedEvents = false;
foreach (var data in dataSet)
this.Add(cDocuments_TravelOrder_OtherExpenses.GetDocuments_TravelOrder_OtherExpenses(data));
RaiseListChangedEvents = true;
}
#endregion //Data Access
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using EnvDTE;
using EnvDTE80;
using Typewriter.Metadata.Interfaces;
namespace Typewriter.Metadata.CodeDom
{
public class CodeDomTypeMetadata : ITypeMetadata
{
private static readonly Dictionary<string, string> primitiveTypes = new Dictionary<string, string>
{
{ "System.Boolean", "bool" },
{ "System.Byte", "byte" },
{ "System.Char", "char" },
{ "System.Decimal", "decimal" },
{ "System.Double", "double" },
{ "System.Int16", "short" },
{ "System.Int32", "int" },
{ "System.Int64", "long" },
{ "System.SByte", "sbyte" },
{ "System.Single", "float" },
{ "System.String", "string" },
{ "System.UInt32", "uint" },
{ "System.UInt16", "ushort" },
{ "System.UInt64", "ulong" },
{ "System.DateTime", "DateTime" },
{ "System.DateTimeOffset", "DateTimeOffset" },
{ "System.Guid", "Guid" },
{ "System.TimeSpan", "TimeSpan" },
};
protected CodeType codeType;
private readonly bool isNullable;
private readonly CodeDomFileMetadata file;
protected virtual CodeType CodeType => codeType;
protected CodeDomTypeMetadata(CodeType codeType, bool isNullable, CodeDomFileMetadata file)
{
this.codeType = codeType;
this.isNullable = isNullable;
this.file = file;
}
public virtual string Name => GetName(CodeType.Name, CodeType.FullName);
public virtual string FullName => GetFullName(CodeType.FullName);
public virtual string Namespace => GetNamespace();
public bool IsGeneric => FullName.IndexOf("<", StringComparison.Ordinal) > -1 && IsNullable == false;
public bool IsNullable => isNullable;
public bool IsEnum => CodeType.Kind == vsCMElement.vsCMElementEnum;
public bool IsEnumerable => IsCollection(FullName);
public IClassMetadata BaseClass => CodeDomClassMetadata.FromCodeElements(CodeType.Bases, file).FirstOrDefault();
public IClassMetadata ContainingClass => CodeDomClassMetadata.FromCodeClass(CodeType.Parent as CodeClass2, file);
public IEnumerable<IAttributeMetadata> Attributes => CodeDomAttributeMetadata.FromCodeElements(CodeType.Attributes, file);
public IEnumerable<IConstantMetadata> Constants => CodeDomConstantMetadata.FromCodeElements(CodeType.Children, file);
public IEnumerable<IFieldMetadata> Fields => CodeDomFieldMetadata.FromCodeElements(CodeType.Children, file);
public IEnumerable<IInterfaceMetadata> Interfaces => CodeDomInterfaceMetadata.FromCodeElements(CodeType.Bases, file);
public IEnumerable<IMethodMetadata> Methods => CodeDomMethodMetadata.FromCodeElements(CodeType.Children, file);
public IEnumerable<IPropertyMetadata> Properties => CodeDomPropertyMetadata.FromCodeElements(CodeType.Children, file);
public IEnumerable<IClassMetadata> NestedClasses => CodeDomClassMetadata.FromCodeElements(CodeType.Members, file);
public IEnumerable<IEnumMetadata> NestedEnums => CodeDomEnumMetadata.FromCodeElements(CodeType.Members, file);
public IEnumerable<IInterfaceMetadata> NestedInterfaces => CodeDomInterfaceMetadata.FromCodeElements(CodeType.Members, file);
public IEnumerable<ITypeMetadata> GenericTypeArguments => LoadGenericTypeArguments();
private string GetNamespace()
{
var parent = CodeType.Parent as CodeClass2;
return parent != null ? parent.FullName : CodeType.Namespace.FullName;
}
protected string GetName(string name, string fullName)
{
if (primitiveTypes.ContainsKey(fullName))
name = primitiveTypes[fullName];
return name + (IsNullable ? "?" : string.Empty);
}
protected string GetFullName(string fullName)
{
return fullName + (IsNullable ? "?" : string.Empty);
}
private IEnumerable<ITypeMetadata> LoadGenericTypeArguments()
{
if (IsGeneric == false) return new ITypeMetadata[0];
return GenericTypeMetadata.ExtractGenericTypeNames(FullName).Select(fullName =>
{
if (fullName.EndsWith("[]"))
fullName = $"System.Collections.Generic.ICollection<{fullName.TrimEnd('[', ']')}>";
var nullable = fullName.EndsWith("?") || fullName.StartsWith("System.Nullable<");
if (nullable)
{
fullName = fullName.EndsWith("?") ? fullName.TrimEnd('?') : fullName.Substring(16, fullName.Length - 17);
return new LazyCodeDomTypeMetadata(fullName, true, file);
}
return new LazyCodeDomTypeMetadata(fullName, false, file);
});
}
public bool IsPrimitive
{
get
{
var fullName = FullName;
if (IsNullable)
{
fullName = fullName.TrimEnd('?');
}
else if (IsEnumerable)
{
var innerType = GenericTypeArguments.FirstOrDefault();
if (innerType != null)
{
fullName = innerType.IsNullable ? innerType.FullName.TrimEnd('?') : innerType.FullName;
}
else
{
return false;
}
}
return IsEnum || primitiveTypes.ContainsKey(fullName);
}
}
private static ITypeMetadata GetType(dynamic element, CodeDomFileMetadata file)
{
//try
//{
var isGenericTypeArgument = element.Type.TypeKind == (int)vsCMTypeRef.vsCMTypeRefOther && element.Type.AsFullName.Split('.').Length == 1;
if (isGenericTypeArgument)
{
return new GenericTypeMetadata(element.Type.AsFullName, file);
}
var isArray = element.Type.TypeKind == (int)vsCMTypeRef.vsCMTypeRefArray;
if (isArray)
{
var name = element.Type.ElementType.AsFullName;
return new LazyCodeDomTypeMetadata($"System.Collections.Generic.ICollection<{name}>", false, file);
}
CodeType codeType = element.Type.CodeType;
var isNullable = codeType.FullName.EndsWith("?") || codeType.FullName.StartsWith("System.Nullable<");
if (isNullable)
{
var name = codeType.FullName;
name = name.EndsWith("?") ? name.TrimEnd('?') : name.Substring(16, name.Length - 17);
return new LazyCodeDomTypeMetadata(name, true, file);
}
return new CodeDomTypeMetadata(codeType, false, file);
//}
//catch (NotImplementedException)
//{
// return new LazyCodeDomType<T>(fullName, parent);
//}
}
private static bool IsCollection(string fullName)
{
if (fullName == "System.Array") return true;
if (fullName.StartsWith("System.Collections.") == false) return false;
fullName = fullName.Split('<')[0];
if (fullName.Contains("Comparer")) return false;
if (fullName.Contains("Enumerator")) return false;
if (fullName.Contains("Provider")) return false;
if (fullName.Contains("Partitioner")) return false;
if (fullName.Contains("Structural")) return false;
if (fullName.Contains("KeyNotFoundException")) return false;
if (fullName.Contains("KeyValuePair")) return false;
return true;
}
public static ITypeMetadata FromCodeElement(CodeVariable2 codeVariable, CodeDomFileMetadata file)
{
return GetType(codeVariable, file);
}
public static ITypeMetadata FromCodeElement(CodeFunction2 codeVariable, CodeDomFileMetadata file)
{
return GetType(codeVariable, file);
}
public static ITypeMetadata FromCodeElement(CodeProperty2 codeVariable, CodeDomFileMetadata file)
{
return GetType(codeVariable, file);
}
public static ITypeMetadata FromCodeElement(CodeParameter2 codeVariable, CodeDomFileMetadata file)
{
return GetType(codeVariable, file);
}
}
}
| |
namespace XenAdmin.Dialogs
{
partial class EvacuateHostDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EvacuateHostDialog));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this.vmListLabel = new System.Windows.Forms.Label();
this.CloseButton = new System.Windows.Forms.Button();
this.EvacuateButton = new System.Windows.Forms.Button();
this.labelBlurb = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.NewMasterComboBox = new System.Windows.Forms.ComboBox();
this.NewMasterLabel = new System.Windows.Forms.Label();
this.labelMasterBlurb = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.dataGridViewVms = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx();
this.columnImage = new System.Windows.Forms.DataGridViewImageColumn();
this.columnVm = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.columnAction = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.lableWLBEnabled = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.panel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewVms)).BeginInit();
this.SuspendLayout();
//
// ActionStatusLabel
//
resources.ApplyResources(this.ActionStatusLabel, "ActionStatusLabel");
//
// ProgressSeparator
//
resources.ApplyResources(this.ProgressSeparator, "ProgressSeparator");
//
// ActionProgressBar
//
resources.ApplyResources(this.ActionProgressBar, "ActionProgressBar");
//
// vmListLabel
//
resources.ApplyResources(this.vmListLabel, "vmListLabel");
this.vmListLabel.Name = "vmListLabel";
//
// CloseButton
//
resources.ApplyResources(this.CloseButton, "CloseButton");
this.CloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CloseButton.Name = "CloseButton";
this.CloseButton.UseVisualStyleBackColor = true;
this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click);
//
// EvacuateButton
//
resources.ApplyResources(this.EvacuateButton, "EvacuateButton");
this.EvacuateButton.Name = "EvacuateButton";
this.EvacuateButton.UseVisualStyleBackColor = true;
this.EvacuateButton.Click += new System.EventHandler(this.RepairButton_Click);
//
// labelBlurb
//
resources.ApplyResources(this.labelBlurb, "labelBlurb");
this.labelBlurb.Name = "labelBlurb";
//
// pictureBox1
//
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Image = global::XenAdmin.Properties.Resources._000_ServerMaintenance_h32bit_32;
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// NewMasterComboBox
//
resources.ApplyResources(this.NewMasterComboBox, "NewMasterComboBox");
this.NewMasterComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.NewMasterComboBox.FormattingEnabled = true;
this.NewMasterComboBox.Name = "NewMasterComboBox";
//
// NewMasterLabel
//
resources.ApplyResources(this.NewMasterLabel, "NewMasterLabel");
this.NewMasterLabel.Name = "NewMasterLabel";
//
// labelMasterBlurb
//
resources.ApplyResources(this.labelMasterBlurb, "labelMasterBlurb");
this.labelMasterBlurb.Name = "labelMasterBlurb";
//
// panel2
//
resources.ApplyResources(this.panel2, "panel2");
this.panel2.Controls.Add(this.dataGridViewVms);
this.panel2.Controls.Add(this.lableWLBEnabled);
this.panel2.Controls.Add(this.vmListLabel);
this.panel2.Name = "panel2";
//
// dataGridViewVms
//
this.dataGridViewVms.AllowUserToResizeColumns = false;
resources.ApplyResources(this.dataGridViewVms, "dataGridViewVms");
this.dataGridViewVms.BackgroundColor = System.Drawing.SystemColors.Window;
this.dataGridViewVms.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Segoe UI", 9F);
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewVms.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dataGridViewVms.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewVms.ColumnHeadersVisible = false;
this.dataGridViewVms.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.columnImage,
this.columnVm,
this.columnAction});
dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle4.BackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle4.Font = new System.Drawing.Font("Segoe UI", 9F);
dataGridViewCellStyle4.ForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Window;
dataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.ControlText;
dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridViewVms.DefaultCellStyle = dataGridViewCellStyle4;
this.dataGridViewVms.HideSelection = true;
this.dataGridViewVms.Name = "dataGridViewVms";
dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle5.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle5.Font = new System.Drawing.Font("Segoe UI", 9F);
dataGridViewCellStyle5.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle5.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle5.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewVms.RowHeadersDefaultCellStyle = dataGridViewCellStyle5;
this.dataGridViewVms.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.RowHeaderSelect;
this.dataGridViewVms.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridViewVms_CellMouseClick);
this.dataGridViewVms.CellMouseMove += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridViewVms_CellMouseMove);
//
// columnImage
//
this.columnImage.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
dataGridViewCellStyle2.NullValue = "System.Drawing.Bitmap";
this.columnImage.DefaultCellStyle = dataGridViewCellStyle2;
resources.ApplyResources(this.columnImage, "columnImage");
this.columnImage.Name = "columnImage";
this.columnImage.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.columnImage.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
//
// columnVm
//
this.columnVm.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.columnVm.FillWeight = 137.8531F;
resources.ApplyResources(this.columnVm, "columnVm");
this.columnVm.Name = "columnVm";
//
// columnAction
//
this.columnAction.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
this.columnAction.DefaultCellStyle = dataGridViewCellStyle3;
this.columnAction.FillWeight = 40F;
resources.ApplyResources(this.columnAction, "columnAction");
this.columnAction.Name = "columnAction";
//
// lableWLBEnabled
//
resources.ApplyResources(this.lableWLBEnabled, "lableWLBEnabled");
this.lableWLBEnabled.Name = "lableWLBEnabled";
//
// EvacuateHostDialog
//
this.AcceptButton = this.EvacuateButton;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.CloseButton;
this.Controls.Add(this.NewMasterComboBox);
this.Controls.Add(this.NewMasterLabel);
this.Controls.Add(this.labelBlurb);
this.Controls.Add(this.labelMasterBlurb);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.panel2);
this.Controls.Add(this.CloseButton);
this.Controls.Add(this.EvacuateButton);
this.Name = "EvacuateHostDialog";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.EvacuateHostDialog_FormClosed);
this.Controls.SetChildIndex(this.ActionProgressBar, 0);
this.Controls.SetChildIndex(this.ProgressSeparator, 0);
this.Controls.SetChildIndex(this.ActionStatusLabel, 0);
this.Controls.SetChildIndex(this.EvacuateButton, 0);
this.Controls.SetChildIndex(this.CloseButton, 0);
this.Controls.SetChildIndex(this.panel2, 0);
this.Controls.SetChildIndex(this.pictureBox1, 0);
this.Controls.SetChildIndex(this.labelMasterBlurb, 0);
this.Controls.SetChildIndex(this.labelBlurb, 0);
this.Controls.SetChildIndex(this.NewMasterLabel, 0);
this.Controls.SetChildIndex(this.NewMasterComboBox, 0);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewVms)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button CloseButton;
private System.Windows.Forms.Button EvacuateButton;
private System.Windows.Forms.Label vmListLabel;
private System.Windows.Forms.Label labelBlurb;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ComboBox NewMasterComboBox;
private System.Windows.Forms.Label NewMasterLabel;
private System.Windows.Forms.Label labelMasterBlurb;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label lableWLBEnabled;
private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridViewVms;
private System.Windows.Forms.DataGridViewImageColumn columnImage;
private System.Windows.Forms.DataGridViewTextBoxColumn columnVm;
private System.Windows.Forms.DataGridViewTextBoxColumn columnAction;
}
}
| |
using UnityEngine;
using System;
[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(CapsuleCollider))]
public sealed class FootIK : AIK
{
#region Fields
public LayerMask raycastLayerMask;
public Transform leftFoot;
public Vector3 leftFootOffset;
private float leftFootWeight = 0.0f;
public Transform rightFoot;
public Vector3 rightFootOffset;
private float rightFootWeight = 0.0f;
private Vector3 leftFootPosition;
private Vector3 rightFootPosition;
private CapsuleCollider myCapsuleCollider;
private Vector3 newColliderCenter;
private float newColliderHeight;
private float transformWeigth = 1.0f;
private const float moveColliderCenterAndHeightSpeedAndTransformWeightSpeed = 10;
#endregion
#region Unity Behaviour
void Start ()
{
this.myCapsuleCollider = GetComponent<CapsuleCollider>();
this.newColliderCenter = this.myCapsuleCollider.center;
this.newColliderHeight = this.myCapsuleCollider.height;
}
void Update()
{
if (EnableIK)
{
if (base.MyAnimator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Idle"))
this.IdleUpdateCollider();
else if (base.MyAnimator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Walk") ||
base.MyAnimator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Run"))
this.WalkRunUpdateCollider();
}
else
{
this.myCapsuleCollider.center = new Vector3(
0.0f,
Mathf.Lerp(this.myCapsuleCollider.center.y, this.newColliderCenter.y, Time.deltaTime * moveColliderCenterAndHeightSpeedAndTransformWeightSpeed),
0.0f);
this.myCapsuleCollider.height = Mathf.Lerp(
this.myCapsuleCollider.height,
this.newColliderHeight,
Time.deltaTime * moveColliderCenterAndHeightSpeedAndTransformWeightSpeed);
}
}
#endregion
#region Override Behaviour
protected override void IKBehaviour()
{
if (this.transformWeigth != 1.0f)
{
this.transformWeigth = Mathf.Lerp(this.transformWeigth, 1.0f, Time.deltaTime * moveColliderCenterAndHeightSpeedAndTransformWeightSpeed);
if (this.transformWeigth >= 0.99)
this.transformWeigth = 1.0f;
}
if (base.MyAnimator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Idle") &&
this.myCapsuleCollider.attachedRigidbody.velocity.magnitude < 0.1f)
{
base.MyAnimator.SetIKPositionWeight(AvatarIKGoal.LeftFoot, this.transformWeigth);
base.MyAnimator.SetIKRotationWeight(AvatarIKGoal.LeftFoot, this.transformWeigth);
base.MyAnimator.SetIKPositionWeight(AvatarIKGoal.RightFoot, this.transformWeigth);
base.MyAnimator.SetIKRotationWeight(AvatarIKGoal.RightFoot, this.transformWeigth);
this.IdleIK();
}
else if (base.MyAnimator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Walk") ||
base.MyAnimator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Run"))
{
base.MyAnimator.SetIKPositionWeight(AvatarIKGoal.LeftFoot, this.transformWeigth * this.leftFootWeight);
base.MyAnimator.SetIKRotationWeight(AvatarIKGoal.LeftFoot, this.transformWeigth * this.leftFootWeight);
base.MyAnimator.SetIKPositionWeight(AvatarIKGoal.RightFoot, this.transformWeigth * this.rightFootWeight);
base.MyAnimator.SetIKRotationWeight(AvatarIKGoal.RightFoot, this.transformWeigth * this.rightFootWeight);
this.WalkRunIK();
}
}
protected override void ResetIK()
{
if (this.transformWeigth != 0.0f)
{
this.transformWeigth = Mathf.Lerp(this.transformWeigth, 0.0f, Time.deltaTime * moveColliderCenterAndHeightSpeedAndTransformWeightSpeed);
if (this.transformWeigth <= 0.01)
this.transformWeigth = 0.0f;
}
base.MyAnimator.SetIKPositionWeight(AvatarIKGoal.LeftFoot, this.transformWeigth);
base.MyAnimator.SetIKRotationWeight(AvatarIKGoal.LeftFoot, this.transformWeigth);
base.MyAnimator.SetIKPositionWeight(AvatarIKGoal.RightFoot, this.transformWeigth);
base.MyAnimator.SetIKRotationWeight(AvatarIKGoal.RightFoot, this.transformWeigth);
}
#endregion
#region Intern Behaviour
private void IdleIK()
{
RaycastHit hit;
this.leftFootPosition = base.MyAnimator.GetIKPosition(AvatarIKGoal.LeftFoot);
if (Physics.Raycast(this.leftFootPosition + Vector3.up, Vector3.down, out hit, 2.0f, this.raycastLayerMask))
{
//Debug.DrawLine(hit.point, hit.point + hit.normal, Color.yellow);
base.MyAnimator.SetIKPosition(AvatarIKGoal.LeftFoot, hit.point + this.leftFootOffset);
base.MyAnimator.SetIKRotation(AvatarIKGoal.LeftFoot, Quaternion.LookRotation(Vector3.ProjectOnPlane(this.leftFoot.forward, hit.normal), hit.normal));
this.leftFootPosition = hit.point;
}
this.rightFootPosition = base.MyAnimator.GetIKPosition(AvatarIKGoal.RightFoot);
if (Physics.Raycast(this.rightFootPosition + Vector3.up, Vector3.down, out hit, 2.0f, this.raycastLayerMask))
{
//Debug.DrawLine(hit.point, hit.point + hit.normal, Color.green);
base.MyAnimator.SetIKPosition(AvatarIKGoal.RightFoot, hit.point + this.rightFootOffset);
base.MyAnimator.SetIKRotation(AvatarIKGoal.RightFoot,Quaternion.LookRotation(Vector3.ProjectOnPlane(this.rightFoot.forward, hit.normal), hit.normal));
this.rightFootPosition = hit.point;
}
}
private void WalkRunIK()
{
RaycastHit hit;
this.leftFootPosition = base.MyAnimator.GetIKPosition(AvatarIKGoal.LeftFoot);
if (Physics.Raycast(this.leftFootPosition + Vector3.up, Vector3.down, out hit, 2.0f, this.raycastLayerMask))
{
//Debug.DrawLine(hit.point, hit.point + hit.normal, Color.yellow);
base.MyAnimator.SetIKPosition(AvatarIKGoal.LeftFoot, hit.point + this.leftFootOffset);
base.MyAnimator.SetIKRotation(AvatarIKGoal.LeftFoot, Quaternion.LookRotation(Vector3.ProjectOnPlane(this.leftFoot.forward, hit.normal), hit.normal));
this.leftFootPosition = hit.point;
}
this.rightFootPosition = base.MyAnimator.GetIKPosition(AvatarIKGoal.RightFoot);
if (Physics.Raycast(this.rightFootPosition + Vector3.up, Vector3.down, out hit, 2.0f, this.raycastLayerMask))
{
//Debug.DrawLine(hit.point, hit.point + hit.normal, Color.green);
base.MyAnimator.SetIKPosition(AvatarIKGoal.RightFoot, hit.point + this.rightFootOffset);
base.MyAnimator.SetIKRotation(AvatarIKGoal.RightFoot, Quaternion.LookRotation(Vector3.ProjectOnPlane(this.rightFoot.forward, hit.normal), hit.normal));
rightFootPosition = hit.point;
}
}
void IdleUpdateCollider ()
{
float dif = this.leftFootPosition.y - this.rightFootPosition.y;
if (dif < 0.0f)
dif *= -1.0f;
this.myCapsuleCollider.center = new Vector3(0.0f, Mathf.Lerp(this.myCapsuleCollider.center.y, this.newColliderCenter.y + dif, Time.deltaTime) ,0.0f);
this.myCapsuleCollider.height = Mathf.Lerp(this.myCapsuleCollider.height, this.newColliderHeight - (dif / 2), Time.deltaTime);
}
void WalkRunUpdateCollider ()
{
RaycastHit hit;
Vector3 myGround = Vector3.zero;
Vector3 dif = Vector3.zero;
if (Physics.Raycast(transform.position + Vector3.up, Vector3.down, out hit, 3.0f, this.raycastLayerMask))
myGround = hit.point;
if (Physics.Raycast(transform.position +
(((transform.forward * (this.myCapsuleCollider.radius))) +
(this.myCapsuleCollider.attachedRigidbody.velocity * Time.deltaTime)) +
Vector3.up, Vector3.down, out hit, 2.0f, this.raycastLayerMask))
{
//Debug.DrawLine(transform.position + (((transform.forward * (myCapsuleCollider.radius))) + (myCapsuleCollider.attachedRigidbody.velocity * Time.deltaTime)) + Vector3.up, hit.point, Color.red);
dif = hit.point - myGround;
if (dif.y < 0.0f)
dif *= -1.0f;
}
if (dif.y < 0.5f)
{
this.myCapsuleCollider.center = new Vector3(0.0f, Mathf.Lerp(this.myCapsuleCollider.center.y, this.newColliderCenter.y + dif.y, Time.deltaTime * moveColliderCenterAndHeightSpeedAndTransformWeightSpeed), 0.0f);
this.myCapsuleCollider.height = Mathf.Lerp(this.myCapsuleCollider.height, this.newColliderHeight - (dif.y / 2.0f), Time.deltaTime * moveColliderCenterAndHeightSpeedAndTransformWeightSpeed);
}
else
{
this.myCapsuleCollider.center = new Vector3(0.0f, Mathf.Lerp(this.myCapsuleCollider.center.y, this.newColliderCenter.y, Time.deltaTime * moveColliderCenterAndHeightSpeedAndTransformWeightSpeed), 0.0f);
this.myCapsuleCollider.height = Mathf.Lerp(this.myCapsuleCollider.height, this.newColliderHeight, Time.deltaTime * moveColliderCenterAndHeightSpeedAndTransformWeightSpeed);
}
}
#endregion
}
| |
using System;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Authentication.Twitter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MusicStore.Components;
using MusicStore.Mocks.Common;
using MusicStore.Mocks.Facebook;
using MusicStore.Mocks.Google;
using MusicStore.Mocks.MicrosoftAccount;
using MusicStore.Mocks.Twitter;
using MusicStore.Models;
namespace MusicStore
{
public class StartupSocialTesting
{
private readonly Platform _platform;
public StartupSocialTesting(IHostingEnvironment hostingEnvironment)
{
//Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources,
//then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely.
var builder = new ConfigurationBuilder()
.SetBasePath(hostingEnvironment.ContentRootPath)
.AddJsonFile("config.json")
.AddEnvironmentVariables() //All environment variables in the process's context flow in as configuration values.
.AddJsonFile("configoverride.json", optional: true); // Used to override some configuration parameters that cannot be overridden by environment.
Configuration = builder.Build();
_platform = new Platform();
}
public IConfiguration Configuration { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
// Add EF services to the services container
if (_platform.UseInMemoryStore)
{
services.AddDbContext<MusicStoreContext>(options =>
options.UseInMemoryDatabase());
}
else
{
services.AddDbContext<MusicStoreContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
}
// Add Identity services to the services container
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied");
})
.AddEntityFrameworkStores<MusicStoreContext>()
.AddDefaultTokenProviders();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder.WithOrigins("http://example.com");
});
});
// Add MVC services to the services container
services.AddMvc();
//Add InMemoryCache
services.AddSingleton<IMemoryCache, MemoryCache>();
// Add session related services.
services.AddMemoryCache();
services.AddDistributedMemoryCache();
services.AddSession();
// Add the system clock service
services.AddSingleton<ISystemClock, SystemClock>();
// Configure Auth
services.AddAuthorization(options =>
{
options.AddPolicy("ManageStore", new AuthorizationPolicyBuilder().RequireClaim("ManageStore", "Allowed").Build());
});
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(minLevel: LogLevel.Warning);
app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage");
// Error page middleware displays a nice formatted HTML page for any unhandled exceptions in the request pipeline.
// Note: Not recommended for production.
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
// Configure Session.
app.UseSession();
// Add static files to the request pipeline
app.UseStaticFiles();
// Add cookie-based authentication to the request pipeline
app.UseIdentity();
app.UseFacebookAuthentication(new FacebookOptions
{
AppId = "[AppId]",
AppSecret = "[AppSecret]",
Events = new OAuthEvents()
{
OnCreatingTicket = TestFacebookEvents.OnCreatingTicket,
OnTicketReceived = TestFacebookEvents.OnTicketReceived,
OnRedirectToAuthorizationEndpoint = TestFacebookEvents.RedirectToAuthorizationEndpoint
},
BackchannelHttpHandler = new FacebookMockBackChannelHttpHandler(),
StateDataFormat = new CustomStateDataFormat(),
Scope = { "email", "read_friendlists", "user_checkins" }
});
app.UseGoogleAuthentication(new GoogleOptions
{
ClientId = "[ClientId]",
ClientSecret = "[ClientSecret]",
AccessType = "offline",
Events = new OAuthEvents()
{
OnCreatingTicket = TestGoogleEvents.OnCreatingTicket,
OnTicketReceived = TestGoogleEvents.OnTicketReceived,
OnRedirectToAuthorizationEndpoint = TestGoogleEvents.RedirectToAuthorizationEndpoint
},
StateDataFormat = new CustomStateDataFormat(),
BackchannelHttpHandler = new GoogleMockBackChannelHttpHandler()
});
app.UseTwitterAuthentication(new TwitterOptions
{
ConsumerKey = "[ConsumerKey]",
ConsumerSecret = "[ConsumerSecret]",
Events = new TwitterEvents()
{
OnCreatingTicket = TestTwitterEvents.OnCreatingTicket,
OnTicketReceived = TestTwitterEvents.OnTicketReceived,
OnRedirectToAuthorizationEndpoint = TestTwitterEvents.RedirectToAuthorizationEndpoint
},
StateDataFormat = new CustomTwitterStateDataFormat(),
BackchannelHttpHandler = new TwitterMockBackChannelHttpHandler()
});
app.UseMicrosoftAccountAuthentication(new MicrosoftAccountOptions
{
DisplayName = "MicrosoftAccount - Requires project changes",
ClientId = "[ClientId]",
ClientSecret = "[ClientSecret]",
Events = new OAuthEvents()
{
OnCreatingTicket = TestMicrosoftAccountEvents.OnCreatingTicket,
OnTicketReceived = TestMicrosoftAccountEvents.OnTicketReceived,
OnRedirectToAuthorizationEndpoint = TestMicrosoftAccountEvents.RedirectToAuthorizationEndpoint
},
BackchannelHttpHandler = new MicrosoftAccountMockBackChannelHandler(),
StateDataFormat = new CustomStateDataFormat(),
Scope = { "wl.basic", "wl.signin" }
});
// Add MVC to the request pipeline
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller}/{action}",
defaults: new { action = "Index" });
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(
name: "api",
template: "{controller}/{id?}");
});
//Populates the MusicStore sample data
SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceBus
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for QueuesOperations.
/// </summary>
public static partial class QueuesOperationsExtensions
{
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
public static IPage<QueueResource> ListAll(this IQueuesOperations operations, string resourceGroupName, string namespaceName)
{
return operations.ListAllAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<QueueResource>> ListAllAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a Service Bus queue. This operation is idempotent.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639395.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update a queue resource.
/// </param>
public static QueueResource CreateOrUpdate(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, QueueCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, queueName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a Service Bus queue. This operation is idempotent.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639395.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create or update a queue resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<QueueResource> CreateOrUpdateAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, QueueCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a queue from the specified namespace in a resource group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639411.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
public static void Delete(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName)
{
operations.DeleteAsync(resourceGroupName, namespaceName, queueName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a queue from the specified namespace in a resource group.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639411.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns a description for the specified queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639380.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
public static QueueResource Get(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName)
{
return operations.GetAsync(resourceGroupName, namespaceName, queueName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a description for the specified queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639380.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<QueueResource> GetAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName)
{
return operations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName, queueName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates an authorization rule for a queue.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates an authorization rule for a queue.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a queue authorization rule.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705609.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
public static void DeleteAuthorizationRule(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName)
{
operations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a queue authorization rule.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705609.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets an authorization rule for a queue by rule name.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705611.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName)
{
return operations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets an authorization rule for a queue by rule name.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705611.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Primary and secondary connection strings to the queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705608.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
public static ResourceListKeys ListKeys(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName)
{
return operations.ListKeysAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName).GetAwaiter().GetResult();
}
/// <summary>
/// Primary and secondary connection strings to the queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705608.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceListKeys> ListKeysAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the primary or secondary connection strings to the queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705606.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the authorization rule.
/// </param>
public static ResourceListKeys RegenerateKeys(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, RegenerateKeysParameters parameters)
{
return operations.RegenerateKeysAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the primary or secondary connection strings to the queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705606.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='queueName'>
/// The queue name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationrule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the authorization rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceListKeys> RegenerateKeysAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, RegenerateKeysParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<QueueResource> ListAllNext(this IQueuesOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the queues within a namespace.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<QueueResource>> ListAllNextAsync(this IQueuesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this IQueuesOperations operations, string nextPageLink)
{
return operations.ListAuthorizationRulesNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all authorization rules for a queue.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this IQueuesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Abp.Extensions;
using Abp.Runtime.Session;
namespace Abp.Domain.Uow
{
/// <summary>
/// Base for all Unit Of Work classes.
/// </summary>
public abstract class UnitOfWorkBase : IUnitOfWork
{
public string Id { get; private set; }
public IUnitOfWork Outer { get; set; }
/// <inheritdoc/>
public event EventHandler Completed;
/// <inheritdoc/>
public event EventHandler<UnitOfWorkFailedEventArgs> Failed;
/// <inheritdoc/>
public event EventHandler Disposed;
/// <inheritdoc/>
public UnitOfWorkOptions Options { get; private set; }
/// <inheritdoc/>
public IReadOnlyList<DataFilterConfiguration> Filters
{
get { return _filters.ToImmutableList(); }
}
private readonly List<DataFilterConfiguration> _filters;
/// <summary>
/// Gets default UOW options.
/// </summary>
protected IUnitOfWorkDefaultOptions DefaultOptions { get; private set; }
/// <summary>
/// Gets the connection string resolver.
/// </summary>
protected IConnectionStringResolver ConnectionStringResolver { get; private set; }
/// <summary>
/// Gets a value indicates that this unit of work is disposed or not.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Reference to current ABP session.
/// </summary>
public IAbpSession AbpSession { private get; set; }
/// <summary>
/// Is <see cref="Begin"/> method called before?
/// </summary>
private bool _isBeginCalledBefore;
/// <summary>
/// Is <see cref="Complete"/> method called before?
/// </summary>
private bool _isCompleteCalledBefore;
/// <summary>
/// Is this unit of work successfully completed.
/// </summary>
private bool _succeed;
/// <summary>
/// A reference to the exception if this unit of work failed.
/// </summary>
private Exception _exception;
private int? _tenantId;
/// <summary>
/// Constructor.
/// </summary>
protected UnitOfWorkBase(IConnectionStringResolver connectionStringResolver, IUnitOfWorkDefaultOptions defaultOptions)
{
DefaultOptions = defaultOptions;
ConnectionStringResolver = connectionStringResolver;
Id = Guid.NewGuid().ToString("N");
_filters = defaultOptions.Filters.ToList();
AbpSession = NullAbpSession.Instance;
}
/// <inheritdoc/>
public void Begin(UnitOfWorkOptions options)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
PreventMultipleBegin();
Options = options; //TODO: Do not set options like that, instead make a copy?
SetFilters(options.FilterOverrides);
SetTenantId(AbpSession.TenantId);
BeginUow();
}
/// <inheritdoc/>
public abstract void SaveChanges();
/// <inheritdoc/>
public abstract Task SaveChangesAsync();
/// <inheritdoc/>
public IDisposable DisableFilter(params string[] filterNames)
{
//TODO: Check if filters exists?
var disabledFilters = new List<string>();
foreach (var filterName in filterNames)
{
var filterIndex = GetFilterIndex(filterName);
if (_filters[filterIndex].IsEnabled)
{
disabledFilters.Add(filterName);
_filters[filterIndex] = new DataFilterConfiguration(filterName, false);
}
}
disabledFilters.ForEach(ApplyDisableFilter);
return new DisposeAction(() => EnableFilter(disabledFilters.ToArray()));
}
/// <inheritdoc/>
public IDisposable EnableFilter(params string[] filterNames)
{
//TODO: Check if filters exists?
var enabledFilters = new List<string>();
foreach (var filterName in filterNames)
{
var filterIndex = GetFilterIndex(filterName);
if (!_filters[filterIndex].IsEnabled)
{
enabledFilters.Add(filterName);
_filters[filterIndex] = new DataFilterConfiguration(filterName, true);
}
}
enabledFilters.ForEach(ApplyEnableFilter);
return new DisposeAction(() => DisableFilter(enabledFilters.ToArray()));
}
/// <inheritdoc/>
public bool IsFilterEnabled(string filterName)
{
return GetFilter(filterName).IsEnabled;
}
/// <inheritdoc/>
public IDisposable SetFilterParameter(string filterName, string parameterName, object value)
{
var filterIndex = GetFilterIndex(filterName);
var newfilter = new DataFilterConfiguration(_filters[filterIndex]);
//Store old value
object oldValue = null;
var hasOldValue = newfilter.FilterParameters.ContainsKey(parameterName);
if (hasOldValue)
{
oldValue = newfilter.FilterParameters[parameterName];
}
newfilter.FilterParameters[parameterName] = value;
_filters[filterIndex] = newfilter;
ApplyFilterParameterValue(filterName, parameterName, value);
return new DisposeAction(() =>
{
//Restore old value
if (hasOldValue)
{
SetFilterParameter(filterName, parameterName, oldValue);
}
});
}
public IDisposable SetTenantId(int? tenantId)
{
var oldTenantId = _tenantId;
_tenantId = tenantId;
var mustHaveTenantEnableChange = tenantId == null
? DisableFilter(AbpDataFilters.MustHaveTenant)
: EnableFilter(AbpDataFilters.MustHaveTenant);
var mayHaveTenantChange = SetFilterParameter(AbpDataFilters.MayHaveTenant, AbpDataFilters.Parameters.TenantId, tenantId);
var mustHaveTenantChange = SetFilterParameter(AbpDataFilters.MustHaveTenant, AbpDataFilters.Parameters.TenantId, tenantId ?? 0);
return new DisposeAction(() =>
{
mayHaveTenantChange.Dispose();
mustHaveTenantChange.Dispose();
mustHaveTenantEnableChange.Dispose();
_tenantId = oldTenantId;
});
}
public int? GetTenantId()
{
return _tenantId;
}
/// <inheritdoc/>
public void Complete()
{
PreventMultipleComplete();
try
{
CompleteUow();
_succeed = true;
OnCompleted();
}
catch (Exception ex)
{
_exception = ex;
throw;
}
}
/// <inheritdoc/>
public async Task CompleteAsync()
{
PreventMultipleComplete();
try
{
await CompleteUowAsync();
_succeed = true;
OnCompleted();
}
catch (Exception ex)
{
_exception = ex;
throw;
}
}
/// <inheritdoc/>
public void Dispose()
{
if (IsDisposed)
{
return;
}
IsDisposed = true;
if (!_succeed)
{
OnFailed(_exception);
}
DisposeUow();
OnDisposed();
}
/// <summary>
/// Should be implemented by derived classes to start UOW.
/// </summary>
protected abstract void BeginUow();
/// <summary>
/// Should be implemented by derived classes to complete UOW.
/// </summary>
protected abstract void CompleteUow();
/// <summary>
/// Should be implemented by derived classes to complete UOW.
/// </summary>
protected abstract Task CompleteUowAsync();
/// <summary>
/// Should be implemented by derived classes to dispose UOW.
/// </summary>
protected abstract void DisposeUow();
/// <summary>
/// Concrete Unit of work classes should implement this
/// method in order to disable a filter.
/// Should not call base method since it throws <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="filterName">Filter name</param>
protected virtual void ApplyDisableFilter(string filterName)
{
//throw new NotImplementedException("DisableFilter is not implemented for " + GetType().FullName);
}
/// <summary>
/// Concrete Unit of work classes should implement this
/// method in order to enable a filter.
/// Should not call base method since it throws <see cref="NotImplementedException"/>.
/// </summary>
/// <param name="filterName">Filter name</param>
protected virtual void ApplyEnableFilter(string filterName)
{
//throw new NotImplementedException("EnableFilter is not implemented for " + GetType().FullName);
}
/// <summary>
/// Concrete Unit of work classes should implement this
/// method in order to set a parameter's value.
/// Should not call base method since it throws <see cref="NotImplementedException"/>.
/// </summary>
protected virtual void ApplyFilterParameterValue(string filterName, string parameterName, object value)
{
//throw new NotImplementedException("SetFilterParameterValue is not implemented for " + GetType().FullName);
}
protected virtual string ResolveConnectionString(ConnectionStringResolveArgs args)
{
return ConnectionStringResolver.GetNameOrConnectionString(args);
}
/// <summary>
/// Called to trigger <see cref="Completed"/> event.
/// </summary>
protected virtual void OnCompleted()
{
Completed.InvokeSafely(this);
}
/// <summary>
/// Called to trigger <see cref="Failed"/> event.
/// </summary>
/// <param name="exception">Exception that cause failure</param>
protected virtual void OnFailed(Exception exception)
{
Failed.InvokeSafely(this, new UnitOfWorkFailedEventArgs(exception));
}
/// <summary>
/// Called to trigger <see cref="Disposed"/> event.
/// </summary>
protected virtual void OnDisposed()
{
Disposed.InvokeSafely(this);
}
private void PreventMultipleBegin()
{
if (_isBeginCalledBefore)
{
throw new AbpException("This unit of work has started before. Can not call Start method more than once.");
}
_isBeginCalledBefore = true;
}
private void PreventMultipleComplete()
{
if (_isCompleteCalledBefore)
{
throw new AbpException("Complete is called before!");
}
_isCompleteCalledBefore = true;
}
private void SetFilters(List<DataFilterConfiguration> filterOverrides)
{
for (var i = 0; i < _filters.Count; i++)
{
var filterOverride = filterOverrides.FirstOrDefault(f => f.FilterName == _filters[i].FilterName);
if (filterOverride != null)
{
_filters[i] = filterOverride;
}
}
if (AbpSession.TenantId == null)
{
ChangeFilterIsEnabledIfNotOverrided(filterOverrides, AbpDataFilters.MustHaveTenant, false);
}
}
private void ChangeFilterIsEnabledIfNotOverrided(List<DataFilterConfiguration> filterOverrides, string filterName, bool isEnabled)
{
if (filterOverrides.Any(f => f.FilterName == filterName))
{
return;
}
var index = _filters.FindIndex(f => f.FilterName == filterName);
if (index < 0)
{
return;
}
if (_filters[index].IsEnabled == isEnabled)
{
return;
}
_filters[index] = new DataFilterConfiguration(filterName, isEnabled);
}
private DataFilterConfiguration GetFilter(string filterName)
{
var filter = _filters.FirstOrDefault(f => f.FilterName == filterName);
if (filter == null)
{
throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before.");
}
return filter;
}
private int GetFilterIndex(string filterName)
{
var filterIndex = _filters.FindIndex(f => f.FilterName == filterName);
if (filterIndex < 0)
{
throw new AbpException("Unknown filter name: " + filterName + ". Be sure this filter is registered before.");
}
return filterIndex;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.PetstoreV2AllSync
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SwaggerPetstoreV2.
/// </summary>
public static partial class SwaggerPetstoreV2Extensions
{
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body)
{
return operations.AddPetAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<Pet> AddPetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.AddPetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body)
{
operations.UpdatePetAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse UpdatePetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.UpdatePetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
public static IList<Pet> FindPetsByStatus(this ISwaggerPetstoreV2 operations, IList<string> status)
{
return operations.FindPetsByStatusAsync(status).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, IList<string> status, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<IList<Pet>> FindPetsByStatusWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<string> status, Dictionary<string, List<string>> customHeaders = null)
{
return operations.FindPetsByStatusWithHttpMessagesAsync(status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
public static IList<Pet> FindPetsByTags(this ISwaggerPetstoreV2 operations, IList<string> tags)
{
return operations.FindPetsByTagsAsync(tags).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, IList<string> tags, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<IList<Pet>> FindPetsByTagsWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<string> tags, Dictionary<string, List<string>> customHeaders = null)
{
return operations.FindPetsByTagsWithHttpMessagesAsync(tags, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long petId)
{
return operations.GetPetByIdAsync(petId).GetAwaiter().GetResult();
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<Pet> GetPetByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetPetByIdWithHttpMessagesAsync(petId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string))
{
operations.UpdatePetWithFormAsync(petId, fileContent, fileName, status).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse UpdatePetWithFormWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null)
{
return operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
public static void DeletePet(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "")
{
operations.DeletePetAsync(petId, apiKey).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse DeletePetWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null)
{
return operations.DeletePetWithHttpMessagesAsync(petId, apiKey, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IDictionary<string, int?> GetInventory(this ISwaggerPetstoreV2 operations)
{
return operations.GetInventoryAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<IDictionary<string, int?>> GetInventoryWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetInventoryWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body)
{
return operations.PlaceOrderAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<Order> PlaceOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, Order body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.PlaceOrderWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId)
{
return operations.GetOrderByIdAsync(orderId).GetAwaiter().GetResult();
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<Order> GetOrderByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetOrderByIdWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId)
{
operations.DeleteOrderAsync(orderId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse DeleteOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary<string, List<string>> customHeaders = null)
{
return operations.DeleteOrderWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
public static void CreateUser(this ISwaggerPetstoreV2 operations, User body)
{
operations.CreateUserAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse CreateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, User body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.CreateUserWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, IList<User> body)
{
operations.CreateUsersWithArrayInputAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse CreateUsersWithArrayInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<User> body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, IList<User> body)
{
operations.CreateUsersWithListInputAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse CreateUsersWithListInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<User> body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.CreateUsersWithListInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password)
{
return operations.LoginUserAsync(username, password).GetAwaiter().GetResult();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<string,LoginUserHeaders> LoginUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, string password, Dictionary<string, List<string>> customHeaders = null)
{
return operations.LoginUserWithHttpMessagesAsync(username, password, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void LogoutUser(this ISwaggerPetstoreV2 operations)
{
operations.LogoutUserAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task LogoutUserAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse LogoutUserWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary<string, List<string>> customHeaders = null)
{
return operations.LogoutUserWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username)
{
return operations.GetUserByNameAsync(username).GetAwaiter().GetResult();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<User> GetUserByNameWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetUserByNameWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body)
{
operations.UpdateUserAsync(username, body).GetAwaiter().GetResult();
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse UpdateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, User body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.UpdateUserWithHttpMessagesAsync(username, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username)
{
operations.DeleteUserAsync(username).GetAwaiter().GetResult();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse DeleteUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary<string, List<string>> customHeaders = null)
{
return operations.DeleteUserWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using System.Security.Principal;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using infiny;
using infiny.Models;
using infiny.Services;
namespace infiny.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
}
//
// GET: /Account/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["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);
}
//
// GET: /Account/RemoveLogin
[HttpGet]
public async Task<IActionResult> RemoveLogin()
{
var user = await GetCurrentUserAsync();
var linkedAccounts = await _userManager.GetLoginsAsync(user);
ViewData["ShowRemoveButton"] = await _userManager.HasPasswordAsync(user) || linkedAccounts.Count > 1;
return View(linkedAccounts);
}
//
// 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(nameof(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);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
}
return RedirectToAction(nameof(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(nameof(Index), "Manage");
}
//
// GET: /Account/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
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(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// GET: /Account/RemovePhoneNumber
[HttpGet]
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
[HttpGet]
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(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
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(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Account/Manage
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["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 otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult 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, User.GetUserId());
return new ChallengeResult(provider, properties);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId());
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<bool> HasPhoneNumber()
{
var user = await _userManager.FindByIdAsync(User.GetUserId());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(Context.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), nameof(HomeController));
}
}
#endregion
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="UrlHandler.cs" company="The Watcher">
// Copyright (c) The Watcher Partial Rights Reserved.
// This software is licensed under the MIT license. See license.txt for details.
// </copyright>
// <summary>
// Code Named: VG-Ripper
// Function : Extracts Images posted on RiP forums and attempts to fetch them to disk.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Ripper
{
using System;
using Ripper.Core.Components;
/// <summary>
/// Class to Convert rip URLs in to xml url
/// </summary>
public class UrlHandler
{
/// <summary>
/// Parse Xml Job Url back to html url
/// </summary>
/// <param name="inputUrl">
/// The Input Url.
/// </param>
/// <returns>
/// Returns the Html URL
/// </returns>
public static string GetHtmlUrl(string inputUrl)
{
return inputUrl.Contains("getSTDpost-imgXML.php?dpver=2&threadid")
? inputUrl.Replace("getSTDpost-imgXML.php?dpver=2&threadid=", "showthread.php?t=")
: inputUrl.Replace("getSTDpost-imgXML.php?dpver=2&postid=", "showpost.php?p=");
}
/// <summary>
/// Parse Job Url or ID to Xml Url
/// </summary>
/// <param name="inputUrl">
/// The Input Url.
/// </param>
/// <param name="comboBoxValue">
/// The Combo Box Value.
/// </param>
/// <returns>
/// Xml Url
/// </returns>
public static string GetXmlUrl(string inputUrl, int comboBoxValue)
{
string xmlUrl;
switch (comboBoxValue)
{
case 0:
{
xmlUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&threadid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(inputUrl));
break;
}
case 1:
{
xmlUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&postid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(inputUrl));
break;
}
default:
{
xmlUrl = inputUrl;
// Make sure url starts with http://
if (xmlUrl.IndexOf("http://") != 0)
{
return string.Empty;
}
/*Old VB Forums 3.x
sXmlUrl = sXmlUrl.Replace("showthread.php?t=", "getSTDpost-imgXML.php?dpver=2&threadid=");
sXmlUrl = sXmlUrl.Replace("showthread.php?goto=newpost&t=", "getSTDpost-imgXML.php?dpver=2&threadid=");
sXmlUrl = sXmlUrl.Replace("showthread.php?p=", "getSTDpost-imgXML.php?dpver=2&postid=");*/
// Old VB Forums 3.x
if (xmlUrl.Contains("showthread.php?t="))
{
// Threads
xmlUrl = xmlUrl.Replace("showthread.php?t=", "getSTDpost-imgXML.php?dpver=2&threadid=");
}
else if (xmlUrl.Contains("showpost.php?p="))
{
// Posts
xmlUrl = xmlUrl.Replace("showpost.php?p=", "getSTDpost-imgXML.php?dpver=2&postid=");
}
else if (!xmlUrl.Contains("#post") && xmlUrl.Contains("showthread.php?"))
{
// New VB Forums 4.x
// http://vipergirls.to/showthread.php?0123456-Thread-Title
// Threads
var threadId = xmlUrl.Substring(xmlUrl.IndexOf(".php?") + 5);
if (xmlUrl.Contains("-"))
{
threadId = threadId.Remove(threadId.IndexOf("-"));
}
xmlUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&threadid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(threadId));
}
else if (xmlUrl.Contains("goto=newpost") && xmlUrl.Contains("showthread.php?"))
{
// http://vipergirls.to/showthread.php?0123456-Thread-Title&goto=newpost#post12345
// Threads
var threadId = xmlUrl.Substring(xmlUrl.IndexOf(".php?") + 5);
if (xmlUrl.Contains("-"))
{
threadId = threadId.Remove(threadId.IndexOf("-"));
}
xmlUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&threadid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(threadId));
}
else if (xmlUrl.Contains("&p=") && xmlUrl.Contains("#post"))
{
// http://vipergirls.to/showthread.php?0123456-Thread-Title&p=123456&viewfull=1#post123456
// Posts
var postId = xmlUrl.Substring(xmlUrl.IndexOf("#post") + 5);
xmlUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&postid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(postId));
}
else if (!xmlUrl.Contains(".php") && !xmlUrl.Contains("#post"))
{
// http://vipergirls.to/subforumname/01234-threadtitle.html
// Threads
var threadId = xmlUrl.Substring(xmlUrl.LastIndexOf("/", StringComparison.Ordinal) + 1);
if (xmlUrl.Contains("-"))
{
threadId = threadId.Remove(threadId.IndexOf("-"));
}
xmlUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&threadid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(threadId));
}
else if (!xmlUrl.Contains(".php") && xmlUrl.Contains("#post"))
{
// Posts
var postId = xmlUrl.Substring(xmlUrl.IndexOf("#post") + 5);
xmlUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&postid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(postId));
}
break;
}
}
return xmlUrl;
}
/// <summary>
/// Get the Index Url
/// </summary>
/// <param name="inputUrl">
/// The input url.
/// </param>
/// <returns>
/// Returns the Index Url
/// </returns>
public static string GetIndexUrl(string inputUrl)
{
var newUrl = inputUrl;
if (newUrl.Contains("showthread.php?t="))
{
// Threads
newUrl = newUrl.Replace("showthread.php?t=", "getSTDpost-imgXML.php?dpver=2&threadid=");
}
else if (newUrl.Contains("showpost.php?p="))
{
// Posts
newUrl = newUrl.Replace("showpost.php?p=", "getSTDpost-imgXML.php?dpver=2&postid=");
}
else if (!newUrl.Contains("#post") && newUrl.Contains("showthread.php?"))
{
// Threads
string sThreadId = newUrl.Substring(newUrl.IndexOf(".php?") + 5);
if (newUrl.Contains("-"))
{
sThreadId = sThreadId.Remove(sThreadId.IndexOf("-"));
}
newUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&threadid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(sThreadId));
}
else if (newUrl.Contains("goto=newpost") && newUrl.Contains("showthread.php?"))
{
// Threads
string sThreadId = newUrl.Substring(newUrl.IndexOf(".php?") + 5);
if (newUrl.Contains("-"))
{
sThreadId = sThreadId.Remove(sThreadId.IndexOf("-"));
}
newUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&threadid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(sThreadId));
}
else if (newUrl.Contains("&p=") && newUrl.Contains("#post"))
{
// Posts
string sPostId = newUrl.Substring(newUrl.IndexOf("#post") + 5);
newUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&postid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(sPostId));
}
else if (!newUrl.Contains(".php") && !newUrl.Contains("#post"))
{
// Threads
string sThreadId = newUrl.Substring(newUrl.LastIndexOf("/", StringComparison.Ordinal) + 1);
if (newUrl.Contains("-"))
{
sThreadId = sThreadId.Remove(sThreadId.IndexOf("-"));
}
newUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&threadid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(sThreadId));
}
else if (!newUrl.Contains(".php") && newUrl.Contains("#post"))
{
// Posts
string sPostId = newUrl.Substring(newUrl.IndexOf("#post") + 5);
newUrl = string.Format(
"{0}getSTDpost-imgXML.php?dpver=2&postid={1}",
CacheController.Instance().UserSettings.ForumURL,
Convert.ToInt64(sPostId));
}
return newUrl;
}
}
}
| |
// Copyright (c) 2015 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using SIL.PlatformUtilities;
namespace SIL.Windows.Forms.GeckoBrowserAdapter
{
public static class NativeReplacements
{
private static Assembly _monoWinFormsAssembly;
// internal mono WinForms type
private static Type _xplatUIX11;
// internal mono WinForms type
private static Type _xplatUI;
// internal mono WinForms type
private static Type _hwnd;
// internal mono WinForms type
private static Type _X11Keyboard;
internal static Assembly MonoWinFormsAssembly
{
get
{
if (_monoWinFormsAssembly == null)
#pragma warning disable 0618 // Using Obsolete method LoadWithPartialName.
_monoWinFormsAssembly = Assembly.LoadWithPartialName("System.Windows.Forms");
#pragma warning restore 0618
return _monoWinFormsAssembly;
}
}
private static Type XplatUIX11
{
get
{
if (_xplatUIX11 == null)
_xplatUIX11 = MonoWinFormsAssembly.GetType("System.Windows.Forms.XplatUIX11");
return _xplatUIX11;
}
}
private static Type XplatUI
{
get
{
if (_xplatUI == null)
_xplatUI = MonoWinFormsAssembly.GetType("System.Windows.Forms.XplatUI");
return _xplatUI;
}
}
private static Type Hwnd
{
get
{
if (_hwnd == null)
_hwnd = MonoWinFormsAssembly.GetType("System.Windows.Forms.Hwnd");
return _hwnd;
}
}
private static Type X11Keyboard
{
get
{
if (_X11Keyboard == null)
_X11Keyboard = MonoWinFormsAssembly.GetType("System.Windows.Forms.X11Keyboard");
return _X11Keyboard;
}
}
#region keyboard
/// <summary>
/// Sets XplatUI.State.ModifierKeys, which is what the Control.ModifierKeys WinForm property returns.
/// </summary>
public static void SetKeyStateTable(int virtualKey, byte value)
{
var keyboard = XplatUIX11.GetField("Keyboard",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (keyboard == null)
return;
var key_state_table = X11Keyboard.GetField("key_state_table", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (key_state_table == null)
return;
var b = (byte[])key_state_table.GetValue(keyboard.GetValue(null));
b[virtualKey] = value;
key_state_table.SetValue(keyboard.GetValue(null), b);
}
#endregion
#region GetFocus
/// <summary>
/// Gets the focus.
/// </summary>
/// <returns>
/// The focus.
/// </returns>
public static IntPtr GetFocus()
{
if (Platform.IsWindows)
return WindowsGetFocus();
return MonoGetFocus();
}
/// <summary></summary>
[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "GetFocus")]
static extern IntPtr WindowsGetFocus();
// internal mono WinForms static instance that traces focus
private static FieldInfo _focusWindow;
// internal mono Winforms static instance handle to the X server.
public static FieldInfo _displayHandle;
// internal mono WinForms Hwnd.whole_window
internal static FieldInfo _wholeWindow;
// internal mono WinForms Hwnd.GetHandleFromWindow
internal static MethodInfo _getHandleFromWindow;
// internal mono WinForms method Hwnd.ObjectFromHandle
internal static MethodInfo _objectFromHandle;
/// <summary>
/// Gets mono's internal Focused Window Ptr/Handle.
/// </summary>
public static IntPtr MonoGetFocus()
{
if (_focusWindow == null)
_focusWindow = XplatUIX11.GetField("FocusWindow",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
// Get static field to determine Focused Window.
return (IntPtr)_focusWindow.GetValue(null);
}
/// <summary>
/// Get mono's internal display handle to the X server
/// </summary>
public static IntPtr MonoGetDisplayHandle()
{
if (_displayHandle == null)
_displayHandle = XplatUIX11.GetField("DisplayHandle",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
return (IntPtr)_displayHandle.GetValue(null);
}
private static object GetHwnd(IntPtr handle)
{
// first call call Hwnd.ObjectFromHandle to get the hwnd.
if (_objectFromHandle == null)
_objectFromHandle = Hwnd.GetMethod("ObjectFromHandle", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
return _objectFromHandle.Invoke(null, new object[] { handle });
}
/// <summary>
/// Get an x11 Window Id from a winforms Control handle
/// </summary>
public static IntPtr MonoGetX11Window(IntPtr handle)
{
if (handle == IntPtr.Zero)
return IntPtr.Zero;
object hwnd = GetHwnd(handle);
if (_wholeWindow == null)
_wholeWindow = Hwnd.GetField("whole_window", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
return (IntPtr)_wholeWindow.GetValue(hwnd);
}
/// <summary>
/// Get a WinForm Control/Handle from an x11 Window Id / windowHandle
/// </summary>
/// <returns>
/// The Control Handle or IntPtr.Zero if window id doesn't represent an winforms control.
/// </returns>
/// <param name='windowHandle'>
/// Window handle / x11 Window Id.
/// </param>
public static IntPtr MonoGetHandleFromWindowHandle(IntPtr windowHandle)
{
if (windowHandle == IntPtr.Zero)
return IntPtr.Zero;
if (_getHandleFromWindow == null)
_getHandleFromWindow = Hwnd.GetMethod("GetHandleFromWindow", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
return (IntPtr)_getHandleFromWindow.Invoke(null, new object[] { windowHandle });
}
#endregion
#region SendSetFocusWindowsMessage
public static void SendSetFocusWindowsMessage(Control control, IntPtr fromHandle)
{
if (control == null)
throw new ArgumentNullException("control");
if (control.IsDisposed)
throw new ObjectDisposedException("control");
if (Platform.IsWindows)
NativeSendMessage(control.Handle, WM_SETFOCUS, (int)fromHandle, 0);
else
{
// NativeSendMessage seem to force creation of the control.
if (!control.IsHandleCreated)
control.CreateControl();
try
{
control.Focus();
}
catch
{ /* FB36027 */
}
}
}
public const int WM_SETFOCUS = 0x7;
[DllImport("user32.dll", EntryPoint = "SendMessage")]
static extern int NativeSendMessage(
IntPtr hWnd, // handle to destination window
uint Msg, // message
int wParam, // first message parameter
int lParam // second message parameter
);
#endregion
#region SendMessage
private static MethodInfo _sendMessage;
/// <summary>
/// Please don't use this unless your really have to, and then only if its for sending messages internaly within the application.
/// For example sending WM_NCPAINT maybe portable but sending WM_USER + N to another application is definitely not poratable.
/// </summary>
public static void SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam)
{
if (Platform.IsDotNet)
{
NativeSendMessage(hWnd, Msg, wParam, lParam);
}
else
{
if (_sendMessage == null)
_sendMessage = XplatUI.GetMethod("SendMessage",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static, null, new Type[] { typeof(IntPtr), typeof(int), typeof(IntPtr), typeof(IntPtr) }, null);
_sendMessage.Invoke(null, new object[] { hWnd, (int)Msg, (IntPtr)wParam, (IntPtr)lParam });
}
}
#endregion
#region X window properties methods
public static void SetWmClass(string name, string @class, IntPtr handle)
{
var a = new NativeX11Methods.XClassHint { res_name = Marshal.StringToCoTaskMemAnsi(name), res_class = Marshal.StringToCoTaskMemAnsi(@class) };
IntPtr classHints = Marshal.AllocCoTaskMem(Marshal.SizeOf(a));
Marshal.StructureToPtr(a, classHints, true);
NativeX11Methods.XSetClassHint(NativeReplacements.MonoGetDisplayHandle(), NativeReplacements.MonoGetX11Window(handle), classHints);
Marshal.FreeCoTaskMem(a.res_name);
Marshal.FreeCoTaskMem(a.res_class);
Marshal.FreeCoTaskMem(classHints);
}
/// <summary>
/// Set a winform windows "X group leader" value.
/// By default all mono winform applications get the same group leader (WM_HINTS property)
/// (use xprop to see a windows WM_HINTS values)
/// </summary>
public static void SetGroupLeader(IntPtr handle, IntPtr newValue)
{
var x11Handle = MonoGetX11Window(handle);
IntPtr ptr = NativeX11Methods.XGetWMHints(NativeReplacements.MonoGetDisplayHandle(), x11Handle);
var wmhints = (NativeX11Methods.XWMHints)Marshal.PtrToStructure(ptr, typeof(NativeX11Methods.XWMHints));
NativeX11Methods.XFree(ptr);
wmhints.window_group = NativeReplacements.MonoGetX11Window(newValue);
NativeX11Methods.XSetWMHints(NativeReplacements.MonoGetDisplayHandle(), NativeReplacements.MonoGetX11Window(x11Handle), ref wmhints);
}
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using MurphyPA.H2D.Interfaces;
#warning much of this is copy and paste from other Component glyph - which in turn was a copy of State glyph - this needs refactoring of common/repeating code.
/// operation contains extra children - a OperationPortGlyph -
/// to which an OperationPortLinkGlyph can hook.
namespace MurphyPA.H2D.Implementation
{
/// <summary>
/// Summary description for OperationGlyph.
/// </summary>
public class OperationGlyph : GroupGlyphBase, IOperationGlyph
{
Rectangle _Bounds = new Rectangle (10, 10, 150, 150);
public OperationGlyph ()
{
BuildContactPoints ();
}
public OperationGlyph (string id, Rectangle bounds)
: base (id)
{
_Bounds = bounds;
BuildContactPoints ();
}
protected void BuildContactPoints ()
{
int halflen = 5;
int len = halflen * 2;
AddContactPoint (new OperationContactPointGlyph (new Rectangle (_Bounds.X - halflen, _Bounds.Y + _Bounds.Height / 2 - halflen, len, len), this, new OffsetChangedHandler (horizontal_ContactPoint)));
AddContactPoint (new OperationContactPointGlyph (new Rectangle (_Bounds.X + _Bounds.Width - halflen, _Bounds.Y + _Bounds.Height / 2 - halflen, len, len), this, new OffsetChangedHandler (horizontal_ContactPoint)));
AddContactPoint (new OperationContactPointGlyph (new Rectangle (_Bounds.X + _Bounds.Width / 2 - halflen, _Bounds.Y - halflen, len, len), this, new OffsetChangedHandler (vertical_ContactPoint)));
AddContactPoint (new OperationContactPointGlyph (new Rectangle (_Bounds.X + _Bounds.Width / 2 - halflen, _Bounds.Y + _Bounds.Height - halflen, len, len), this, new OffsetChangedHandler (vertical_ContactPoint)));
halflen = 10;
len = halflen * 2;
for (int index = 0; index < 3; index++)
{
IGlyph child = new OperationPortGlyph (new Rectangle (_Bounds.X + len, _Bounds.Y + len + len * index * 2, len, len), this, "Param" + index.ToString ());
child.Parent = this;
}
}
private void horizontal_ContactPoint (IGlyph glyph, OffsetEventArgs offsetEventArgs)
{
if (glyph is IOperationContactPointGlyph)
{
int expectedYPos = _Bounds.Y + _Bounds.Height / 2;
int currentYPos = glyph.Bounds.Y + glyph.Bounds.Height / 2;
offsetEventArgs.Offset = new Point (offsetEventArgs.Offset.X, expectedYPos - currentYPos);
}
}
private void vertical_ContactPoint (IGlyph glyph, OffsetEventArgs offsetEventArgs)
{
if (glyph is IOperationContactPointGlyph)
{
int expectedXPos = _Bounds.X + _Bounds.Width / 2;
int currentXPos = glyph.Bounds.X + glyph.Bounds.Width / 2;
offsetEventArgs.Offset = new Point (expectedXPos - currentXPos, offsetEventArgs.Offset.Y);
}
}
public int CountParentDepth ()
{
int depth = 0;
IGlyph p = _Parent;
while (p != null)
{
depth++;
p = p.Parent;
}
return depth;
}
public Color ComponentColor
{
get
{
int depth = CountParentDepth ();
Color color = _Colors [depth];
return color;
}
}
Color[] _Colors = new Color[] {Color.Blue, Color.Aquamarine, Color.BurlyWood, Color.BlueViolet, Color.MidnightBlue, Color.Moccasin, Color.DarkTurquoise};
public override void Draw (IGraphicsContext gc)
{
int depth = CountParentDepth ();
Color color = _Colors [depth];
Color contactColor = color;
if (Name == null || Name.Trim () == "")
{
color = Color.Red;
}
gc.Color = color;
DrawComponent (gc, _Bounds.Left, _Bounds.Top, _Bounds.Width, _Bounds.Height, 20, 2+depth, color);
gc.Color = contactColor;
gc.Thickness = 2 + depth;
foreach (IGlyph contact in ContactPoints)
{
contact.Draw (gc);
}
foreach (IGlyph child in Children)
{
if (child is IOperationPortGlyph)
{
child.Draw (gc);
}
}
}
protected void DrawComponent (IGraphicsContext g, int x_left, int y_top, int width, int height, int radius, int thickness, Color color)
{
GraphicsPath path = new GraphicsPath ();
path.StartFigure ();
path.AddRectangle (Bounds);
if (Selected)
{
path.AddLine (x_left + 5 + thickness, y_top + height / 2, x_left + 5 + thickness, y_top + radius);
path.AddLine (x_left + 5 + thickness, y_top + 5 + thickness, x_left + 5 + thickness + width / 2, y_top + 5 + thickness);
path.AddLine (x_left + 5 + thickness + width / 2, y_top + 5 + thickness, x_left + 5 + thickness, y_top + 5 + thickness);
}
path.CloseFigure ();
using (Brush brush = new System.Drawing.SolidBrush (color))
{
using (Pen pen = new Pen (brush, thickness))
{
g.DrawPath (pen, path);
if (Name != null && Name.Trim () != "")
{
g.DrawString (Name, brush, radius, new Point (x_left + radius, y_top + 1), false);
}
}
}
}
#region IGlyph Members
public override void MoveTo (Point point)
{
_Bounds.Offset (point.X - _Bounds.X, point.Y - _Bounds.Y);
}
public override void Offset (Point point)
{
_Bounds.Offset (point);
foreach (IGlyph child in _Children)
{
if (!_ContactPoints.Contains (child))
{
ReOffsetChild (child, point);
}
}
foreach (IGlyph contact in _ContactPoints)
{
ReOffsetContactPoint (contact, point);
}
}
#endregion
void ReOffsetContactPoint (int index, Point offset)
{
IGlyph contact = _ContactPoints [index] as IGlyph;
ReOffsetContactPoint (contact, offset);
}
void ReOffsetChild (IGlyph child, Point point)
{
child.Offset (point);
}
protected override void contactPoint_OffsetChanged(IGlyph glyph, OffsetEventArgs offsetEventArgs)
{
Point offset = offsetEventArgs.Offset;
int index = _ContactPoints.IndexOf (glyph);
if (glyph is IOperationPortGlyph)
{
_Bounds.Offset (offset);
foreach (IGlyph contactPoint in ContactPoints)
{
if (contactPoint is IOperationContactPointGlyph)
{
ReOffsetContactPoint (contactPoint, offset);
}
}
}
else
{
switch (index)
{
case 0:
{
_Bounds.X += offset.X;
_Bounds.Width -= offset.X;
_Bounds.Height += offset.Y;
ReOffsetContactPoint (2, offset);
ReOffsetContactPoint (3, offset);
} break;
case 1:
{
_Bounds.Width += offset.X;
_Bounds.Height += offset.Y;
ReOffsetContactPoint (2, offset);
ReOffsetContactPoint (3, offset);
} break;
case 2:
{
_Bounds.Y += offset.Y;
_Bounds.Height -= offset.Y;
_Bounds.Width += offset.X;
ReOffsetContactPoint (0, offset);
ReOffsetContactPoint (1, offset);
} break;
case 3:
{
_Bounds.Height += offset.Y;
_Bounds.Width += offset.X;
ReOffsetContactPoint (0, offset);
ReOffsetContactPoint (1, offset);
} break;
}
}
}
protected override Rectangle GetBounds ()
{
return _Bounds;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.Compute.V1
{
/// <summary>Settings for <see cref="ZonesClient"/> instances.</summary>
public sealed partial class ZonesSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="ZonesSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="ZonesSettings"/>.</returns>
public static ZonesSettings GetDefault() => new ZonesSettings();
/// <summary>Constructs a new <see cref="ZonesSettings"/> object with default settings.</summary>
public ZonesSettings()
{
}
private ZonesSettings(ZonesSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetSettings = existing.GetSettings;
ListSettings = existing.ListSettings;
OnCopy(existing);
}
partial void OnCopy(ZonesSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>ZonesClient.Get</c> and
/// <c>ZonesClient.GetAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>ZonesClient.List</c> and
/// <c>ZonesClient.ListAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="ZonesSettings"/> object.</returns>
public ZonesSettings Clone() => new ZonesSettings(this);
}
/// <summary>
/// Builder class for <see cref="ZonesClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class ZonesClientBuilder : gaxgrpc::ClientBuilderBase<ZonesClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public ZonesSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public ZonesClientBuilder()
{
UseJwtAccessWithScopes = ZonesClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref ZonesClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ZonesClient> task);
/// <summary>Builds the resulting client.</summary>
public override ZonesClient Build()
{
ZonesClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<ZonesClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<ZonesClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private ZonesClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return ZonesClient.Create(callInvoker, Settings);
}
private async stt::Task<ZonesClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return ZonesClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => ZonesClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => ZonesClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => ZonesClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => ComputeRestAdapter.ComputeAdapter;
}
/// <summary>Zones client wrapper, for convenient use.</summary>
/// <remarks>
/// The Zones API.
/// </remarks>
public abstract partial class ZonesClient
{
/// <summary>
/// The default endpoint for the Zones service, which is a host of "compute.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "compute.googleapis.com:443";
/// <summary>The default Zones scopes.</summary>
/// <remarks>
/// The default Zones scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/compute.readonly</description></item>
/// <item><description>https://www.googleapis.com/auth/compute</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/compute.readonly",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
});
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="ZonesClient"/> using the default credentials, endpoint and settings. To
/// specify custom credentials or other settings, use <see cref="ZonesClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="ZonesClient"/>.</returns>
public static stt::Task<ZonesClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new ZonesClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="ZonesClient"/> using the default credentials, endpoint and settings. To
/// specify custom credentials or other settings, use <see cref="ZonesClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="ZonesClient"/>.</returns>
public static ZonesClient Create() => new ZonesClientBuilder().Build();
/// <summary>
/// Creates a <see cref="ZonesClient"/> 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="ZonesSettings"/>.</param>
/// <returns>The created <see cref="ZonesClient"/>.</returns>
internal static ZonesClient Create(grpccore::CallInvoker callInvoker, ZonesSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Zones.ZonesClient grpcClient = new Zones.ZonesClient(callInvoker);
return new ZonesClientImpl(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 Zones client</summary>
public virtual Zones.ZonesClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified Zone resource. Gets a list of available zones by making a list() request.
/// </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 Zone Get(GetZoneRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified Zone resource. Gets a list of available zones by making a list() request.
/// </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<Zone> GetAsync(GetZoneRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the specified Zone resource. Gets a list of available zones by making a list() request.
/// </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<Zone> GetAsync(GetZoneRequest request, st::CancellationToken cancellationToken) =>
GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the specified Zone resource. Gets a list of available zones by making a list() request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="zone">
/// Name of the zone resource to return.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Zone Get(string project, string zone, gaxgrpc::CallSettings callSettings = null) =>
Get(new GetZoneRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)),
}, callSettings);
/// <summary>
/// Returns the specified Zone resource. Gets a list of available zones by making a list() request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="zone">
/// Name of the zone resource to return.
/// </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<Zone> GetAsync(string project, string zone, gaxgrpc::CallSettings callSettings = null) =>
GetAsync(new GetZoneRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
Zone = gax::GaxPreconditions.CheckNotNullOrEmpty(zone, nameof(zone)),
}, callSettings);
/// <summary>
/// Returns the specified Zone resource. Gets a list of available zones by making a list() request.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="zone">
/// Name of the zone resource to return.
/// </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<Zone> GetAsync(string project, string zone, st::CancellationToken cancellationToken) =>
GetAsync(project, zone, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Retrieves the list of Zone resources available to the specified project.
/// </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 pageable sequence of <see cref="Zone"/> resources.</returns>
public virtual gax::PagedEnumerable<ZoneList, Zone> List(ListZonesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves the list of Zone resources available to the specified project.
/// </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 pageable asynchronous sequence of <see cref="Zone"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ZoneList, Zone> ListAsync(ListZonesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Retrieves the list of Zone resources available to the specified project.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="Zone"/> resources.</returns>
public virtual gax::PagedEnumerable<ZoneList, Zone> List(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
List(new ListZonesRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
/// <summary>
/// Retrieves the list of Zone resources available to the specified project.
/// </summary>
/// <param name="project">
/// Project ID for this request.
/// </param>
/// <param name="pageToken">
/// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first
/// page.
/// </param>
/// <param name="pageSize">
/// The size of page to request. The response will not be larger than this, but may be smaller. A value of
/// <c>null</c> or <c>0</c> uses a server-defined page size.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="Zone"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ZoneList, Zone> ListAsync(string project, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) =>
ListAsync(new ListZonesRequest
{
Project = gax::GaxPreconditions.CheckNotNullOrEmpty(project, nameof(project)),
PageToken = pageToken ?? "",
PageSize = pageSize ?? 0,
}, callSettings);
}
/// <summary>Zones client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// The Zones API.
/// </remarks>
public sealed partial class ZonesClientImpl : ZonesClient
{
private readonly gaxgrpc::ApiCall<GetZoneRequest, Zone> _callGet;
private readonly gaxgrpc::ApiCall<ListZonesRequest, ZoneList> _callList;
/// <summary>
/// Constructs a client wrapper for the Zones service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="ZonesSettings"/> used within this client.</param>
public ZonesClientImpl(Zones.ZonesClient grpcClient, ZonesSettings settings)
{
GrpcClient = grpcClient;
ZonesSettings effectiveSettings = settings ?? ZonesSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGet = clientHelper.BuildApiCall<GetZoneRequest, Zone>(grpcClient.GetAsync, grpcClient.Get, effectiveSettings.GetSettings).WithGoogleRequestParam("project", request => request.Project).WithGoogleRequestParam("zone", request => request.Zone);
Modify_ApiCall(ref _callGet);
Modify_GetApiCall(ref _callGet);
_callList = clientHelper.BuildApiCall<ListZonesRequest, ZoneList>(grpcClient.ListAsync, grpcClient.List, effectiveSettings.ListSettings).WithGoogleRequestParam("project", request => request.Project);
Modify_ApiCall(ref _callList);
Modify_ListApiCall(ref _callList);
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_GetApiCall(ref gaxgrpc::ApiCall<GetZoneRequest, Zone> call);
partial void Modify_ListApiCall(ref gaxgrpc::ApiCall<ListZonesRequest, ZoneList> call);
partial void OnConstruction(Zones.ZonesClient grpcClient, ZonesSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC Zones client</summary>
public override Zones.ZonesClient GrpcClient { get; }
partial void Modify_GetZoneRequest(ref GetZoneRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_ListZonesRequest(ref ListZonesRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the specified Zone resource. Gets a list of available zones by making a list() request.
/// </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 Zone Get(GetZoneRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetZoneRequest(ref request, ref callSettings);
return _callGet.Sync(request, callSettings);
}
/// <summary>
/// Returns the specified Zone resource. Gets a list of available zones by making a list() request.
/// </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<Zone> GetAsync(GetZoneRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetZoneRequest(ref request, ref callSettings);
return _callGet.Async(request, callSettings);
}
/// <summary>
/// Retrieves the list of Zone resources available to the specified project.
/// </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 pageable sequence of <see cref="Zone"/> resources.</returns>
public override gax::PagedEnumerable<ZoneList, Zone> List(ListZonesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListZonesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListZonesRequest, ZoneList, Zone>(_callList, request, callSettings);
}
/// <summary>
/// Retrieves the list of Zone resources available to the specified project.
/// </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 pageable asynchronous sequence of <see cref="Zone"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ZoneList, Zone> ListAsync(ListZonesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListZonesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListZonesRequest, ZoneList, Zone>(_callList, request, callSettings);
}
}
public partial class ListZonesRequest : gaxgrpc::IPageRequest
{
/// <inheritdoc/>
public int PageSize
{
get => checked((int)MaxResults);
set => MaxResults = checked((uint)value);
}
}
public partial class ZoneList : gaxgrpc::IPageResponse<Zone>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<Zone> GetEnumerator() => Items.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using Mono.Cecil.Metadata;
namespace Mono.Cecil {
public abstract class TypeSystem {
sealed class CoreTypeSystem : TypeSystem {
public CoreTypeSystem (ModuleDefinition module)
: base (module)
{
}
internal override TypeReference LookupType (string @namespace, string name)
{
var type = LookupTypeDefinition (@namespace, name) ?? LookupTypeForwarded (@namespace, name);
if (type != null)
return type;
throw new NotSupportedException ();
}
TypeReference LookupTypeDefinition (string @namespace, string name)
{
var metadata = module.MetadataSystem;
if (metadata.Types == null)
Initialize (module.Types);
return module.Read (new Row<string, string> (@namespace, name), (row, reader) => {
var types = reader.metadata.Types;
for (int i = 0; i < types.Length; i++) {
if (types [i] == null)
types [i] = reader.GetTypeDefinition ((uint) i + 1);
var type = types [i];
if (type.Name == row.Col2 && type.Namespace == row.Col1)
return type;
}
return null;
});
}
TypeReference LookupTypeForwarded (string @namespace, string name)
{
if (!module.HasExportedTypes)
return null;
var exported_types = module.ExportedTypes;
for (int i = 0; i < exported_types.Count; i++) {
var exported_type = exported_types [i];
if (exported_type.Name == name && exported_type.Namespace == @namespace)
return exported_type.CreateReference ();
}
return null;
}
static void Initialize (object obj)
{
}
}
sealed class CommonTypeSystem : TypeSystem {
AssemblyNameReference corlib;
public CommonTypeSystem (ModuleDefinition module)
: base (module)
{
}
internal override TypeReference LookupType (string @namespace, string name)
{
return CreateTypeReference (@namespace, name);
}
public AssemblyNameReference GetCorlibReference ()
{
if (corlib != null)
return corlib;
const string mscorlib = "mscorlib";
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (reference.Name == mscorlib)
return corlib = reference;
}
corlib = new AssemblyNameReference {
Name = mscorlib,
Version = GetCorlibVersion (),
PublicKeyToken = new byte [] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 },
};
references.Add (corlib);
return corlib;
}
Version GetCorlibVersion ()
{
switch (module.Runtime) {
case TargetRuntime.Net_1_0:
case TargetRuntime.Net_1_1:
return new Version (1, 0, 0, 0);
case TargetRuntime.Net_2_0:
return new Version (2, 0, 0, 0);
case TargetRuntime.Net_4_0:
return new Version (4, 0, 0, 0);
default:
throw new NotSupportedException ();
}
}
TypeReference CreateTypeReference (string @namespace, string name)
{
return new TypeReference (@namespace, name, module, GetCorlibReference ());
}
}
readonly ModuleDefinition module;
TypeReference type_object;
TypeReference type_void;
TypeReference type_bool;
TypeReference type_char;
TypeReference type_sbyte;
TypeReference type_byte;
TypeReference type_int16;
TypeReference type_uint16;
TypeReference type_int32;
TypeReference type_uint32;
TypeReference type_int64;
TypeReference type_uint64;
TypeReference type_single;
TypeReference type_double;
TypeReference type_intptr;
TypeReference type_uintptr;
TypeReference type_string;
TypeReference type_typedref;
TypeSystem (ModuleDefinition module)
{
this.module = module;
}
internal static TypeSystem CreateTypeSystem (ModuleDefinition module)
{
if (module.IsCorlib ())
return new CoreTypeSystem (module);
return new CommonTypeSystem (module);
}
internal abstract TypeReference LookupType (string @namespace, string name);
TypeReference LookupSystemType (ref TypeReference reference, string name, ElementType element_type)
{
lock (module.SyncRoot) {
if (reference != null)
return reference;
var type = LookupType ("System", name);
type.etype = element_type;
return reference = type;
}
}
TypeReference LookupSystemValueType (ref TypeReference typeRef, string name, ElementType element_type)
{
lock (module.SyncRoot) {
if (typeRef != null)
return typeRef;
var type = LookupType ("System", name);
type.etype = element_type;
type.IsValueType = true;
return typeRef = type;
}
}
public IMetadataScope Corlib {
get {
var common = this as CommonTypeSystem;
if (common == null)
return module;
return common.GetCorlibReference ();
}
}
public TypeReference Object {
get { return type_object ?? (LookupSystemType (ref type_object, "Object", ElementType.Object)); }
}
public TypeReference Void {
get { return type_void ?? (LookupSystemType (ref type_void, "Void", ElementType.Void)); }
}
public TypeReference Boolean {
get { return type_bool ?? (LookupSystemValueType (ref type_bool, "Boolean", ElementType.Boolean)); }
}
public TypeReference Char {
get { return type_char ?? (LookupSystemValueType (ref type_char, "Char", ElementType.Char)); }
}
public TypeReference SByte {
get { return type_sbyte ?? (LookupSystemValueType (ref type_sbyte, "SByte", ElementType.I1)); }
}
public TypeReference Byte {
get { return type_byte ?? (LookupSystemValueType (ref type_byte, "Byte", ElementType.U1)); }
}
public TypeReference Int16 {
get { return type_int16 ?? (LookupSystemValueType (ref type_int16, "Int16", ElementType.I2)); }
}
public TypeReference UInt16 {
get { return type_uint16 ?? (LookupSystemValueType (ref type_uint16, "UInt16", ElementType.U2)); }
}
public TypeReference Int32 {
get { return type_int32 ?? (LookupSystemValueType (ref type_int32, "Int32", ElementType.I4)); }
}
public TypeReference UInt32 {
get { return type_uint32 ?? (LookupSystemValueType (ref type_uint32, "UInt32", ElementType.U4)); }
}
public TypeReference Int64 {
get { return type_int64 ?? (LookupSystemValueType (ref type_int64, "Int64", ElementType.I8)); }
}
public TypeReference UInt64 {
get { return type_uint64 ?? (LookupSystemValueType (ref type_uint64, "UInt64", ElementType.U8)); }
}
public TypeReference Single {
get { return type_single ?? (LookupSystemValueType (ref type_single, "Single", ElementType.R4)); }
}
public TypeReference Double {
get { return type_double ?? (LookupSystemValueType (ref type_double, "Double", ElementType.R8)); }
}
public TypeReference IntPtr {
get { return type_intptr ?? (LookupSystemValueType (ref type_intptr, "IntPtr", ElementType.I)); }
}
public TypeReference UIntPtr {
get { return type_uintptr ?? (LookupSystemValueType (ref type_uintptr, "UIntPtr", ElementType.U)); }
}
public TypeReference String {
get { return type_string ?? (LookupSystemType (ref type_string, "String", ElementType.String)); }
}
public TypeReference TypedReference {
get { return type_typedref ?? (LookupSystemValueType (ref type_typedref, "TypedReference", ElementType.TypedByRef)); }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using AgentRalph.CloneCandidateDetection;
using ICSharpCode.NRefactory;
using NUnit.Framework;
namespace AgentRalph.Tests.CloneCandidateDetectionTests
{
[TestFixture]
public class OtherCloneFinderTests
{
private MethodsOnASingleClassCloneFinder cloneFinder;
[SetUp]
public void SetUp()
{
cloneFinder = new MethodsOnASingleClassCloneFinder(new OscillatingExtractMethodExpansionFactory());
}
/// <summary>
/// Note that there are two classes. Their respective Foos and Bars are identical,
/// but the classes themselves do not match. Per the specific type of clone finder
/// we are testing here, which only scans mehods on a single class.
/// </summary>
[Test]
public void RestrictsScopeToDuplicateMembersOnASingleClass()
{
const string codeText =
@"
public class One
{
void Foo()
{
Console.Write(""zippy"");
}
void Bar()
{
Console.Write(""foo"");
}
}
public class Two
{
void Foo()
{
Console.Write(""zippy"");
}
void Bar()
{
Console.Write(""foo"");
}
} ";
var clones = cloneFinder.GetCloneReplacements(codeText).Clones;
PrintClones(clones);
Assert.AreEqual(0, clones.Count, "While the input does have duplicates, they are not however within a single class.");
}
[Test]
public void SimpleCaseOfIdenticalCloneMethods()
{
const string codeText =
@"
public class One
{
void Foo()
{
string str = ""zippy"";
Console.Write(str);
}
void Bar()
{
string str = ""zippy"";
Console.Write(str);
}
} ";
Assert.AreEqual(2,
cloneFinder.GetCloneReplacements(codeText).Clones.Count,
"Expected 2 matches, one for Bar matches Foo, and vice versa.");
}
[Test]
public void WithExtractMethodRefactoring()
{
// Same as above. Just different test data.
const string codeText =
@"
using System;
class FooBar
{
void Foo()
{
Console.WriteLine(""Hello world"");
Console.WriteLine(""2nd line"");
Console.WriteLine(""3rd line"");
Console.WriteLine(""fourth"");
}
void Template()
{
Console.WriteLine(""3rd line"");
}
}";
var replacements = cloneFinder.GetCloneReplacements(codeText);
foreach (var clone in replacements.Clones)
{
Console.WriteLine("---------------------------------");
Console.WriteLine(clone);
}
Assert.AreEqual(1, replacements.Clones.Count);
}
private const string RenameLocalVariableCodeText =
@"
using System;
public class One
{
void Foo()
{
string foo_str = ""zippy"";
Console.Write(foo_str);
}
void Bar()
{
string bar_str = ""zippy"";
Console.Write(bar_str);
}
} ";
[Test]
public void WithRenameLocalVariableRefactoring()
{
cloneFinder.AddRefactoring(new RenameLocalVariableExpansion());
Assert.AreEqual(2,
cloneFinder.GetCloneReplacements(RenameLocalVariableCodeText).Clones.Count,
"Expected 2 matches, one for Bar matches Foo, and vice versa.");
}
[Test]
[Ignore("Since I bundled variable renaming into the match method, this test doesn't make sense. But I'm not sure about doing the match that way, so I'm keeping this test around.")]
[Description("Needs a rename local var refactoring to match.")]
public void WithoutRenameLocalVariableRefactoring()
{
Assert.AreEqual(0,
cloneFinder.GetCloneReplacements(RenameLocalVariableCodeText).Clones.Count,
"Expected 0 matches, as the refactoring was not added.");
}
[Test]
public void MultipleRefactoringsDoNotStepOnEachOther()
{
cloneFinder.AddRefactoring(new RenameLocalVariableExpansion());
Assert.AreEqual(2,
cloneFinder.GetCloneReplacements(RenameLocalVariableCodeText).Clones.Count,
"Expected 2 matches, one for Bar matches Foo, and vice versa.");
}
[Test]
[Description("Demonstrates the extract method processing the children of statements and blocks.")]
public void ScansAstChildren()
{
const string codeText =
@"
using System;
public class CloneInNestedBlock
{
void Foo()
{
double w = 7;
double l = 8;
if (DateTime.Now.Day == 3)
{
Console.WriteLine(""stuff"");
}
double area = l*w;
}
void Bar()
{
Console.WriteLine(""stuff"");
}
}";
var clones = cloneFinder.GetCloneReplacements(codeText).Clones;
PrintClones(clones);
Assert.AreEqual(1, clones.Count, "Bar should be a clone of the body of the if statement.");
var enumeration = codeText.Split(Convert.ToChar("\n"));
Assert.IsTrue(enumeration[clones.First().ReplacementSectionStartLine - 1].Contains(@"Console.WriteLine(""stuff"");"),
"Demonstrates a bug where replacement position did not take the locations of the children into account.");
}
private static void PrintClones(IList<QuickFixInfo> clones)
{
foreach (var clone in clones)
{
Debug.WriteLine(clone + "\n------------------------------");
}
}
[Test]
[Ignore("Needs implementation.")]
[Description("First crack at wiring up Interceptor support.")]
public void CollapsationInterception()
{
const string codeText = @"using System;
public class One
{
private void Foo()
{
int i1 = 7;
int i2 = 9;
Assert.AreEqual(i1, i2);
}
[Template(Interceptor=""Baz"")]
private void Bar(int i1, int i2)
{
Assert.AreEqual(i1, i2);
}
private void Baz(int i1, int i2)
{
Assert.That(i1, Is.EqualTo(i2));
}
}
internal class Template : Attribute
{
public string Interceptor;
}
internal static class Is
{
public static object EqualTo(int s2)
{
throw new NotImplementedException();
}
}
internal static class Assert
{
public static void AreEqual(int s1, int s2)
{
throw new NotImplementedException();
}
public static void That(int s1, object to)
{
throw new NotImplementedException();
}
}";
// The TemplateAttribute on Bar is causing this clone match to fail.
ScanResult scanResult = cloneFinder.GetCloneReplacements(codeText);
Assert.AreEqual(1, scanResult.Clones.Count, "Foo contains a clone of Bar.");
QuickFixInfo clone = scanResult.Clones[0];
Assert.IsTrue(clone.TextForACallToJanga.Contains("Baz"),
"The interceptor attribute should have caused a call to Baz, instead of Bar");
}
[Test]
[Description("For example, AssemblyInfo.cs. Doesn't assert anything. Simply not throwing an exception is all I am looking for here.")]
public void CsFilesWithoutClassesAreOk()
{
const string codeText = @"using System; namespace zippy {}";
cloneFinder.GetCloneReplacements(codeText);
}
[Test]
public void OverloadsDoNotCauseException()
{
const string codeText = @"
public class One
{
void Foo()
{
Console.Write(1);
}
void Foo(object o)
{
Console.Write(o);
}
}";
cloneFinder.GetCloneReplacements(codeText);
}
[Test]
public void AbstractMembersDoNotCauseException()
{
const string codeText = @" abstract class Test030
{
public abstract void Foo();
public abstract void Bar();
}";
ScanResult scanResult = cloneFinder.GetCloneReplacements(codeText);
TestLog.EmbedPlainText("codeText", codeText);
Assert.AreEqual(0, scanResult.Clones.Count, "Abstract methods should not be treated as clones.");
}
[Test][Description("Simply exercises the event by finding the largest extracted method, and printing it.")]
public void ExerciseOnExtractedCandidateEvent()
{
const string codeText = @"
public class CloneInDoWhileBlock
{
void Foo()
{
do
{
int i = 7 + 8;
int j = 9 +10;
Console.WriteLine(i + j);
/* BEGIN */
Console.WriteLine(7);
/* END */
}
while (DateTime.Now < DateTime.Today);
}
private void Bar()
{
Console.WriteLine(7);
Console.WriteLine(7);
Console.WriteLine(7);
}
}";
MethodsOnASingleClassCloneFinder finder = new MethodsOnASingleClassCloneFinder(new OscillatingExtractMethodExpansionFactory());
CloneDesc largest = null;
finder.OnExtractedCandidate += ((sender, args) =>
{
TestLog.EmbedPlainText("Each: ", args.Candidate.PermutatedMethod.Print());
if (largest == null || largest.PermutatedMethod.CountNodes() < args.Candidate.PermutatedMethod.CountNodes())
largest = args.Candidate;
});
finder.GetCloneReplacements(codeText);
TestLog.EmbedPlainText("The largest:", largest.PermutatedMethod.Print());
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using AutoRest.Core.Model;
using AutoRest.Core.Properties;
using AutoRest.Core.Utilities;
using AutoRest.Core.Utilities.Collections;
using static AutoRest.Core.Utilities.DependencyInjection;
namespace AutoRest.Core
{
public class CodeNamer
{
private static readonly IDictionary<char, string> basicLaticCharacters = new Dictionary<char, string>
{
[(char) 32] = "Space",
[(char) 33] = "ExclamationMark",
[(char) 34] = "QuotationMark",
[(char) 35] = "NumberSign",
[(char) 36] = "DollarSign",
[(char) 37] = "PercentSign",
[(char) 38] = "Ampersand",
[(char) 39] = "Apostrophe",
[(char) 40] = "LeftParenthesis",
[(char) 41] = "RightParenthesis",
[(char) 42] = "Asterisk",
[(char) 43] = "PlusSign",
[(char) 44] = "Comma",
[(char) 45] = "HyphenMinus",
[(char) 46] = "FullStop",
[(char) 47] = "Slash",
[(char) 48] = "Zero",
[(char) 49] = "One",
[(char) 50] = "Two",
[(char) 51] = "Three",
[(char) 52] = "Four",
[(char) 53] = "Five",
[(char) 54] = "Six",
[(char) 55] = "Seven",
[(char) 56] = "Eight",
[(char) 57] = "Nine",
[(char) 58] = "Colon",
[(char) 59] = "Semicolon",
[(char) 60] = "LessThanSign",
[(char) 61] = "EqualSign",
[(char) 62] = "GreaterThanSign",
[(char) 63] = "QuestionMark",
[(char) 64] = "AtSign",
[(char) 91] = "LeftSquareBracket",
[(char) 92] = "Backslash",
[(char) 93] = "RightSquareBracket",
[(char) 94] = "CircumflexAccent",
[(char) 96] = "GraveAccent",
[(char) 123] = "LeftCurlyBracket",
[(char) 124] = "VerticalBar",
[(char) 125] = "RightCurlyBracket",
[(char) 126] = "Tilde"
};
public CodeNamer()
{
}
/// <summary>
/// Gets the current code namer instance (using the active context).
/// A subclass should set the singleton on creation of their context.
/// </summary>
public static CodeNamer Instance
=>
Singleton<CodeNamer>.HasInstance
? Singleton<CodeNamer>.Instance
: (Singleton<CodeNamer>.Instance = new CodeNamer());
/// <summary>
/// Gets collection of reserved words.
/// </summary>
public HashSet<string> ReservedWords { get; } = new HashSet<string>();
/// <summary>
/// Formats segments of a string split by underscores or hyphens into "Camel" case strings.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string CamelCase(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
if (name[0] == '_')
// Preserve leading underscores.
{
return '_' + CamelCase(name.Substring(1));
}
return
name.Split('_', '-', ' ')
.Where(s => !string.IsNullOrEmpty(s))
.Select((s, i) => FormatCase(s, i == 0)) // Pass true/toLower for just the first element.
.DefaultIfEmpty("")
.Aggregate(string.Concat);
}
/// <summary>
/// Formats segments of a string split by underscores or hyphens into "Pascal" case.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string PascalCase(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
if (name[0] == '_')
// Preserve leading underscores and treat them like
// uppercase characters by calling 'CamelCase()' on the rest.
{
return '_' + CamelCase(name.Substring(1));
}
return
name.Split('_', '-', ' ')
.Where(s => !string.IsNullOrEmpty(s))
.Select(s => FormatCase(s, false))
.DefaultIfEmpty("")
.Aggregate(string.Concat);
}
/// <summary>
/// Wraps value in quotes and escapes quotes inside.
/// </summary>
/// <param name="value">String to quote</param>
/// <param name="quoteChar">Quote character</param>
/// <param name="escapeChar">Escape character</param>
/// <exception cref="System.ArgumentNullException">Throw when either quoteChar or escapeChar are null.</exception>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public virtual string QuoteValue(string value, string quoteChar = "\"", string escapeChar = "\\")
{
if (quoteChar == null)
{
throw new ArgumentNullException(nameof(quoteChar));
}
if (escapeChar == null)
{
throw new ArgumentNullException(nameof(escapeChar));
}
if (string.IsNullOrWhiteSpace(value))
{
value = string.Empty;
}
return quoteChar + value.Replace(quoteChar, escapeChar + quoteChar) + quoteChar;
}
/// <summary>
/// Returns a quoted string for the given language if applicable.
/// </summary>
/// <param name="defaultValue">Value to quote.</param>
/// <param name="type">Data type.</param>
public virtual string EscapeDefaultValue(string defaultValue, IModelType type)
{
return defaultValue;
}
/// <summary>
/// Formats a string for naming members of an enum using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetEnumMemberName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(name));
}
/// <summary>
/// Formats a string for naming fields using a prefix '_' and VariableName Camel case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetFieldName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return '_' + GetVariableName(name);
}
/// <summary>
/// Formats a string for naming interfaces using a prefix 'I' and Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetInterfaceName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return $"I{PascalCase(RemoveInvalidCharacters(name))}";
}
/// <summary>
/// Formats a string for naming a method using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetMethodName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Operation")));
}
/// <summary>
/// Formats a string for identifying a namespace using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetNamespaceName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharactersNamespace(name));
}
/// <summary>
/// Formats a string for naming method parameters using GetVariableName Camel case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetParameterName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return GetVariableName(GetEscapedReservedName(name, "Parameter"));
}
/// <summary>
/// Formats a string for naming properties using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetPropertyName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Property")));
}
/// <summary>
/// Formats a string for naming a Type or Object using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetTypeName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
}
/// <summary>
/// Formats a string for naming a Method Group using Pascal case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetMethodGroupName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
}
public virtual string GetClientName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model")));
}
/// <summary>
/// Formats a string for naming a local variable using Camel case by default.
/// </summary>
/// <param name="name"></param>
/// <returns>The formatted string.</returns>
public virtual string GetVariableName(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return name;
}
return CamelCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Variable")));
}
/// <summary>
/// Formats a string as upper or lower case. Two-letter inputs that are all upper case are both lowered.
/// Example: ID = > id, Ex => ex
/// </summary>
/// <param name="name"></param>
/// <param name="toLower"></param>
/// <returns>The formatted string.</returns>
private string FormatCase(string name, bool toLower)
{
if (!string.IsNullOrEmpty(name))
{
if ((name.Length < 2) || ((name.Length == 2) && char.IsUpper(name[0]) && char.IsUpper(name[1])))
{
name = toLower ? name.ToLowerInvariant() : name.ToUpperInvariant();
}
else
{
name =
(toLower
? char.ToLowerInvariant(name[0])
: char.ToUpperInvariant(name[0])) + name.Substring(1, name.Length - 1);
}
}
return name;
}
/// <summary>
/// Removes invalid characters from the name. Everything but alpha-numeral, underscore,
/// and dash.
/// </summary>
/// <param name="name">String to parse.</param>
/// <returns>Name with invalid characters removed.</returns>
public virtual string RemoveInvalidCharacters(string name)
{
return GetValidName(name, '_', '-');
}
/// <summary>
/// Removes invalid characters from the namespace. Everything but alpha-numeral, underscore,
/// period, and dash.
/// </summary>
/// <param name="name">String to parse.</param>
/// <returns>Namespace with invalid characters removed.</returns>
protected virtual string RemoveInvalidCharactersNamespace(string name)
{
return GetValidName(name, '_', '-', '.');
}
/// <summary>
/// Gets valid name for the identifier.
/// </summary>
/// <param name="name">String to parse.</param>
/// <param name="allowedCharacters">Allowed characters.</param>
/// <returns>Name with invalid characters removed.</returns>
public virtual string GetValidName(string name, params char[] allowedCharacters)
{
var correctName = RemoveInvalidCharacters(name, allowedCharacters);
// here we have only letters and digits or an empty string
if (string.IsNullOrEmpty(correctName) ||
basicLaticCharacters.ContainsKey(correctName[0]))
{
var sb = new StringBuilder();
foreach (var symbol in name)
{
if (basicLaticCharacters.ContainsKey(symbol))
{
sb.Append(basicLaticCharacters[symbol]);
}
else
{
sb.Append(symbol);
}
}
correctName = RemoveInvalidCharacters(sb.ToString(), allowedCharacters);
}
// if it is still empty string, throw
if (correctName.IsNullOrEmpty())
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName,
name));
}
return correctName;
}
/// <summary>
/// Removes invalid characters from the name.
/// </summary>
/// <param name="name">String to parse.</param>
/// <param name="allowerCharacters">Allowed characters.</param>
/// <returns>Name with invalid characters removed.</returns>
private string RemoveInvalidCharacters(string name, params char[] allowerCharacters)
{
return new string(name.Replace("[]", "Sequence")
.Where(c => char.IsLetterOrDigit(c) || allowerCharacters.Contains(c))
.ToArray());
}
/// <summary>
/// If the provided name is a reserved word in a programming language then the method converts the
/// name by appending the provided appendValue
/// </summary>
/// <param name="name">Name.</param>
/// <param name="appendValue">String to append.</param>
/// <returns>The transformed reserved name</returns>
protected virtual string GetEscapedReservedName(string name, string appendValue)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (appendValue == null)
{
throw new ArgumentNullException("appendValue");
}
if (ReservedWords.Contains(name, StringComparer.OrdinalIgnoreCase))
{
name += appendValue;
}
return name;
}
public virtual string IsNameLegal(string desiredName, IIdentifier whoIsAsking)
{
if (string.IsNullOrWhiteSpace(desiredName))
{
// should have never got to this point with an blank name.
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName,
desiredName));
}
if (ReservedWords.Contains(desiredName))
{
return desiredName;
}
return null; // null == no conflict
}
public virtual IIdentifier IsNameAvailable(string desiredName, HashSet<IIdentifier> reservedNames)
{
// null == name is available
return
reservedNames.FirstOrDefault(
each => each.MyReservedNames.WhereNotNull().Any(name => name.Equals(desiredName)));
}
/// <summary>
/// Returns true when the name comparison is a special case and should not
/// be used to determine name conflicts.
///
/// Override in subclasses so when the model is loaded into the language specific
/// context, the behavior can be stricter than here.
/// </summary>
/// <param name="whoIsAsking">the identifier that is checking to see if there is a conflict</param>
/// <param name="reservedName">the identifier that would normally be reserved.</param>
/// <returns></returns>
public virtual bool IsSpecialCase(IIdentifier whoIsAsking, IIdentifier reservedName)
{
// special case: properties can actually have the same name as a composite type
if (whoIsAsking is Property && reservedName is CompositeType)
{
return true;
}
// special case: parameters can actually have the same name as a method
if (whoIsAsking is Parameter && reservedName is Method)
{
return true;
}
// special case: method groups win
if (whoIsAsking is MethodGroup)
{
return true;
}
return false;
}
public virtual string GetUnique(string desiredName, IIdentifier whoIsAsking,
IEnumerable<IIdentifier> reservedNames, IEnumerable<IIdentifier> siblingNames,
HashSet<string> locallyReservedNames = null)
{
// can't disambiguate on an empty name.
if (string.IsNullOrEmpty(desiredName))
{
return desiredName;
}
var names = new HashSet<IIdentifier>(reservedNames.Where(each => !IsSpecialCase(whoIsAsking, each)));
// is this a legal name? -- add a Qualifier Suffix (ie, Method/Model/Property/etc)
string conflict;
while ((conflict = IsNameLegal(desiredName, whoIsAsking)) != null)
{
desiredName += whoIsAsking.Qualifier;
// todo: gws: log the name change because it conflicted with a reserved word.
// Singleton<Log>.Instance?.Add(new Message {Text = $"todo:{conflict}"});
}
// does it conflict with a type name locally? (add a Qualifier Suffix)
IIdentifier confl;
while (null != (confl = IsNameAvailable(desiredName, names)))
{
desiredName += whoIsAsking.Qualifier;
// todo: gws: log the name change because there was something else named that.
// Singleton<Log>.Instance?.Add(new Message {Text = $"todo:{confl}"});
// reason = string.Format(CultureInfo.InvariantCulture, Resources.NamespaceConflictReasonMessage,desiredName, ...?
}
// special case (corolary): a compositeType can actually have the same name as a property
if (whoIsAsking is CompositeType)
{
siblingNames= siblingNames.Where(each => !(each is Property));
}
if (whoIsAsking is Property)
{
siblingNames = siblingNames.Where(each => !(each is CompositeType));
}
// does it have a sibling collision?
names = new HashSet<IIdentifier>(siblingNames);
var baseName = desiredName;
var suffix = 0;
while (IsNameAvailable(desiredName, names) != null)
{
desiredName = baseName + ++suffix;
}
// is there a collision with any local name we care about?
while (true == locallyReservedNames?.Contains(desiredName))
{
desiredName = baseName + ++suffix;
}
return desiredName;
}
}
}
| |
namespace NotePad__
{
partial class PreferencesForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PreferencesForm));
this.menuListBox = new System.Windows.Forms.ListBox();
this.generalPanel = new System.Windows.Forms.Panel();
this.showStatusBarCheckBox = new System.Windows.Forms.CheckBox();
this.hideTaskBarCheckBox = new System.Windows.Forms.CheckBox();
this.taskBarGroupBox = new System.Windows.Forms.GroupBox();
this.fontCheckBox = new System.Windows.Forms.CheckBox();
this.underlineCheckBox = new System.Windows.Forms.CheckBox();
this.upperCheckBox = new System.Windows.Forms.CheckBox();
this.versionsCheckBox = new System.Windows.Forms.CheckBox();
this.italicCheckBox = new System.Windows.Forms.CheckBox();
this.boldCheckBox = new System.Windows.Forms.CheckBox();
this.documentMapCheckBox = new System.Windows.Forms.CheckBox();
this.findAndReplaceCheckBox = new System.Windows.Forms.CheckBox();
this.pasteCheckBox = new System.Windows.Forms.CheckBox();
this.cutCheckBox = new System.Windows.Forms.CheckBox();
this.copyCheckBox = new System.Windows.Forms.CheckBox();
this.findCheckBox = new System.Windows.Forms.CheckBox();
this.saveCheckBox = new System.Windows.Forms.CheckBox();
this.openCheckBox = new System.Windows.Forms.CheckBox();
this.newCheckBox = new System.Windows.Forms.CheckBox();
this.themeGroupBox = new System.Windows.Forms.GroupBox();
this.customThemeRadioButton = new System.Windows.Forms.RadioButton();
this.darkThemeRadioButton = new System.Windows.Forms.RadioButton();
this.defaultThemeRadioButton = new System.Windows.Forms.RadioButton();
this.label1 = new System.Windows.Forms.Label();
this.backColorButton = new System.Windows.Forms.Button();
this.colorDialog = new System.Windows.Forms.ColorDialog();
this.closeButton = new System.Windows.Forms.Button();
this.languagePanel = new System.Windows.Forms.Panel();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label8 = new System.Windows.Forms.Label();
this.defaultLaguageComboBox = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.commentBlocksColorButton = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.keywordsColorButton = new System.Windows.Forms.Button();
this.label6 = new System.Windows.Forms.Label();
this.defaultLanguageColorButton = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.commentLinesColorButton = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.stringsColorButton = new System.Windows.Forms.Button();
this.othersPanel = new System.Windows.Forms.Panel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label15 = new System.Windows.Forms.Label();
this.bookmarkMarginForeColorButton = new System.Windows.Forms.Button();
this.label10 = new System.Windows.Forms.Label();
this.bookmarkMarginBackColorButton = new System.Windows.Forms.Button();
this.label11 = new System.Windows.Forms.Label();
this.documentMapForeColorButton = new System.Windows.Forms.Button();
this.label12 = new System.Windows.Forms.Label();
this.documentMapBackColorButton = new System.Windows.Forms.Button();
this.label13 = new System.Windows.Forms.Label();
this.numberMarginForeColorButton = new System.Windows.Forms.Button();
this.label14 = new System.Windows.Forms.Label();
this.numberMarginBackColorButton = new System.Windows.Forms.Button();
this.setDefaultButton = new System.Windows.Forms.Button();
this.generalPanel.SuspendLayout();
this.taskBarGroupBox.SuspendLayout();
this.themeGroupBox.SuspendLayout();
this.languagePanel.SuspendLayout();
this.groupBox2.SuspendLayout();
this.othersPanel.SuspendLayout();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// menuListBox
//
this.menuListBox.BackColor = System.Drawing.SystemColors.Control;
this.menuListBox.FormattingEnabled = true;
this.menuListBox.ItemHeight = 16;
this.menuListBox.Items.AddRange(new object[] {
"General",
"Language",
"Others"});
this.menuListBox.Location = new System.Drawing.Point(33, 37);
this.menuListBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.menuListBox.Name = "menuListBox";
this.menuListBox.Size = new System.Drawing.Size(127, 276);
this.menuListBox.TabIndex = 0;
this.menuListBox.SelectedIndexChanged += new System.EventHandler(this.menuListBox_SelectedIndexChanged);
//
// generalPanel
//
this.generalPanel.Controls.Add(this.showStatusBarCheckBox);
this.generalPanel.Controls.Add(this.hideTaskBarCheckBox);
this.generalPanel.Controls.Add(this.taskBarGroupBox);
this.generalPanel.Controls.Add(this.themeGroupBox);
this.generalPanel.Location = new System.Drawing.Point(233, 37);
this.generalPanel.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.generalPanel.Name = "generalPanel";
this.generalPanel.Size = new System.Drawing.Size(548, 277);
this.generalPanel.TabIndex = 1;
this.generalPanel.Visible = false;
//
// showStatusBarCheckBox
//
this.showStatusBarCheckBox.AutoSize = true;
this.showStatusBarCheckBox.Checked = true;
this.showStatusBarCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.showStatusBarCheckBox.Location = new System.Drawing.Point(4, 252);
this.showStatusBarCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.showStatusBarCheckBox.Name = "showStatusBarCheckBox";
this.showStatusBarCheckBox.Size = new System.Drawing.Size(131, 21);
this.showStatusBarCheckBox.TabIndex = 3;
this.showStatusBarCheckBox.Text = "Show status bar";
this.showStatusBarCheckBox.UseVisualStyleBackColor = true;
this.showStatusBarCheckBox.Click += new System.EventHandler(this.showStatusBarCheckBox_Click);
//
// hideTaskBarCheckBox
//
this.hideTaskBarCheckBox.AutoSize = true;
this.hideTaskBarCheckBox.Location = new System.Drawing.Point(255, 252);
this.hideTaskBarCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.hideTaskBarCheckBox.Name = "hideTaskBarCheckBox";
this.hideTaskBarCheckBox.Size = new System.Drawing.Size(114, 21);
this.hideTaskBarCheckBox.TabIndex = 2;
this.hideTaskBarCheckBox.Text = "Hide task bar";
this.hideTaskBarCheckBox.UseVisualStyleBackColor = true;
this.hideTaskBarCheckBox.Click += new System.EventHandler(this.hideTaskBarcheckBox_Click);
//
// taskBarGroupBox
//
this.taskBarGroupBox.Controls.Add(this.fontCheckBox);
this.taskBarGroupBox.Controls.Add(this.underlineCheckBox);
this.taskBarGroupBox.Controls.Add(this.upperCheckBox);
this.taskBarGroupBox.Controls.Add(this.versionsCheckBox);
this.taskBarGroupBox.Controls.Add(this.italicCheckBox);
this.taskBarGroupBox.Controls.Add(this.boldCheckBox);
this.taskBarGroupBox.Controls.Add(this.documentMapCheckBox);
this.taskBarGroupBox.Controls.Add(this.findAndReplaceCheckBox);
this.taskBarGroupBox.Controls.Add(this.pasteCheckBox);
this.taskBarGroupBox.Controls.Add(this.cutCheckBox);
this.taskBarGroupBox.Controls.Add(this.copyCheckBox);
this.taskBarGroupBox.Controls.Add(this.findCheckBox);
this.taskBarGroupBox.Controls.Add(this.saveCheckBox);
this.taskBarGroupBox.Controls.Add(this.openCheckBox);
this.taskBarGroupBox.Controls.Add(this.newCheckBox);
this.taskBarGroupBox.Location = new System.Drawing.Point(255, 4);
this.taskBarGroupBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.taskBarGroupBox.Name = "taskBarGroupBox";
this.taskBarGroupBox.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.taskBarGroupBox.Size = new System.Drawing.Size(276, 241);
this.taskBarGroupBox.TabIndex = 1;
this.taskBarGroupBox.TabStop = false;
this.taskBarGroupBox.Text = "Task Bar";
//
// fontCheckBox
//
this.fontCheckBox.AutoSize = true;
this.fontCheckBox.Checked = true;
this.fontCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.fontCheckBox.Location = new System.Drawing.Point(169, 106);
this.fontCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.fontCheckBox.Name = "fontCheckBox";
this.fontCheckBox.Size = new System.Drawing.Size(58, 21);
this.fontCheckBox.TabIndex = 18;
this.fontCheckBox.Text = "Font";
this.fontCheckBox.UseVisualStyleBackColor = true;
this.fontCheckBox.Visible = false;
this.fontCheckBox.Click += new System.EventHandler(this.fontCheckBox_Click);
//
// underlineCheckBox
//
this.underlineCheckBox.AutoSize = true;
this.underlineCheckBox.Checked = true;
this.underlineCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.underlineCheckBox.Location = new System.Drawing.Point(168, 188);
this.underlineCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.underlineCheckBox.Name = "underlineCheckBox";
this.underlineCheckBox.Size = new System.Drawing.Size(91, 21);
this.underlineCheckBox.TabIndex = 17;
this.underlineCheckBox.Text = "Underline";
this.underlineCheckBox.UseVisualStyleBackColor = true;
this.underlineCheckBox.Visible = false;
this.underlineCheckBox.CheckedChanged += new System.EventHandler(this.underlineCheckBox_CheckedChanged);
//
// upperCheckBox
//
this.upperCheckBox.AutoSize = true;
this.upperCheckBox.Checked = true;
this.upperCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.upperCheckBox.Location = new System.Drawing.Point(20, 188);
this.upperCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.upperCheckBox.Name = "upperCheckBox";
this.upperCheckBox.Size = new System.Drawing.Size(90, 21);
this.upperCheckBox.TabIndex = 14;
this.upperCheckBox.Text = "To Upper";
this.upperCheckBox.UseVisualStyleBackColor = true;
this.upperCheckBox.Click += new System.EventHandler(this.upperCheckBox_Click);
//
// versionsCheckBox
//
this.versionsCheckBox.AutoSize = true;
this.versionsCheckBox.Checked = true;
this.versionsCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.versionsCheckBox.Location = new System.Drawing.Point(20, 214);
this.versionsCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.versionsCheckBox.Name = "versionsCheckBox";
this.versionsCheckBox.Size = new System.Drawing.Size(85, 21);
this.versionsCheckBox.TabIndex = 13;
this.versionsCheckBox.Text = "Versions";
this.versionsCheckBox.UseVisualStyleBackColor = true;
this.versionsCheckBox.Click += new System.EventHandler(this.versionsCheckBox_Click);
//
// italicCheckBox
//
this.italicCheckBox.AutoSize = true;
this.italicCheckBox.Checked = true;
this.italicCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.italicCheckBox.Location = new System.Drawing.Point(168, 161);
this.italicCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.italicCheckBox.Name = "italicCheckBox";
this.italicCheckBox.Size = new System.Drawing.Size(58, 21);
this.italicCheckBox.TabIndex = 16;
this.italicCheckBox.Text = "Italic";
this.italicCheckBox.UseVisualStyleBackColor = true;
this.italicCheckBox.Visible = false;
this.italicCheckBox.Click += new System.EventHandler(this.italicCheckBox_Click);
//
// boldCheckBox
//
this.boldCheckBox.AutoSize = true;
this.boldCheckBox.Checked = true;
this.boldCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.boldCheckBox.Location = new System.Drawing.Point(168, 134);
this.boldCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.boldCheckBox.Name = "boldCheckBox";
this.boldCheckBox.Size = new System.Drawing.Size(58, 21);
this.boldCheckBox.TabIndex = 15;
this.boldCheckBox.Text = "Bold";
this.boldCheckBox.UseVisualStyleBackColor = true;
this.boldCheckBox.Visible = false;
this.boldCheckBox.Click += new System.EventHandler(this.boldCheckBox_Click);
//
// documentMapCheckBox
//
this.documentMapCheckBox.AutoSize = true;
this.documentMapCheckBox.Checked = true;
this.documentMapCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.documentMapCheckBox.Location = new System.Drawing.Point(20, 103);
this.documentMapCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.documentMapCheckBox.Name = "documentMapCheckBox";
this.documentMapCheckBox.Size = new System.Drawing.Size(125, 21);
this.documentMapCheckBox.TabIndex = 12;
this.documentMapCheckBox.Text = "Document map";
this.documentMapCheckBox.UseVisualStyleBackColor = true;
this.documentMapCheckBox.Click += new System.EventHandler(this.documentMapCheckBox_Click);
//
// findAndReplaceCheckBox
//
this.findAndReplaceCheckBox.AutoSize = true;
this.findAndReplaceCheckBox.Checked = true;
this.findAndReplaceCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.findAndReplaceCheckBox.Location = new System.Drawing.Point(20, 161);
this.findAndReplaceCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.findAndReplaceCheckBox.Name = "findAndReplaceCheckBox";
this.findAndReplaceCheckBox.Size = new System.Drawing.Size(141, 21);
this.findAndReplaceCheckBox.TabIndex = 11;
this.findAndReplaceCheckBox.Text = "Find and Replace";
this.findAndReplaceCheckBox.UseVisualStyleBackColor = true;
this.findAndReplaceCheckBox.Click += new System.EventHandler(this.findAndReplaceCheckBox_Click);
//
// pasteCheckBox
//
this.pasteCheckBox.AutoSize = true;
this.pasteCheckBox.Checked = true;
this.pasteCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.pasteCheckBox.Location = new System.Drawing.Point(169, 78);
this.pasteCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.pasteCheckBox.Name = "pasteCheckBox";
this.pasteCheckBox.Size = new System.Drawing.Size(66, 21);
this.pasteCheckBox.TabIndex = 10;
this.pasteCheckBox.Text = "Paste";
this.pasteCheckBox.UseVisualStyleBackColor = true;
this.pasteCheckBox.Click += new System.EventHandler(this.pasteCheckBox_Click);
//
// cutCheckBox
//
this.cutCheckBox.AutoSize = true;
this.cutCheckBox.Checked = true;
this.cutCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.cutCheckBox.Location = new System.Drawing.Point(169, 48);
this.cutCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.cutCheckBox.Name = "cutCheckBox";
this.cutCheckBox.Size = new System.Drawing.Size(51, 21);
this.cutCheckBox.TabIndex = 9;
this.cutCheckBox.Text = "Cut";
this.cutCheckBox.UseVisualStyleBackColor = true;
this.cutCheckBox.Click += new System.EventHandler(this.cutCheckBox_Click);
//
// copyCheckBox
//
this.copyCheckBox.AutoSize = true;
this.copyCheckBox.Checked = true;
this.copyCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.copyCheckBox.Location = new System.Drawing.Point(169, 21);
this.copyCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.copyCheckBox.Name = "copyCheckBox";
this.copyCheckBox.Size = new System.Drawing.Size(62, 21);
this.copyCheckBox.TabIndex = 8;
this.copyCheckBox.Text = "Copy";
this.copyCheckBox.UseVisualStyleBackColor = true;
this.copyCheckBox.Click += new System.EventHandler(this.copyCheckBox_Click);
//
// findCheckBox
//
this.findCheckBox.AutoSize = true;
this.findCheckBox.Checked = true;
this.findCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.findCheckBox.Location = new System.Drawing.Point(20, 132);
this.findCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.findCheckBox.Name = "findCheckBox";
this.findCheckBox.Size = new System.Drawing.Size(57, 21);
this.findCheckBox.TabIndex = 7;
this.findCheckBox.Text = "Find";
this.findCheckBox.UseVisualStyleBackColor = true;
this.findCheckBox.Click += new System.EventHandler(this.findCheckBox_Click);
//
// saveCheckBox
//
this.saveCheckBox.AutoSize = true;
this.saveCheckBox.Checked = true;
this.saveCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.saveCheckBox.Location = new System.Drawing.Point(20, 75);
this.saveCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.saveCheckBox.Name = "saveCheckBox";
this.saveCheckBox.Size = new System.Drawing.Size(62, 21);
this.saveCheckBox.TabIndex = 6;
this.saveCheckBox.Text = "Save";
this.saveCheckBox.UseVisualStyleBackColor = true;
this.saveCheckBox.Click += new System.EventHandler(this.saveCheckBox_Click);
//
// openCheckBox
//
this.openCheckBox.AutoSize = true;
this.openCheckBox.Checked = true;
this.openCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.openCheckBox.Location = new System.Drawing.Point(20, 48);
this.openCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.openCheckBox.Name = "openCheckBox";
this.openCheckBox.Size = new System.Drawing.Size(65, 21);
this.openCheckBox.TabIndex = 5;
this.openCheckBox.Text = "Open";
this.openCheckBox.UseVisualStyleBackColor = true;
this.openCheckBox.Click += new System.EventHandler(this.openCheckBox_Click);
//
// newCheckBox
//
this.newCheckBox.AutoSize = true;
this.newCheckBox.Checked = true;
this.newCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.newCheckBox.Location = new System.Drawing.Point(20, 20);
this.newCheckBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.newCheckBox.Name = "newCheckBox";
this.newCheckBox.Size = new System.Drawing.Size(57, 21);
this.newCheckBox.TabIndex = 4;
this.newCheckBox.Text = "New";
this.newCheckBox.UseVisualStyleBackColor = true;
this.newCheckBox.Click += new System.EventHandler(this.newCheckBox_Click);
//
// themeGroupBox
//
this.themeGroupBox.Controls.Add(this.customThemeRadioButton);
this.themeGroupBox.Controls.Add(this.darkThemeRadioButton);
this.themeGroupBox.Controls.Add(this.defaultThemeRadioButton);
this.themeGroupBox.Controls.Add(this.label1);
this.themeGroupBox.Controls.Add(this.backColorButton);
this.themeGroupBox.Location = new System.Drawing.Point(4, 4);
this.themeGroupBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.themeGroupBox.Name = "themeGroupBox";
this.themeGroupBox.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.themeGroupBox.Size = new System.Drawing.Size(227, 241);
this.themeGroupBox.TabIndex = 0;
this.themeGroupBox.TabStop = false;
this.themeGroupBox.Text = "Theme";
//
// customThemeRadioButton
//
this.customThemeRadioButton.AutoSize = true;
this.customThemeRadioButton.Location = new System.Drawing.Point(23, 106);
this.customThemeRadioButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.customThemeRadioButton.Name = "customThemeRadioButton";
this.customThemeRadioButton.Size = new System.Drawing.Size(124, 21);
this.customThemeRadioButton.TabIndex = 6;
this.customThemeRadioButton.Text = "Custom Theme";
this.customThemeRadioButton.UseVisualStyleBackColor = true;
//
// darkThemeRadioButton
//
this.darkThemeRadioButton.AutoSize = true;
this.darkThemeRadioButton.Location = new System.Drawing.Point(23, 53);
this.darkThemeRadioButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.darkThemeRadioButton.Name = "darkThemeRadioButton";
this.darkThemeRadioButton.Size = new System.Drawing.Size(107, 21);
this.darkThemeRadioButton.TabIndex = 5;
this.darkThemeRadioButton.Text = "Dark Theme";
this.darkThemeRadioButton.UseVisualStyleBackColor = true;
//
// defaultThemeRadioButton
//
this.defaultThemeRadioButton.AutoSize = true;
this.defaultThemeRadioButton.Checked = true;
this.defaultThemeRadioButton.Location = new System.Drawing.Point(23, 25);
this.defaultThemeRadioButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.defaultThemeRadioButton.Name = "defaultThemeRadioButton";
this.defaultThemeRadioButton.Size = new System.Drawing.Size(122, 21);
this.defaultThemeRadioButton.TabIndex = 4;
this.defaultThemeRadioButton.TabStop = true;
this.defaultThemeRadioButton.Text = "Default Theme";
this.defaultThemeRadioButton.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(19, 142);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(121, 17);
this.label1.TabIndex = 1;
this.label1.Text = "Background Color";
//
// backColorButton
//
this.backColorButton.BackColor = System.Drawing.Color.White;
this.backColorButton.Location = new System.Drawing.Point(149, 135);
this.backColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.backColorButton.Name = "backColorButton";
this.backColorButton.Size = new System.Drawing.Size(55, 28);
this.backColorButton.TabIndex = 0;
this.backColorButton.UseVisualStyleBackColor = false;
this.backColorButton.Click += new System.EventHandler(this.backColorDialogButton_Click);
//
// closeButton
//
this.closeButton.Location = new System.Drawing.Point(343, 358);
this.closeButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.closeButton.Name = "closeButton";
this.closeButton.Size = new System.Drawing.Size(100, 28);
this.closeButton.TabIndex = 2;
this.closeButton.Text = "Close";
this.closeButton.UseVisualStyleBackColor = true;
this.closeButton.Click += new System.EventHandler(this.closeButton_Click);
//
// languagePanel
//
this.languagePanel.Controls.Add(this.groupBox2);
this.languagePanel.Location = new System.Drawing.Point(808, 37);
this.languagePanel.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.languagePanel.Name = "languagePanel";
this.languagePanel.Size = new System.Drawing.Size(311, 277);
this.languagePanel.TabIndex = 3;
this.languagePanel.Visible = false;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.label8);
this.groupBox2.Controls.Add(this.defaultLaguageComboBox);
this.groupBox2.Controls.Add(this.label7);
this.groupBox2.Controls.Add(this.commentBlocksColorButton);
this.groupBox2.Controls.Add(this.label5);
this.groupBox2.Controls.Add(this.keywordsColorButton);
this.groupBox2.Controls.Add(this.label6);
this.groupBox2.Controls.Add(this.defaultLanguageColorButton);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Controls.Add(this.commentLinesColorButton);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.stringsColorButton);
this.groupBox2.Location = new System.Drawing.Point(17, 4);
this.groupBox2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.groupBox2.Size = new System.Drawing.Size(273, 241);
this.groupBox2.TabIndex = 0;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Laguage";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(8, 201);
this.label8.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(121, 17);
this.label8.TabIndex = 11;
this.label8.Text = "Default Language";
//
// defaultLaguageComboBox
//
this.defaultLaguageComboBox.FormattingEnabled = true;
this.defaultLaguageComboBox.Items.AddRange(new object[] {
"NormalText",
"C",
"C++",
"C#",
"VB"});
this.defaultLaguageComboBox.Location = new System.Drawing.Point(163, 197);
this.defaultLaguageComboBox.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.defaultLaguageComboBox.Name = "defaultLaguageComboBox";
this.defaultLaguageComboBox.Size = new System.Drawing.Size(101, 24);
this.defaultLaguageComboBox.TabIndex = 10;
this.defaultLaguageComboBox.Text = "NormalText";
this.defaultLaguageComboBox.SelectedIndexChanged += new System.EventHandler(this.defaultLaguageComboBox_SelectedIndexChanged);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(8, 166);
this.label7.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(149, 17);
this.label7.TabIndex = 9;
this.label7.Text = "Comment Blocks Color";
//
// commentBlocksColorButton
//
this.commentBlocksColorButton.BackColor = System.Drawing.Color.DarkGreen;
this.commentBlocksColorButton.Location = new System.Drawing.Point(163, 161);
this.commentBlocksColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.commentBlocksColorButton.Name = "commentBlocksColorButton";
this.commentBlocksColorButton.Size = new System.Drawing.Size(55, 28);
this.commentBlocksColorButton.TabIndex = 8;
this.commentBlocksColorButton.UseVisualStyleBackColor = false;
this.commentBlocksColorButton.Click += new System.EventHandler(this.commentBlocksColorButton_Click);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(8, 60);
this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(106, 17);
this.label5.TabIndex = 7;
this.label5.Text = "Keywords Color";
//
// keywordsColorButton
//
this.keywordsColorButton.BackColor = System.Drawing.Color.Blue;
this.keywordsColorButton.Location = new System.Drawing.Point(163, 54);
this.keywordsColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.keywordsColorButton.Name = "keywordsColorButton";
this.keywordsColorButton.Size = new System.Drawing.Size(55, 28);
this.keywordsColorButton.TabIndex = 6;
this.keywordsColorButton.UseVisualStyleBackColor = false;
this.keywordsColorButton.Click += new System.EventHandler(this.keywordColorButton_Click);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(8, 25);
this.label6.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(90, 17);
this.label6.TabIndex = 5;
this.label6.Text = "Default Color";
//
// defaultLanguageColorButton
//
this.defaultLanguageColorButton.BackColor = System.Drawing.Color.Black;
this.defaultLanguageColorButton.Location = new System.Drawing.Point(163, 18);
this.defaultLanguageColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.defaultLanguageColorButton.Name = "defaultLanguageColorButton";
this.defaultLanguageColorButton.Size = new System.Drawing.Size(55, 28);
this.defaultLanguageColorButton.TabIndex = 4;
this.defaultLanguageColorButton.UseVisualStyleBackColor = false;
this.defaultLanguageColorButton.Click += new System.EventHandler(this.defaultColorButton_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(8, 130);
this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(142, 17);
this.label3.TabIndex = 3;
this.label3.Text = "Comment Lines Color";
//
// commentLinesColorButton
//
this.commentLinesColorButton.BackColor = System.Drawing.Color.Green;
this.commentLinesColorButton.Location = new System.Drawing.Point(163, 124);
this.commentLinesColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.commentLinesColorButton.Name = "commentLinesColorButton";
this.commentLinesColorButton.Size = new System.Drawing.Size(55, 28);
this.commentLinesColorButton.TabIndex = 2;
this.commentLinesColorButton.UseVisualStyleBackColor = false;
this.commentLinesColorButton.Click += new System.EventHandler(this.commentLinesColorButton_Click);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(8, 97);
this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(89, 17);
this.label4.TabIndex = 1;
this.label4.Text = "Strings Color";
//
// stringsColorButton
//
this.stringsColorButton.BackColor = System.Drawing.Color.Brown;
this.stringsColorButton.Location = new System.Drawing.Point(163, 89);
this.stringsColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.stringsColorButton.Name = "stringsColorButton";
this.stringsColorButton.Size = new System.Drawing.Size(55, 28);
this.stringsColorButton.TabIndex = 0;
this.stringsColorButton.UseVisualStyleBackColor = false;
this.stringsColorButton.Click += new System.EventHandler(this.stringsColorButton_Click);
//
// othersPanel
//
this.othersPanel.Controls.Add(this.groupBox1);
this.othersPanel.Location = new System.Drawing.Point(1127, 37);
this.othersPanel.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.othersPanel.Name = "othersPanel";
this.othersPanel.Size = new System.Drawing.Size(365, 277);
this.othersPanel.TabIndex = 4;
this.othersPanel.Visible = false;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label15);
this.groupBox1.Controls.Add(this.bookmarkMarginForeColorButton);
this.groupBox1.Controls.Add(this.label10);
this.groupBox1.Controls.Add(this.bookmarkMarginBackColorButton);
this.groupBox1.Controls.Add(this.label11);
this.groupBox1.Controls.Add(this.documentMapForeColorButton);
this.groupBox1.Controls.Add(this.label12);
this.groupBox1.Controls.Add(this.documentMapBackColorButton);
this.groupBox1.Controls.Add(this.label13);
this.groupBox1.Controls.Add(this.numberMarginForeColorButton);
this.groupBox1.Controls.Add(this.label14);
this.groupBox1.Controls.Add(this.numberMarginBackColorButton);
this.groupBox1.Location = new System.Drawing.Point(17, 4);
this.groupBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.groupBox1.Size = new System.Drawing.Size(325, 241);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Others";
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(8, 201);
this.label15.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(227, 17);
this.label15.TabIndex = 11;
this.label15.Text = "Bookmark margin foreground color";
//
// bookmarkMarginForeColorButton
//
this.bookmarkMarginForeColorButton.BackColor = System.Drawing.Color.Red;
this.bookmarkMarginForeColorButton.Location = new System.Drawing.Point(251, 193);
this.bookmarkMarginForeColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.bookmarkMarginForeColorButton.Name = "bookmarkMarginForeColorButton";
this.bookmarkMarginForeColorButton.Size = new System.Drawing.Size(55, 28);
this.bookmarkMarginForeColorButton.TabIndex = 10;
this.bookmarkMarginForeColorButton.UseVisualStyleBackColor = false;
this.bookmarkMarginForeColorButton.Click += new System.EventHandler(this.bookmarkMarginForeColorButton_Click);
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(8, 166);
this.label10.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(232, 17);
this.label10.TabIndex = 9;
this.label10.Text = "Bookmark margin background color";
//
// bookmarkMarginBackColorButton
//
this.bookmarkMarginBackColorButton.BackColor = System.Drawing.SystemColors.ControlDark;
this.bookmarkMarginBackColorButton.Location = new System.Drawing.Point(251, 160);
this.bookmarkMarginBackColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.bookmarkMarginBackColorButton.Name = "bookmarkMarginBackColorButton";
this.bookmarkMarginBackColorButton.Size = new System.Drawing.Size(55, 28);
this.bookmarkMarginBackColorButton.TabIndex = 8;
this.bookmarkMarginBackColorButton.UseVisualStyleBackColor = false;
this.bookmarkMarginBackColorButton.Click += new System.EventHandler(this.bookmarkMarginBackColorButton_Click);
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(8, 60);
this.label11.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(212, 17);
this.label11.TabIndex = 7;
this.label11.Text = "Document map foreground color";
//
// documentMapForeColorButton
//
this.documentMapForeColorButton.BackColor = System.Drawing.Color.Black;
this.documentMapForeColorButton.Location = new System.Drawing.Point(251, 53);
this.documentMapForeColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.documentMapForeColorButton.Name = "documentMapForeColorButton";
this.documentMapForeColorButton.Size = new System.Drawing.Size(55, 28);
this.documentMapForeColorButton.TabIndex = 6;
this.documentMapForeColorButton.UseVisualStyleBackColor = false;
this.documentMapForeColorButton.Click += new System.EventHandler(this.documentMapForeColorButton_Click);
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(8, 25);
this.label12.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(217, 17);
this.label12.TabIndex = 5;
this.label12.Text = "Document map background color";
//
// documentMapBackColorButton
//
this.documentMapBackColorButton.BackColor = System.Drawing.SystemColors.InactiveBorder;
this.documentMapBackColorButton.Location = new System.Drawing.Point(251, 18);
this.documentMapBackColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.documentMapBackColorButton.Name = "documentMapBackColorButton";
this.documentMapBackColorButton.Size = new System.Drawing.Size(55, 28);
this.documentMapBackColorButton.TabIndex = 4;
this.documentMapBackColorButton.UseVisualStyleBackColor = false;
this.documentMapBackColorButton.Click += new System.EventHandler(this.documentMapBackColorButton_Click);
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(8, 130);
this.label13.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(214, 17);
this.label13.TabIndex = 3;
this.label13.Text = "Number margin foreground color";
//
// numberMarginForeColorButton
//
this.numberMarginForeColorButton.BackColor = System.Drawing.Color.Black;
this.numberMarginForeColorButton.Location = new System.Drawing.Point(251, 123);
this.numberMarginForeColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.numberMarginForeColorButton.Name = "numberMarginForeColorButton";
this.numberMarginForeColorButton.Size = new System.Drawing.Size(55, 28);
this.numberMarginForeColorButton.TabIndex = 2;
this.numberMarginForeColorButton.UseVisualStyleBackColor = false;
this.numberMarginForeColorButton.Click += new System.EventHandler(this.numberMarginForeColorButton_Click);
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(8, 97);
this.label14.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(219, 17);
this.label14.TabIndex = 1;
this.label14.Text = "Number margin background color";
//
// numberMarginBackColorButton
//
this.numberMarginBackColorButton.BackColor = System.Drawing.SystemColors.ControlDark;
this.numberMarginBackColorButton.Location = new System.Drawing.Point(251, 87);
this.numberMarginBackColorButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.numberMarginBackColorButton.Name = "numberMarginBackColorButton";
this.numberMarginBackColorButton.Size = new System.Drawing.Size(55, 28);
this.numberMarginBackColorButton.TabIndex = 0;
this.numberMarginBackColorButton.UseVisualStyleBackColor = false;
this.numberMarginBackColorButton.Click += new System.EventHandler(this.numberMarginBackColorButton_Click);
//
// setDefaultButton
//
this.setDefaultButton.Location = new System.Drawing.Point(451, 358);
this.setDefaultButton.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.setDefaultButton.Name = "setDefaultButton";
this.setDefaultButton.Size = new System.Drawing.Size(127, 28);
this.setDefaultButton.TabIndex = 5;
this.setDefaultButton.Text = "Set As Default";
this.setDefaultButton.UseVisualStyleBackColor = true;
this.setDefaultButton.Click += new System.EventHandler(this.setDefaultButton_Click);
//
// PreferencesForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1508, 401);
this.Controls.Add(this.setDefaultButton);
this.Controls.Add(this.othersPanel);
this.Controls.Add(this.languagePanel);
this.Controls.Add(this.closeButton);
this.Controls.Add(this.generalPanel);
this.Controls.Add(this.menuListBox);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PreferencesForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Preferences";
this.TopMost = true;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.PreferencesForm_FormClosing);
this.Load += new System.EventHandler(this.PreferencesForm_Load);
this.generalPanel.ResumeLayout(false);
this.generalPanel.PerformLayout();
this.taskBarGroupBox.ResumeLayout(false);
this.taskBarGroupBox.PerformLayout();
this.themeGroupBox.ResumeLayout(false);
this.themeGroupBox.PerformLayout();
this.languagePanel.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.othersPanel.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListBox menuListBox;
private System.Windows.Forms.Panel generalPanel;
private System.Windows.Forms.CheckBox showStatusBarCheckBox;
private System.Windows.Forms.CheckBox hideTaskBarCheckBox;
private System.Windows.Forms.GroupBox taskBarGroupBox;
private System.Windows.Forms.GroupBox themeGroupBox;
private System.Windows.Forms.ColorDialog colorDialog;
private System.Windows.Forms.Button closeButton;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button backColorButton;
private System.Windows.Forms.RadioButton defaultThemeRadioButton;
private System.Windows.Forms.RadioButton darkThemeRadioButton;
private System.Windows.Forms.CheckBox findCheckBox;
private System.Windows.Forms.CheckBox saveCheckBox;
private System.Windows.Forms.CheckBox openCheckBox;
private System.Windows.Forms.CheckBox newCheckBox;
private System.Windows.Forms.CheckBox pasteCheckBox;
private System.Windows.Forms.CheckBox cutCheckBox;
private System.Windows.Forms.CheckBox copyCheckBox;
private System.Windows.Forms.CheckBox findAndReplaceCheckBox;
private System.Windows.Forms.CheckBox documentMapCheckBox;
private System.Windows.Forms.CheckBox versionsCheckBox;
private System.Windows.Forms.CheckBox upperCheckBox;
private System.Windows.Forms.CheckBox underlineCheckBox;
private System.Windows.Forms.CheckBox italicCheckBox;
private System.Windows.Forms.CheckBox boldCheckBox;
private System.Windows.Forms.CheckBox fontCheckBox;
private System.Windows.Forms.Panel languagePanel;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button commentLinesColorButton;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button stringsColorButton;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button keywordsColorButton;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Button defaultLanguageColorButton;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Button commentBlocksColorButton;
private System.Windows.Forms.ComboBox defaultLaguageComboBox;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Panel othersPanel;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Button bookmarkMarginBackColorButton;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Button documentMapForeColorButton;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Button documentMapBackColorButton;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Button numberMarginForeColorButton;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Button numberMarginBackColorButton;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Button bookmarkMarginForeColorButton;
private System.Windows.Forms.RadioButton customThemeRadioButton;
private System.Windows.Forms.Button setDefaultButton;
}
}
| |
// Generated by TinyPG v1.3 available at www.codeproject.com
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace TwoMGFX
{
#region Scanner
public partial class Scanner
{
public string Input;
public int StartPos = 0;
public int EndPos = 0;
public string CurrentFile;
public int CurrentLine;
public int CurrentColumn;
public int CurrentPosition;
public List<Token> Skipped; // tokens that were skipped
public Dictionary<TokenType, Regex> Patterns;
private Token LookAheadToken;
private List<TokenType> Tokens;
private List<TokenType> SkipList; // tokens to be skipped
private readonly TokenType FileAndLine;
public Scanner()
{
Regex regex;
Patterns = new Dictionary<TokenType, Regex>();
Tokens = new List<TokenType>();
LookAheadToken = null;
Skipped = new List<Token>();
SkipList = new List<TokenType>();
SkipList.Add(TokenType.BlockComment);
SkipList.Add(TokenType.Comment);
SkipList.Add(TokenType.Whitespace);
SkipList.Add(TokenType.LinePragma);
FileAndLine = TokenType.LinePragma;
regex = new Regex(@"/\*([^*]|\*[^/])*\*/", RegexOptions.Compiled);
Patterns.Add(TokenType.BlockComment, regex);
Tokens.Add(TokenType.BlockComment);
regex = new Regex(@"//[^\n\r]*", RegexOptions.Compiled);
Patterns.Add(TokenType.Comment, regex);
Tokens.Add(TokenType.Comment);
regex = new Regex(@"[ \t\n\r]+", RegexOptions.Compiled);
Patterns.Add(TokenType.Whitespace, regex);
Tokens.Add(TokenType.Whitespace);
regex = new Regex(@"^[ \t]*#line[ \t]*(?<Line>\d*)[ \t]*(\""(?<File>[^\""\\]*(?:\\.[^\""\\]*)*)\"")?\n", RegexOptions.Compiled);
Patterns.Add(TokenType.LinePragma, regex);
Tokens.Add(TokenType.LinePragma);
regex = new Regex(@"pass", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Patterns.Add(TokenType.Pass, regex);
Tokens.Add(TokenType.Pass);
regex = new Regex(@"technique", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Patterns.Add(TokenType.Technique, regex);
Tokens.Add(TokenType.Technique);
regex = new Regex(@"sampler1D|sampler2D|sampler3D|samplerCUBE|sampler", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Patterns.Add(TokenType.Sampler, regex);
Tokens.Add(TokenType.Sampler);
regex = new Regex(@"sampler_state", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Patterns.Add(TokenType.SamplerState, regex);
Tokens.Add(TokenType.SamplerState);
regex = new Regex(@"VertexShader", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Patterns.Add(TokenType.VertexShader, regex);
Tokens.Add(TokenType.VertexShader);
regex = new Regex(@"PixelShader", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Patterns.Add(TokenType.PixelShader, regex);
Tokens.Add(TokenType.PixelShader);
regex = new Regex(@"register", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Patterns.Add(TokenType.Register, regex);
Tokens.Add(TokenType.Register);
regex = new Regex(@"[0-9]?\.?[0-9]+", RegexOptions.Compiled);
Patterns.Add(TokenType.Number, regex);
Tokens.Add(TokenType.Number);
regex = new Regex(@"-|\+", RegexOptions.Compiled);
Patterns.Add(TokenType.Sign, regex);
Tokens.Add(TokenType.Sign);
regex = new Regex(@"[A-Za-z_][A-Za-z0-9_]*", RegexOptions.Compiled);
Patterns.Add(TokenType.Identifier, regex);
Tokens.Add(TokenType.Identifier);
regex = new Regex(@"{", RegexOptions.Compiled);
Patterns.Add(TokenType.OpenBracket, regex);
Tokens.Add(TokenType.OpenBracket);
regex = new Regex(@"}", RegexOptions.Compiled);
Patterns.Add(TokenType.CloseBracket, regex);
Tokens.Add(TokenType.CloseBracket);
regex = new Regex(@"=", RegexOptions.Compiled);
Patterns.Add(TokenType.Equals, regex);
Tokens.Add(TokenType.Equals);
regex = new Regex(@":", RegexOptions.Compiled);
Patterns.Add(TokenType.Colon, regex);
Tokens.Add(TokenType.Colon);
regex = new Regex(@",", RegexOptions.Compiled);
Patterns.Add(TokenType.Comma, regex);
Tokens.Add(TokenType.Comma);
regex = new Regex(@";", RegexOptions.Compiled);
Patterns.Add(TokenType.Semicolon, regex);
Tokens.Add(TokenType.Semicolon);
regex = new Regex(@"\(", RegexOptions.Compiled);
Patterns.Add(TokenType.OpenParenthesis, regex);
Tokens.Add(TokenType.OpenParenthesis);
regex = new Regex(@"\)", RegexOptions.Compiled);
Patterns.Add(TokenType.CloseParenthesis, regex);
Tokens.Add(TokenType.CloseParenthesis);
regex = new Regex(@"\[", RegexOptions.Compiled);
Patterns.Add(TokenType.OpenSquareBracket, regex);
Tokens.Add(TokenType.OpenSquareBracket);
regex = new Regex(@"\]", RegexOptions.Compiled);
Patterns.Add(TokenType.CloseSquareBracket, regex);
Tokens.Add(TokenType.CloseSquareBracket);
regex = new Regex(@"<", RegexOptions.Compiled);
Patterns.Add(TokenType.LessThan, regex);
Tokens.Add(TokenType.LessThan);
regex = new Regex(@">", RegexOptions.Compiled);
Patterns.Add(TokenType.GreaterThan, regex);
Tokens.Add(TokenType.GreaterThan);
regex = new Regex(@"compile", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Patterns.Add(TokenType.Compile, regex);
Tokens.Add(TokenType.Compile);
regex = new Regex(@"(vs_|ps_)(2_0|3_0|4_0|5_0)((_level_)(9_1|9_2|9_3))?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Patterns.Add(TokenType.ShaderModel, regex);
Tokens.Add(TokenType.ShaderModel);
regex = new Regex(@"[\S]+", RegexOptions.Compiled);
Patterns.Add(TokenType.Code, regex);
Tokens.Add(TokenType.Code);
regex = new Regex(@"^$", RegexOptions.Compiled);
Patterns.Add(TokenType.EndOfFile, regex);
Tokens.Add(TokenType.EndOfFile);
}
public void Init(string input, string fileName)
{
this.Input = input;
StartPos = 0;
EndPos = 0;
CurrentFile = fileName;
CurrentLine = 1;
CurrentColumn = 1;
CurrentPosition = 0;
LookAheadToken = null;
}
public Token GetToken(TokenType type)
{
Token t = new Token(this.StartPos, this.EndPos);
t.Type = type;
return t;
}
/// <summary>
/// executes a lookahead of the next token
/// and will advance the scan on the input string
/// </summary>
/// <returns></returns>
public Token Scan(params TokenType[] expectedtokens)
{
Token tok = LookAhead(expectedtokens); // temporarely retrieve the lookahead
LookAheadToken = null; // reset lookahead token, so scanning will continue
StartPos = tok.EndPos;
EndPos = tok.EndPos; // set the tokenizer to the new scan position
CurrentLine = tok.Line + (tok.Text.Length - tok.Text.Replace("\n", "").Length);
CurrentFile = tok.File;
return tok;
}
/// <summary>
/// returns token with longest best match
/// </summary>
/// <returns></returns>
public Token LookAhead(params TokenType[] expectedtokens)
{
int i;
int startpos = StartPos;
int endpos = EndPos;
int currentline = CurrentLine;
string currentFile = CurrentFile;
Token tok = null;
List<TokenType> scantokens;
// this prevents double scanning and matching
// increased performance
if (LookAheadToken != null
&& LookAheadToken.Type != TokenType._UNDETERMINED_
&& LookAheadToken.Type != TokenType._NONE_) return LookAheadToken;
// if no scantokens specified, then scan for all of them (= backward compatible)
if (expectedtokens.Length == 0)
scantokens = Tokens;
else
{
scantokens = new List<TokenType>(expectedtokens);
scantokens.AddRange(SkipList);
}
do
{
int len = -1;
TokenType index = (TokenType)int.MaxValue;
string input = Input.Substring(startpos);
tok = new Token(startpos, endpos);
for (i = 0; i < scantokens.Count; i++)
{
Regex r = Patterns[scantokens[i]];
Match m = r.Match(input);
if (m.Success && m.Index == 0 && ((m.Length > len) || (scantokens[i] < index && m.Length == len )))
{
len = m.Length;
index = scantokens[i];
}
}
if (index >= 0 && len >= 0)
{
tok.EndPos = startpos + len;
tok.Text = Input.Substring(tok.StartPos, len);
tok.Type = index;
}
else if (tok.StartPos < tok.EndPos - 1)
{
tok.Text = Input.Substring(tok.StartPos, 1);
}
// Update the line and column count for error reporting.
tok.File = currentFile;
tok.Line = currentline;
if (tok.StartPos < Input.Length)
tok.Column = tok.StartPos - Input.LastIndexOf('\n', tok.StartPos);
if (SkipList.Contains(tok.Type))
{
startpos = tok.EndPos;
endpos = tok.EndPos;
currentline = tok.Line + (tok.Text.Length - tok.Text.Replace("\n", "").Length);
currentFile = tok.File;
Skipped.Add(tok);
}
else
{
// only assign to non-skipped tokens
tok.Skipped = Skipped; // assign prior skips to this token
Skipped = new List<Token>(); //reset skips
}
// Check to see if the parsed token wants to
// alter the file and line number.
if (tok.Type == FileAndLine)
{
var match = Patterns[tok.Type].Match(tok.Text);
var fileMatch = match.Groups["File"];
if (fileMatch.Success)
currentFile = fileMatch.Value;
var lineMatch = match.Groups["Line"];
if (lineMatch.Success)
currentline = int.Parse(lineMatch.Value);
}
}
while (SkipList.Contains(tok.Type));
LookAheadToken = tok;
return tok;
}
}
#endregion
#region Token
public enum TokenType
{
//Non terminal tokens:
_NONE_ = 0,
_UNDETERMINED_= 1,
//Non terminal tokens:
Start = 2,
Technique_Declaration= 3,
Render_State_Expression= 4,
Pass_Declaration= 5,
VertexShader_Pass_Expression= 6,
PixelShader_Pass_Expression= 7,
Sampler_State_Expression= 8,
Sampler_Register_Expression= 9,
Sampler_Declaration= 10,
//Terminal tokens:
BlockComment= 11,
Comment = 12,
Whitespace= 13,
LinePragma= 14,
Pass = 15,
Technique= 16,
Sampler = 17,
SamplerState= 18,
VertexShader= 19,
PixelShader= 20,
Register= 21,
Number = 22,
Sign = 23,
Identifier= 24,
OpenBracket= 25,
CloseBracket= 26,
Equals = 27,
Colon = 28,
Comma = 29,
Semicolon= 30,
OpenParenthesis= 31,
CloseParenthesis= 32,
OpenSquareBracket= 33,
CloseSquareBracket= 34,
LessThan= 35,
GreaterThan= 36,
Compile = 37,
ShaderModel= 38,
Code = 39,
EndOfFile= 40
}
public class Token
{
private string file;
private int line;
private int column;
private int startpos;
private int endpos;
private string text;
private object value;
// contains all prior skipped symbols
private List<Token> skipped;
public string File {
get { return file; }
set { file = value; }
}
public int Line {
get { return line; }
set { line = value; }
}
public int Column {
get { return column; }
set { column = value; }
}
public int StartPos {
get { return startpos;}
set { startpos = value; }
}
public int Length {
get { return endpos - startpos;}
}
public int EndPos {
get { return endpos;}
set { endpos = value; }
}
public string Text {
get { return text;}
set { text = value; }
}
public List<Token> Skipped {
get { return skipped;}
set { skipped = value; }
}
public object Value {
get { return value;}
set { this.value = value; }
}
[XmlAttribute]
public TokenType Type;
public Token()
: this(0, 0)
{
}
public Token(int start, int end)
{
Type = TokenType._UNDETERMINED_;
startpos = start;
endpos = end;
Text = ""; // must initialize with empty string, may cause null reference exceptions otherwise
Value = null;
}
public void UpdateRange(Token token)
{
if (token.StartPos < startpos) startpos = token.StartPos;
if (token.EndPos > endpos) endpos = token.EndPos;
}
public override string ToString()
{
if (Text != null)
return Type.ToString() + " '" + Text + "'";
else
return Type.ToString();
}
}
#endregion
}
| |
using UnityEngine;
using System.Collections;
using System.Xml;
using System.Collections.Generic;
[RequireComponent(typeof(PrefabDictionary),typeof(ReplayGUI))]
public class ReplayAnalysisEngine : MonoBehaviour {
#region Flags
private bool done = true;
private bool initialized = false;
public bool Initialized {
get {
return initialized;
}
}
private bool running;
public bool Running {
get {
return running;
}
}
private bool addActions;
public bool AddActions {
get {
return addActions;
}
set {
addActions = value;
}
}
private bool takeScreenShot;
public bool TakeScreenShots {
get {
return takeScreenShot;
}
set {
takeScreenShot = value;
}
}
#endregion
#region Iteration Settings
public enum IterationMode {
FinalStates=1,
ActionByAction=2
}
public IterationMode iterationMode = IterationMode.ActionByAction;
private long numberSinceRun = 0;
private long pauseEvery = -1;
public long PauseAfter {
get {
return pauseEvery;
}
set {
if (value <= 0)
pauseEvery = -1;
else
pauseEvery = value;
}
}
#endregion
#region Simulation Settings
public enum StoppingCondition {
Instant=0,
WaitForStop=1,
Time=2,
Custom=3
}
public StoppingCondition stopCondition = StoppingCondition.Instant;
private float timeAcceleraton = 1.0f;
public float TimeAcceleration {
get {
return timeAcceleraton;
}
set {
if (value > 1f)
timeAcceleraton = value;
else
timeAcceleraton = 1f;
}
}
private float timeOut = 20.0f;
public float TimeOut {
get {
return timeOut;
}
set {
if (value > 0)
timeOut = value;
else
timeOut = float.NaN;
}
}
#endregion
#region Component Pointers
private PrefabDictionary dictionary;
private LogReader reader;
private AnalysisWriter writer;
private Calculator calculator;
private ReplayExtender extender;
#endregion
#region Unity Methods
void Awake() {
Logger.Instance.Enabled = false;
}
// Use this for initialization
void Start () {
dictionary = GetComponent<PrefabDictionary>();
reader = GetComponent<LogReader>();
if(reader == null)
Debug.LogError("No LogReader attached to the Replay Analysis Engine.");
calculator = GetComponent<Calculator>();
if (calculator == null)
Debug.LogError("No Calculator attached to the Replay Analysis Engine.");
writer = GetComponent<AnalysisWriter>();
if (writer == null)
Debug.LogError("No LogWriter attached to the Replay Analysis Engine.");
extender = GetComponent<ReplayExtender>();
if (extender == null)
Debug.LogWarning("No ReplayExtender attached to the Replay Analysis Engine. Adding a DummyExtender.");
this.gameObject.AddComponent<ReplayExtender>();
foreach (GameObject go in (FindObjectsOfType(typeof(GameObject)) as GameObject[])) {
if (go != this.gameObject && go.GetComponent<ReplayBehavior>() == null) {
ReplayBehavior rb = go.AddComponent<ReplayBehavior>();
rb.ReplayTag = ReplayBehavior.RAETag.Given;
rb.RecordTouching = false;
}
}
}
void Update() {
if (running && done && initialized) {
if(!extender.SkipAction(reader.Current))
RunState(reader.Current);
numberSinceRun++;
if (this.pauseEvery > 0 && numberSinceRun > this.pauseEvery) {
running = false;
}
if (reader.HasNext) {
AdvanceReader();
}
else {
running = false;
}
}
}
void OnDestroy() {
if (initialized)
writer.Close(calculator.FooterLine);
}
#endregion
#region Replay Logic
IEnumerator Prep() {
if (initialized) yield break;
writer.Open(calculator.HeaderLine);
reader.Load();
while (!writer.Opened && !calculator.Ready && !reader.Loaded && !extender.Ready) {
running = false;
yield return 0;
}
initialized = true;
yield break;
}
private void AdvanceReader() {
if (reader.HasNext) {
switch (iterationMode) {
case IterationMode.ActionByAction:
reader.GetNextStudentAction();
break;
case IterationMode.FinalStates:
reader.GetNextStudentAction();
while (reader.HasNext && reader.Current.IsSameAttempt(reader.Previous)) {
reader.GetNextStudentAction();
}
Debug.Log("Current: " + reader.Current);
break;
}
}
}
public void RunNextAction() {
if (initialized && done) {
if (reader.HasNext) {
reader.GetNextStudentAction();
if (reader.IsNewAttempt) {
extender.OnNewLevel(reader.LastStartState);
}
if (!extender.SkipAction(reader.Current))
RunState(reader.Current);
}
}
else {
StartCoroutine(Prep());
}
}
public void Run() {
if (running)
return;
if (!initialized)
StartCoroutine(Prep());
running = reader.HasNext;
numberSinceRun = 0;
}
public void Pause() {
running = false;
}
public void RunState(StudentAction action) {
//Debug.Log(action);
Time.timeScale = 1.0f;
done = false;
calculator.ResetScores();
extender.OnActionPre(action);
ClearState();
ClearAction();
InstantiateState(action);
if (addActions)
InstantiateAction(action);
extender.OnActionPost(action);
Time.timeScale = timeAcceleraton;
StartCoroutine(WaitForStop(action));
}
IEnumerator WaitForStop(StudentAction action) {
List<GameObject> state = new List<GameObject>(ReplayBehavior.GetGameObjectsWithRAETag(ReplayBehavior.RAETag.State));
state.AddRange(ReplayBehavior.GetGameObjectsWithRAETag(ReplayBehavior.RAETag.Action));
float callTime = Time.time;
switch (stopCondition) {
case StoppingCondition.Instant:
break;
case StoppingCondition.WaitForStop:
bool allSleeping = false;
while (!allSleeping) {
allSleeping = true;
if (Time.time - callTime > timeOut) {
break;
}
foreach (GameObject go in state) {
if (go != null && go.rigidbody != null & !go.rigidbody.IsSleeping()) {
allSleeping = false;
yield return null;
break;
}
}
}
break;
case StoppingCondition.Time :
while (Time.time - callTime < timeOut) {
yield return null;
}
break;
case StoppingCondition.Custom :
yield return extender.StoppingCoroutine();
break;
}
Stop(action);
}
private void Stop(StudentAction action) {
Time.timeScale = 0f;
extender.OnStop(action);
//calculate
calculator.CalculateScores(action);
//screenshot
if (takeScreenShot) {
writer.CaptureScreenShotPNG(calculator.ScreenShotName);
}
//record
writer.Write(calculator.CurrentLine);
done = true;
}
private void InstantiateStartState(StudentAction startState) {
if (startState.Equals(StudentAction.NullAction) || startState.Action != Logger.START_STATE)
return;
ClearState();
ClearAction();
ClearStartState();
if (startState.StateXML != null) {
XmlNodeList objects = startState.StateXML.SelectNodes(Logger.OBJECT);
foreach (XmlNode entry in objects) {
GameObject gob = SpawnObject(entry, startState);
if (gob != null) {
gob.GetComponent<ReplayBehavior>().ReplayTag = ReplayBehavior.RAETag.StartState;
extender.SpecializeNewObject(gob, entry, startState);
}
}
}
}
private void InstantiateState(StudentAction action) {
if (action.Equals(StudentAction.NullAction))
return;
ClearState();
ClearAction();
if (action.StateXML != null) {
XmlNodeList objects = action.StateXML.SelectNodes(Logger.OBJECT);
foreach (XmlNode entry in objects) {
if (entry[Logger.NAME].InnerText != action.Selection) {
GameObject gob = SpawnObject(entry, action);
if (gob != null) {
gob.GetComponent<ReplayBehavior>().ReplayTag = ReplayBehavior.RAETag.State;
extender.SpecializeNewObject(gob, entry, action);
}
}
}
}
}
private void InstantiateAction(StudentAction action) {
if (action.Equals(StudentAction.NullAction))
return;
if (!action.HasObjectInput())
return;
//Debug.Log(action);
XmlNodeList objects = action.InputXML.SelectNodes(Logger.OBJECT);
if (objects.Count == 0) {
return;
}
else foreach (XmlNode node in objects) {
GameObject gob = SpawnObject(node, action);
if (gob != null) {
gob.GetComponent<ReplayBehavior>().ReplayTag = ReplayBehavior.RAETag.Action;
extender.SpecializeNewObject(gob, node, action);
}
}
}
private GameObject SpawnObject(XmlNode node, StudentAction action) {
string key = extender.LookupPrefab(node, action);
if (string.IsNullOrEmpty(key)) {
if (node[Logger.PREFAB] == null) {
Debug.LogWarning("XmlNode contains no <Prefab> element, attempting to use the <Name> element instead.");
if (node[Logger.NAME] == null) {
Debug.LogWarning("XmlNode contains no <Name> element. Giving up. Consider writing an extension to the LookupPrefab() "+
"method in the ReplayExtender class if your log files do not conform to the standard format.\nNode:" + node.OuterXml);
return null;
}
key = node[Logger.NAME].InnerText;
}
else {
key = node[Logger.PREFAB].InnerText;
}
}
GameObject prefab = dictionary.GetPrefab(key);
if (prefab == null) {
Debug.LogWarning("No Prefab found in dictionary for name:" + key + ", did you forget to add it, or spell the (case-sensative) key wrong? Giving up.");
return null;
}
GameObject gob = null;
float posX = float.Parse(node[Logger.TRANSFORM][Logger.POSITION]["X"].InnerText);
float posY = float.Parse(node[Logger.TRANSFORM][Logger.POSITION]["Y"].InnerText);
Vector3 pos = new Vector3(posX, posY, 0f);
float rotZ = float.Parse(node[Logger.TRANSFORM][Logger.ROTATION].InnerText);
Quaternion rot = Quaternion.Euler(0f, 0f, rotZ);
gob = GameObject.Instantiate(prefab, pos, rot) as GameObject;
gob.name = node[Logger.NAME].InnerText;
ReplayBehavior rb = gob.AddComponent<ReplayBehavior>();
if (node[Logger.PREFAB] != null)
rb.PrefabName = node[Logger.PREFAB].InnerText;
else
rb.PrefabName = ReplayBehavior.NO_PREFAB_TAG;
if (node[Logger.UNITY_TAG] != null)
rb.UnityTag = node[Logger.UNITY_TAG].InnerText;
else
rb.UnityTag = ReplayBehavior.NO_UNITY_TAG;
if (node[Logger.EXTRA_TAGS] != null) {
List<string> newTags = new List<string>();
foreach(XmlNode subNode in node[Logger.EXTRA_TAGS]) {
if (subNode[Logger.TAG] != null) {
newTags.Add(subNode[Logger.TAG].InnerText);
}
}
rb.AddTags(newTags);
}
return gob;
}
private void ClearStartState() {
extender.ClearStartState();
foreach (GameObject go in ReplayBehavior.GetGameObjectsWithRAETag(ReplayBehavior.RAETag.StartState)) {
GameObject.Destroy(go);
}
}
private void ClearState() {
extender.ClearState();
foreach (GameObject go in ReplayBehavior.GetGameObjectsWithRAETag(ReplayBehavior.RAETag.State)) {
GameObject.Destroy(go);
}
}
private void ClearAction() {
extender.ClearAction();
foreach (GameObject go in ReplayBehavior.GetGameObjectsWithRAETag(ReplayBehavior.RAETag.Action)) {
GameObject.Destroy(go);
}
}
#endregion
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using System.IO;
using System.Xml;
using log4net.Config;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Setup;
namespace OpenSim.Region.CoreModules.World.Serialiser.Tests
{
[TestFixture]
public class SerialiserTests
{
private string xml = @"
<SceneObjectGroup>
<RootPart>
<SceneObjectPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<AllowedDrop>false</AllowedDrop>
<CreatorID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></CreatorID>
<FolderID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></FolderID>
<InventorySerial>1</InventorySerial>
<TaskInventory />
<ObjectFlags>0</ObjectFlags>
<UUID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></UUID>
<LocalId>2698615125</LocalId>
<Name>PrimMyRide</Name>
<Material>0</Material>
<PassTouches>false</PassTouches>
<RegionHandle>1099511628032000</RegionHandle>
<ScriptAccessPin>0</ScriptAccessPin>
<GroupPosition><X>147.23</X><Y>92.698</Y><Z>22.78084</Z></GroupPosition>
<OffsetPosition><X>0</X><Y>0</Y><Z>0</Z></OffsetPosition>
<RotationOffset><X>-4.371139E-08</X><Y>-1</Y><Z>-4.371139E-08</Z><W>0</W></RotationOffset>
<Velocity><X>0</X><Y>0</Y><Z>0</Z></Velocity>
<RotationalVelocity><X>0</X><Y>0</Y><Z>0</Z></RotationalVelocity>
<AngularVelocity><X>0</X><Y>0</Y><Z>0</Z></AngularVelocity>
<Acceleration><X>0</X><Y>0</Y><Z>0</Z></Acceleration>
<Description />
<Color />
<Text />
<SitName />
<TouchName />
<LinkNum>0</LinkNum>
<ClickAction>0</ClickAction>
<Shape>
<ProfileCurve>1</ProfileCurve>
<TextureEntry>AAAAAAAAERGZmQAAAAAABQCVlZUAAAAAQEAAAABAQAAAAAAAAAAAAAAAAAAAAA==</TextureEntry>
<ExtraParams>AA==</ExtraParams>
<PathBegin>0</PathBegin>
<PathCurve>16</PathCurve>
<PathEnd>0</PathEnd>
<PathRadiusOffset>0</PathRadiusOffset>
<PathRevolutions>0</PathRevolutions>
<PathScaleX>100</PathScaleX>
<PathScaleY>100</PathScaleY>
<PathShearX>0</PathShearX>
<PathShearY>0</PathShearY>
<PathSkew>0</PathSkew>
<PathTaperX>0</PathTaperX>
<PathTaperY>0</PathTaperY>
<PathTwist>0</PathTwist>
<PathTwistBegin>0</PathTwistBegin>
<PCode>9</PCode>
<ProfileBegin>0</ProfileBegin>
<ProfileEnd>0</ProfileEnd>
<ProfileHollow>0</ProfileHollow>
<Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale>
<State>0</State>
<ProfileShape>Square</ProfileShape>
<HollowShape>Same</HollowShape>
<SculptTexture><Guid>00000000-0000-0000-0000-000000000000</Guid></SculptTexture>
<SculptType>0</SculptType><SculptData />
<FlexiSoftness>0</FlexiSoftness>
<FlexiTension>0</FlexiTension>
<FlexiDrag>0</FlexiDrag>
<FlexiGravity>0</FlexiGravity>
<FlexiWind>0</FlexiWind>
<FlexiForceX>0</FlexiForceX>
<FlexiForceY>0</FlexiForceY>
<FlexiForceZ>0</FlexiForceZ>
<LightColorR>0</LightColorR>
<LightColorG>0</LightColorG>
<LightColorB>0</LightColorB>
<LightColorA>1</LightColorA>
<LightRadius>0</LightRadius>
<LightCutoff>0</LightCutoff>
<LightFalloff>0</LightFalloff>
<LightIntensity>1</LightIntensity>
<FlexiEntry>false</FlexiEntry>
<LightEntry>false</LightEntry>
<SculptEntry>false</SculptEntry>
</Shape>
<Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale>
<UpdateFlag>0</UpdateFlag>
<SitTargetOrientation><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientation>
<SitTargetPosition><X>0</X><Y>0</Y><Z>0</Z></SitTargetPosition>
<SitTargetPositionLL><X>0</X><Y>0</Y><Z>0</Z></SitTargetPositionLL>
<SitTargetOrientationLL><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientationLL>
<ParentID>0</ParentID>
<CreationDate>1211330445</CreationDate>
<Category>0</Category>
<SalePrice>0</SalePrice>
<ObjectSaleType>0</ObjectSaleType>
<OwnershipCost>0</OwnershipCost>
<GroupID><Guid>00000000-0000-0000-0000-000000000000</Guid></GroupID>
<OwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></OwnerID>
<LastOwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></LastOwnerID>
<BaseMask>2147483647</BaseMask>
<OwnerMask>2147483647</OwnerMask>
<GroupMask>0</GroupMask>
<EveryoneMask>0</EveryoneMask>
<NextOwnerMask>2147483647</NextOwnerMask>
<Flags>None</Flags>
<CollisionSound><Guid>00000000-0000-0000-0000-000000000000</Guid></CollisionSound>
<CollisionSoundVolume>0</CollisionSoundVolume>
</SceneObjectPart>
</RootPart>
<OtherParts />
</SceneObjectGroup>";
private string xml2 = @"
<SceneObjectGroup>
<SceneObjectPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<CreatorID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></CreatorID>
<FolderID><UUID>9be68fdd-f740-4a0f-9675-dfbbb536b946</UUID></FolderID>
<InventorySerial>0</InventorySerial>
<TaskInventory />
<ObjectFlags>0</ObjectFlags>
<UUID><UUID>9be68fdd-f740-4a0f-9675-dfbbb536b946</UUID></UUID>
<LocalId>720005</LocalId>
<Name>PrimFun</Name>
<Material>0</Material>
<RegionHandle>1099511628032000</RegionHandle>
<ScriptAccessPin>0</ScriptAccessPin>
<GroupPosition><X>153.9854</X><Y>121.4908</Y><Z>62.21781</Z></GroupPosition>
<OffsetPosition><X>0</X><Y>0</Y><Z>0</Z></OffsetPosition>
<RotationOffset><X>0</X><Y>0</Y><Z>0</Z><W>1</W></RotationOffset>
<Velocity><X>0</X><Y>0</Y><Z>0</Z></Velocity>
<RotationalVelocity><X>0</X><Y>0</Y><Z>0</Z></RotationalVelocity>
<AngularVelocity><X>0</X><Y>0</Y><Z>0</Z></AngularVelocity>
<Acceleration><X>0</X><Y>0</Y><Z>0</Z></Acceleration>
<Description />
<Color />
<Text />
<SitName />
<TouchName />
<LinkNum>0</LinkNum>
<ClickAction>0</ClickAction>
<Shape>
<PathBegin>0</PathBegin>
<PathCurve>16</PathCurve>
<PathEnd>0</PathEnd>
<PathRadiusOffset>0</PathRadiusOffset>
<PathRevolutions>0</PathRevolutions>
<PathScaleX>200</PathScaleX>
<PathScaleY>200</PathScaleY>
<PathShearX>0</PathShearX>
<PathShearY>0</PathShearY>
<PathSkew>0</PathSkew>
<PathTaperX>0</PathTaperX>
<PathTaperY>0</PathTaperY>
<PathTwist>0</PathTwist>
<PathTwistBegin>0</PathTwistBegin>
<PCode>9</PCode>
<ProfileBegin>0</ProfileBegin>
<ProfileEnd>0</ProfileEnd>
<ProfileHollow>0</ProfileHollow>
<Scale><X>1.283131</X><Y>5.903858</Y><Z>4.266288</Z></Scale>
<State>0</State>
<ProfileShape>Circle</ProfileShape>
<HollowShape>Same</HollowShape>
<ProfileCurve>0</ProfileCurve>
<TextureEntry>iVVnRyTLQ+2SC0fK7RVGXwJ6yc/SU4RDA5nhJbLUw3R1AAAAAAAAaOw8QQOhPSRAAKE9JEAAAAAAAAAAAAAAAAAAAAA=</TextureEntry>
<ExtraParams>AA==</ExtraParams>
</Shape>
<Scale><X>1.283131</X><Y>5.903858</Y><Z>4.266288</Z></Scale>
<UpdateFlag>0</UpdateFlag>
<SitTargetOrientation><w>0</w><x>0</x><y>0</y><z>1</z></SitTargetOrientation>
<SitTargetPosition><x>0</x><y>0</y><z>0</z></SitTargetPosition>
<SitTargetPositionLL><X>0</X><Y>0</Y><Z>0</Z></SitTargetPositionLL>
<SitTargetOrientationLL><X>0</X><Y>0</Y><Z>1</Z><W>0</W></SitTargetOrientationLL>
<ParentID>0</ParentID>
<CreationDate>1216066902</CreationDate>
<Category>0</Category>
<SalePrice>0</SalePrice>
<ObjectSaleType>0</ObjectSaleType>
<OwnershipCost>0</OwnershipCost>
<GroupID><UUID>00000000-0000-0000-0000-000000000000</UUID></GroupID>
<OwnerID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></OwnerID>
<LastOwnerID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></LastOwnerID>
<BaseMask>2147483647</BaseMask>
<OwnerMask>2147483647</OwnerMask>
<GroupMask>0</GroupMask>
<EveryoneMask>0</EveryoneMask>
<NextOwnerMask>2147483647</NextOwnerMask>
<Flags>None</Flags>
<SitTargetAvatar><UUID>00000000-0000-0000-0000-000000000000</UUID></SitTargetAvatar>
</SceneObjectPart>
<OtherParts />
</SceneObjectGroup>";
protected Scene m_scene;
protected SerialiserModule m_serialiserModule;
[TestFixtureSetUp]
public void Init()
{
m_serialiserModule = new SerialiserModule();
m_scene = SceneSetupHelpers.SetupScene("");
SceneSetupHelpers.SetupSceneModules(m_scene, m_serialiserModule);
}
[Test]
public void TestDeserializeXml()
{
TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
SceneObjectGroup so = SceneObjectSerializer.FromOriginalXmlFormat(xml);
SceneObjectPart rootPart = so.RootPart;
Assert.That(rootPart.UUID, Is.EqualTo(new UUID("e6a5a05e-e8cc-4816-8701-04165e335790")));
Assert.That(rootPart.CreatorID, Is.EqualTo(new UUID("a6dacf01-4636-4bb9-8a97-30609438af9d")));
Assert.That(rootPart.Name, Is.EqualTo("PrimMyRide"));
// TODO: Check other properties
}
[Test]
public void TestSerializeXml()
{
TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
string rpName = "My Little Donkey";
UUID rpUuid = UUID.Parse("00000000-0000-0000-0000-000000000964");
UUID rpCreatorId = UUID.Parse("00000000-0000-0000-0000-000000000915");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
// Vector3 groupPosition = new Vector3(10, 20, 30);
// Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
// Vector3 offsetPosition = new Vector3(5, 10, 15);
SceneObjectPart rp = new SceneObjectPart();
rp.UUID = rpUuid;
rp.Name = rpName;
rp.CreatorID = rpCreatorId;
rp.Shape = shape;
SceneObjectGroup so = new SceneObjectGroup(rp);
// Need to add the object to the scene so that the request to get script state succeeds
m_scene.AddSceneObject(so);
string xml = SceneObjectSerializer.ToOriginalXmlFormat(so);
XmlTextReader xtr = new XmlTextReader(new StringReader(xml));
xtr.ReadStartElement("SceneObjectGroup");
xtr.ReadStartElement("RootPart");
xtr.ReadStartElement("SceneObjectPart");
UUID uuid = UUID.Zero;
string name = null;
UUID creatorId = UUID.Zero;
while (xtr.Read() && xtr.Name != "SceneObjectPart")
{
if (xtr.NodeType != XmlNodeType.Element)
continue;
switch (xtr.Name)
{
case "UUID":
xtr.ReadStartElement("UUID");
try
{
uuid = UUID.Parse(xtr.ReadElementString("UUID"));
xtr.ReadEndElement();
}
catch { } // ignore everything but <UUID><UUID>...</UUID></UUID>
break;
case "Name":
name = xtr.ReadElementContentAsString();
break;
case "CreatorID":
xtr.ReadStartElement("CreatorID");
creatorId = UUID.Parse(xtr.ReadElementString("UUID"));
xtr.ReadEndElement();
break;
}
}
xtr.ReadEndElement();
xtr.ReadEndElement();
xtr.ReadStartElement("OtherParts");
xtr.ReadEndElement();
xtr.Close();
// TODO: More checks
Assert.That(uuid, Is.EqualTo(rpUuid));
Assert.That(name, Is.EqualTo(rpName));
Assert.That(creatorId, Is.EqualTo(rpCreatorId));
}
[Test]
public void TestDeserializeXml2()
{
TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
SceneObjectGroup so = m_serialiserModule.DeserializeGroupFromXml2(xml2);
SceneObjectPart rootPart = so.RootPart;
Assert.That(rootPart.UUID, Is.EqualTo(new UUID("9be68fdd-f740-4a0f-9675-dfbbb536b946")));
Assert.That(rootPart.CreatorID, Is.EqualTo(new UUID("b46ef588-411e-4a8b-a284-d7dcfe8e74ef")));
Assert.That(rootPart.Name, Is.EqualTo("PrimFun"));
// TODO: Check other properties
}
[Test]
public void TestSerializeXml2()
{
TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
string rpName = "My Little Pony";
UUID rpUuid = UUID.Parse("00000000-0000-0000-0000-000000000064");
UUID rpCreatorId = UUID.Parse("00000000-0000-0000-0000-000000000015");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
// Vector3 groupPosition = new Vector3(10, 20, 30);
// Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
// Vector3 offsetPosition = new Vector3(5, 10, 15);
SceneObjectPart rp = new SceneObjectPart();
rp.UUID = rpUuid;
rp.Name = rpName;
rp.CreatorID = rpCreatorId;
rp.Shape = shape;
SceneObjectGroup so = new SceneObjectGroup(rp);
// Need to add the object to the scene so that the request to get script state succeeds
m_scene.AddSceneObject(so);
Dictionary<string, object> options = new Dictionary<string, object>();
options["old-guids"] = true;
string xml2 = m_serialiserModule.SerializeGroupToXml2(so, options);
XmlTextReader xtr = new XmlTextReader(new StringReader(xml2));
xtr.ReadStartElement("SceneObjectGroup");
xtr.ReadStartElement("SceneObjectPart");
UUID uuid = UUID.Zero;
string name = null;
UUID creatorId = UUID.Zero;
while (xtr.Read() && xtr.Name != "SceneObjectPart")
{
if (xtr.NodeType != XmlNodeType.Element)
continue;
switch (xtr.Name)
{
case "UUID":
xtr.ReadStartElement("UUID");
uuid = UUID.Parse(xtr.ReadElementString("Guid"));
xtr.ReadEndElement();
break;
case "Name":
name = xtr.ReadElementContentAsString();
break;
case "CreatorID":
xtr.ReadStartElement("CreatorID");
creatorId = UUID.Parse(xtr.ReadElementString("Guid"));
xtr.ReadEndElement();
break;
}
}
xtr.ReadEndElement();
xtr.ReadStartElement("OtherParts");
xtr.ReadEndElement();
xtr.Close();
// TODO: More checks
Assert.That(uuid, Is.EqualTo(rpUuid));
Assert.That(name, Is.EqualTo(rpName));
Assert.That(creatorId, Is.EqualTo(rpCreatorId));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
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;
public static partial class SkipUrlEncodingOperationsExtensions
{
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetMethodPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodPathValidAsync( this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetPathPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathPathValidAsync( this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetPathPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// An unencoded path parameter with value 'path1/path2/path3'. Possible
/// values for this parameter include: 'path1/path2/path3'
/// </param>
public static void GetSwaggerPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerPathValidAsync(unencodedPathParam), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// An unencoded path parameter with value 'path1/path2/path3'. Possible
/// values for this parameter include: 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerPathValidAsync( this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetSwaggerPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetMethodQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryValidAsync( this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
public static void GetMethodQueryNull(this ISkipUrlEncodingOperations operations, string q1 = default(string))
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetMethodQueryNullAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryNullAsync( this ISkipUrlEncodingOperations operations, string q1 = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetMethodQueryNullWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetPathQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetPathQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathQueryValidAsync( this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetPathQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// An unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'. Possible values for this parameter
/// include: 'value1&q2=value2&q3=value3'
/// </param>
public static void GetSwaggerQueryValid(this ISkipUrlEncodingOperations operations, string q1 = default(string))
{
Task.Factory.StartNew(s => ((ISkipUrlEncodingOperations)s).GetSwaggerQueryValidAsync(q1), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// An unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'. Possible values for this parameter
/// include: 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerQueryValidAsync( this ISkipUrlEncodingOperations operations, string q1 = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.GetSwaggerQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
using System;
using System.CodeDom;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
namespace Orleans.Messaging
{
// <summary>
// This class is used on the client only.
// It provides the client counterpart to the Gateway and GatewayAcceptor classes on the silo side.
//
// There is one ProxiedMessageCenter instance per OutsideRuntimeClient. There can be multiple ProxiedMessageCenter instances
// in a single process, but because RuntimeClient keeps a static pointer to a single OutsideRuntimeClient instance, this is not
// generally done in practice.
//
// Each ProxiedMessageCenter keeps a collection of GatewayConnection instances. Each of these represents a bidirectional connection
// to a single gateway endpoint. Requests are assigned to a specific connection based on the target grain ID, so that requests to
// the same grain will go to the same gateway, in sending order. To do this efficiently and scalably, we bucket grains together
// based on their hash code mod a reasonably large number (currently 8192).
//
// When the first message is sent to a bucket, we assign a gateway to that bucket, selecting in round-robin fashion from the known
// gateways. If this is the first message to be sent to the gateway, we will create a new connection for it and assign the bucket to
// the new connection. Either way, all messages to grains in that bucket will be sent to the assigned connection as long as the
// connection is live.
//
// Connections stay live as long as possible. If a socket error or other communications error occurs, then the client will try to
// reconnect twice before giving up on the gateway. If the connection cannot be re-established, then the gateway is deemed (temporarily)
// dead, and any buckets assigned to the connection are unassigned (so that the next message sent will cause a new gateway to be selected).
// There is no assumption that this death is permanent; the system will try to reuse the gateway every 5 minutes.
//
// The list of known gateways is managed by the GatewayManager class. See comments there for details...
// =======================================================================================================================================
// Locking and lock protocol:
// The ProxiedMessageCenter instance itself may be accessed by many client threads simultaneously, and each GatewayConnection instance
// is accessed by its own thread, by the thread for its Receiver, and potentially by client threads from within the ProxiedMessageCenter.
// Thus, we need locks to protect the various data structured from concurrent modifications.
//
// Each GatewayConnection instance has a "lockable" field that is used to lock local information. This lock is used by both the GatewayConnection
// thread and the Receiver thread.
//
// The ProxiedMessageCenter instance also has a "lockable" field. This lock is used by any client thread running methods within the instance.
//
// Note that we take care to ensure that client threads never need locked access to GatewayConnection state and GatewayConnection threads never need
// locked access to ProxiedMessageCenter state. Thus, we don't need to worry about lock ordering across these objects.
//
// Finally, the GatewayManager instance within the ProxiedMessageCenter has two collections, knownGateways and knownDead, that it needs to
// protect with locks. Rather than using a "lockable" field, each collection is lcoked to protect the collection.
// All sorts of threads can run within the GatewayManager, including client threads and GatewayConnection threads, so we need to
// be careful about locks here. The protocol we use is to always take GatewayManager locks last, to only take them within GatewayManager methods,
// and to always release them before returning from the method. In addition, we never simultaneously hold the knownGateways and knownDead locks,
// so there's no need to worry about the order in which we take and release those locks.
// </summary>
internal class ProxiedMessageCenter : IMessageCenter, IDisposable
{
#region Constants
internal static readonly TimeSpan MINIMUM_INTERCONNECT_DELAY = TimeSpan.FromMilliseconds(100); // wait one tenth of a second between connect attempts
internal const int CONNECT_RETRY_COUNT = 2; // Retry twice before giving up on a gateway server
#endregion
internal GrainId ClientId { get; private set; }
internal bool Running { get; private set; }
internal readonly GatewayManager GatewayManager;
internal readonly BlockingCollection<Message> PendingInboundMessages;
private readonly Dictionary<Uri, GatewayConnection> gatewayConnections;
private int numMessages;
// The grainBuckets array is used to select the connection to use when sending an ordered message to a grain.
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
private readonly WeakReference[] grainBuckets;
private readonly Logger logger;
private readonly object lockable;
public SiloAddress MyAddress { get; private set; }
public IMessagingConfiguration MessagingConfiguration { get; private set; }
private readonly QueueTrackingStatistic queueTracking;
public ProxiedMessageCenter(ClientConfiguration config, IPAddress localAddress, int gen, GrainId clientId, IGatewayListProvider gatewayListProvider)
{
lockable = new object();
MyAddress = SiloAddress.New(new IPEndPoint(localAddress, 0), gen);
ClientId = clientId;
Running = false;
MessagingConfiguration = config;
GatewayManager = new GatewayManager(config, gatewayListProvider);
PendingInboundMessages = new BlockingCollection<Message>();
gatewayConnections = new Dictionary<Uri, GatewayConnection>();
numMessages = 0;
grainBuckets = new WeakReference[config.ClientSenderBuckets];
logger = LogManager.GetLogger("Messaging.ProxiedMessageCenter", LoggerType.Runtime);
if (logger.IsVerbose) logger.Verbose("Proxy grain client constructed");
IntValueStatistic.FindOrCreate(StatisticNames.CLIENT_CONNECTED_GATEWAY_COUNT, () =>
{
lock (gatewayConnections)
{
return gatewayConnections.Values.Count(conn => conn.IsLive);
}
});
if (StatisticsCollector.CollectQueueStats)
{
queueTracking = new QueueTrackingStatistic("ClientReceiver");
}
}
public void Start()
{
Running = true;
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnStartExecution();
}
if (logger.IsVerbose) logger.Verbose("Proxy grain client started");
}
public void PrepareToStop()
{
// put any pre stop logic here.
}
public void Stop()
{
Running = false;
Utils.SafeExecute(() =>
{
PendingInboundMessages.CompleteAdding();
});
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnStopExecution();
}
GatewayManager.Stop();
foreach (var gateway in gatewayConnections.Values)
{
gateway.Stop();
}
}
public void SendMessage(Message msg)
{
GatewayConnection gatewayConnection = null;
bool startRequired = false;
// If there's a specific gateway specified, use it
if (msg.TargetSilo != null)
{
Uri addr = msg.TargetSilo.ToGatewayUri();
lock (lockable)
{
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose("Creating gateway to {0} for pre-addressed message", addr);
startRequired = true;
}
}
}
// For untargeted messages to system targets, and for unordered messages, pick a next connection in round robin fashion.
else if (msg.TargetGrain.IsSystemTarget || msg.IsUnordered)
{
// Get the cached list of live gateways.
// Pick a next gateway name in a round robin fashion.
// See if we have a live connection to it.
// If Yes, use it.
// If not, create a new GatewayConnection and start it.
// If start fails, we will mark this connection as dead and remove it from the GetCachedLiveGatewayNames.
lock (lockable)
{
int msgNumber = numMessages;
numMessages = unchecked(numMessages + 1);
IList<Uri> gatewayNames = GatewayManager.GetLiveGateways();
int numGateways = gatewayNames.Count;
if (numGateways == 0)
{
RejectMessage(msg, "No gateways available");
logger.Warn(ErrorCode.ProxyClient_CannotSend, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager);
return;
}
Uri addr = gatewayNames[msgNumber % numGateways];
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayUnordered, "Creating gateway to {0} for unordered message to grain {1}", addr, msg.TargetGrain);
startRequired = true;
}
// else - Fast path - we've got a live gatewayConnection to use
}
}
// Otherwise, use the buckets to ensure ordering.
else
{
var index = msg.TargetGrain.GetHashCode_Modulo((uint)grainBuckets.Length);
lock (lockable)
{
// Repeated from above, at the declaration of the grainBuckets array:
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
var weakRef = grainBuckets[index];
if ((weakRef != null) && weakRef.IsAlive)
{
gatewayConnection = weakRef.Target as GatewayConnection;
}
if ((gatewayConnection == null) || !gatewayConnection.IsLive)
{
var addr = GatewayManager.GetLiveGateway();
if (addr == null)
{
RejectMessage(msg, "No gateways available");
logger.Warn(ErrorCode.ProxyClient_CannotSend_NoGateway, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager);
return;
}
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_NewBucketIndex, "Starting new bucket index {0} for ordered messages to grain {1}", index, msg.TargetGrain);
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayToGrain, "Creating gateway to {0} for message to grain {1}, bucket {2}, grain id hash code {3}X", addr, msg.TargetGrain, index,
msg.TargetGrain.GetHashCode().ToString("x"));
startRequired = true;
}
grainBuckets[index] = new WeakReference(gatewayConnection);
}
}
}
if (startRequired)
{
gatewayConnection.Start();
if (!gatewayConnection.IsLive)
{
// if failed to start Gateway connection (failed to connect), try sending this msg to another Gateway.
RejectOrResend(msg);
return;
}
}
try
{
gatewayConnection.QueueRequest(msg);
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", msg, gatewayConnection.Address);
}
catch (InvalidOperationException)
{
// This exception can be thrown if the gateway connection we selected was closed since we checked (i.e., we lost the race)
// If this happens, we reject if the message is targeted to a specific silo, or try again if not
RejectOrResend(msg);
}
}
private void RejectOrResend(Message msg)
{
if (msg.TargetSilo != null)
{
RejectMessage(msg, String.Format("Target silo {0} is unavailable", msg.TargetSilo));
}
else
{
SendMessage(msg);
}
}
public Task<IGrainTypeResolver> GetTypeCodeMap(GrainFactory grainFactory)
{
var silo = GetLiveGatewaySiloAddress();
return GetTypeManager(silo, grainFactory).GetClusterTypeCodeMap();
}
public Task<Streams.ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(GrainFactory grainFactory)
{
var silo = GetLiveGatewaySiloAddress();
return GetTypeManager(silo, grainFactory).GetImplicitStreamSubscriberTable(silo);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public Message WaitMessage(Message.Categories type, CancellationToken ct)
{
try
{
if (ct.IsCancellationRequested)
{
return null;
}
// Don't pass CancellationToken to Take. It causes too much spinning.
Message msg = PendingInboundMessages.Take();
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnDeQueueRequest(msg);
}
#endif
return msg;
}
#if !NETSTANDARD
catch (ThreadAbortException exc)
{
// Silo may be shutting-down, so downgrade to verbose log
logger.Verbose(ErrorCode.ProxyClient_ThreadAbort, "Received thread abort exception -- exiting. {0}", exc);
Thread.ResetAbort();
return null;
}
#endif
catch (OperationCanceledException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received operation cancelled exception -- exiting. {0}", exc);
return null;
}
catch (ObjectDisposedException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Object Disposed exception -- exiting. {0}", exc);
return null;
}
catch (InvalidOperationException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Invalid Operation exception -- exiting. {0}", exc);
return null;
}
catch (Exception ex)
{
logger.Error(ErrorCode.ProxyClient_ReceiveError, "Unexpected error getting an inbound message", ex);
return null;
}
}
internal void QueueIncomingMessage(Message msg)
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnEnQueueRequest(1, PendingInboundMessages.Count, msg);
}
#endif
PendingInboundMessages.Add(msg);
}
private void RejectMessage(Message msg, string reasonFormat, params object[] reasonParams)
{
if (!Running) return;
var reason = String.Format(reasonFormat, reasonParams);
if (msg.Direction != Message.Directions.Request)
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason);
}
else
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable, reason);
QueueIncomingMessage(error);
}
}
/// <summary>
/// For testing use only
/// </summary>
public void Disconnect()
{
throw new NotImplementedException("Disconnect");
}
/// <summary>
/// For testing use only.
/// </summary>
public void Reconnect()
{
throw new NotImplementedException("Reconnect");
}
#region Random IMessageCenter stuff
public int SendQueueLength
{
get { return 0; }
}
public int ReceiveQueueLength
{
get { return 0; }
}
#endregion
private IClusterTypeManager GetTypeManager(SiloAddress destination, GrainFactory grainFactory)
{
return grainFactory.GetSystemTarget<IClusterTypeManager>(Constants.TypeManagerId, destination);
}
private SiloAddress GetLiveGatewaySiloAddress()
{
var gateway = GatewayManager.GetLiveGateway();
if (gateway == null)
{
throw new OrleansException("Not connected to a gateway");
}
return gateway.ToSiloAddress();
}
internal void UpdateClientId(GrainId clientId)
{
if (ClientId.Category != UniqueKey.Category.Client)
throw new InvalidOperationException("Only handshake client ID can be updated with a cluster ID.");
if (clientId.Category != UniqueKey.Category.GeoClient)
throw new ArgumentException("Handshake client ID can only be updated with a geo client.", nameof(clientId));
ClientId = clientId;
}
public void Dispose()
{
PendingInboundMessages.Dispose();
if (gatewayConnections != null)
foreach (var item in gatewayConnections)
{
item.Value.Dispose();
}
GatewayManager.Dispose();
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfilePCPBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileEnabledState))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileULong))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfilePortNumber))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileString))]
public partial class LocalLBProfilePCP : iControlInterface {
public LocalLBProfilePCP() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_third_party_allowed_subnet
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void add_third_party_allowed_subnet(
string [] profile_names,
string [] [] subnets
) {
this.Invoke("add_third_party_allowed_subnet", new object [] {
profile_names,
subnets});
}
public System.IAsyncResult Beginadd_third_party_allowed_subnet(string [] profile_names,string [] [] subnets, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_third_party_allowed_subnet", new object[] {
profile_names,
subnets}, callback, asyncState);
}
public void Endadd_third_party_allowed_subnet(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void create(
string [] profile_names
) {
this.Invoke("create", new object [] {
profile_names});
}
public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
profile_names}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_profiles
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void delete_all_profiles(
) {
this.Invoke("delete_all_profiles", new object [0]);
}
public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState);
}
public void Enddelete_all_profiles(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void delete_profile(
string [] profile_names
) {
this.Invoke("delete_profile", new object [] {
profile_names});
}
public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_profile", new object[] {
profile_names}, callback, asyncState);
}
public void Enddelete_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_announce_after_failover_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_announce_after_failover_state(
string [] profile_names
) {
object [] results = this.Invoke("get_announce_after_failover_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_announce_after_failover_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_announce_after_failover_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_announce_after_failover_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_announce_multicast_repeats
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_announce_multicast_repeats(
string [] profile_names
) {
object [] results = this.Invoke("get_announce_multicast_repeats", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_announce_multicast_repeats(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_announce_multicast_repeats", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_announce_multicast_repeats(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_default_profile(
string [] profile_names
) {
object [] results = this.Invoke("get_default_profile", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_profile", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] profile_names
) {
object [] results = this.Invoke("get_description", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_listening_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfilePortNumber [] get_listening_port(
string [] profile_names
) {
object [] results = this.Invoke("get_listening_port", new object [] {
profile_names});
return ((LocalLBProfilePortNumber [])(results[0]));
}
public System.IAsyncResult Beginget_listening_port(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_listening_port", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfilePortNumber [] Endget_listening_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfilePortNumber [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mapping_filter_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_mapping_filter_limit(
string [] profile_names
) {
object [] results = this.Invoke("get_mapping_filter_limit", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_mapping_filter_limit(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mapping_filter_limit", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_mapping_filter_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mapping_limit_per_client
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_mapping_limit_per_client(
string [] profile_names
) {
object [] results = this.Invoke("get_mapping_limit_per_client", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_mapping_limit_per_client(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mapping_limit_per_client", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_mapping_limit_per_client(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_mapping_recycle_delay
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_mapping_recycle_delay(
string [] profile_names
) {
object [] results = this.Invoke("get_mapping_recycle_delay", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_mapping_recycle_delay(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_mapping_recycle_delay", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_mapping_recycle_delay(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_maximum_mapping_lifetime
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_maximum_mapping_lifetime(
string [] profile_names
) {
object [] results = this.Invoke("get_maximum_mapping_lifetime", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_maximum_mapping_lifetime(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_maximum_mapping_lifetime", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_maximum_mapping_lifetime(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_minimum_mapping_lifetime
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileULong [] get_minimum_mapping_lifetime(
string [] profile_names
) {
object [] results = this.Invoke("get_minimum_mapping_lifetime", new object [] {
profile_names});
return ((LocalLBProfileULong [])(results[0]));
}
public System.IAsyncResult Beginget_minimum_mapping_lifetime(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_minimum_mapping_lifetime", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileULong [] Endget_minimum_mapping_lifetime(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileULong [])(results[0]));
}
//-----------------------------------------------------------------------
// get_multicast_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfilePortNumber [] get_multicast_port(
string [] profile_names
) {
object [] results = this.Invoke("get_multicast_port", new object [] {
profile_names});
return ((LocalLBProfilePortNumber [])(results[0]));
}
public System.IAsyncResult Beginget_multicast_port(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_multicast_port", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfilePortNumber [] Endget_multicast_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfilePortNumber [])(results[0]));
}
//-----------------------------------------------------------------------
// get_rule
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileString [] get_rule(
string [] profile_names
) {
object [] results = this.Invoke("get_rule", new object [] {
profile_names});
return ((LocalLBProfileString [])(results[0]));
}
public System.IAsyncResult Beginget_rule(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_rule", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileString [] Endget_rule(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileString [])(results[0]));
}
//-----------------------------------------------------------------------
// get_third_party_allowed_subnet
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_third_party_allowed_subnet(
string [] profile_names
) {
object [] results = this.Invoke("get_third_party_allowed_subnet", new object [] {
profile_names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_third_party_allowed_subnet(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_third_party_allowed_subnet", new object[] {
profile_names}, callback, asyncState);
}
public string [] [] Endget_third_party_allowed_subnet(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_third_party_option_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_third_party_option_state(
string [] profile_names
) {
object [] results = this.Invoke("get_third_party_option_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_third_party_option_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_third_party_option_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_third_party_option_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// is_base_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_base_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_base_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_base_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_base_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// is_system_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_system_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_system_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_system_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_system_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_third_party_allowed_subnets
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void remove_all_third_party_allowed_subnets(
string [] profile_names
) {
this.Invoke("remove_all_third_party_allowed_subnets", new object [] {
profile_names});
}
public System.IAsyncResult Beginremove_all_third_party_allowed_subnets(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_third_party_allowed_subnets", new object[] {
profile_names}, callback, asyncState);
}
public void Endremove_all_third_party_allowed_subnets(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_third_party_allowed_subnet
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void remove_third_party_allowed_subnet(
string [] profile_names,
string [] [] subnets
) {
this.Invoke("remove_third_party_allowed_subnet", new object [] {
profile_names,
subnets});
}
public System.IAsyncResult Beginremove_third_party_allowed_subnet(string [] profile_names,string [] [] subnets, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_third_party_allowed_subnet", new object[] {
profile_names,
subnets}, callback, asyncState);
}
public void Endremove_third_party_allowed_subnet(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_announce_after_failover_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_announce_after_failover_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_announce_after_failover_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_announce_after_failover_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_announce_after_failover_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_announce_after_failover_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_announce_multicast_repeats
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_announce_multicast_repeats(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_announce_multicast_repeats", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_announce_multicast_repeats(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_announce_multicast_repeats", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_announce_multicast_repeats(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_default_profile(
string [] profile_names,
string [] defaults
) {
this.Invoke("set_default_profile", new object [] {
profile_names,
defaults});
}
public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_profile", new object[] {
profile_names,
defaults}, callback, asyncState);
}
public void Endset_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_description(
string [] profile_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
profile_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
profile_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_mapping_filter_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_mapping_filter_limit(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_mapping_filter_limit", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_mapping_filter_limit(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_mapping_filter_limit", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_mapping_filter_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_mapping_limit_per_client
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_mapping_limit_per_client(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_mapping_limit_per_client", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_mapping_limit_per_client(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_mapping_limit_per_client", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_mapping_limit_per_client(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_mapping_recycle_delay
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_mapping_recycle_delay(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_mapping_recycle_delay", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_mapping_recycle_delay(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_mapping_recycle_delay", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_mapping_recycle_delay(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_maximum_mapping_lifetime
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_maximum_mapping_lifetime(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_maximum_mapping_lifetime", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_maximum_mapping_lifetime(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_maximum_mapping_lifetime", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_maximum_mapping_lifetime(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_minimum_mapping_lifetime
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_minimum_mapping_lifetime(
string [] profile_names,
LocalLBProfileULong [] values
) {
this.Invoke("set_minimum_mapping_lifetime", new object [] {
profile_names,
values});
}
public System.IAsyncResult Beginset_minimum_mapping_lifetime(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_minimum_mapping_lifetime", new object[] {
profile_names,
values}, callback, asyncState);
}
public void Endset_minimum_mapping_lifetime(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_rule
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_rule(
string [] profile_names,
LocalLBProfileString [] rules
) {
this.Invoke("set_rule", new object [] {
profile_names,
rules});
}
public System.IAsyncResult Beginset_rule(string [] profile_names,LocalLBProfileString [] rules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_rule", new object[] {
profile_names,
rules}, callback, asyncState);
}
public void Endset_rule(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_third_party_option_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePCP",
RequestNamespace="urn:iControl:LocalLB/ProfilePCP", ResponseNamespace="urn:iControl:LocalLB/ProfilePCP")]
public void set_third_party_option_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_third_party_option_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_third_party_option_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_third_party_option_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_third_party_option_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
using System;
using System.Drawing;
using MonoTouch.ObjCRuntime;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.StoreKit;
namespace BBlockLibrary
{
public delegate void NSObjectBBlock (NSString keyPath, NSObject obj, NSDictionary change);
public delegate void SKStoreProductViewControllerBBlock (SKProductsResponse response, NSError error);
public delegate void UIActionSheetBBlock (int buttonIndex, UIActionSheet actionSheet);
public delegate void UIAlertViewBBlock (int buttonIndex, UIAlertView alertView);
public delegate void BBlockUIControlBlock (NSObject control, UIEvent evt);
public delegate void UIGestureRecognizerBBlock (NSObject gestureRecognizer);
public delegate void UITextFieldShouldReturnBBlock (UITextField textField);
public delegate void BBlockBlock ();
[BaseType (typeof (NSObject))]
public partial interface BBlock
{
[Export ("test:")]
string test (string test);
[Static, Export ("dispatchOnMainThread:")]
void DispatchOnMainThread (BBlockBlock block);
[Static, Export ("dispatchAfter:onMainThread:")]
void DispatchAfter (double delay, BBlockBlock block);
[Static, Export ("dispatchOnSynchronousQueue:")]
void DispatchOnSynchronousQueue (BBlockBlock block);
[Static, Export ("dispatchOnSynchronousFileQueue:")]
void DispatchOnSynchronousFileQueue (BBlockBlock block);
[Static, Export ("dispatchOnDefaultPriorityConcurrentQueue:")]
void DispatchOnDefaultPriorityConcurrentQueue (BBlockBlock block);
[Static, Export ("dispatchOnLowPriorityConcurrentQueue:")]
void DispatchOnLowPriorityConcurrentQueue (BBlockBlock block);
[Static, Export ("dispatchOnHighPriorityConcurrentQueue:")]
void DispatchOnHighPriorityConcurrentQueue (BBlockBlock block);
// UIImage helper methods
[Static, Export ("imageForSize:withDrawingBlock:")]
UIImage ImageForSize (SizeF size, BBlockBlock drawingBlock);
[Static, Export ("imageForSize:opaque:withDrawingBlock:")]
UIImage ImageForSize (SizeF size, bool opaque, BBlockBlock drawingBlock);
[Static, Export ("imageWithIdentifier:forSize:andDrawingBlock:")]
UIImage ImageWithIdentifier (string identifier, SizeF size, BBlockBlock drawingBlock);
[Static, Export ("imageWithIdentifier:opaque:forSize:andDrawingBlock:")]
UIImage ImageWithIdentifier (string identifier, bool opaque, SizeF size, BBlockBlock drawingBlock);
[Static, Export ("imageWithIdentifier:")]
UIImage ImageWithIdentifier (string identifier);
[Static, Export ("removeImageWithIdentifier:")]
void RemoveImageWithIdentifier (string identifier);
[Static, Export ("removeAllImages")]
void RemoveAllImages ();
}
[Category, BaseType (typeof (NSArray))]
public partial interface BBlock_NSArray
{
[Export ("enumerateEachObjectUsingBlock:")]
void EnumerateEachObjectUsingBlock (BBlockBlock block);
[Export ("arrayWithObjectsMappedWithBlock:")]
NSObject [] ArrayWithObjectsMappedWithBlock (BBlockBlock block);
}
[Category, BaseType (typeof (NSDictionary))]
public partial interface BBlock_NSDictionary
{
[Export ("enumerateEachKeyAndObjectUsingBlock:")]
void EnumerateEachKeyAndObjectUsingBlock (BBlockBlock block);
[Export ("enumerateEachSortedKeyAndObjectUsingBlock:")]
void EnumerateEachSortedKeyAndObjectUsingBlock (BBlockBlock block);
}
[Category, BaseType (typeof (NSObject))]
public partial interface BBlock_NSObject
{
[Export ("addObserverForKeyPath:options:block:")]
string AddObserverForKeyPath (string keyPath, NSKeyValueObservingOptions options, NSObjectBBlock block);
[Export ("removeObserverForToken:")]
void RemoveObserverForToken (string identifier);
[Export ("removeObserverBlocksForKeyPath:")]
void RemoveObserverBlocksForKeyPath (string keyPath);
[Export ("changeValueWithKey:changeBlock:")]
void ChangeValueWithKey (string key, BBlockBlock changeBlock);
}
[Category, BaseType (typeof (NSTimer))]
public partial interface BBlock_NSTimer
{
[Static, Export ("timerWithTimeInterval:andBlock:")]
NSTimer TimerWithTimeInterval (double timeInterval, BBlockBlock block);
[Static, Export ("timerRepeats:withTimeInterval:andBlock:")]
NSTimer TimerRepeats (bool repeats, double timeInterval, BBlockBlock block);
[Static, Export ("scheduledTimerWithTimeInterval:andBlock:")]
NSTimer ScheduledTimerWithTimeInterval (double timeInterval, BBlockBlock block);
[Static, Export ("scheduledTimerRepeats:withTimeInterval:andBlock:")]
NSTimer ScheduledTimerRepeats (bool repeats, double timeInterval, BBlockBlock block);
}
[Category, BaseType (typeof (UIControl))]
public partial interface BBlock_UIControl
{
[Export ("addActionForControlEvents:withBlock:")]
void AddActionForControlEvents (UIControlEvent events, BBlockUIControlBlock block);
}
[Category, BaseType (typeof (UIImage))]
public partial interface BBlock_UIImage
{
[Static, Export ("imageForSize:withDrawingBlock:")]
UIImage ImageForSize (SizeF size, BBlockBlock drawingBlock);
[Static, Export ("imageForSize:opaque:withDrawingBlock:")]
UIImage ImageForSize (SizeF size, bool opaque, BBlockBlock drawingBlock);
[Static, Export ("imageWithIdentifier:forSize:andDrawingBlock:")]
UIImage ImageWithIdentifier (string identifier, SizeF size, BBlockBlock drawingBlock);
[Static, Export ("imageWithIdentifier:opaque:forSize:andDrawingBlock:")]
UIImage ImageWithIdentifier (string identifier, bool opaque, SizeF size, BBlockBlock drawingBlock);
[Static, Export ("imageWithIdentifier:")]
UIImage ImageWithIdentifier (string identifier);
[Static, Export ("removeImageWithIdentifier:")]
void RemoveImageWithIdentifier (string identifier);
[Static, Export ("removeAllImages")]
void RemoveAllImages ();
}
[Category, BaseType (typeof (SKStoreProductViewController))]
public partial interface BBlock_SKStoreProductViewController
{
[Static, Export ("productViewControllerWithDidFinishBlock:")]
IntPtr ProductViewControllerWithDidFinishBlock (SKStoreProductViewControllerBBlock block);
[Export ("initWithProductViewControllerWithDidFinishBlock:")]
IntPtr InitWithProductViewControllerWithDidFinishBlock (SKStoreProductViewControllerBBlock block);
}
[Category, BaseType (typeof (UIActionSheet))]
public partial interface BBlock_UIActionSheet
{
[Export ("completionBlock")]
void SetCompletionBlock (UIActionSheetBBlock block);
[Export ("initWithTitle:cancelButtonTitle:destructiveButtonTitle:otherButtonTitle:completionBlock:")]
IntPtr InitWithTitle (string title, string cancelTitle, string destructiveTitle, string otherTitle, UIActionSheetBBlock block);
}
[Category, BaseType (typeof (UIAlertView))]
public partial interface BBlock_UIAlertView
{
[Export ("completionBlock")]
void SetCompletionBlock (UIAlertViewBBlock block);
[Export ("initWithTitle:message:cancelButtonTitle:otherButtonTitle:completionBlock:")]
IntPtr InitWithTitle (string title, string message, string cancelTitle, string otherButtonTitle, UIAlertViewBBlock block);
}
[Category, BaseType (typeof (UIGestureRecognizer))]
public partial interface BBlock_UIGestureRecognizer
{
[Export ("initWithBlock:")]
IntPtr InitWithBlock (UIGestureRecognizerBBlock block);
[Static, Export ("gestureRecognizerWithBlock:")]
IntPtr GestureRecognizerWithBlock (UIGestureRecognizerBBlock block);
}
[Category, BaseType (typeof (UISwipeGestureRecognizer))]
public partial interface BBlock_UISwipeGestureRecognizer
{
[Export ("initWithDirection:andBlock:")]
IntPtr InitWithDirection (UISwipeGestureRecognizerDirection direction, UIGestureRecognizerBBlock block);
[Static, Export ("gestureRecognizerWithDirection:andBlock:")]
IntPtr GestureRecognizerWithDirection (UISwipeGestureRecognizerDirection direction, UIGestureRecognizerBBlock block);
}
[Category, BaseType (typeof (UITextField))]
public partial interface BBlock_UITextField
{
[Export ("textFieldShouldReturnWithBlock:")]
void TextFieldShouldReturnWithBlock (UITextFieldShouldReturnBBlock block);
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
namespace Utilities
{
public class FileSystemHelper
{
const string thisClassName = "FileSystemHelper";
public FileSystemHelper()
{ }
#region export methods
/// <summary>
/// ExportDataTableAsCsv - formats a DataTable in CSV format and then streams to the browser
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="tempFilename">Name of temporary file</param>
public void ExportDataTableAsCsv( DataTable dt, string tempFilename )
{
string datePrefix = System.DateTime.Today.ToString( "u" ).Substring( 0, 10 );
string filePath = UtilityManager.GetAppKeyValue( "path.ReportsOutputPath", "" );
string outputFile = filePath + datePrefix + "_" + tempFilename;
//
//string filename = "budgetExport.csv";
string csvFilename = this.DataTableAsCsv( dt, outputFile, false );
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader( "Content-Disposition", "attachment; filename=" + tempFilename + "" );
HttpContext.Current.Response.WriteFile( csvFilename );
HttpContext.Current.Response.End();
// Delete the newly created file.
//TODO: - this line is not actually executed - need scheduled clean ups?
//File.Delete(Server.MapPath(csvFilename));
}
/// <summary>
/// DataTableAsCsv - formats a DataTable in csv format
/// The code first loops through the columns of the data table
/// to export the names of all the data columns.
/// Then in next loop the code iterates over each data row to export
/// all the values in the table.
/// This method creates a temporary file on the server. This temporary file will
/// need to be manually deleted at a later time.
/// </summary>
/// <param name="dt">DataTable</param>
/// <param name="tempFilename">Name of temporary file</param>
/// <param name="doingMapPath">If true use Server.MapPath(</param>///
/// <returns>Name of temp file created on the server</returns>
public string DataTableAsCsv( DataTable dt, string tempFilename, bool doingMapPath )
{
string strColumn = "";
string strCorrected = "";
StreamWriter sw;
string serverFilename = ""; ;
if ( doingMapPath )
{
serverFilename = "~/" + tempFilename;
// Create the CSV file to which grid data will be exported.
sw = new StreamWriter( System.Web.HttpContext.Current.Server.MapPath( serverFilename ), false );
} else
{
serverFilename = tempFilename;
sw = new StreamWriter( serverFilename, false );
}
// First we will write the headers.
int intCount = dt.Columns.Count;
for ( int i = 0; i < intCount; i++ )
{
sw.Write( dt.Columns[ i ].ToString() );
if ( i < intCount - 1 )
{
sw.Write( "," );
}
}
sw.Write( sw.NewLine );
// Now write all the rows.
foreach ( DataRow dr in dt.Rows )
{
for ( int i = 0; i < intCount; i++ )
{
if ( !Convert.IsDBNull( dr[ i ] ) )
{
strColumn = dr[ i ].ToString();
strCorrected = strColumn.Replace( "\"", "\'" );
sw.Write( "\"" + strCorrected + "\"" );
} else
{
sw.Write( "" );
}
if ( i < intCount - 1 )
{
sw.Write( "," );
}
}
sw.Write( sw.NewLine );
}
sw.Close();
return serverFilename;
} //
//public FileContentResult ExportConversion(MyFilters filters)
//{
// try
// {
// var Data = IService.SomeMethod("filters").ToList();
// var bytes = GenericHelper.GetBytesForCSVFile(Data, DataPreparer.FormatCSV,
// "TotalItemsPerday, SpecialItemsPerDay, SpecialItemsPercentage");
// return File(bytes, "text/csv", "FileName");
// }
// catch (Exception exception)
// {
// //_logger.LogError(exception);
// throw;
// }
//}
//public static class GenericHelper
//{
// public static byte[] GetBytesForCSVFile<T>(List<T> Data, Converter<T, string> converter,string headerrow="")
// {
// if (Data.Any())
// {
// var convertAll = Data.ConvertAll(converter);
// convertAll.Insert(0, headerrow + Environment.NewLine);
// string completeString = String.Concat(convertAll);
// return new UTF8Encoding().GetBytes(completeString);
// }
// else
// {
// return new byte[]{};
// }
// }
//}
//public static class DataPreparer
//{
// public static string FormatCSV(Item item)
// {
// return TotalItemsPerDay.ToString() +
// "," + SpecialItemsPerday.ToString() +
// "," + SpecialItemsPercentage.ToString() +"%" + Environment.NewLine;
// }
//}
#endregion
#region Folders and files
/// <summary>
/// Analyze a filename, and return system friendly name
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string SanitizeFilename( string filename )
{
return SanitizeFilename( filename, 0 );
}
/// <summary>
/// Analyze a filename, and return system friendly name
/// </summary>
/// <param name="filename"></param>
/// <param name="maxLength">If greater than zero, use to truncate the file length</param>
/// <returns></returns>
public static string SanitizeFilename( string filename, int maxLength )
{
if ( filename == null || filename.Trim().Length == 0 )
return "";
string file = filename.Trim();
file = string.Concat( file.Split( System.IO.Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries ) );
if ( maxLength > 0 && file.Length > maxLength )
{
file = file.Substring( 0, maxLength );
}
return file;
} //
/// <summary>
/// Return true if the passed path exists
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool DoesPathExist( string path )
{
if ( path == null )
return false;
try
{
if ( Directory.Exists( path ) )
{
return true;
} else
{
return false;
}
} catch ( Exception ex )
{
LoggingHelper.LogError( ex, thisClassName + ".DoesPathExist(" + path + ")" );
return false;
}
}
/// <summary>
/// Check if file exists on server
/// </summary>
/// <param name="documentFolder"></param>
/// <param name="fileName"></param>
public static bool DoesFileExist( string documentFolder, string fileName )
{
if ( documentFolder == null || fileName == null )
return false;
string pathAndFileName = documentFolder + "\\" + fileName;
return DoesFileExist( pathAndFileName );
}
/// <summary>
/// Check if file exists on server
/// </summary>
/// <param name="documentFolder"></param>
/// <param name="fileName"></param>
public static bool DoesFileExist( string pathAndFileName )
{
if ( pathAndFileName == null || pathAndFileName == null )
return false;
try
{
if ( System.IO.File.Exists( pathAndFileName ) )
{
return true;
} else
{
return false;
}
} catch ( Exception ex )
{
LoggingHelper.LogError( ex, thisClassName + ".DoesFileExist() - Unexpected error encountered while retrieving document. File: " + pathAndFileName );
return false;
}
}//
/// <summary>
/// Create the passed directory structure
/// As System.IO.Directory.CreateDirectory() checks folder existence from root to lowest folder, it will fail if an intermediate folder
/// doesn't exist. This method performs the scan in the reverse way - from lowest to upper. Therefore, it won't fail unless it will get to
/// some folder with no read permissions.
/// requires Microsoft Scripting Runtime COM (windows\system32\scrrun.dll)
/// ref: http://www.codeproject.com/KB/files/createdirectorymethod.aspx
/// </summary>
/// <param name="path"></param>
public static void CreateDirectory( string path )
{
// trim leading \ character
try
{
//first check if already exists
if ( DoesPathExist( path ) )
return;
path = path.TrimEnd( Path.DirectorySeparatorChar );
// check if folder exists, if yes - no work to do
if ( !Directory.Exists( path ) )
{
int i = path.LastIndexOf( Path.DirectorySeparatorChar );
// find last\lowest folder name
string CurrentDirectoryName = path.Substring( i + 1, path.Length - i - 1 );
// find parent folder of the last folder
string ParentDirectoryPath = path.Substring( 0, i );
// recursive calling of function to create all parent folders
CreateDirectory( ParentDirectoryPath );
// create last folder in current path
DirectoryInfo dirInfo = new DirectoryInfo(ParentDirectoryPath);
dirInfo.CreateSubdirectory(CurrentDirectoryName);
//Scripting.Folder folder = fso.GetFolder( ParentDirectoryPath );
//folder.SubFolders.Add( CurrentDirectoryName );
}
} catch ( Exception ex )
{
LoggingHelper.LogError( ex, thisClassName + ".CreateDirectory(" + path + ")" );
}
}
/// <summary>
/// Get the root path for the current environment
/// </summary>
/// <returns></returns>
//public static string GetThisRootPath()
//{
// return UtilityManager.GetAppKeyValue( "path.RootPath" );
//}
///// <summary>
///// Get absolute url for cache
///// </summary>
///// <returns></returns>
//public static string GetCacheOutputUrl()
//{
// return GetCacheOutputUrl( "" );
//}
///// <summary>
///// Get absolute url for cache
///// </summary>
///// <param name="subPath"></param>
///// <returns></returns>
//public static string GetCacheOutputUrl( string subPath )
//{
// string domain = GetThisDomainUrl();
// string cacheUrl = UtilityManager.GetAppKeyValue( "path.CacheUrl" );
// if ( subPath.Length > 0 )
// return domain + cacheUrl + "/" + subPath + "/";
// else
// return domain + cacheUrl + "/";
//}
///// <summary>
///// Get output path for cache
///// </summary>
///// <returns></returns>
//public static string GetCacheOutputPath()
//{
// return GetCacheOutputPath( "" );
//}
//public static string GetCacheOutputPath(string subPath)
//{
// string root = GetThisRootPath();
// string cacheFolder = UtilityManager.GetAppKeyValue( "path.CacheFolder" );
// if (subPath.Length > 0)
// return root + cacheFolder + "\\" + subPath + "\\";
// else
// return root + cacheFolder + "\\";
//}
#endregion
}
public class Item
{
public int Id { get; set; }
public decimal TotalItemsPerDay { get; set; }
public decimal SpecialItemsPerDay { get; set; }
public decimal SpecialItemsPercentage { get; set; }
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERCLevel;
namespace ParentLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// F07_RegionColl (editable child list).<br/>
/// This is a generated base class of <see cref="F07_RegionColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="F06_Country"/> editable child object.<br/>
/// The items of the collection are <see cref="F08_Region"/> objects.
/// </remarks>
[Serializable]
public partial class F07_RegionColl : BusinessListBase<F07_RegionColl, F08_Region>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="F08_Region"/> item from the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to be removed.</param>
public void Remove(int region_ID)
{
foreach (var f08_Region in this)
{
if (f08_Region.Region_ID == region_ID)
{
Remove(f08_Region);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="F08_Region"/> item is in the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the F08_Region is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int region_ID)
{
foreach (var f08_Region in this)
{
if (f08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="F08_Region"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the F08_Region is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int region_ID)
{
foreach (var f08_Region in DeletedList)
{
if (f08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="F08_Region"/> item of the <see cref="F07_RegionColl"/> collection, based on item key properties.
/// </summary>
/// <param name="region_ID">The Region_ID.</param>
/// <returns>A <see cref="F08_Region"/> object.</returns>
public F08_Region FindF08_RegionByParentProperties(int region_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Region_ID.Equals(region_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="F07_RegionColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="F07_RegionColl"/> collection.</returns>
internal static F07_RegionColl NewF07_RegionColl()
{
return DataPortal.CreateChild<F07_RegionColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="F07_RegionColl"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="F07_RegionColl"/> object.</returns>
internal static F07_RegionColl GetF07_RegionColl(SafeDataReader dr)
{
F07_RegionColl obj = new F07_RegionColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="F07_RegionColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public F07_RegionColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="F07_RegionColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(dr);
OnFetchPre(args);
while (dr.Read())
{
Add(F08_Region.GetF08_Region(dr));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="F08_Region"/> items on the F07_RegionObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="F05_CountryColl"/> collection.</param>
internal void LoadItems(F05_CountryColl collection)
{
foreach (var item in this)
{
var obj = collection.FindF06_CountryByParentProperties(item.parent_Country_ID);
var rlce = obj.F07_RegionObjects.RaiseListChangedEvents;
obj.F07_RegionObjects.RaiseListChangedEvents = false;
obj.F07_RegionObjects.Add(item);
obj.F07_RegionObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright 2020 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.
using Google.Cloud.EntityFrameworkCore.Spanner.Storage;
using Google.Cloud.Spanner.Data;
using Google.Cloud.Spanner.V1;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
namespace Google.Cloud.EntityFrameworkCore.Spanner.IntegrationTests
{
public class SpannerMigrationTest : IClassFixture<MigrationTestFixture>
{
private readonly MigrationTestFixture _fixture;
public SpannerMigrationTest(MigrationTestFixture fixture) => _fixture = fixture;
[Fact]
public async Task AllTablesAreGenerated()
{
using var connection = _fixture.GetConnection();
var tableNames = new string[] { "Products", "Categories", "Orders", "OrderDetails", "Articles", "Authors" };
var tables = new SpannerParameterCollection
{
{ "tables", SpannerDbType.ArrayOf(SpannerDbType.String), tableNames }
};
var cmd = connection.CreateSelectCommand(
"SELECT COUNT(*) " +
"FROM INFORMATION_SCHEMA.TABLES " +
"WHERE TABLE_CATALOG='' AND TABLE_SCHEMA='' AND TABLE_NAME IN UNNEST (@tables)", tables);
using var reader = await cmd.ExecuteReaderAsync();
Assert.True(await reader.ReadAsync());
Assert.Equal(tableNames.Length, reader.GetInt64(0));
Assert.False(await reader.ReadAsync());
}
[Fact]
public async Task CanInsertUpdateCategories()
{
using var context = new TestMigrationDbContext(_fixture.DatabaseName);
context.Categories.AddRange(new List<Category>
{
new Category {
CategoryId = 3,
CategoryName = "Beverages",
CategoryDescription = "Soft drinks, coffees, teas, beers, and ales"
}, new Category {
CategoryId = 4,
CategoryName = "Seafood",
CategoryDescription = "Seaweed and fish"
}
});
var rowCount = await context.SaveChangesAsync();
Assert.Equal(2, rowCount);
// Update category
var category = await context.Categories.FindAsync(1L);
category.CategoryName = "Dairy Products";
category.CategoryDescription = "Cheeses";
await context.SaveChangesAsync();
// Get updated category from db
category = await context.Categories.FindAsync(1L);
Assert.Equal("Dairy Products", category.CategoryName);
Assert.Equal("Cheeses", category.CategoryDescription);
}
[Fact]
public async Task CanInsertAndUpdateNullValues()
{
using var context = new TestMigrationDbContext(_fixture.DatabaseName);
context.AllColTypes.Add(new AllColType
{
Id = 1,
ColString = "Test String"
});
var rowCount = await context.SaveChangesAsync();
Assert.Equal(1, rowCount);
var row = await context.AllColTypes.FindAsync(1);
Assert.Null(row.ColTimestamp);
Assert.Null(row.ColShort);
Assert.Null(row.ColInt);
// Update from null to non-null.
row.ColBool = true;
row.ColBoolArray = new bool[] { true, false };
row.ColBytes = Encoding.UTF8.GetBytes("string 1");
row.ColBytesArray = new byte[][] { Encoding.UTF8.GetBytes("string 1"), Encoding.UTF8.GetBytes("string 2") };
row.ColBoolList = new List<bool> { false, true };
row.ColTimestampList = new List<DateTime> { DateTime.Now, DateTime.Now.AddDays(1) };
await context.SaveChangesAsync();
// Retrieve updated row from database
row = await context.AllColTypes.FindAsync(1);
Assert.NotNull(row.ColBool);
Assert.NotNull(row.ColBoolArray);
Assert.NotNull(row.ColBytes);
Assert.NotNull(row.ColBytesArray);
Assert.NotNull(row.ColBoolList);
Assert.NotNull(row.ColTimestampList);
// Update from non-null back to null.
row.ColBool = null;
row.ColBoolArray = null;
row.ColBytes = null;
row.ColBytesArray = null;
row.ColBoolList = null;
row.ColTimestampList = null;
await context.SaveChangesAsync();
// Retrieve updated row from database
row = await context.AllColTypes.FindAsync(1);
Assert.Null(row.ColBool);
Assert.Null(row.ColBoolArray);
Assert.Null(row.ColBytes);
Assert.Null(row.ColBytesArray);
Assert.Null(row.ColBoolList);
Assert.Null(row.ColTimestampList);
}
[Fact]
public async Task CanInsertAndUpdateRowWithAllDataTypes()
{
var now = DateTime.UtcNow;
var guid = Guid.NewGuid();
using (var context = new TestMigrationDbContext(_fixture.DatabaseName))
{
var row = new AllColType
{
Id = 10,
ColBool = true,
ColBoolArray = new bool[] { true, false },
ColBoolList = new List<bool> { false, true },
ColBytes = Encoding.UTF8.GetBytes("string 1"),
ColBytesArray = new byte[][] { Encoding.UTF8.GetBytes("string 1"), Encoding.UTF8.GetBytes("string 2") },
ColBytesList = new List<byte[]> { Encoding.UTF8.GetBytes("string 3"), Encoding.UTF8.GetBytes("string 4") },
ColTimestamp = new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288),
ColTimestampArray = new DateTime[] { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), now },
ColTimestampList = new List<DateTime> { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), now },
ColDecimal = (SpannerNumeric)10.100m,
ColDecimalArray = new SpannerNumeric[] { (SpannerNumeric)10.1m, (SpannerNumeric)13.5m },
ColDecimalList = new List<SpannerNumeric> { (SpannerNumeric)10.1m, (SpannerNumeric)13.5m },
ColDouble = 12.01,
ColDoubleArray = new double[] { 12.01, 12.02 },
ColDoubleList = new List<double> { 13.01, 13.02 },
ColFloat = 15.999f,
ColGuid = guid,
ColInt = 10,
ColJson = JsonDocument.Parse("{\"key\": \"value\"}"),
ColJsonArray = new []{ JsonDocument.Parse("{\"key1\": \"value1\"}"), JsonDocument.Parse("{\"key2\": \"value2\"}") },
ColJsonList = new List<JsonDocument> {JsonDocument.Parse("{\"key1\": \"value1\"}"), JsonDocument.Parse("{\"key2\": \"value2\"}")},
ColLong = 155,
ColLongArray = new long[] { 15, 16 },
ColLongList = new List<long> { 20, 25 },
ColShort = 10,
ColString = "String 1",
ColStringArray = new string[] { "string1", "string2", "string3" },
ColStringList = new List<string> { "string4", "string5" },
ColUint = 12,
ColDate = new SpannerDate(2021, 1, 1),
ColDateArray = new SpannerDate[] { new SpannerDate(2021, 1, 1), new SpannerDate(2021, 1, 2) },
ColDateList = new List<SpannerDate> { new SpannerDate(2021, 1, 3), new SpannerDate(2021, 1, 4) },
ColByte = 10,
ColSbyte = -120,
ColULong = 1000000,
ColUShort = 2,
ColChar = 'a',
ASC = "sample string"
};
context.AllColTypes.Add(row);
var rowCount = await context.SaveChangesAsync();
Assert.Equal(1, rowCount);
}
// Get inserted Rows from database.
using (var context = new TestMigrationDbContext(_fixture.DatabaseName))
{
var row = await context.AllColTypes.FindAsync(10);
Assert.Equal(10, row.Id);
Assert.True(row.ColBool);
Assert.Equal(new bool[] { true, false }, row.ColBoolArray);
Assert.Equal(new List<bool> { false, true }, row.ColBoolList);
Assert.Equal(Encoding.UTF8.GetBytes("string 1"), row.ColBytes);
Assert.Equal(new byte[][] { Encoding.UTF8.GetBytes("string 1"), Encoding.UTF8.GetBytes("string 2") }, row.ColBytesArray);
Assert.Equal(new List<byte[]> { Encoding.UTF8.GetBytes("string 3"), Encoding.UTF8.GetBytes("string 4") }, row.ColBytesList);
Assert.Equal(new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), row.ColTimestamp);
Assert.Equal(new DateTime[] { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), now }, row.ColTimestampArray);
Assert.Equal(new List<DateTime> { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(1839288), now }, row.ColTimestampList);
Assert.Equal((SpannerNumeric)10.100m, row.ColDecimal);
Assert.Equal(new SpannerNumeric[] { (SpannerNumeric)10.1m, (SpannerNumeric)13.5m }, row.ColDecimalArray);
Assert.Equal(new List<SpannerNumeric> { (SpannerNumeric)10.1m, (SpannerNumeric)13.5m }, row.ColDecimalList);
Assert.Equal(12.01, row.ColDouble);
Assert.Equal(new double[] { 12.01, 12.02 }, row.ColDoubleArray);
Assert.Equal(new List<double> { 13.01, 13.02 }, row.ColDoubleList);
Assert.Equal(15.999f, row.ColFloat);
Assert.Equal(guid, row.ColGuid);
Assert.Equal(10, row.ColInt);
if (!SpannerFixtureBase.IsEmulator)
{
Assert.Equal("{\"key\":\"value\"}", row.ColJson.RootElement.ToString());
Assert.Equal(new[] { "{\"key1\":\"value1\"}", "{\"key2\":\"value2\"}" },
row.ColJsonArray.Select(v => v?.RootElement.ToString()).ToArray());
Assert.Equal(new[] { "{\"key1\":\"value1\"}", "{\"key2\":\"value2\"}" },
row.ColJsonList.Select(v => v?.RootElement.ToString()).ToList());
}
Assert.Equal(155, row.ColLong);
Assert.Equal(new long[] { 15, 16 }, row.ColLongArray);
Assert.Equal(new List<long> { 20, 25 }, row.ColLongList);
Assert.Equal((short)10, row.ColShort);
Assert.Equal("String 1", row.ColString);
Assert.Equal(new string[] { "string1", "string2", "string3" }, row.ColStringArray);
Assert.Equal(new List<string> { "string4", "string5" }, row.ColStringList);
Assert.Equal((uint)12, row.ColUint);
Assert.Equal(new SpannerDate(2021, 1, 1), row.ColDate);
Assert.Equal(new SpannerDate[] { new SpannerDate(2021, 1, 1), new SpannerDate(2021, 1, 2) }, row.ColDateArray);
Assert.Equal(new List<SpannerDate> { new SpannerDate(2021, 1, 3), new SpannerDate(2021, 1, 4) }, row.ColDateList);
Assert.Equal((byte)10, row.ColByte);
Assert.Equal((sbyte)-120, row.ColSbyte);
Assert.Equal((ulong)1000000, row.ColULong);
Assert.Equal((ushort)2, row.ColUShort);
Assert.Equal('a', row.ColChar);
Assert.Equal("sample string", row.ASC);
// The commit timestamp was automatically set by Cloud Spanner.
Assert.NotEqual(new DateTime(), row.ColCommitTimestamp);
// This assumes that the local time does not differ more than 10 minutes with TrueTime.
if (!SpannerFixtureBase.IsEmulator)
{
Assert.True(Math.Abs(DateTime.UtcNow.Subtract(row.ColCommitTimestamp.GetValueOrDefault()).TotalMinutes) < 10, $"Commit timestamp {row.ColCommitTimestamp} differs with more than 10 minutes from now ({DateTime.UtcNow})");
}
// Update rows
row.ColBool = false;
row.ColBoolArray = new bool[] { false, true, false };
row.ColBoolList = new List<bool> { true, true };
row.ColBytes = Encoding.UTF8.GetBytes("This string has changed");
row.ColBytesArray = new byte[][] { Encoding.UTF8.GetBytes("string change 1"), Encoding.UTF8.GetBytes("string change 2") };
row.ColBytesList = new List<byte[]> { Encoding.UTF8.GetBytes("string change 3"), Encoding.UTF8.GetBytes("string change 4") };
row.ColTimestamp = new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(5000);
row.ColTimestampArray = new DateTime[] { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(5000), now };
row.ColTimestampList = new List<DateTime> { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(500), now };
row.ColDecimal = (SpannerNumeric)10.5m;
row.ColDecimalArray = new SpannerNumeric[] { (SpannerNumeric)20.1m, (SpannerNumeric)30.5m };
row.ColDecimalList = new List<SpannerNumeric> { (SpannerNumeric)50m, (SpannerNumeric)15.5m };
row.ColDouble = 15;
row.ColDoubleArray = new double[] { 15.5 };
row.ColDoubleList = new List<double> { 30.9 };
row.ColFloat = 16.52f;
row.ColInt = 200;
row.ColJson = JsonDocument.Parse("{\"key\": \"new-value\"}");
row.ColJsonArray = new[]
{ JsonDocument.Parse("{\"key1\": \"new-value1\"}"), JsonDocument.Parse("{\"key2\": \"new-value2\"}") };
row.ColJsonList = new List<JsonDocument>
{ JsonDocument.Parse("{\"key1\": \"new-value1\"}"), JsonDocument.Parse("{\"key2\": \"new-value2\"}") };
row.ColLong = 19999;
row.ColLongArray = new long[] { 17, 18 };
row.ColLongList = new List<long> { 25, 26 };
row.ColShort = 1;
row.ColString = "Updated String 1";
row.ColStringArray = new string[] { "string1 Updated" };
row.ColStringList = new List<string> { "string2 Updated" };
row.ColUint = 3;
row.ColDate = new SpannerDate(2021, 1, 2);
row.ColDateArray = new SpannerDate[] { new SpannerDate(2021, 1, 3), new SpannerDate(2021, 1, 4) };
row.ColDateList = new List<SpannerDate> { new SpannerDate(2021, 1, 5), new SpannerDate(2021, 1, 6) };
row.ColByte = 20;
row.ColSbyte = -101;
row.ColULong = 2000000;
row.ColUShort = 5;
row.ColChar = 'b';
row.ASC = "sample string updated";
await context.SaveChangesAsync();
}
// Retrieve Updated Rows
using (var context = new TestMigrationDbContext(_fixture.DatabaseName))
{
var row = await context.AllColTypes.FindAsync(10);
Assert.False(row.ColBool);
Assert.Equal(new bool[] { false, true, false }, row.ColBoolArray);
Assert.Equal(new List<bool> { true, true }, row.ColBoolList);
Assert.Equal(Encoding.UTF8.GetBytes("This string has changed"), row.ColBytes);
Assert.Equal(new byte[][] { Encoding.UTF8.GetBytes("string change 1"), Encoding.UTF8.GetBytes("string change 2") }, row.ColBytesArray);
Assert.Equal(new List<byte[]> { Encoding.UTF8.GetBytes("string change 3"), Encoding.UTF8.GetBytes("string change 4") }, row.ColBytesList);
Assert.Equal(new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(5000), row.ColTimestamp);
Assert.Equal(new DateTime[] { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(5000), now }, row.ColTimestampArray);
Assert.Equal(new List<DateTime> { new DateTime(2020, 12, 28, 15, 16, 28, 148).AddTicks(500), now }, row.ColTimestampList);
Assert.Equal((SpannerNumeric)10.5m, row.ColDecimal);
Assert.Equal(new SpannerNumeric[] { (SpannerNumeric)20.1m, (SpannerNumeric)30.5m }, row.ColDecimalArray);
Assert.Equal(new List<SpannerNumeric> { (SpannerNumeric)50m, (SpannerNumeric)15.5m }, row.ColDecimalList);
Assert.Equal(15, row.ColDouble);
Assert.Equal(new double[] { 15.5 }, row.ColDoubleArray);
Assert.Equal(new List<double> { 30.9 }, row.ColDoubleList);
Assert.Equal(16.52f, row.ColFloat);
Assert.Equal(200, row.ColInt);
if (!SpannerFixtureBase.IsEmulator)
{
Assert.Equal("{\"key\":\"new-value\"}", row.ColJson.RootElement.ToString());
Assert.Equal(new[] { "{\"key1\":\"new-value1\"}", "{\"key2\":\"new-value2\"}" },
row.ColJsonArray.Select(v => v?.RootElement.ToString()).ToArray());
Assert.Equal(new[] { "{\"key1\":\"new-value1\"}", "{\"key2\":\"new-value2\"}" },
row.ColJsonList.Select(v => v?.RootElement.ToString()).ToList());
}
Assert.Equal(19999, row.ColLong);
Assert.Equal(new long[] { 17, 18 }, row.ColLongArray);
Assert.Equal(new List<long> { 25, 26 }, row.ColLongList);
Assert.Equal((short)1, row.ColShort);
Assert.Equal("Updated String 1", row.ColString);
Assert.Equal(new string[] { "string1 Updated" }, row.ColStringArray);
Assert.Equal(new List<string> { "string2 Updated" }, row.ColStringList);
Assert.Equal((uint)3, row.ColUint);
Assert.Equal(new SpannerDate(2021, 1, 2), row.ColDate);
Assert.Equal(new SpannerDate[] { new SpannerDate(2021, 1, 3), new SpannerDate(2021, 1, 4) }, row.ColDateArray);
Assert.Equal(new List<SpannerDate> { new SpannerDate(2021, 1, 5), new SpannerDate(2021, 1, 6) }, row.ColDateList);
Assert.Equal((byte)20, row.ColByte);
Assert.Equal((sbyte)-101, row.ColSbyte);
Assert.Equal((ulong)2000000, row.ColULong);
Assert.Equal((ushort)5, row.ColUShort);
Assert.Equal('b', row.ColChar);
Assert.Equal("sample string updated", row.ASC);
}
}
[Fact]
public async Task CanInsertOrderDetils()
{
using var context = new TestMigrationDbContext(_fixture.DatabaseName);
context.OrderDetails.Add(new OrderDetail
{
OrderId = 1,
ProductId = 1,
Order = new Order
{
OrderId = 1,
OrderDate = DateTime.Now,
Freight = 155555.10f,
ShipAddress = "Statue of Liberty-New York Access",
ShipCountry = "USA",
ShipCity = "New York",
ShipPostalCode = "10004"
},
Discount = 10.0f,
Product = new Product
{
ProductId = 1,
CategoryId = 1,
ProductName = "Product 1",
Category = new Category
{
CategoryId = 1,
CategoryName = "Grains/Cereals",
CategoryDescription = "Breads, crackers, pasta, and cereal"
}
},
Quantity = 56,
UnitPrice = 15000
});
var rowCount = await context.SaveChangesAsync();
Assert.Equal(4, rowCount);
}
[Fact]
public async void CanDeleteData()
{
using var context = new TestMigrationDbContext(_fixture.DatabaseName);
// Insert Category
var category = new Category
{
CategoryId = 99,
CategoryName = "Confections",
CategoryDescription = "Desserts, candies, and sweet breads"
};
context.Categories.Add(category);
// Insert Products
var product = new Product
{
ProductId = 99,
CategoryId = 99,
ProductName = "Product 99"
};
context.Products.Add(product);
// Insert Order
var order = new Order
{
OrderDate = DateTime.Now,
OrderId = 99,
ShipCity = "New York",
ShipName = "Back yard",
ShipAddress = "South Street Seaport",
ShipPostalCode = " 10038",
ShipCountry = "USA",
ShippedDate = DateTime.Now.AddDays(10),
ShipVia = "Transport"
};
context.Orders.Add(order);
// Insert Order Details
var orderDetail = new OrderDetail
{
ProductId = 99,
OrderId = 99,
Discount = 10.5f,
UnitPrice = 1900,
Quantity = 150
};
context.OrderDetails.Add(orderDetail);
// Insert AllColType
var allColType = new AllColType
{
Id = 99
};
context.AllColTypes.Add(allColType);
await context.SaveChangesAsync();
// Delete Data
context.Categories.Remove(category);
context.Products.Remove(product);
context.Orders.Remove(order);
context.OrderDetails.Remove(orderDetail);
context.AllColTypes.Remove(allColType);
await context.SaveChangesAsync();
// Verify that all rows were deleted.
Assert.Null(await context.Categories.FindAsync(category.CategoryId));
Assert.Null(await context.Products.FindAsync(product.ProductId));
Assert.Null(await context.Orders.FindAsync(order.OrderId));
Assert.Null(await context.OrderDetails.FindAsync(orderDetail.OrderId, orderDetail.ProductId));
Assert.Null(await context.AllColTypes.FindAsync(allColType.Id));
}
[Fact]
public void ShouldThrowLengthValidationException()
{
using var context = new TestMigrationDbContext(_fixture.DatabaseName);
context.Products.Add(new Product
{
ProductId = 9,
Category = new Category
{
CategoryId = 9,
CategoryName = "Soft Drink",
},
ProductName = "this is too long string should throw length validation error " +
"this is too long string should throw length validation error"
});
Assert.Throws<SpannerException>(() => context.SaveChanges());
}
[Fact]
public void ShouldThrowRequiredFieldValidationException()
{
using var context = new TestMigrationDbContext(_fixture.DatabaseName);
context.Products.Add(new Product
{
ProductId = 9,
Category = new Category
{
CategoryId = 9,
CategoryName = "Soft Drink",
}
});
Assert.Throws<SpannerException>(() => context.SaveChanges());
}
[Fact]
public async Task CanInsertAndDeleteInterleaveOnDeleteCascade()
{
using (var context = new TestMigrationDbContext(_fixture.DatabaseName))
{
var article = new Article
{
ArticleId = 1,
Author = new Author
{
AuthorId = 3,
FirstName = "Calvin",
LastName = "Saunders"
},
ArticleTitle = "Research on Resource Reports",
ArticleContent = "This is simple content on resource report research.",
PublishDate = new DateTime(2020, 12, 1)
};
context.Articles.Add(article);
var rowCount = await context.SaveChangesAsync();
Assert.Equal(2, rowCount);
}
using (var context = new TestMigrationDbContext(_fixture.DatabaseName))
{
// Delete Author Should delete the Article's as well.
var author = new Author
{
AuthorId = 3,
FirstName = "Calvin",
LastName = "Saunders"
};
context.Authors.Remove(author);
await context.SaveChangesAsync();
// Find Article with deleted Author
var article = context.Articles.FirstOrDefault(c => c.ArticleId == 1 && c.AuthorId == 3);
Assert.Null(article);
}
}
[Fact]
public void ShouldThrowInterleaveTableOnInsert()
{
using var context = new TestMigrationDbContext(_fixture.DatabaseName);
var article = new Article
{
ArticleId = 1,
AuthorId = 9999,
ArticleTitle = "Research on Perspectives",
ArticleContent = "This is simple content on Perspectives research.",
PublishDate = new DateTime(2020, 12, 1)
};
context.Articles.Add(article);
Assert.Throws<SpannerException>(() => context.SaveChanges());
}
[Fact]
public async Task ComputedColumn()
{
using var context = new TestMigrationDbContext(_fixture.DatabaseName);
using var transaction = await context.Database.BeginTransactionAsync();
var author = new Author
{
AuthorId = 10,
FirstName = "Loren",
LastName = "Ritchie"
};
context.Authors.Add(author);
var rowCount = await context.SaveChangesAsync();
await transaction.CommitAsync();
author = await context.Authors.FindAsync(10L);
Assert.Equal("Loren Ritchie", author.FullName);
}
[Fact]
public async Task CanSeedData()
{
using var context = new TestMigrationDbContext(_fixture.DatabaseName);
var authors = await context.Authors.Where(c => c.AuthorId == 1 || c.AuthorId == 2).ToListAsync();
if (_fixture.Database.Fresh)
{
Assert.Collection(authors,
s => Assert.Equal("Belinda Stiles", s.FullName),
s => Assert.Equal("Kelly Houser", s.FullName));
}
else
{
Assert.Empty(authors);
}
}
}
}
| |
/*
* 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.Core.Tests.Cache.Affinity
{
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using NUnit.Framework;
/// <summary>
/// Affinity key tests.
/// </summary>
public sealed class AffinityTest
{
/// <summary>
/// Test set up.
/// </summary>
[TestFixtureSetUp]
public void StartGrids()
{
for (var i = 0; i < 3; i++)
{
Ignition.Start(GetConfig(i, client: i == 2));
}
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TestFixtureTearDown]
public void StopGrids()
{
Ignition.StopAll(true);
}
/// <summary>
/// Test affinity key.
/// </summary>
[Test]
public void TestAffinity()
{
IIgnite g = Ignition.GetIgnite("grid-0");
ICacheAffinity aff = g.GetAffinity("default");
IClusterNode node = aff.MapKeyToNode(new AffinityTestKey(0, 1));
for (int i = 0; i < 10; i++)
Assert.AreEqual(node.Id, aff.MapKeyToNode(new AffinityTestKey(i, 1)).Id);
}
/// <summary>
/// Tests that affinity can be retrieved from client node right after the cache has been started on server node.
/// </summary>
[Test]
public void TestAffinityRetrievalForNewCache()
{
var server = Ignition.GetIgnite("grid-0");
var client = Ignition.GetIgnite("grid-2");
var serverCache = server.CreateCache<int, int>(TestUtils.TestName);
var clientAff = client.GetAffinity(serverCache.Name);
Assert.IsNotNull(clientAff);
}
/// <summary>
/// Test affinity with binary flag.
/// </summary>
[Test]
public void TestAffinityBinary()
{
IIgnite g = Ignition.GetIgnite("grid-0");
ICacheAffinity aff = g.GetAffinity("default");
IBinaryObject affKey = g.GetBinary().ToBinary<IBinaryObject>(new AffinityTestKey(0, 1));
IClusterNode node = aff.MapKeyToNode(affKey);
for (int i = 0; i < 10; i++)
{
IBinaryObject otherAffKey =
g.GetBinary().ToBinary<IBinaryObject>(new AffinityTestKey(i, 1));
Assert.AreEqual(node.Id, aff.MapKeyToNode(otherAffKey).Id);
}
}
/// <summary>
/// Tests that <see cref="AffinityKeyMappedAttribute"/> works when used on a property of a type that is
/// specified as <see cref="QueryEntity.KeyType"/> or <see cref="QueryEntity.ValueType"/> and
/// configured in a Spring XML file.
/// </summary>
[Test]
public void TestAffinityKeyMappedWithQueryEntitySpringXml()
{
foreach (var ignite in Ignition.GetAll())
{
TestAffinityKeyMappedWithQueryEntity0(ignite, "cache1");
}
}
/// <summary>
/// Tests that <see cref="AffinityKey"/> works when used as <see cref="QueryEntity.KeyType"/>.
/// </summary>
[Test]
public void TestAffinityKeyWithQueryEntity()
{
var cacheCfg = new CacheConfiguration(TestUtils.TestName)
{
QueryEntities = new List<QueryEntity>
{
new QueryEntity(typeof(AffinityKey), typeof(QueryEntityValue))
}
};
var ignite = Ignition.GetIgnite("grid-0");
var cache = ignite.GetOrCreateCache<AffinityKey, QueryEntityValue>(cacheCfg);
var aff = ignite.GetAffinity(cache.Name);
var ignite2 = Ignition.GetIgnite("grid-1");
var cache2 = ignite2.GetOrCreateCache<AffinityKey, QueryEntityValue>(cacheCfg);
var aff2 = ignite2.GetAffinity(cache2.Name);
// Check mapping.
for (var i = 0; i < 100; i++)
{
Assert.AreEqual(aff.GetPartition(i), aff.GetPartition(new AffinityKey("foo" + i, i)));
Assert.AreEqual(aff2.GetPartition(i), aff2.GetPartition(new AffinityKey("bar" + i, i)));
Assert.AreEqual(aff.GetPartition(i), aff2.GetPartition(i));
}
// Check put/get.
var key = new AffinityKey("x", 123);
var expected = new QueryEntityValue {Name = "y", AffKey = 321};
cache[key] = expected;
var val = cache2[key];
Assert.AreEqual(expected.Name, val.Name);
Assert.AreEqual(expected.AffKey, val.AffKey);
}
/// <summary>
/// Tests that <see cref="AffinityKeyMappedAttribute"/> works when used on a property of a type that is
/// specified as <see cref="QueryEntity.KeyType"/> or <see cref="QueryEntity.ValueType"/>.
/// </summary>
[Test]
public void TestAffinityKeyMappedWithQueryEntity()
{
var cacheCfg = new CacheConfiguration(TestUtils.TestName)
{
QueryEntities = new List<QueryEntity>
{
new QueryEntity(typeof(QueryEntityKey), typeof(QueryEntityValue))
}
};
var cache = Ignition.GetIgnite("grid-0").GetOrCreateCache<QueryEntityKey, QueryEntityValue>(cacheCfg);
var cache2 = Ignition.GetIgnite("grid-1").GetOrCreateCache<QueryEntityKey, QueryEntityValue>(cacheCfg);
TestAffinityKeyMappedWithQueryEntity0(Ignition.GetIgnite("grid-0"), cacheCfg.Name);
TestAffinityKeyMappedWithQueryEntity0(Ignition.GetIgnite("grid-1"), cacheCfg.Name);
// Check put/get.
var key = new QueryEntityKey {Data = "x", AffinityKey = 123};
cache[key] = new QueryEntityValue {Name = "y", AffKey = 321};
var val = cache2[key];
Assert.AreEqual("y", val.Name);
Assert.AreEqual(321, val.AffKey);
}
/// <summary>
/// Checks affinity mapping.
/// </summary>
private static void TestAffinityKeyMappedWithQueryEntity0(IIgnite ignite, string cacheName)
{
var aff = ignite.GetAffinity(cacheName);
var key1 = new QueryEntityKey {Data = "data1", AffinityKey = 1};
var key2 = new QueryEntityKey {Data = "data2", AffinityKey = 1};
var val1 = new QueryEntityValue {Name = "foo", AffKey = 100};
var val2 = new QueryEntityValue {Name = "bar", AffKey = 100};
Assert.AreEqual(aff.GetPartition(key1), aff.GetPartition(key2));
Assert.AreEqual(aff.GetPartition(val1), aff.GetPartition(val2));
}
/// <summary>
/// Affinity key.
/// </summary>
private class AffinityTestKey
{
/** ID. */
private readonly int _id;
/** Affinity key. */
// ReSharper disable once NotAccessedField.Local
private readonly int _affKey;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="id">ID.</param>
/// <param name="affKey">Affinity key.</param>
public AffinityTestKey(int id, int affKey)
{
_id = id;
_affKey = affKey;
}
/** <inheritdoc /> */
public override bool Equals(object obj)
{
var other = obj as AffinityTestKey;
return other != null && _id == other._id;
}
/** <inheritdoc /> */
public override int GetHashCode()
{
return _id;
}
}
/// <summary>
/// Gets Ignite config.
/// </summary>
private static IgniteConfiguration GetConfig(int idx, bool client = false)
{
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
SpringConfigUrl = Path.Combine("Config", "native-client-test-cache-affinity.xml"),
IgniteInstanceName = "grid-" + idx,
ClientMode = client
};
}
/// <summary>
/// Query entity key.
/// </summary>
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
private class QueryEntityKey
{
/** */
[QuerySqlField]
public string Data { get; set; }
/** */
[AffinityKeyMapped]
public long AffinityKey { get; set; }
}
/// <summary>
/// Query entity key.
/// </summary>
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
private class QueryEntityValue
{
/** */
[QuerySqlField]
public string Name { get; set; }
/** */
[AffinityKeyMapped]
public long AffKey { get; set; }
}
}
}
| |
namespace Nancy.Testing.Tests
{
using System;
using System.Linq;
using CsQuery;
using Xunit;
public class AssertExtensionsTests
{
private readonly QueryWrapper query;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Object"/> class.
/// </summary>
public AssertExtensionsTests()
{
var document =
CQ.Create(@"<html><head></head><body><div id='testId' class='myClass' attribute1 attribute2='value2'>Test</div><div class='anotherClass'>Tes</div><span class='class'>some contents</span><span class='class'>This has contents</span></body></html>");
this.query =
new QueryWrapper(document);
}
[Fact]
public void Should_throw_assertexception_when_id_does_not_exist()
{
// Given, When
var result = Record.Exception(() => this.query["#notThere"].ShouldExist());
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void Should_not_throw_exception_when_id_does_exist()
{
// Given, When
var result = Record.Exception(() => this.query["#testId"].ShouldExist());
// Then
Assert.Null(result);
}
[Fact]
public void Should_detect_nonexistence()
{
// Given, When
var result = Record.Exception(() => this.query["#jamesIsAwesome"].ShouldNotExist());
// Then
Assert.Null(result);
}
[Fact]
public void Should_not_throw_exception_when_id_that_should_only_exists_once_only_exists_once()
{
// Given, When
var result = Record.Exception(() => this.query["#testId"].ShouldExistOnce());
// Then
Assert.Null(result);
}
[Fact]
public void ShouldExistOnce_ExistsOnce_ReturnsSingleItemAndConnector()
{
// Given, When
var result = this.query["#testId"].ShouldExistOnce();
// Then
Assert.IsType<AndConnector<NodeWrapper>>(result);
}
[Fact]
public void ShouldExistsExactly2_Exists2_ReturnsResultAndConnector()
{
// Given, when
var result = this.query[".class"].ShouldExistExactly(2);
// Then
Assert.IsType<AndConnector<QueryWrapper>>(result);
}
[Fact]
public void ShouldExistsExactly3_Exists2_ReturnsResultAndConnector()
{
// When
var result = Record.Exception(() => this.query[".class"].ShouldExistExactly(3));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldExistOnce_DoesNotExist_ShouldThrowAssert()
{
// Given, When
var result = Record.Exception(() => this.query["#notHere"].ShouldExistOnce());
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldExistOnce_ExistsMoreThanOnce_ShouldThrowAssert()
{
// Given, When
var result = Record.Exception(() => this.query["div"].ShouldExistOnce());
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldBeClass_ZeroElements_ShouldThrowAssert()
{
// Given
var queryWrapper = this.query["#missing"];
// When
var result = Record.Exception(() => queryWrapper.ShouldBeOfClass("nope"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldBeClass_SingleElementNotThatClass_ShouldThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldBeOfClass("nope"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldBeClass_SingleElementWithThatClass_ShouldNotThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldBeOfClass("myClass"));
// Then
Assert.Null(result);
}
[Fact]
public void ShouldBeClass_MultipleElementsOneNotThatClass_ShouldThrowAssert()
{
// Given
var htmlNodes = this.query["div"];
// When
var result = Record.Exception(() => htmlNodes.ShouldBeOfClass("myClass"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldBeClass_MultipleElementsAllThatClass_ShouldNotThrowAssert()
{
// Given
var htmlNodes = this.query["span"];
// When
var result = Record.Exception(() => htmlNodes.ShouldBeOfClass("class"));
// Then
Assert.Null(result);
}
[Fact]
public void AllShouldContain_ZeroElements_ShouldThrowAssert()
{
// Given
var queryWrapper = this.query["#missing"];
// When
var result = Record.Exception(() => queryWrapper.AllShouldContain("Anything"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void AnyShouldContain_ZeroElements_ShouldThrowAssert()
{
// Given
var queryWrapper = this.query["#missing"];
// When
var result = Record.Exception(() => queryWrapper.AnyShouldContain("Anything"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldContain_SingleElementThatContainsText_ShouldNotThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContain("Test"));
// Then
Assert.Null(result);
}
[Fact]
public void ShouldContain_SingleElementWithTextInDifferentCase_ShouldHonorCompareType()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContain("test", StringComparison.OrdinalIgnoreCase));
// Then
Assert.Null(result);
}
[Fact]
public void ShouldContain_SingleElementDoesntContainText_ShouldThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContain("nope"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void AllShouldContain_MultipleElementsAllContainingText_ShouldntThrowAssert()
{
// Given
var htmlNodes = this.query["span"];
// When
var result = Record.Exception(() => htmlNodes.AllShouldContain("contents"));
// Then
Assert.Null(result);
}
[Fact]
public void AnyShouldContain_MultipleElementsAllContainingText_ShouldntThrowAssert()
{
// Given
var htmlNodes = this.query["span"];
// When
var result = Record.Exception(() => htmlNodes.AnyShouldContain("contents"));
// Then
Assert.Null(result);
}
[Fact]
public void AllShouldContain_MultipleElementsOneNotContainingText_ShouldThrowAssert()
{
// Given
var htmlNodes = this.query["div"];
// When
var result = Record.Exception(() => htmlNodes.AllShouldContain("Test"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void AnyShouldContain_MultipleElementsOneNotContainingText_ShouldntThrowAssert()
{
// Given
var htmlNodes = this.query["div"];
// When
var result = Record.Exception(() => htmlNodes.AnyShouldContain("Test"));
// Then
Assert.Null(result);
}
[Fact]
public void ShouldContainAttribute_ZeroElements_ShouldThrowAssert()
{
// Given
var queryWrapper = this.query["#missing"];
// When
var result = Record.Exception(() => queryWrapper.ShouldContainAttribute("nope"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldContainAttribute_ZeroElementsNameAndValue_ShouldThrowAssert()
{
// Given
var queryWrapper = this.query["#missing"];
// When
var result = Record.Exception(() => queryWrapper.ShouldContainAttribute("nope", "nope"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldContainAttribute_SingleElementNotContainingAttribute_ShouldThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("nope"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldContainAttribute_SingleElementNotContainingAttributeAndValue_ShouldThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("nope", "nope"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldContainAttribute_SingleElementContainingAttributeWithoutValueButShouldContainValue_ShouldThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute1", "nope"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldContainAttribute_SingleElementContainingAttributeWithDifferentValue_ShouldThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute2", "nope"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldContainAttribute_SingleElementContainingAttribute_ShouldNotThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute1"));
// Then
Assert.Null(result);
}
[Fact]
public void ShouldContainAttribute_SingleElementContainingAttributeAndValueButIngoringValue_ShouldNotThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute2"));
// Then
Assert.Null(result);
}
[Fact]
public void ShouldContainAttribute_SingleElementContainingAttributeAndValue_ShouldNotThrowAssert()
{
// Given
var htmlNode = this.query["#testId"].First();
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute2", "value2"));
// Then
Assert.Null(result);
}
[Fact]
public void ShouldContainAttribute_MultipleElementsOneNotContainingAttribute_ShouldThrowAssert()
{
// Given
var htmlNode = this.query["div"];
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("attribute1"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldContainAttribute_MultipleElementsOneNotContainingAttributeAndValue_ShouldThrowAssert()
{
// Given
var htmlNode = this.query["div"];
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("class", "myClass"));
// Then
Assert.IsAssignableFrom<AssertException>(result);
}
[Fact]
public void ShouldContainAttribute_MultipleElementsContainingAttribute_ShouldNotThrowAssert()
{
// Given
var htmlNode = this.query["div"];
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("class"));
// Then
Assert.Null(result);
}
[Fact]
public void ShouldContainAttribute_MultipleElementsContainingAttributeAndValue_ShouldNotThrowAssert()
{
// Given
var htmlNode = this.query["span"];
// When
var result = Record.Exception(() => htmlNode.ShouldContainAttribute("class", "class"));
// Then
Assert.Null(result);
}
}
}
| |
// File generated from our OpenAPI spec
namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
/// <summary>
/// This object represents a customer of your business. It lets you create recurring charges
/// and track payments that belong to the same customer.
///
/// Related guide: <a href="https://stripe.com/docs/payments/save-during-payment">Save a
/// card during payment</a>.
/// </summary>
public class Customer : StripeEntity<Customer>, IHasId, IHasMetadata, IHasObject
{
/// <summary>
/// Unique identifier for the object.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// String representing the object's type. Objects of the same type share the same value.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
/// <summary>
/// The customer's address.
/// </summary>
[JsonProperty("address")]
public Address Address { get; set; }
/// <summary>
/// Current balance, if any, being stored on the customer. If negative, the customer has
/// credit to apply to their next invoice. If positive, the customer has an amount owed that
/// will be added to their next invoice. The balance does not refer to any unpaid invoices;
/// it solely takes into account amounts that have yet to be successfully applied to any
/// invoice. This balance is only taken into account as invoices are finalized.
/// </summary>
[JsonProperty("balance")]
public long Balance { get; set; }
/// <summary>
/// Time at which the object was created. Measured in seconds since the Unix epoch.
/// </summary>
[JsonProperty("created")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime Created { get; set; } = Stripe.Infrastructure.DateTimeUtils.UnixEpoch;
/// <summary>
/// Three-letter <a href="https://stripe.com/docs/currencies">ISO code for the currency</a>
/// the customer can be charged in for recurring billing purposes.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
#region Expandable DefaultSource
/// <summary>
/// (ID of the IPaymentSource)
/// ID of the default payment source for the customer.
///
/// If you are using payment methods created via the PaymentMethods API, see the <a
/// href="https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method">invoice_settings.default_payment_method</a>
/// field instead.
/// </summary>
[JsonIgnore]
public string DefaultSourceId
{
get => this.InternalDefaultSource?.Id;
set => this.InternalDefaultSource = SetExpandableFieldId(value, this.InternalDefaultSource);
}
/// <summary>
/// (Expanded)
/// ID of the default payment source for the customer.
///
/// If you are using payment methods created via the PaymentMethods API, see the <a
/// href="https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method">invoice_settings.default_payment_method</a>
/// field instead.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public IPaymentSource DefaultSource
{
get => this.InternalDefaultSource?.ExpandedObject;
set => this.InternalDefaultSource = SetExpandableFieldObject(value, this.InternalDefaultSource);
}
[JsonProperty("default_source")]
[JsonConverter(typeof(ExpandableFieldConverter<IPaymentSource>))]
internal ExpandableField<IPaymentSource> InternalDefaultSource { get; set; }
#endregion
/// <summary>
/// Warning: this is not in the documentation.
/// </summary>
[JsonProperty("default_source_type")]
public string DefaultSourceType { get; set; }
/// <summary>
/// Whether this object is deleted or not.
/// </summary>
[JsonProperty("deleted", NullValueHandling = NullValueHandling.Ignore)]
public bool? Deleted { get; set; }
/// <summary>
/// When the customer's latest invoice is billed by charging automatically,
/// <c>delinquent</c> is <c>true</c> if the invoice's latest charge failed. When the
/// customer's latest invoice is billed by sending an invoice, <c>delinquent</c> is
/// <c>true</c> if the invoice isn't paid by its due date.
///
/// If an invoice is marked uncollectible by <a
/// href="https://stripe.com/docs/billing/automatic-collection">dunning</a>,
/// <c>delinquent</c> doesn't get reset to <c>false</c>.
/// </summary>
[JsonProperty("delinquent")]
public bool Delinquent { get; set; }
/// <summary>
/// An arbitrary string attached to the object. Often useful for displaying to users.
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
/// <summary>
/// Describes the current discount active on the customer, if there is one.
/// </summary>
[JsonProperty("discount")]
public Discount Discount { get; set; }
/// <summary>
/// The customer's email address.
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// The prefix for the customer used to generate unique invoice numbers.
/// </summary>
[JsonProperty("invoice_prefix")]
public string InvoicePrefix { get; set; }
[JsonProperty("invoice_settings")]
public CustomerInvoiceSettings InvoiceSettings { get; set; }
/// <summary>
/// Has the value <c>true</c> if the object exists in live mode or the value <c>false</c> if
/// the object exists in test mode.
/// </summary>
[JsonProperty("livemode")]
public bool Livemode { get; set; }
/// <summary>
/// Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can
/// attach to an object. This can be useful for storing additional information about the
/// object in a structured format.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
/// <summary>
/// The customer's full name or business name.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
/// <summary>
/// The suffix of the customer's next invoice number, e.g., 0001.
/// </summary>
[JsonProperty("next_invoice_sequence")]
public long NextInvoiceSequence { get; set; }
/// <summary>
/// The customer's phone number.
/// </summary>
[JsonProperty("phone")]
public string Phone { get; set; }
/// <summary>
/// The customer's preferred locales (languages), ordered by preference.
/// </summary>
[JsonProperty("preferred_locales")]
public List<string> PreferredLocales { get; set; }
/// <summary>
/// Mailing and shipping address for the customer. Appears on invoices emailed to this
/// customer.
/// </summary>
[JsonProperty("shipping")]
public Shipping Shipping { get; set; }
/// <summary>
/// The customer's payment sources, if any.
/// </summary>
[JsonProperty("sources")]
public StripeList<IPaymentSource> Sources { get; set; }
/// <summary>
/// The customer's current subscriptions, if any.
/// </summary>
[JsonProperty("subscriptions")]
public StripeList<Subscription> Subscriptions { get; set; }
[JsonProperty("tax")]
public CustomerTax Tax { get; set; }
/// <summary>
/// Describes the customer's tax exemption status. One of <c>none</c>, <c>exempt</c>, or
/// <c>reverse</c>. When set to <c>reverse</c>, invoice and receipt PDFs include the text
/// <strong>"Reverse charge"</strong>.
/// One of: <c>exempt</c>, <c>none</c>, or <c>reverse</c>.
/// </summary>
[JsonProperty("tax_exempt")]
public string TaxExempt { get; set; }
/// <summary>
/// The customer's tax IDs.
/// </summary>
[JsonProperty("tax_ids")]
public StripeList<TaxId> TaxIds { get; set; }
#region Expandable TestClock
/// <summary>
/// (ID of the TestHelpers.TestClock)
/// ID of the test clock this customer belongs to.
/// </summary>
[JsonIgnore]
public string TestClockId
{
get => this.InternalTestClock?.Id;
set => this.InternalTestClock = SetExpandableFieldId(value, this.InternalTestClock);
}
/// <summary>
/// (Expanded)
/// ID of the test clock this customer belongs to.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public TestHelpers.TestClock TestClock
{
get => this.InternalTestClock?.ExpandedObject;
set => this.InternalTestClock = SetExpandableFieldObject(value, this.InternalTestClock);
}
[JsonProperty("test_clock")]
[JsonConverter(typeof(ExpandableFieldConverter<TestHelpers.TestClock>))]
internal ExpandableField<TestHelpers.TestClock> InternalTestClock { get; set; }
#endregion
}
}
| |
#region Header
//
// CmdNewTextNote.cs - Create a new text note and determine its exact width
//
// Copyright (C) 2014-2020 by Scott Wilson and Jeremy Tammik,
// Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using OperationCanceledException = Autodesk.Revit.Exceptions.OperationCanceledException;
#endregion // Namespaces
namespace BuildingCoder
{
[Transaction(TransactionMode.Manual)]
internal class CmdNewTextNote : IExternalCommand
{
private void SetTextAlignment(TextNote textNote)
{
var doc = textNote.Document;
using var t = new Transaction(doc);
t.Start("AlignTextNote");
var p = textNote.get_Parameter(
BuiltInParameter.TEXT_ALIGN_VERT);
p.Set((int)
TextAlignFlags.TEF_ALIGN_MIDDLE);
t.Commit();
}
#region Get specific TextNoteType by name
// implemented for https://forums.autodesk.com/t5/revit-api-forum/creating-a-textnote-with-a-specific-type-i-e-1-10-quot-arial-1/m-p/8765648
/// <summary>
/// Return the first text note type matching the given name.
/// Note that TextNoteType is a subclass of ElementType,
/// so this method is more restrictive above all faster
/// than Util.GetElementTypeByName.
/// This filter could be speeded up by using a (quick)
/// parameter filter instead of the (slower than slow)
/// LINQ post-processing.
/// </summary>
private TextNoteType GetTextNoteTypeByName(
Document doc,
string name)
{
return new FilteredElementCollector(doc)
.OfClass(typeof(TextNoteType))
.First(q => q.Name.Equals(name))
as TextNoteType;
}
#endregion // Get specific TextNoteType by name
#region Solution 1 using TextRenderer.MeasureText
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hwnd);
/// <summary>
/// Determine the current display
/// horizontal dots per inch.
/// </summary>
private static float DpiX
{
get
{
float xDpi, yDpi;
var dc = GetDC(IntPtr.Zero);
using (var g = Graphics.FromHdc(dc))
{
xDpi = g.DpiX;
yDpi = g.DpiY;
}
if (ReleaseDC(IntPtr.Zero) != 0)
{
// GetLastError and handle...
}
return xDpi;
}
}
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
var uiapp = commandData.Application;
var uidoc = uiapp.ActiveUIDocument;
var doc = uidoc.Document;
var view = doc.ActiveView;
XYZ p;
try
{
p = uidoc.Selection.PickPoint(
"Please pick text insertion point");
}
catch (OperationCanceledException)
{
return Result.Cancelled;
}
//TextNoteType boldTextType = doc.GetElement(
// new ElementId( 1212838 ) ) as TextNoteType; // Arial 3/32" Bold
// 1 inch = 72 points
// 3/32" = 72 * 3/32 points = ...
var textType
= new FilteredElementCollector(doc)
.OfClass(typeof(TextNoteType))
.FirstElement() as TextNoteType;
Debug.Print($"TextNoteType.Name = {textType.Name}");
// 6 mm Arial happens to be the first text type found
// 6 mm = 6 / 25.4 inch = 72 * 6 / 25.4 points = 17 pt.
// Nowadays, Windows does not assume that a point is
// 1/72", but moved to 1/96" instead.
float text_type_height_mm = 6;
var mm_per_inch = 25.4f;
float points_per_inch = 96; // not 72
var em_size = points_per_inch
* (text_type_height_mm / mm_per_inch);
em_size += 2.5f;
var font = new Font("Arial", em_size,
FontStyle.Regular);
TextNote txNote = null;
using (var t = new Transaction(doc))
{
t.Start("Create TextNote");
//string s = "TEST BOLD";
var s = "The quick brown fox jumps over the lazy dog";
var txtBox = TextRenderer
.MeasureText(s, font);
double w_inch = txtBox.Width / DpiX;
double v_scale = view.Scale; // ratio of true model size to paper size
Debug.Print(
"Text box width in pixels {0} = {1} inch, "
+ "view scale = {2}",
txtBox.Width, w_inch, v_scale);
var newWidth = w_inch / 12;
//TextNote txNote = doc.Create.NewTextNote(
// doc.ActiveView, p, XYZ.BasisX, XYZ.BasisY,
// newWidth, TextAlignFlags.TEF_ALIGN_LEFT
// | TextAlignFlags.TEF_ALIGN_BOTTOM, s ); // 2015
//txNote.TextNoteType = textType; // 2015
txNote = TextNote.Create(doc,
doc.ActiveView.Id, p, s, textType.Id); // 2016
Debug.Print(
"NewTextNote lineWidth {0} times view scale "
+ "{1} = {2} generated TextNote.Width {3}",
Util.RealString(newWidth),
Util.RealString(v_scale),
Util.RealString(newWidth * v_scale),
Util.RealString(txNote.Width));
// This fails.
//Debug.Assert(
// Util.IsEqual( newWidth * v_scale, txNote.Width ),
// "expected the NewTextNote lineWidth "
// + "argument to determine the resulting "
// + "text note width" );
var wmin = txNote.GetMinimumAllowedWidth();
var wmax = txNote.GetMaximumAllowedWidth();
//double wnew = newWidth * v_scale; // this is 100 times too big
var wnew = newWidth;
txNote.Width = wnew;
//6mm Arial
//Text box width in pixels 668 = 6.95833349227905 inch, scale 100
//NewTextNote lineWidth 0.58 times view scale 100 = 57.99 generated TextNote.Width 59.32
t.Commit();
}
using (var t = new Transaction(doc))
{
t.Start("Change Text Colour");
var color = Util.ToColorParameterValue(
255, 0, 0);
var textNoteType = doc.GetElement(
txNote.GetTypeId());
var param = textNoteType.get_Parameter(
BuiltInParameter.LINE_COLOR);
// Note that this modifies the existing text
// note type for all instances using it. If
// not desired, use Duplicate() first.
param.Set(color);
t.Commit();
}
return Result.Succeeded;
}
#endregion // Solution 1 using TextRenderer.MeasureText
#region Solution 2 using Graphics.MeasureString
private static float GetDpiX()
{
float xDpi, yDpi;
using var g = Graphics.FromHwnd(IntPtr.Zero);
xDpi = g.DpiX;
yDpi = g.DpiY;
return xDpi;
}
private static double GetStringWidth(string text, Font font)
{
var textWidth = 0.0;
using var g = Graphics.FromHwnd(IntPtr.Zero);
textWidth = g.MeasureString(text, font).Width;
return textWidth;
}
public Result Execute_2(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
var commandResult = Result.Succeeded;
try
{
var uiApp = commandData.Application;
var uiDoc = uiApp.ActiveUIDocument;
var dbDoc = uiDoc.Document;
var view = uiDoc.ActiveGraphicalView;
var pLoc = XYZ.Zero;
try
{
pLoc = uiDoc.Selection.PickPoint(
"Please pick text insertion point");
}
catch (OperationCanceledException)
{
Debug.WriteLine("Operation cancelled.");
message = "Operation cancelled.";
return Result.Succeeded;
}
var noteTypeList
= new FilteredElementCollector(dbDoc)
.OfClass(typeof(TextNoteType))
.Cast<TextNoteType>()
.ToList();
// Sort note types into ascending text size
var bipTextSize
= BuiltInParameter.TEXT_SIZE;
noteTypeList.Sort((a, b)
=> a.get_Parameter(bipTextSize).AsDouble()
.CompareTo(
b.get_Parameter(bipTextSize).AsDouble()));
foreach (var textType in noteTypeList)
{
Debug.WriteLine(textType.Name);
var paramTextFont
= textType.get_Parameter(
BuiltInParameter.TEXT_FONT);
var paramTextSize
= textType.get_Parameter(
BuiltInParameter.TEXT_SIZE);
var paramBorderSize
= textType.get_Parameter(
BuiltInParameter.LEADER_OFFSET_SHEET);
var paramTextBold
= textType.get_Parameter(
BuiltInParameter.TEXT_STYLE_BOLD);
var paramTextItalic
= textType.get_Parameter(
BuiltInParameter.TEXT_STYLE_ITALIC);
var paramTextUnderline
= textType.get_Parameter(
BuiltInParameter.TEXT_STYLE_UNDERLINE);
var paramTextWidthScale
= textType.get_Parameter(
BuiltInParameter.TEXT_WIDTH_SCALE);
var fontName = paramTextFont.AsString();
var textHeight = paramTextSize.AsDouble();
var textBold = paramTextBold.AsInteger() == 1
? true
: false;
var textItalic = paramTextItalic.AsInteger() == 1
? true
: false;
var textUnderline = paramTextUnderline.AsInteger() == 1
? true
: false;
var textBorder = paramBorderSize.AsDouble();
var textWidthScale = paramTextWidthScale.AsDouble();
var textStyle = FontStyle.Regular;
if (textBold) textStyle |= FontStyle.Bold;
if (textItalic) textStyle |= FontStyle.Italic;
if (textUnderline) textStyle |= FontStyle.Underline;
var fontHeightInch = (float) textHeight * 12.0f;
var displayDpiX = GetDpiX();
var fontDpi = 96.0f;
var pointSize = (float) (textHeight * 12.0 * fontDpi);
var font = new Font(fontName, pointSize, textStyle);
var viewScale = view.Scale;
using (var t = new Transaction(dbDoc))
{
t.Start("Test TextNote lineWidth calculation");
var textString =
$"{textType.Name} ({fontName} {textHeight * 304.8:0.##}mm, {textStyle}, {textWidthScale * 100.0:0.##}%): The quick brown fox jumps over the lazy dog.";
var stringWidthPx = GetStringWidth(textString, font);
var stringWidthIn = stringWidthPx / displayDpiX;
Debug.WriteLine($"String Width in pixels: {stringWidthPx:F3}");
Debug.WriteLine($"{stringWidthIn * 25.4 * viewScale:F3} mm at 1:{viewScale}");
var stringWidthFt = stringWidthIn / 12.0;
var lineWidth = (stringWidthFt * textWidthScale
+ textBorder * 2.0) * viewScale;
//TextNote textNote = dbDoc.Create.NewTextNote(
// view, pLoc, XYZ.BasisX, XYZ.BasisY, 0.001,
// TextAlignFlags.TEF_ALIGN_LEFT
// | TextAlignFlags.TEF_ALIGN_TOP, textString ); // 2015
//textNote.TextNoteType = textType; // 2015
var textNote = TextNote.Create(dbDoc,
view.Id, pLoc, textString, textType.Id); // 2016
textNote.Width = lineWidth;
t.Commit();
}
// Place next text note below this one with 5 mm gap
pLoc += view.UpDirection.Multiply(
(textHeight + 5.0 / 304.8)
* viewScale).Negate();
}
}
catch (ExternalApplicationException e)
{
message = e.Message;
Debug.WriteLine($"Exception Encountered (Application)\n{e.Message}\nStack Trace: {e.StackTrace}");
commandResult = Result.Failed;
}
catch (Exception e)
{
message = e.Message;
Debug.WriteLine($"Exception Encountered (General)\n{e.Message}\nStack Trace: {e.StackTrace}");
commandResult = Result.Failed;
}
return commandResult;
}
#endregion // Solution 2 using Graphics.MeasureString
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using com.calitha.goldparser;
using Epi;
using Epi.Collections;
using Epi.Data;
using Epi.Data.Services;
using Epi.Fields;
using VariableCollection = Epi.Collections.NamedObjectCollection<Epi.IVariable>;
namespace Epi.Core.AnalysisInterpreter.Rules
{
public class Rule_Display : AnalysisRule
{
#region Private Data Members
string commandText = null;
string displayType = null;
string outputOpt = string.Empty;
string dbVariablesOpt = string.Empty;
string dbViewsOpt = string.Empty;
string identifierList = string.Empty;
string displayOpt = string.Empty;
string outTable = string.Empty;
//private IMetadataProvider metadata = null;
#endregion Private Data Members
/// <summary>
/// Constructor - Rule_Display
/// </summary>
/// <param name="pToken">The token to be parsed.</param>
/// <returns>void</returns>
public Rule_Display(Rule_Context pContext, NonterminalToken pToken)
: base(pContext)
{
this.commandText = this.ExtractTokens(pToken.Tokens);
// <Variables_Display_Statement> ::= DISPLAY DBVARIABLES <DbVariablesOpt> <DisplayOpt>
// <Views_Display_Statement> ::= DISPLAY DBVIEWS <DbViewsOpt> <DisplayOpt>
// <Tables_Display_Statement> ::= DISPLAY TABLES <DbViewsOpt> <DisplayOpt>
// <DbVariablesOpt> ::= DEFINE | FIELDVAR | LIST <IdentifierList> | <IdentifierList> | !Null
// <DisplayOpt> ::= <DefaultDisplayOpt> | !Null
// <DefaultDisplayOpt> ::= OUTTABLE '=' Identifier
// <DbViewsOpt> ::= <DefaultDbViewsOpt> | !Null
// <DefaultDbViewsOpt> ::= File
this.displayType = this.GetCommandElement(pToken.Tokens, 1);
switch (pToken.Rule.Lhs.ToString())
{
case "<Variables_Display_Statement>":
if (pToken.Tokens.Length > 2)
{
dbVariablesOpt = this.GetCommandElement(pToken.Tokens, 2).Trim(new char[] { '"' }).ToUpperInvariant();
if (dbVariablesOpt.ToUpperInvariant().StartsWith(CommandNames.LIST))
{
identifierList = dbVariablesOpt.Substring(4).Trim();
}
}
break;
case "<Views_Display_Statement>":
case "<Tables_Display_Statement>":
if (pToken.Tokens.Length > 2)
{
dbViewsOpt = this.GetCommandElement(pToken.Tokens, 2);
}
break;
}
if (pToken.Tokens.Length > 3)
{
if (!string.IsNullOrEmpty(this.GetCommandElement(pToken.Tokens, 3)))
{
string tokenFour = this.GetCommandElement(pToken.Tokens, 3);
if (tokenFour.ToUpperInvariant().Contains("OUTTABLE"))
{
outTable = this.GetCommandElement(pToken.Tokens, 3);
outTable = outTable.Substring(outTable.LastIndexOf('=') + 1).Trim();
}
}
}
}
/// <summary>
/// Performs execution of the DISPLAY command.
/// </summary>
/// <returns>Returns a null object because it's the end of the recursion.</returns>
public override object Execute()
{
string markup = string.Empty;
DataTable dataTable = null;
switch (this.displayType.ToUpperInvariant())
{
case CommandNames.DBVARIABLES:
markup = GetVariableMarkup(out dataTable);
break;
case CommandNames.DBVIEWS:
markup = GetViewMarkup(out dataTable);
break;
case CommandNames.TABLES:
markup = GetTableMarkup(out dataTable);
break;
}
if (!string.IsNullOrEmpty(this.outTable))
{
WriteToOutTable(dataTable, outTable);
}
Dictionary<string, string> args = new Dictionary<string, string>();
args.Add("COMMANDNAME", CommandNames.DISPLAY);
args.Add("COMMANDTEXT", this.commandText);
args.Add("DISPLAYTYPE", this.displayType);
args.Add("OUTPUTOPTION", this.outputOpt);
args.Add("VARIABLEOPTION", this.dbVariablesOpt);
args.Add("HTMLRESULTS", markup);
this.Context.AnalysisCheckCodeInterface.Display(args);
return null;
}
/// <summary>
/// GetVariableMarkup gets both the markup used in the HTMLRESULTS section and a DataTable
/// with a row for each DBVARIABLE and its properties.
/// </summary>
/// <param name="table">An instance of a DataTable containing properties of DBVARIABLES.</param>
/// <returns>Returns the markup used in the HTMLRESULTS section.</returns>
private string GetVariableMarkup(out DataTable table)
{
StringBuilder sb = new StringBuilder();
string[] varNames = null;
table = new DataTable();
if (!string.IsNullOrEmpty(this.identifierList))
{
varNames = this.identifierList.Split(' ');
foreach (string s in varNames) s.Trim();
}
VariableCollection vars = this.GetVariables(varNames, this.dbVariablesOpt);
this.Context.GetOutput();
/*
table.Columns.Add(new DataColumn(ColumnNames.VARIABLE, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.TABLE, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.FIELDTYPE, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.FORMATVALUE, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.SPECIALINFO, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.PROMPT, typeof(string)));
*/
table.Columns.Add(new DataColumn(ColumnNames.PAGE_NUMBER, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.PROMPT, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.FIELDTYPE, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.VARIABLE, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.VARIABLE_VALUE, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.FORMATVALUE, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.SPECIALINFO, typeof(string)));
table.Columns.Add(new DataColumn(ColumnNames.TABLE, typeof(string)));
string tableText = string.Empty;
string pattern = string.Empty;
IDbDriver driver = null;
DataTable viewTable = null;
DataRow[] rows = null;
Dictionary<string, string> formatStrings = new Dictionary<string, string>();
if (this.Context.CurrentRead != null)
{
tableText = this.Context.CurrentRead.Identifier;
driver = Epi.Data.DBReadExecute.GetDataDriver(this.Context.CurrentRead.File);
List<string> tableNames = driver.GetTableNames();
string viewTableName = "view" + tableText;
List<string> tableNamesUpper = new List<string> { };
foreach (string name in tableNames)
{
tableNamesUpper.Add(name.ToUpperInvariant());
}
//if TableNamesUpper contains an Epi 3 viewTable then get that table's data
if (tableNamesUpper.Contains(viewTableName.ToUpperInvariant()))
{
viewTable = driver.GetTableData(viewTableName);
if (varNames == null)
{
rows = viewTable.Select();
}
else
{
StringBuilder filter = new StringBuilder();
foreach (string name in varNames)
{
filter.Append(string.Format(" OR Name = '{0}'", name));
}
rows = viewTable.Select(filter.ToString().Substring(4));
}
foreach (DataRow row in rows)
{
formatStrings.Add(row[ColumnNames.NAME].ToString(), row[ColumnNames.FORMATSTRING].ToString());
}
}
}
List<string> RelatedTableList = new List<string>();
if (this.Context.CurrentRead != null)
{
for (int i = 0; Context.CurrentRead.RelatedTables.Count > i; i++)
{
RelatedTableList.Add(Context.CurrentRead.RelatedTables[i]);
}
}
List<string> varnamelist = new List<string>();
if (varNames != null)
{
foreach (string name in varNames)
{
varnamelist.Add(name);
}
}
//foreach (IVariable var in vars)
foreach (DataColumn dataColumn in this.Context.DataSet.Tables["output"].Columns)
{
string ColumnsNames = "";
tableText = "";
if (this.Context.CurrentRead != null)
{
foreach (var RTable in RelatedTableList)
{
if (this.Context.CurrentRead.IsEpi7ProjectRead && this.Context.CurrentProject.Views.Exists(RTable))
{
View tempView = this.Context.CurrentProject.Metadata.GetViewByFullName(RTable);
ColumnsNames = this.Context.CurrentProject.Metadata.GetTableColumnNames(tempView.Id);
if (ColumnsNames.Contains(dataColumn.ToString()))
{
tableText = RTable;
break;
}
}
}
if (string.IsNullOrEmpty(tableText))
{
tableText = this.Context.CurrentRead.Identifier;
}
}
else
{
tableText = "output";
}
if (varNames != null)
{
if (varnamelist.Contains(dataColumn.Caption.ToString().ToUpperInvariant()))
{
table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table));
}
}
else if (vars != null)
{
if (vars.Contains(dataColumn.Caption.ToString().ToUpperInvariant()))
{
if (this.dbVariablesOpt == "FIELDVAR")
{
IVariable var = (IVariable)this.Context.GetVariable(dataColumn.ColumnName);
if (var.VarType == VariableType.DataSource || var.VarType == VariableType.DataSourceRedefined)
{
table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table));
}
}
else
{
table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table));
}
}
}
else
{
if (this.dbVariablesOpt == "FIELDVAR")
{
IVariable var = (IVariable)this.Context.GetVariable(dataColumn.ColumnName);
if (var.VarType == VariableType.DataSource || var.VarType == VariableType.DataSourceRedefined)
{
table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table));
}
}
else
{
table.Rows.Add(GetDataTable(dataColumn, tableText, pattern, formatStrings, rows, table));
}
}
//pattern = string.Empty;
//IVariable var = (IVariable)this.Context.GetVariable(dataColumn.ColumnName);
//if (var != null && (var.VarType == VariableType.DataSource) || (var.VarType == VariableType.DataSourceRedefined))
//{
// formatStrings.TryGetValue(var.Name, out pattern);
//}
//else
//{
// tableText = "Defined";
//}
//DataRow row = table.NewRow();
/*
row[ColumnNames.VARIABLE] = var.Name;
row[ColumnNames.TABLE] = tableText;
row[ColumnNames.FIELDTYPE] = var.DataType.ToString();
row[ColumnNames.FORMATVALUE] = pattern;
row[ColumnNames.SPECIALINFO] = var.VarType.ToString();
row[ColumnNames.PROMPT] = var.PromptText;
*/
// row[ColumnNames.PAGE_NUMBER] = var.???;
//if (this.Context.CurrentRead.IsEpi7ProjectRead && this.Context.CurrentProject.Views.Exists(this.Context.CurrentRead.Identifier) && this.Context.CurrentProject.Views[this.Context.CurrentRead.Identifier].Fields.Exists(var.Name))
//{
// Epi.Fields.Field field = this.Context.CurrentProject.Views[this.Context.CurrentRead.Identifier].Fields[var.Name];
// if (field is FieldWithSeparatePrompt)
// {
// row[ColumnNames.PROMPT] = ((FieldWithSeparatePrompt)field).PromptText;
// }
// else
// {
// row[ColumnNames.PROMPT] = var.PromptText;
// }
//}
//else
//{
// row[ColumnNames.PROMPT] = var.PromptText;
//}
//if (this.Context.DataSet.Tables.Contains("output"))
//{
// row[ColumnNames.FIELDTYPE] = this.Context.DataSet.Tables["output"].Columns[var.Name].DataType.ToString();
//}
//else
//{
// row[ColumnNames.FIELDTYPE] = var.DataType.ToString();
//}
//row[ColumnNames.VARIABLE] = var.Name;
////row[ColumnNames.VARIABLE_VALUE] = var.???;
//row[ColumnNames.FORMATVALUE] = pattern;
//row[ColumnNames.SPECIALINFO] = var.VarType.ToString();
//row[ColumnNames.TABLE] = tableText;
//table.Rows.Add(row);
}
return BuildMarkupFromTable(table, string.Format("{0} ASC, {1} ASC", ColumnNames.TABLE, ColumnNames.VARIABLE));
}
private DataRow GetDataTable(DataColumn dataColumn, string tableText, string pattern, Dictionary<string, string> formatStrings, DataRow[] rows, DataTable table)
{
pattern = string.Empty;
IVariable var = (IVariable)this.Context.GetVariable(dataColumn.ColumnName);
if (var != null)
{
if (var.VarType == VariableType.DataSource || var.VarType == VariableType.DataSourceRedefined)
{
formatStrings.TryGetValue(var.Name, out pattern);
}
else
{
tableText = "Defined";
}
}
else
{
//tableText = "Defined";
var = new DataSourceVariable(dataColumn.ColumnName, DataType.Unknown);
}
DataRow row = table.NewRow();
if (
this.Context.CurrentRead != null &&
this.Context.CurrentRead.IsEpi7ProjectRead &&
this.Context.CurrentProject.Views.Exists(this.Context.CurrentRead.Identifier) &&
this.Context.CurrentProject.Views[this.Context.CurrentRead.Identifier].Fields.Exists(var.Name)
)
{
Epi.Fields.Field field = this.Context.CurrentProject.Views[this.Context.CurrentRead.Identifier].Fields[var.Name];
if (field is FieldWithSeparatePrompt)
{
row[ColumnNames.PROMPT] = ((FieldWithSeparatePrompt)field).PromptText;
}
else
{
row[ColumnNames.PROMPT] = var.PromptText;
}
//Fiexes for Issue: 943
if (field.FieldType.ToString() == MetaFieldType.Checkbox.ToString())
{
row[ColumnNames.FIELDTYPE] = "Checkbox";
}
else
{
row[ColumnNames.FIELDTYPE] = field.FieldType.ToString();
}
}
else
{
row[ColumnNames.PROMPT] = var.PromptText;
if (var.VarType == VariableType.Permanent)
{
row[ColumnNames.FIELDTYPE] = var.DataType.ToString();
}
else
{
if (this.Context.DataSet.Tables.Contains("output"))
{
row[ColumnNames.FIELDTYPE] = GetVariableType(this.Context.DataSet.Tables["output"].Columns[var.Name].DataType.ToString());
}
else
{
row[ColumnNames.FIELDTYPE] = var.DataType.ToString();
}
}
}
row[ColumnNames.VARIABLE] = var.Name;
row[ColumnNames.FORMATVALUE] = pattern;
row[ColumnNames.SPECIALINFO] = var.VarType.ToString();
row[ColumnNames.TABLE] = tableText;
// table.Rows.Add(row);
return row;
}
private string GetVariableType(string vartype)
{
switch (vartype)
{
case "System.String" :
return "Text";
case "System.Byte" :
return "YesNo";
case "System.Int16" :
case "System.Int32":
case "System.Int64":
case "System.Double":
case "System.Decimal":
return "Number";
case "System.Boolean":
return "Checkbox";
case "System.DateTime" :
return "DateTime";
default :
return "Text";
}
}
/// <summary>
/// GetViewMarkup gets both the markup used in the HTMLRESULTS section and a DataTable
/// with a row for each DBVIEW and its properties.
/// </summary>
/// <param name="table">An instance of a DataTable containing properties of DBVIEW.</param>
/// <returns>Returns the markup used in the HTMLRESULTS section.</returns>
private string GetViewMarkup(out DataTable table)
{
StringBuilder sb = new StringBuilder();
table = new DataTable();
table.Columns.Add(ColumnNames.DATA_TABLE_NAME, typeof(string));
table.Columns.Add(ColumnNames.TYPE, typeof(string));
table.Columns.Add(ColumnNames.LINK, typeof(string));
table.Columns.Add(ColumnNames.PARENT_VIEW, typeof(string));
table.Columns.Add(ColumnNames.CHILD_TYPE, typeof(string));
table.Columns.Add(ColumnNames.CHILD_TABLES, typeof(string));
try
{
IDbDriver driver = null;
if (this.Context.CurrentRead != null)
{
driver = Epi.Data.DBReadExecute.GetDataDriver(this.Context.CurrentRead.File);
}
if (!string.IsNullOrEmpty(dbViewsOpt))
{
driver = Epi.Data.DBReadExecute.GetDataDriver(dbViewsOpt);
}
List<string> tableNames = driver.GetTableNames();
int colCount;
/////////////////////////////////
//ViewCollection Views = metadata.GetViews();
//////Views parent list
//List<string> pViewsList = new List<string>();
//foreach (var view in Views)
//{
// pViewsList.Add(metadata.GetAvailDataTableName(((Epi.View)(view)).Name));
//}
//////Views list
//List<string> ViewsList = new List<string>();
//foreach (var view in Views)
//{
// ViewsList.Add(((Epi.View)(view)).Name);
//}
//////Code table list
//List<string> CodeTableList = new List<string>();
//DataTable CodeTables = metadata.GetCodeTableList();
//foreach (DataRow CodeTable in CodeTables.Rows)
//{
// CodeTableList.Add(((Epi.DataSets.TableSchema.TablesRow)(CodeTable)).TABLE_NAME);
//}
//////Data table list
//List<string> DataTableList = new List<string>();
//DataTableList = metadata.GetDataTableList();
////////////////////////////////
foreach (string name in tableNames)
{
StringBuilder primaryKeys = new StringBuilder();
DataTable currentTable = driver.GetTableData(name);
colCount = table.Columns.Count;
DataRow row = table.NewRow();
row[ColumnNames.DATA_TABLE_NAME] = name;
//issue 769 start
//if (this.Context.CurrentRead != null)
//{
// if (this.Context.CurrentProject != null && this.Context.CurrentProject.Views.Exists(this.Context.CurrentRead.Identifier))
// {
// row[ColumnNames.TYPE] = "View";
// }
// else
// {
// row[ColumnNames.TYPE] = "Data";
// }
//}
//else
//{
// row[ColumnNames.TYPE] = "Data";
//}
row[ColumnNames.TYPE] = GetTableTypeName(name, colCount);
//issue 769 end
row[ColumnNames.LINK] = string.Empty;
row[ColumnNames.PARENT_VIEW] = string.Empty;
row[ColumnNames.CHILD_TYPE] = string.Empty;
row[ColumnNames.CHILD_TABLES] = string.Empty;
table.Rows.Add(row);
}
}
catch (NullReferenceException)
{
throw new GeneralException(SharedStrings.NO_DATA_SOURCE);
}
return BuildMarkupFromTable(table, string.Empty);
}
/// <summary>
/// GetVariableMarkup gets both the markup used in the HTMLRESULTS section and a DataTable
/// with a row for each TABLES and its properties.
/// </summary>
/// <param name="table">An instance of a DataTable containing properties of TABLES.</param>
/// <returns>Returns the markup used in the HTMLRESULTS section.</returns>
private string GetTableMarkup(out DataTable table)
{
StringBuilder sb = new StringBuilder();
table = new DataTable();
table.Columns.Add(ColumnNames.DATA_TABLE_NAME, typeof(string));
table.Columns.Add(ColumnNames.TYPE, typeof(string));
table.Columns.Add(ColumnNames.NUMBER_OF_FIELDS, typeof(Int16));
table.Columns.Add(ColumnNames.LINK, typeof(string));
table.Columns.Add(ColumnNames.PRIMARY_KEY, typeof(string));
table.Columns.Add(ColumnNames.DESCRIPTION, typeof(string));
try
{
IDbDriver driver = null;
if (this.Context.CurrentRead != null)
{
driver = Epi.Data.DBReadExecute.GetDataDriver(this.Context.CurrentRead.File);
}
if (!string.IsNullOrEmpty(dbViewsOpt))
{
driver = Epi.Data.DBReadExecute.GetDataDriver(dbViewsOpt);
}
List<string> tableNames = driver.GetTableNames();
int colCount;
foreach (string name in tableNames)
{
StringBuilder primaryKeys = new StringBuilder();
colCount = driver.GetTableData(name).Columns.Count;
foreach (DataColumn key in driver.GetTableData(name).PrimaryKey)
{
primaryKeys.Append(string.Format("{0} ", key.ColumnName));
}
DataRow row = table.NewRow();
row[ColumnNames.DATA_TABLE_NAME] = name;
row[ColumnNames.TYPE] = GetTableTypeName(name, colCount);
row[ColumnNames.NUMBER_OF_FIELDS] = colCount;
row[ColumnNames.LINK] = string.Empty;
row[ColumnNames.PRIMARY_KEY] = primaryKeys.ToString();
row[ColumnNames.DESCRIPTION] = string.Empty;
table.Rows.Add(row);
}
}
catch (NullReferenceException)
{
throw new GeneralException(SharedStrings.NO_DATA_SOURCE);
}
return BuildMarkupFromTable(table, string.Empty);
}
#region Protected Methods
/// <summary>
/// BuildMarkupFromTable takes the DataTable from any one of the Get...Markup methods in
/// this class and builds a table in HTML.
/// <para>
/// It does a select on the table to get an arry of DataRows, prints a table header then
/// prints each row.
/// </para>
/// </summary>
/// <param name="table">A DataTable containing the information to be displayed.</param>
/// <param name="sortOrder">The sort string used in the select statement used on the table
/// for each DataTable</param>
/// <returns>The HTML markup of the DataTable</returns>
private string BuildMarkupFromTable(DataTable table, string sortOrder)
{
StringBuilder builder = new StringBuilder();
DataRow[] rows = table.Select("", sortOrder);
builder.Append("<table>");
PrintHeaderRow(table, builder);
for (int i = 0; i < rows.Length; i++)
{
PrintRow(table, rows[i], builder);
}
builder.Append("</table>");
return builder.ToString();
}
/// <summary>
/// PrintRow appends HTML markup to a StringBuilder object from the given
/// DataRow using the column names from the given DataTable
/// </summary>
/// <param name="table">The DataTable used to provide.</param>
/// <param name="row">The DataRow to be displayed in the markup table.</param>
/// <param name="builder">The StringBuilder that contains the HTML table markup.</param>
private void PrintRow(DataTable table, DataRow row, StringBuilder builder)
{
builder.Append("<tr>");
object[] Items = row.ItemArray;
for (int i = 0; i < table.Columns.Count; i++)
{
DataColumn col = table.Columns[i];
builder.Append("<td>");
if (this.Context.Recodes.ContainsKey(col.ColumnName))
{
builder.Append(this.Context.Recodes[col.ColumnName].GetRecode(row[this.Context.Recodes[col.ColumnName].SourceName]));
}
else
{
builder.Append(row[col.ColumnName].ToString());
}
builder.Append("</td>");
}
builder.Append("</tr>");
}
/// <summary>
/// PrintHeaderRow just adds the header (column names) to the HTML markup
/// table. It gets the column names from the given DataTable.
/// </summary>
/// <param name="table">The DataTable that will be written to the HTML table.</param>
/// <param name="builder">The StringBuilder that contains the HTML table markup.</param>
private void PrintHeaderRow(DataTable table, StringBuilder builder)
{
builder.Append("<tr>");
for (int i = 0; i < table.Columns.Count; i++)
{
DataColumn col = table.Columns[i];
builder.Append("<th>");
builder.Append(col.ColumnName);
builder.Append("</th>");
}
builder.Append("</tr>");
}
/// <summary>
/// GetVariables returns a NamedObjectCollection generic for the given variable
/// names in the string array varList. The option string is used to set the type
/// of variables returned.
/// </summary>
/// <param name="varList">varList is a string array containing the variable names.</param>
/// <param name="opt"></param>
/// <returns>VariableCollection is a Epi.Collections.NamedObjectCollection.</returns>
private VariableCollection GetVariables(string[] varList, string option)
{
VariableType scopeCombination = 0;
VariableCollection vars = null;
switch (option)
{
case "DEFINE":
scopeCombination = VariableType.Global | VariableType.Permanent | VariableType.Standard;
break;
case "FIELDVAR":
scopeCombination = VariableType.DataSource | VariableType.DataSourceRedefined;
break;
case "LIST":
scopeCombination = VariableType.Global | VariableType.Permanent | VariableType.Standard |
VariableType.DataSource | VariableType.DataSourceRedefined;
break;
default:
scopeCombination = VariableType.Global | VariableType.Permanent | VariableType.Standard |
VariableType.DataSource | VariableType.DataSourceRedefined;
break;
}
if (varList != null)
{
vars = new VariableCollection();
foreach (string varname in varList)
{
IVariable var = null;
if (this.Context.MemoryRegion.TryGetVariable(varname, out var))
{
vars.Add(var);
}
}
}
else
{
vars = this.Context.MemoryRegion.GetVariablesInScope(scopeCombination);
}
return vars;
}
/// <summary>
/// GetTableTypeName gets the type of a table as a string value based on
/// the name of the table of the number of columns in the table.
/// </summary>
/// <param name="tableName">tableName is the name of the table.</param>
/// <param name="numOfColumns">numOfColumn in the table.</param>
/// <returns></returns>
private string GetTableTypeName(string tableName, int numOfColumns)
{
string firstFourChars = tableName.Substring(0, 4).ToLowerInvariant();
//issue 769 start
if (firstFourChars == "view")
{
firstFourChars = "View";
}
else if (firstFourChars == "code")
{
firstFourChars = "Code";
}
else if (firstFourChars == "meta")
{
firstFourChars = "Meta";
}
else
{
firstFourChars = "Data";
}
//issue 769 end
return firstFourChars;
}
/// <summary>
/// WriteToOutTable deletes the table named in the outTableName param
/// then creates and inserts and new table with the name given.
/// </summary>
/// <param name="table">The DataTable that will be copied to the database.</param>
/// <param name="outTableName">The name of the new table to be persised</param>
private void WriteToOutTable(DataTable table, string outTableName)
{
if (!string.IsNullOrEmpty(outTableName))
{
if (this.Context.CurrentRead != null)
{
if (DBReadExecute.CheckDatabaseTableExistance(this.Context.CurrentRead.File, outTableName))
{
DBReadExecute.ExecuteSQL(this.Context.CurrentRead.File, "Delete From " + outTableName);
DBReadExecute.ExecuteSQL(this.Context.CurrentRead.File, "Drop Table " + outTableName);
}
DBReadExecute.ExecuteSQL(this.Context.CurrentRead.File, DBReadExecute.GetCreateFromDataTableSQL(outTableName, table));
DBReadExecute.InsertData(this.Context.CurrentRead.File, "Select * from " + outTableName, table.CreateDataReader());
}
}
}
#endregion Protected Methods
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyDuration
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Duration operations.
/// </summary>
public partial class Duration : IServiceOperations<AutoRestDurationTestService>, IDuration
{
/// <summary>
/// Initializes a new instance of the Duration class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Duration(AutoRestDurationTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestDurationTestService
/// </summary>
public AutoRestDurationTestService Client { get; private set; }
/// <summary>
/// Get null duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<TimeSpan?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<TimeSpan?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put a positive duration value
/// </summary>
/// <param name='durationBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutPositiveDurationWithHttpMessagesAsync(TimeSpan? durationBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (durationBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "durationBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("durationBody", durationBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get a positive duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<TimeSpan?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get an invalid duration value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<TimeSpan?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<TimeSpan?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
_result.Body = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
throw new RestException("Unable to deserialize the response.", ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
namespace Spring.Expressions.Parser.antlr
{
/* ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/license.html
*/
//
// ANTLR C# Code Generator by Micheal Jordan
// Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com
// Anthony Oguntimehin
//
using System;
using IList = System.Collections.IList;
using IDictionary = System.Collections.IDictionary;
using ArrayList = System.Collections.ArrayList;
using Hashtable = System.Collections.Hashtable;
using IComparer = System.Collections.IComparer;
using StringBuilder = System.Text.StringBuilder;
using BitSet = antlr.collections.impl.BitSet;
/// <summary>
/// This token stream tracks the *entire* token stream coming from
/// a lexer, but does not pass on the whitespace (or whatever else
/// you want to discard) to the parser.
/// </summary>
/// <remarks>
/// <para>
/// This class can then be asked for the ith token in the input stream.
/// Useful for dumping out the input stream exactly after doing some
/// augmentation or other manipulations. Tokens are index from 0..n-1
/// </para>
/// <para>
/// You can insert stuff, replace, and delete chunks. Note that the
/// operations are done lazily--only if you convert the buffer to a
/// string. This is very efficient because you are not moving data around
/// all the time. As the buffer of tokens is converted to strings, the
/// toString() method(s) check to see if there is an operation at the
/// current index. If so, the operation is done and then normal string
/// rendering continues on the buffer. This is like having multiple Turing
/// machine instruction streams (programs) operating on a single input tape. :)
/// </para>
/// <para>
/// Since the operations are done lazily at toString-time, operations do not
/// screw up the token index values. That is, an insert operation at token
/// index i does not change the index values for tokens i+1..n-1.
/// </para>
/// <para>
/// Because operations never actually alter the buffer, you may always get
/// the original token stream back without undoing anything. Since
/// the instructions are queued up, you can easily simulate transactions and
/// roll back any changes if there is an error just by removing instructions.
/// For example,
/// </para>
/// <example>For example:
/// <code>
/// TokenStreamRewriteEngine rewriteEngine = new TokenStreamRewriteEngine(lexer);
/// JavaRecognizer parser = new JavaRecognizer(rewriteEngine);
/// ...
/// rewriteEngine.insertAfter("pass1", t, "foobar");}
/// rewriteEngine.insertAfter("pass2", u, "start");}
/// System.Console.Out.WriteLine(rewriteEngine.ToString("pass1"));
/// System.Console.Out.WriteLine(rewriteEngine.ToString("pass2"));
/// </code>
/// </example>
/// <para>
/// You can also have multiple "instruction streams" and get multiple
/// rewrites from a single pass over the input. Just name the instruction
/// streams and use that name again when printing the buffer. This could be
/// useful for generating a C file and also its header file--all from the
/// same buffer.
/// </para>
/// <para>
/// If you don't use named rewrite streams, a "default" stream is used.
/// </para>
/// <para>
/// Terence Parr, [email protected]
/// University of San Francisco
/// February 2004
/// </para>
/// </remarks>
public class TokenStreamRewriteEngine : TokenStream
{
public const int MIN_TOKEN_INDEX = 0;
protected class RewriteOperation
{
protected internal int index;
protected internal string text;
protected RewriteOperation(int index, string text)
{
this.index = index;
this.text = text;
}
/// <summary>
/// Execute the rewrite operation by possibly adding to the buffer.
/// </summary>
/// <param name="buf">rewrite buffer</param>
/// <returns>The index of the next token to operate on.</returns>
public virtual int execute(StringBuilder buf)
{
return index;
}
}
protected class InsertBeforeOp : RewriteOperation
{
public InsertBeforeOp(int index, string text) : base(index, text)
{
}
public override int execute(StringBuilder buf)
{
buf.Append(text);
return index;
}
}
protected class ReplaceOp : RewriteOperation
{
protected int lastIndex;
public ReplaceOp(int from, int to, string text) : base(from, text)
{
lastIndex = to;
}
public override int execute(StringBuilder buf)
{
if ( text != null )
{
buf.Append(text);
}
return lastIndex+1;
}
}
protected class DeleteOp : ReplaceOp
{
public DeleteOp(int from, int to) : base(from, to, null)
{
}
}
public const string DEFAULT_PROGRAM_NAME = "default";
public const int PROGRAM_INIT_SIZE = 100;
/// <summary>
/// Track the incoming list of tokens
/// </summary>
protected IList tokens;
/// <summary>
/// You may have multiple, named streams of rewrite operations.
/// I'm calling these things "programs."
/// Maps string (name) -> rewrite (List)
/// </summary>
protected IDictionary programs = null;
/// <summary>
/// Map string (program name) -> Integer index
/// </summary>
protected IDictionary lastRewriteTokenIndexes = null;
/// <summary>
/// track index of tokens
/// </summary>
protected int index = MIN_TOKEN_INDEX;
/// <summary>
/// Who do we suck tokens from?
/// </summary>
protected TokenStream stream;
/// <summary>
/// Which (whitespace) token(s) to throw out
/// </summary>
protected BitSet discardMask = new BitSet();
public TokenStreamRewriteEngine(TokenStream upstream) : this(upstream, 1000)
{
}
public TokenStreamRewriteEngine(TokenStream upstream, int initialSize)
{
stream = upstream;
tokens = new ArrayList(initialSize);
programs = new Hashtable();
programs[DEFAULT_PROGRAM_NAME] = new ArrayList(PROGRAM_INIT_SIZE);
lastRewriteTokenIndexes = new Hashtable();
}
public IToken nextToken() // throws TokenStreamException
{
TokenWithIndex t;
// suck tokens until end of stream or we find a non-discarded token
do
{
t = (TokenWithIndex) stream.nextToken();
if ( t != null )
{
t.setIndex(index); // what is t's index in list?
if ( t.Type != Token.EOF_TYPE )
{
tokens.Add(t); // track all tokens except EOF
}
index++; // move to next position
}
} while ( (t != null) && (discardMask.member(t.Type)) );
return t;
}
public void rollback(int instructionIndex)
{
rollback(DEFAULT_PROGRAM_NAME, instructionIndex);
}
/// <summary>
/// Rollback the instruction stream for a program so that
/// the indicated instruction (via instructionIndex) is no
/// longer in the stream.
/// </summary>
/// <remarks>
/// UNTESTED!
/// </remarks>
/// <param name="programName"></param>
/// <param name="instructionIndex"></param>
public void rollback(string programName, int instructionIndex)
{
ArrayList il = (ArrayList) programs[programName];
if ( il != null )
{
programs[programName] = il.GetRange(MIN_TOKEN_INDEX, (instructionIndex - MIN_TOKEN_INDEX));
}
}
public void deleteProgram()
{
deleteProgram(DEFAULT_PROGRAM_NAME);
}
/// <summary>
/// Reset the program so that no instructions exist
/// </summary>
/// <param name="programName"></param>
public void deleteProgram(string programName)
{
rollback(programName, MIN_TOKEN_INDEX);
}
/// <summary>
/// If op.index > lastRewriteTokenIndexes, just add to the end.
/// Otherwise, do linear
/// </summary>
/// <param name="op"></param>
protected void addToSortedRewriteList(RewriteOperation op)
{
addToSortedRewriteList(DEFAULT_PROGRAM_NAME, op);
}
protected void addToSortedRewriteList(string programName, RewriteOperation op)
{
ArrayList rewrites = (ArrayList) getProgram(programName);
// if at or beyond last op's index, just append
if ( op.index >= getLastRewriteTokenIndex(programName) )
{
rewrites.Add(op); // append to list of operations
// record the index of this operation for next time through
setLastRewriteTokenIndex(programName, op.index);
return;
}
// not after the last one, so must insert to ordered list
int pos = rewrites.BinarySearch(op, RewriteOperationComparer.Default);
if (pos < 0)
{
rewrites.Insert(-pos-1, op);
}
}
public void insertAfter(IToken t, string text)
{
insertAfter(DEFAULT_PROGRAM_NAME, t, text);
}
public void insertAfter(int index, string text)
{
insertAfter(DEFAULT_PROGRAM_NAME, index, text);
}
public void insertAfter(string programName, IToken t, string text)
{
insertAfter(programName,((TokenWithIndex) t).getIndex(), text);
}
public void insertAfter(string programName, int index, string text)
{
// to insert after, just insert before next index (even if past end)
insertBefore(programName, index+1, text);
}
public void insertBefore(IToken t, string text)
{
insertBefore(DEFAULT_PROGRAM_NAME, t, text);
}
public void insertBefore(int index, string text)
{
insertBefore(DEFAULT_PROGRAM_NAME, index, text);
}
public void insertBefore(string programName, IToken t, string text)
{
insertBefore(programName, ((TokenWithIndex) t).getIndex(), text);
}
public void insertBefore(string programName, int index, string text)
{
addToSortedRewriteList(programName, new InsertBeforeOp(index, text));
}
public void replace(int index, string text)
{
replace(DEFAULT_PROGRAM_NAME, index, index, text);
}
public void replace(int from, int to, string text)
{
replace(DEFAULT_PROGRAM_NAME, from, to, text);
}
public void replace(IToken indexT, string text)
{
replace(DEFAULT_PROGRAM_NAME, indexT, indexT, text);
}
public void replace(IToken from, IToken to, string text)
{
replace(DEFAULT_PROGRAM_NAME, from, to, text);
}
public void replace(string programName, int from, int to, string text)
{
addToSortedRewriteList(new ReplaceOp(from, to, text));
}
public void replace(string programName, IToken from, IToken to, string text)
{
replace(programName,
((TokenWithIndex) from).getIndex(),
((TokenWithIndex) to).getIndex(),
text);
}
public void delete(int index)
{
delete(DEFAULT_PROGRAM_NAME, index, index);
}
public void delete(int from, int to)
{
delete(DEFAULT_PROGRAM_NAME, from, to);
}
public void delete(IToken indexT)
{
delete(DEFAULT_PROGRAM_NAME, indexT, indexT);
}
public void delete(IToken from, IToken to)
{
delete(DEFAULT_PROGRAM_NAME, from, to);
}
public void delete(string programName, int from, int to)
{
replace(programName, from, to, null);
}
public void delete(string programName, IToken from, IToken to)
{
replace(programName, from, to, null);
}
public void discard(int ttype)
{
discardMask.add(ttype);
}
public TokenWithIndex getToken(int i)
{
return (TokenWithIndex) tokens[i];
}
public int getTokenStreamSize()
{
return tokens.Count;
}
public string ToOriginalString()
{
return ToOriginalString(MIN_TOKEN_INDEX, getTokenStreamSize()-1);
}
public string ToOriginalString(int start, int end)
{
StringBuilder buf = new StringBuilder();
for (int i = start; (i >= MIN_TOKEN_INDEX) && (i <= end) && (i < tokens.Count); i++)
{
buf.Append(getToken(i).getText());
}
return buf.ToString();
}
public override string ToString()
{
return ToString(MIN_TOKEN_INDEX, getTokenStreamSize());
}
public string ToString(string programName)
{
return ToString(programName, MIN_TOKEN_INDEX, getTokenStreamSize());
}
public string ToString(int start, int end)
{
return ToString(DEFAULT_PROGRAM_NAME, start, end);
}
public string ToString(string programName, int start, int end)
{
IList rewrites = (IList) programs[programName];
if (rewrites == null)
{
return null; // invalid program
}
StringBuilder buf = new StringBuilder();
// Index of first rewrite we have not done
int rewriteOpIndex = 0;
int tokenCursor = start;
while ( (tokenCursor >= MIN_TOKEN_INDEX) &&
(tokenCursor <= end) &&
(tokenCursor < tokens.Count) )
{
if (rewriteOpIndex < rewrites.Count)
{
RewriteOperation op = (RewriteOperation) rewrites[rewriteOpIndex];
while ( (tokenCursor == op.index) && (rewriteOpIndex < rewrites.Count) )
{
/*
Console.Out.WriteLine("execute op "+rewriteOpIndex+
" (type "+op.GetType().FullName+")"
+" at index "+op.index);
*/
tokenCursor = op.execute(buf);
rewriteOpIndex++;
if (rewriteOpIndex < rewrites.Count)
{
op = (RewriteOperation) rewrites[rewriteOpIndex];
}
}
}
if ( tokenCursor < end )
{
buf.Append(getToken(tokenCursor).getText());
tokenCursor++;
}
}
// now see if there are operations (append) beyond last token index
for (int opi = rewriteOpIndex; opi < rewrites.Count; opi++)
{
RewriteOperation op = (RewriteOperation) rewrites[opi];
op.execute(buf); // must be insertions if after last token
}
return buf.ToString();
}
public string ToDebugString()
{
return ToDebugString(MIN_TOKEN_INDEX, getTokenStreamSize());
}
public string ToDebugString(int start, int end)
{
StringBuilder buf = new StringBuilder();
for (int i = start; (i >= MIN_TOKEN_INDEX) && (i <= end) && (i < tokens.Count); i++)
{
buf.Append(getToken(i));
}
return buf.ToString();
}
public int getLastRewriteTokenIndex()
{
return getLastRewriteTokenIndex(DEFAULT_PROGRAM_NAME);
}
protected int getLastRewriteTokenIndex(string programName)
{
object i = lastRewriteTokenIndexes[programName];
if (i == null)
{
return -1;
}
return (int) i;
}
protected void setLastRewriteTokenIndex(string programName, int i)
{
lastRewriteTokenIndexes[programName] = (object) i;
}
protected IList getProgram(string name)
{
IList il = (IList) programs[name];
if ( il == null )
{
il = initializeProgram(name);
}
return il;
}
private IList initializeProgram(string name)
{
IList il = new ArrayList(PROGRAM_INIT_SIZE);
programs[name] = il;
return il;
}
public class RewriteOperationComparer : IComparer
{
public static readonly RewriteOperationComparer Default = new RewriteOperationComparer();
public virtual int Compare(object o1, object o2)
{
RewriteOperation rop1 = (RewriteOperation) o1;
RewriteOperation rop2 = (RewriteOperation) o2;
if (rop1.index < rop2.index) return -1;
if (rop1.index > rop2.index) return 1;
return 0;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using hutel.Models;
namespace hutel.Logic
{
public static class TagFieldConstants
{
public const string IntType = "int";
public const string FloatType = "float";
public const string StringType = "string";
public const string DateType = "date";
public const string TimeType = "time";
public const string EnumType = "enum";
}
public abstract class BaseTagField
{
public abstract string TypeString { get; }
public string Name { get; }
protected BaseTagField(TagFieldDataContract tagFieldDataContract)
{
Name = tagFieldDataContract.Name;
}
public abstract Object ValueFromDataContract(Object obj);
public abstract Object ValueToDataContract(Object obj);
public virtual TagFieldDataContract ToDataContract()
{
return new TagFieldDataContract
{
Name = Name,
Type = TypeString
};
}
public static BaseTagField FromDataContract(TagFieldDataContract fieldDataContract)
{
if (string.IsNullOrEmpty(fieldDataContract.Name))
{
throw new TagValidationException("Field name is empty");
}
if (!StringToFieldType.TryGetValue(fieldDataContract.Type, out Type type))
{
throw new TagValidationException(
$"Unknown type {fieldDataContract.Type} in tag field {fieldDataContract.Name}");
}
try
{
return (BaseTagField)Activator.CreateInstance(type, fieldDataContract);
}
catch (Exception ex)
{
throw new TagValidationException(
$"Cannot initialize field {fieldDataContract.Name}", ex);
}
}
private static readonly Dictionary<string, Type> StringToFieldType =
new Dictionary<string, Type>
{
{ "int", typeof(IntTagField) },
{ "float", typeof(FloatTagField) },
{ "string", typeof(StringTagField) },
{ "date", typeof(DateTagField) },
{ "time", typeof(TimeTagField) },
{ "enum", typeof(EnumTagField) }
};
}
public class IntTagField : BaseTagField
{
public override string TypeString { get { return TagFieldConstants.IntType; } }
public override Object ValueFromDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(Int64));
return obj;
}
public override Object ValueToDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(Int64));
return obj;
}
public IntTagField(TagFieldDataContract fieldDataContract) : base(fieldDataContract) {}
}
public class FloatTagField : BaseTagField
{
public override string TypeString { get { return TagFieldConstants.FloatType; } }
public override Object ValueFromDataContract(Object obj)
{
var intObj = obj as Int64?;
if (intObj != null)
{
return (Double)intObj;
}
TypeValidationHelper.Validate(obj, typeof(Double));
return obj;
}
public override Object ValueToDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(Double));
return obj;
}
public FloatTagField(TagFieldDataContract fieldDataContract) : base(fieldDataContract) {}
}
public class StringTagField : BaseTagField
{
public override string TypeString { get { return TagFieldConstants.StringType; } }
public override Object ValueFromDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(string));
return obj;
}
public override Object ValueToDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(string));
return obj;
}
public StringTagField(TagFieldDataContract fieldDataContract) : base(fieldDataContract) {}
}
public class DateTagField : BaseTagField
{
public override string TypeString { get { return TagFieldConstants.DateType; } }
public DateTagField(TagFieldDataContract fieldDataContract) : base(fieldDataContract) {}
public override Object ValueFromDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(string));
try
{
return new HutelDate((string)obj);
}
catch(Exception ex)
{
throw new TypeValidationException("Error in date constructor", ex);
}
}
public override Object ValueToDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(HutelDate));
return ((HutelDate)obj).ToString();
}
}
public class TimeTagField : BaseTagField
{
public override string TypeString { get { return TagFieldConstants.TimeType; } }
public TimeTagField(TagFieldDataContract fieldDataContract) : base(fieldDataContract) {}
public override Object ValueFromDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(string));
try
{
return new HutelTime((string)obj);
}
catch(Exception ex)
{
throw new TypeValidationException("Error in time constructor", ex);
}
}
public override Object ValueToDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(HutelTime));
return ((HutelTime)obj).ToString();
}
}
public class EnumTagField : BaseTagField
{
public override string TypeString { get { return TagFieldConstants.EnumType; } }
public ICollection<string> Values
{
get
{
return _values;
}
}
public EnumTagField(TagFieldDataContract fieldDataContract)
: base(fieldDataContract)
{
if (fieldDataContract.Values == null || !fieldDataContract.Values.Any())
{
throw new ArgumentOutOfRangeException(nameof(fieldDataContract), "Empty enum is useless");
}
_values = fieldDataContract.Values;
}
public override Object ValueFromDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(string));
ThrowIfNotInCollection(obj);
return obj;
}
public override Object ValueToDataContract(Object obj)
{
TypeValidationHelper.Validate(obj, typeof(string));
ThrowIfNotInCollection(obj);
return obj;
}
public override TagFieldDataContract ToDataContract()
{
return new TagFieldDataContract
{
Name = Name,
Type = TypeString,
Values = _values.ToList()
};
}
private void ThrowIfNotInCollection(object obj)
{
var str = (string)obj;
if (!_values.Contains(str))
{
throw new TypeValidationException($"Invalid enum value: {str}");
}
}
private readonly ICollection<string> _values;
}
public class TypeValidationException : Exception
{
public TypeValidationException()
{
}
public TypeValidationException(string message): base(message)
{
}
public TypeValidationException(string message, Exception inner) : base(message, inner)
{
}
}
public static class TypeValidationHelper
{
public static void Validate(Object obj, Type expectedType)
{
var objType = obj.GetType();
if (!(expectedType.IsAssignableFrom(objType)))
{
throw new TypeValidationException(
$"Expected {expectedType.Name}, received {objType.Name} instead");
}
}
}
}
| |
using System;
namespace GuruComponents.Netrix
{
/// <summary>
/// Used to inform about the ability to do a command.
/// </summary>
/// <remarks>
///
/// </remarks>
public enum HtmlCommandInfo
{
/// <summary>
/// Command is available.
/// </summary>
Enabled = 1,
/// <summary>
/// Informs that the state of the command is on or the related element is selected.
/// </summary>
Checked = 2,
/// <summary>
/// Set if the command is checked (on) and still available.
/// </summary>
Both = 3,
/// <summary>
/// Set if the command is a toggle command and is currently active.
/// </summary>
Latched = 4,
/// <summary>
/// Set if the command is not checked (off) and not available at that point.
/// </summary>
None = 0,
/// <summary>
/// Set if the control has not successfully recognized the given command.
/// </summary>
/// <remarks>
/// This does not mean that the command is unavailable. It just means that there is no valid information present.
/// </remarks>
Error = 9
}
/// <summary>
/// These commands can be used to check if the options is on or available.
/// </summary>
public enum HtmlCommand
{
/// <summary>
/// Align elements to bottom border in absolute position mode.
/// </summary>
AlignBottom = 1,
/// <summary>
/// Align elements to horizontal centered lines in absolute position mode.
/// </summary>
AlignHorizontalCenter = 2,
/// <summary>
/// Align elements to left border in absolute position mode.
/// </summary>
AlignLeft = 3,
/// <summary>
/// Align elements to right border in absolute position mode.
/// </summary>
AlignRight = 4,
/// <summary>
/// Align element to grid lines in absolute position mode.
/// </summary>
AlignToGrid = 5,
/// <summary>
/// Align elements to top border in absolute position mode.
/// </summary>
Aligntop = 6,
/// <summary>
///
/// </summary>
AlignVerticalCenter = 7,
/// <summary>
///
/// </summary>
ArrangeBottom = 8,
/// <summary>
///
/// </summary>
ArrangeRight = 9,
/// <summary>
///
/// </summary>
BringForward = 10,
/// <summary>
///
/// </summary>
BringToFront = 11,
/// <summary>
///
/// </summary>
CenterHorizontally = 12,
/// <summary>
///
/// </summary>
CenterVertically = 13,
/// <summary>
/// Delete element.
/// </summary>
Delete = 17,
/// <summary>
/// Set font name (family name).
/// </summary>
Fontname = 18,
/// <summary>
/// Set font size in HTML units (1...7).
/// </summary>
Fontsize = 19,
/// <summary>
/// Send an element backwards in absolute position mode.
/// </summary>
SendBackward = 32,
/// <summary>
/// Send an element to back in absolute position mode.
/// </summary>
SendToBack = 33,
/// <summary>
/// Justify the selected paragraph.
/// </summary>
JustifyFull = 50,
/// <summary>
/// Set the back color.
/// </summary>
BackColor = 51,
/// <summary>
/// Set bold.
/// </summary>
Bold = 52,
/// <summary>
/// Set border color.
/// </summary>
BorderColor = 53,
/// <summary>
/// Set fore color of text.
/// </summary>
ForeColor = 55,
/// <summary>
/// Set italic.
/// </summary>
Italic = 56,
/// <summary>
///
/// </summary>
JustifyCenter = 57,
/// <summary>
///
/// </summary>
JustifyGeneral = 58,
/// <summary>
///
/// </summary>
JustifyLeft = 59,
/// <summary>
///
/// </summary>
JustifyRight = 60,
/// <summary>
/// Underline text.
/// </summary>
Underline = 63,
/// <summary>
///
/// </summary>
Font = 90,
/// <summary>
///
/// </summary>
StrikeThrough = 91,
/// <summary>
/// Delete word under caret.
/// </summary>
DeleteWord = 92,
/// <summary>
///
/// </summary>
ExecPrint = 93,
/// <summary>
///
/// </summary>
JustifyNone = 94,
/// <summary>
///
/// </summary>
InputImage = 2114,
/// <summary>
///
/// </summary>
InputButton = 2115,
/// <summary>
///
/// </summary>
InputReset = 2116,
/// <summary>
///
/// </summary>
InputSubmit = 2117,
/// <summary>
///
/// </summary>
InputUpload = 2118,
/// <summary>
///
/// </summary>
FieldSet = 2119,
/// <summary>
///
/// </summary>
Bookmark = 2123,
/// <summary>
///
/// </summary>
Hyperlink = 2124,
/// <summary>
///
/// </summary>
Unlink = 2125,
/// <summary>
///
/// </summary>
Unbookmark = 2128,
/// <summary>
///
/// </summary>
HorizontalRule = 2150,
/// <summary>
///
/// </summary>
LinebreakNormal = 2151,
/// <summary>
///
/// </summary>
LinebreakLeft = 2152,
/// <summary>
///
/// </summary>
LinebreakRight = 2153,
/// <summary>
///
/// </summary>
LinebreakBoth = 2154,
/// <summary>
///
/// </summary>
NonBreak = 2155,
/// <summary>
///
/// </summary>
InputTextbox = 2161,
/// <summary>
///
/// </summary>
InputTextarea = 2162,
/// <summary>
///
/// </summary>
InputCheckbox = 2163,
/// <summary>
///
/// </summary>
InputRadiobutton = 2164,
/// <summary>
///
/// </summary>
InputDropdownbox = 2165,
/// <summary>
///
/// </summary>
InputListbox = 2166,
/// <summary>
///
/// </summary>
Button = 2167,
/// <summary>
///
/// </summary>
Image = 2168,
/// <summary>
///
/// </summary>
ImageMap = 2171,
/// <summary>
///
/// </summary>
File = 2172,
/// <summary>
///
/// </summary>
Comment = 2173,
/// <summary>
///
/// </summary>
Script = 2174,
/// <summary>
///
/// </summary>
JavaApplet = 2175,
/// <summary>
///
/// </summary>
Plugin = 2176,
/// <summary>
///
/// </summary>
PageBreak = 2177,
/// <summary>
///
/// </summary>
Area = 2178,
/// <summary>
///
/// </summary>
Paragraph = 2180,
/// <summary>
///
/// </summary>
Form = 2181,
/// <summary>
///
/// </summary>
Marquee = 2182,
/// <summary>
///
/// </summary>
List = 2183,
/// <summary>
///
/// </summary>
OrderList = 2184,
/// <summary>
///
/// </summary>
UnorderList = 2185,
/// <summary>
///
/// </summary>
Indent = 2186,
/// <summary>
///
/// </summary>
Outdent = 2187,
/// <summary>
///
/// </summary>
Preformatted = 2188,
/// <summary>
///
/// </summary>
Address = 2189,
/// <summary>
///
/// </summary>
Blink = 2190,
/// <summary>
///
/// </summary>
Div = 2191,
/// <summary>
/// Remove block/paragraph format.
/// </summary>
RemoveFormat = 2230,
/// <summary>
///
/// </summary>
TeleType = 2232,
/// <summary>
///
/// </summary>
SetBlockFormat = 2234,
/// <summary>
///
/// </summary>
SubScript = 2247,
/// <summary>
///
/// </summary>
SuperScript = 2248,
/// <summary>
///
/// </summary>
CenterAlignPara = 2250,
/// <summary>
///
/// </summary>
LeftAlignPara = 2251,
/// <summary>
///
/// </summary>
RightAlignPara = 2252,
/// <summary>
///
/// </summary>
DirLtr = 2350,
/// <summary>
///
/// </summary>
DirRtl = 2351,
/// <summary>
///
/// </summary>
BlockDirLtr = 2352,
/// <summary>
///
/// </summary>
BlockDirRtl = 2353,
/// <summary>
///
/// </summary>
InlineDirLtr = 2354,
/// <summary>
///
/// </summary>
InlineDirRtl = 2355,
/// <summary>
///
/// </summary>
InsertSpan = 2357,
/// <summary>
///
/// </summary>
MultipleSelection = 2393,
/// <summary>
///
/// </summary>
AbsolutePosition = 2394,
/// <summary>
///
/// </summary>
AbsoluteElement2D = 2395,
/// <summary>
///
/// </summary>
AbsoluteElement1D = 2396,
/// <summary>
///
/// </summary>
AbsolutePositioned = 2397,
/// <summary>
///
/// </summary>
LiveResize = 2398,
/// <summary>
///
/// </summary>
AtomicSelection = 2399,
/// <summary>
///
/// </summary>
AutourlDetectMode = 2400,
/// <summary>
///
/// </summary>
Print = 27,
/// <summary>
///
/// </summary>
ClearSelection = 2007,
/// <summary>
///
/// </summary>
Redo = 29,
/// <summary>
///
/// </summary>
Undo = 43,
/// <summary>
///
/// </summary>
SelectAll = 31,
/// <summary>
///
/// </summary>
Copy = 15,
/// <summary>
///
/// </summary>
Cut = 16,
/// <summary>
///
/// </summary>
Paste = 26,
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface IAddressTypeOriginalData : ISchemaBaseOriginalData
{
string Name { get; }
string rowguid { get; }
}
public partial class AddressType : OGM<AddressType, AddressType.AddressTypeData, System.String>, ISchemaBase, INeo4jBase, IAddressTypeOriginalData
{
#region Initialize
static AddressType()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, AddressType> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.AddressTypeAlias, IWhereQuery> query)
{
q.AddressTypeAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.AddressType.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"AddressType => Name : {this.Name}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new AddressTypeData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.Name == null)
throw new PersistenceException(string.Format("Cannot save AddressType with key '{0}' because the Name cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.rowguid == null)
throw new PersistenceException(string.Format("Cannot save AddressType with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save AddressType with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class AddressTypeData : Data<System.String>
{
public AddressTypeData()
{
}
public AddressTypeData(AddressTypeData data)
{
Name = data.Name;
rowguid = data.rowguid;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "AddressType";
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Name", Name);
dictionary.Add("rowguid", rowguid);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("Name", out value))
Name = (string)value;
if (properties.TryGetValue("rowguid", out value))
rowguid = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface IAddressType
public string Name { get; set; }
public string rowguid { get; set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface IAddressType
public string Name { get { LazyGet(); return InnerData.Name; } set { if (LazySet(Members.Name, InnerData.Name, value)) InnerData.Name = value; } }
public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static AddressTypeMembers members = null;
public static AddressTypeMembers Members
{
get
{
if (members == null)
{
lock (typeof(AddressType))
{
if (members == null)
members = new AddressTypeMembers();
}
}
return members;
}
}
public class AddressTypeMembers
{
internal AddressTypeMembers() { }
#region Members for interface IAddressType
public Property Name { get; } = Datastore.AdventureWorks.Model.Entities["AddressType"].Properties["Name"];
public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["AddressType"].Properties["rowguid"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static AddressTypeFullTextMembers fullTextMembers = null;
public static AddressTypeFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(AddressType))
{
if (fullTextMembers == null)
fullTextMembers = new AddressTypeFullTextMembers();
}
}
return fullTextMembers;
}
}
public class AddressTypeFullTextMembers
{
internal AddressTypeFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(AddressType))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["AddressType"];
}
}
return entity;
}
private static AddressTypeEvents events = null;
public static AddressTypeEvents Events
{
get
{
if (events == null)
{
lock (typeof(AddressType))
{
if (events == null)
events = new AddressTypeEvents();
}
}
return events;
}
}
public class AddressTypeEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<AddressType, EntityEventArgs> onNew;
public event EventHandler<AddressType, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<AddressType, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((AddressType)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<AddressType, EntityEventArgs> onDelete;
public event EventHandler<AddressType, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<AddressType, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((AddressType)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<AddressType, EntityEventArgs> onSave;
public event EventHandler<AddressType, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<AddressType, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((AddressType)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnName
private static bool onNameIsRegistered = false;
private static EventHandler<AddressType, PropertyEventArgs> onName;
public static event EventHandler<AddressType, PropertyEventArgs> OnName
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onNameIsRegistered)
{
Members.Name.Events.OnChange -= onNameProxy;
Members.Name.Events.OnChange += onNameProxy;
onNameIsRegistered = true;
}
onName += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onName -= value;
if (onName == null && onNameIsRegistered)
{
Members.Name.Events.OnChange -= onNameProxy;
onNameIsRegistered = false;
}
}
}
}
private static void onNameProxy(object sender, PropertyEventArgs args)
{
EventHandler<AddressType, PropertyEventArgs> handler = onName;
if ((object)handler != null)
handler.Invoke((AddressType)sender, args);
}
#endregion
#region Onrowguid
private static bool onrowguidIsRegistered = false;
private static EventHandler<AddressType, PropertyEventArgs> onrowguid;
public static event EventHandler<AddressType, PropertyEventArgs> Onrowguid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
Members.rowguid.Events.OnChange += onrowguidProxy;
onrowguidIsRegistered = true;
}
onrowguid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onrowguid -= value;
if (onrowguid == null && onrowguidIsRegistered)
{
Members.rowguid.Events.OnChange -= onrowguidProxy;
onrowguidIsRegistered = false;
}
}
}
}
private static void onrowguidProxy(object sender, PropertyEventArgs args)
{
EventHandler<AddressType, PropertyEventArgs> handler = onrowguid;
if ((object)handler != null)
handler.Invoke((AddressType)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<AddressType, PropertyEventArgs> onModifiedDate;
public static event EventHandler<AddressType, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<AddressType, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((AddressType)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<AddressType, PropertyEventArgs> onUid;
public static event EventHandler<AddressType, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<AddressType, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((AddressType)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region IAddressTypeOriginalData
public IAddressTypeOriginalData OriginalVersion { get { return this; } }
#region Members for interface IAddressType
string IAddressTypeOriginalData.Name { get { return OriginalData.Name; } }
string IAddressTypeOriginalData.rowguid { get { return OriginalData.rowguid; } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CppSharp.AST;
namespace CppSharp.Generators
{
public enum NewLineKind
{
Never,
Always,
BeforeNextBlock,
IfNotEmpty
}
public class BlockKind
{
public const int Unknown = 0;
public const int BlockComment = 1;
public const int InlineComment = 2;
public const int Header = 3;
public const int Footer = 4;
public const int LAST = 5;
}
public class Block : ITextGenerator
{
public TextGenerator Text { get; set; }
public int Kind { get; set; }
public NewLineKind NewLineKind { get; set; }
public Block Parent { get; set; }
public List<Block> Blocks { get; set; }
public Declaration Declaration { get; set; }
private bool hasIndentChanged;
private bool isSubBlock;
public Func<bool> CheckGenerate;
public Block() : this(BlockKind.Unknown)
{
}
public Block(int kind)
{
Kind = kind;
Blocks = new List<Block>();
Text = new TextGenerator();
hasIndentChanged = false;
isSubBlock = false;
}
public void AddBlock(Block block)
{
if (Text.StringBuilder.Length != 0 || hasIndentChanged)
{
hasIndentChanged = false;
var newBlock = new Block { Text = Text.Clone(), isSubBlock = true };
Text.StringBuilder.Clear();
AddBlock(newBlock);
}
block.Parent = this;
Blocks.Add(block);
}
public IEnumerable<Block> FindBlocks(int kind)
{
foreach (var block in Blocks)
{
if (block.Kind == kind)
yield return block;
foreach (var childBlock in block.FindBlocks(kind))
yield return childBlock;
}
}
public virtual string Generate(DriverOptions options)
{
if (CheckGenerate != null && !CheckGenerate())
return "";
if (Blocks.Count == 0)
return Text.ToString();
var builder = new StringBuilder();
uint totalIndent = 0;
Block previousBlock = null;
var blockIndex = 0;
foreach (var childBlock in Blocks)
{
var childText = childBlock.Generate(options);
var nextBlock = (++blockIndex < Blocks.Count)
? Blocks[blockIndex]
: null;
var skipBlock = false;
if (nextBlock != null)
{
var nextText = nextBlock.Generate(options);
if (string.IsNullOrEmpty(nextText) &&
childBlock.NewLineKind == NewLineKind.IfNotEmpty)
skipBlock = true;
}
if (skipBlock)
continue;
if (string.IsNullOrEmpty(childText))
continue;
var lines = childText.SplitAndKeep(Environment.NewLine).ToList();
if (previousBlock != null &&
previousBlock.NewLineKind == NewLineKind.BeforeNextBlock)
builder.AppendLine();
if (childBlock.isSubBlock)
totalIndent = 0;
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line))
continue;
if (!string.IsNullOrWhiteSpace(line))
builder.Append(new string(' ', (int)totalIndent));
if (childBlock.Kind == BlockKind.BlockComment &&
!line.StartsWith(options.CommentPrefix))
{
builder.Append(options.CommentPrefix);
builder.Append(' ');
}
builder.Append(line);
if (!line.EndsWith(Environment.NewLine))
builder.AppendLine();
}
if (childBlock.NewLineKind == NewLineKind.Always)
builder.AppendLine();
totalIndent += childBlock.Text.Indent;
previousBlock = childBlock;
}
if (Text.StringBuilder.Length != 0)
builder.Append(Text.StringBuilder);
return builder.ToString();
}
public bool IsEmpty
{
get
{
if (Blocks.Any(block => !block.IsEmpty))
return false;
return string.IsNullOrEmpty(Text.ToString());
}
}
#region ITextGenerator implementation
public uint Indent { get { return Text.Indent; } }
public void Write(string msg, params object[] args)
{
Text.Write(msg, args);
}
public void WriteLine(string msg, params object[] args)
{
Text.WriteLine(msg, args);
}
public void WriteLineIndent(string msg, params object[] args)
{
Text.WriteLineIndent(msg, args);
}
public void NewLine()
{
Text.NewLine();
}
public void NewLineIfNeeded()
{
Text.NewLineIfNeeded();
}
public void NeedNewLine()
{
Text.NeedNewLine();
}
public void ResetNewLine()
{
Text.ResetNewLine();
}
public void PushIndent(uint indent = 4u)
{
hasIndentChanged = true;
Text.PushIndent(indent);
}
public void PopIndent()
{
hasIndentChanged = true;
Text.PopIndent();
}
public void WriteStartBraceIndent()
{
Text.WriteStartBraceIndent();
}
public void WriteCloseBraceIndent()
{
Text.WriteCloseBraceIndent();
}
#endregion
}
public abstract class Template : ITextGenerator
{
public Driver Driver { get; private set; }
public DriverOptions Options { get; private set; }
public List<TranslationUnit> TranslationUnits { get; private set; }
public TranslationUnit TranslationUnit { get { return TranslationUnits[0]; } }
public IDiagnosticConsumer Log
{
get { return Driver.Diagnostics; }
}
public Block RootBlock { get; private set; }
public Block ActiveBlock { get; private set; }
public abstract string FileExtension { get; }
protected Template(Driver driver, IEnumerable<TranslationUnit> units)
{
Driver = driver;
Options = driver.Options;
TranslationUnits = new List<TranslationUnit>(units);
RootBlock = new Block();
ActiveBlock = RootBlock;
}
public abstract void Process();
public string Generate()
{
return RootBlock.Generate(Options);
}
#region Block helpers
public void AddBlock(Block block)
{
ActiveBlock.AddBlock(block);
}
public void PushBlock(int kind, Declaration decl = null)
{
var block = new Block { Kind = kind, Declaration = decl };
PushBlock(block);
}
public void PushBlock(Block block)
{
block.Parent = ActiveBlock;
ActiveBlock.AddBlock(block);
ActiveBlock = block;
}
public Block PopBlock(NewLineKind newLineKind = NewLineKind.Never)
{
var block = ActiveBlock;
ActiveBlock.NewLineKind = newLineKind;
ActiveBlock = ActiveBlock.Parent;
return block;
}
public IEnumerable<Block> FindBlocks(int kind)
{
return RootBlock.FindBlocks(kind);
}
public Block FindBlock(int kind)
{
return FindBlocks(kind).SingleOrDefault();
}
#endregion
#region ITextGenerator implementation
public uint Indent { get { return ActiveBlock.Indent; } }
public void Write(string msg, params object[] args)
{
ActiveBlock.Write(msg, args);
}
public void WriteLine(string msg, params object[] args)
{
ActiveBlock.WriteLine(msg, args);
}
public void WriteLineIndent(string msg, params object[] args)
{
ActiveBlock.WriteLineIndent(msg, args);
}
public void NewLine()
{
ActiveBlock.NewLine();
}
public void NewLineIfNeeded()
{
ActiveBlock.NewLineIfNeeded();
}
public void NeedNewLine()
{
ActiveBlock.NeedNewLine();
}
public void ResetNewLine()
{
ActiveBlock.ResetNewLine();
}
public void PushIndent(uint indent = 4u)
{
ActiveBlock.PushIndent(indent);
}
public void PopIndent()
{
ActiveBlock.PopIndent();
}
public void WriteStartBraceIndent()
{
ActiveBlock.WriteStartBraceIndent();
}
public void WriteCloseBraceIndent()
{
ActiveBlock.WriteCloseBraceIndent();
}
#endregion
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//#ifndef AGG_RASTERIZER_SL_CLIP_INCLUDED
//#define AGG_RASTERIZER_SL_CLIP_INCLUDED
//#include "agg_clip_liang_barsky.h"
using poly_subpixel_scale_e = MatterHackers.Agg.agg_basics.poly_subpixel_scale_e;
namespace MatterHackers.Agg
{
//--------------------------------------------------------poly_max_coord_e
internal enum poly_max_coord_e
{
poly_max_coord = (1 << 30) - 1 //----poly_max_coord
};
public class VectorClipper
{
public RectangleInt clipBox;
private int m_x1;
private int m_y1;
private int m_f1;
private bool m_clipping;
private int mul_div(double a, double b, double c)
{
return agg_basics.iround(a * b / c);
}
private int xi(int v)
{
return v;
}
private int yi(int v)
{
return v;
}
public int upscale(double v)
{
return agg_basics.iround(v * (int)poly_subpixel_scale_e.poly_subpixel_scale);
}
public int downscale(int v)
{
return v / (int)poly_subpixel_scale_e.poly_subpixel_scale;
}
//--------------------------------------------------------------------
public VectorClipper()
{
clipBox = new RectangleInt(0, 0, 0, 0);
m_x1 = (0);
m_y1 = (0);
m_f1 = (0);
m_clipping = (false);
}
//--------------------------------------------------------------------
public void reset_clipping()
{
m_clipping = false;
}
//--------------------------------------------------------------------
public void clip_box(int x1, int y1, int x2, int y2)
{
clipBox = new RectangleInt(x1, y1, x2, y2);
clipBox.normalize();
m_clipping = true;
}
//--------------------------------------------------------------------
public void move_to(int x1, int y1)
{
m_x1 = x1;
m_y1 = y1;
if (m_clipping)
{
m_f1 = ClipLiangBarsky.clipping_flags(x1, y1, clipBox);
}
}
//------------------------------------------------------------------------
private void line_clip_y(rasterizer_cells_aa ras,
int x1, int y1,
int x2, int y2,
int f1, int f2)
{
f1 &= 10;
f2 &= 10;
if ((f1 | f2) == 0)
{
// Fully visible
ras.line(x1, y1, x2, y2);
}
else
{
if (f1 == f2)
{
// Invisible by Y
return;
}
int tx1 = x1;
int ty1 = y1;
int tx2 = x2;
int ty2 = y2;
if ((f1 & 8) != 0) // y1 < clip.y1
{
tx1 = x1 + mul_div(clipBox.Bottom - y1, x2 - x1, y2 - y1);
ty1 = clipBox.Bottom;
}
if ((f1 & 2) != 0) // y1 > clip.y2
{
tx1 = x1 + mul_div(clipBox.Top - y1, x2 - x1, y2 - y1);
ty1 = clipBox.Top;
}
if ((f2 & 8) != 0) // y2 < clip.y1
{
tx2 = x1 + mul_div(clipBox.Bottom - y1, x2 - x1, y2 - y1);
ty2 = clipBox.Bottom;
}
if ((f2 & 2) != 0) // y2 > clip.y2
{
tx2 = x1 + mul_div(clipBox.Top - y1, x2 - x1, y2 - y1);
ty2 = clipBox.Top;
}
ras.line(tx1, ty1, tx2, ty2);
}
}
//--------------------------------------------------------------------
public void line_to(rasterizer_cells_aa ras, int x2, int y2)
{
if (m_clipping)
{
int f2 = ClipLiangBarsky.clipping_flags(x2, y2, clipBox);
if ((m_f1 & 10) == (f2 & 10) && (m_f1 & 10) != 0)
{
// Invisible by Y
m_x1 = x2;
m_y1 = y2;
m_f1 = f2;
return;
}
int x1 = m_x1;
int y1 = m_y1;
int f1 = m_f1;
int y3, y4;
int f3, f4;
switch (((f1 & 5) << 1) | (f2 & 5))
{
case 0: // Visible by X
line_clip_y(ras, x1, y1, x2, y2, f1, f2);
break;
case 1: // x2 > clip.x2
y3 = y1 + mul_div(clipBox.Right - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.clipping_flags_y(y3, clipBox);
line_clip_y(ras, x1, y1, clipBox.Right, y3, f1, f3);
line_clip_y(ras, clipBox.Right, y3, clipBox.Right, y2, f3, f2);
break;
case 2: // x1 > clip.x2
y3 = y1 + mul_div(clipBox.Right - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.clipping_flags_y(y3, clipBox);
line_clip_y(ras, clipBox.Right, y1, clipBox.Right, y3, f1, f3);
line_clip_y(ras, clipBox.Right, y3, x2, y2, f3, f2);
break;
case 3: // x1 > clip.x2 && x2 > clip.x2
line_clip_y(ras, clipBox.Right, y1, clipBox.Right, y2, f1, f2);
break;
case 4: // x2 < clip.x1
y3 = y1 + mul_div(clipBox.Left - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.clipping_flags_y(y3, clipBox);
line_clip_y(ras, x1, y1, clipBox.Left, y3, f1, f3);
line_clip_y(ras, clipBox.Left, y3, clipBox.Left, y2, f3, f2);
break;
case 6: // x1 > clip.x2 && x2 < clip.x1
y3 = y1 + mul_div(clipBox.Right - x1, y2 - y1, x2 - x1);
y4 = y1 + mul_div(clipBox.Left - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.clipping_flags_y(y3, clipBox);
f4 = ClipLiangBarsky.clipping_flags_y(y4, clipBox);
line_clip_y(ras, clipBox.Right, y1, clipBox.Right, y3, f1, f3);
line_clip_y(ras, clipBox.Right, y3, clipBox.Left, y4, f3, f4);
line_clip_y(ras, clipBox.Left, y4, clipBox.Left, y2, f4, f2);
break;
case 8: // x1 < clip.x1
y3 = y1 + mul_div(clipBox.Left - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.clipping_flags_y(y3, clipBox);
line_clip_y(ras, clipBox.Left, y1, clipBox.Left, y3, f1, f3);
line_clip_y(ras, clipBox.Left, y3, x2, y2, f3, f2);
break;
case 9: // x1 < clip.x1 && x2 > clip.x2
y3 = y1 + mul_div(clipBox.Left - x1, y2 - y1, x2 - x1);
y4 = y1 + mul_div(clipBox.Right - x1, y2 - y1, x2 - x1);
f3 = ClipLiangBarsky.clipping_flags_y(y3, clipBox);
f4 = ClipLiangBarsky.clipping_flags_y(y4, clipBox);
line_clip_y(ras, clipBox.Left, y1, clipBox.Left, y3, f1, f3);
line_clip_y(ras, clipBox.Left, y3, clipBox.Right, y4, f3, f4);
line_clip_y(ras, clipBox.Right, y4, clipBox.Right, y2, f4, f2);
break;
case 12: // x1 < clip.x1 && x2 < clip.x1
line_clip_y(ras, clipBox.Left, y1, clipBox.Left, y2, f1, f2);
break;
}
m_f1 = f2;
}
else
{
ras.line(m_x1, m_y1,
x2, y2);
}
m_x1 = x2;
m_y1 = y2;
}
}
}
| |
// 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 PermuteSingle2()
{
var test = new ImmUnaryOpTest__PermuteSingle2();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__PermuteSingle2
{
private struct TestStruct
{
public Vector128<Single> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__PermuteSingle2 testClass)
{
var result = Avx.Permute(_fld, 2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data = new Single[Op1ElementCount];
private static Vector128<Single> _clsVar;
private Vector128<Single> _fld;
private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable;
static ImmUnaryOpTest__PermuteSingle2()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public ImmUnaryOpTest__PermuteSingle2()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.Permute(
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.Permute(
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.Permute(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.Permute), new Type[] { typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.Permute(
_clsVar,
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr);
var result = Avx.Permute(firstOp, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr));
var result = Avx.Permute(firstOp, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr));
var result = Avx.Permute(firstOp, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__PermuteSingle2();
var result = Avx.Permute(test._fld, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.Permute(_fld, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.Permute(test._fld, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Single[] inArray = new Single[Op1ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(firstOp[2]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[1]) != BitConverter.SingleToInt32Bits(firstOp[0]) || BitConverter.SingleToInt32Bits(result[2]) != BitConverter.SingleToInt32Bits(firstOp[0]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Permute)}<Single>(Vector128<Single><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// 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.Reflection;
using System.Diagnostics;
namespace System.Runtime.Serialization.Formatters.Binary
{
// Routines to convert between the runtime type and the type as it appears on the wire
internal static class BinaryTypeConverter
{
// From the type create the BinaryTypeEnum and typeInformation which describes the type on the wire
internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo objectInfo, string typeName, ObjectWriter objectWriter, out object typeInformation, out int assemId)
{
BinaryTypeEnum binaryTypeEnum;
assemId = 0;
typeInformation = null;
if (ReferenceEquals(type, Converter.s_typeofString))
{
binaryTypeEnum = BinaryTypeEnum.String;
}
else if (((objectInfo == null) || ((objectInfo != null) && !objectInfo._isSi)) && (ReferenceEquals(type, Converter.s_typeofObject)))
{
// If objectInfo.Si then can be a surrogate which will change the type
binaryTypeEnum = BinaryTypeEnum.Object;
}
else if (ReferenceEquals(type, Converter.s_typeofStringArray))
{
binaryTypeEnum = BinaryTypeEnum.StringArray;
}
else if (ReferenceEquals(type, Converter.s_typeofObjectArray))
{
binaryTypeEnum = BinaryTypeEnum.ObjectArray;
}
else if (Converter.IsPrimitiveArray(type, out typeInformation))
{
binaryTypeEnum = BinaryTypeEnum.PrimitiveArray;
}
else
{
InternalPrimitiveTypeE primitiveTypeEnum = objectWriter.ToCode(type);
switch (primitiveTypeEnum)
{
case InternalPrimitiveTypeE.Invalid:
string assembly = null;
if (objectInfo == null)
{
assembly = type.Assembly.FullName;
typeInformation = type.FullName;
}
else
{
assembly = objectInfo.GetAssemblyString();
typeInformation = objectInfo.GetTypeFullName();
}
if (assembly.Equals(Converter.s_urtAssemblyString))
{
binaryTypeEnum = BinaryTypeEnum.ObjectUrt;
assemId = 0;
}
else
{
binaryTypeEnum = BinaryTypeEnum.ObjectUser;
Debug.Assert(objectInfo != null, "[BinaryConverter.GetBinaryTypeInfo]objectInfo null for user object");
assemId = (int)objectInfo._assemId;
if (assemId == 0)
{
throw new SerializationException(SR.Format(SR.Serialization_AssemblyId, typeInformation));
}
}
break;
default:
binaryTypeEnum = BinaryTypeEnum.Primitive;
typeInformation = primitiveTypeEnum;
break;
}
}
return binaryTypeEnum;
}
// Used for non Si types when Parsing
internal static BinaryTypeEnum GetParserBinaryTypeInfo(Type type, out object typeInformation)
{
BinaryTypeEnum binaryTypeEnum;
typeInformation = null;
if (ReferenceEquals(type, Converter.s_typeofString))
{
binaryTypeEnum = BinaryTypeEnum.String;
}
else if (ReferenceEquals(type, Converter.s_typeofObject))
{
binaryTypeEnum = BinaryTypeEnum.Object;
}
else if (ReferenceEquals(type, Converter.s_typeofObjectArray))
{
binaryTypeEnum = BinaryTypeEnum.ObjectArray;
}
else if (ReferenceEquals(type, Converter.s_typeofStringArray))
{
binaryTypeEnum = BinaryTypeEnum.StringArray;
}
else if (Converter.IsPrimitiveArray(type, out typeInformation))
{
binaryTypeEnum = BinaryTypeEnum.PrimitiveArray;
}
else
{
InternalPrimitiveTypeE primitiveTypeEnum = Converter.ToCode(type);
switch (primitiveTypeEnum)
{
case InternalPrimitiveTypeE.Invalid:
binaryTypeEnum = type.Assembly == Converter.s_urtAssembly ?
BinaryTypeEnum.ObjectUrt :
BinaryTypeEnum.ObjectUser;
typeInformation = type.FullName;
break;
default:
binaryTypeEnum = BinaryTypeEnum.Primitive;
typeInformation = primitiveTypeEnum;
break;
}
}
return binaryTypeEnum;
}
// Writes the type information on the wire
internal static void WriteTypeInfo(BinaryTypeEnum binaryTypeEnum, object typeInformation, int assemId, BinaryFormatterWriter output)
{
switch (binaryTypeEnum)
{
case BinaryTypeEnum.Primitive:
case BinaryTypeEnum.PrimitiveArray:
Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
output.WriteByte((byte)((InternalPrimitiveTypeE)typeInformation));
break;
case BinaryTypeEnum.String:
case BinaryTypeEnum.Object:
case BinaryTypeEnum.StringArray:
case BinaryTypeEnum.ObjectArray:
break;
case BinaryTypeEnum.ObjectUrt:
Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
output.WriteString(typeInformation.ToString());
break;
case BinaryTypeEnum.ObjectUser:
Debug.Assert(typeInformation != null, "[BinaryConverter.WriteTypeInfo]typeInformation!=null");
output.WriteString(typeInformation.ToString());
output.WriteInt32(assemId);
break;
default:
throw new SerializationException(SR.Format(SR.Serialization_TypeWrite, binaryTypeEnum.ToString()));
}
}
// Reads the type information from the wire
internal static object ReadTypeInfo(BinaryTypeEnum binaryTypeEnum, BinaryParser input, out int assemId)
{
object var = null;
int readAssemId = 0;
switch (binaryTypeEnum)
{
case BinaryTypeEnum.Primitive:
case BinaryTypeEnum.PrimitiveArray:
var = (InternalPrimitiveTypeE)input.ReadByte();
break;
case BinaryTypeEnum.String:
case BinaryTypeEnum.Object:
case BinaryTypeEnum.StringArray:
case BinaryTypeEnum.ObjectArray:
break;
case BinaryTypeEnum.ObjectUrt:
var = input.ReadString();
break;
case BinaryTypeEnum.ObjectUser:
var = input.ReadString();
readAssemId = input.ReadInt32();
break;
default:
throw new SerializationException(SR.Format(SR.Serialization_TypeRead, binaryTypeEnum.ToString()));
}
assemId = readAssemId;
return var;
}
// Given the wire type information, returns the actual type and additional information
internal static void TypeFromInfo(BinaryTypeEnum binaryTypeEnum,
object typeInformation,
ObjectReader objectReader,
BinaryAssemblyInfo assemblyInfo,
out InternalPrimitiveTypeE primitiveTypeEnum,
out string typeString,
out Type type,
out bool isVariant)
{
isVariant = false;
primitiveTypeEnum = InternalPrimitiveTypeE.Invalid;
typeString = null;
type = null;
switch (binaryTypeEnum)
{
case BinaryTypeEnum.Primitive:
primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation;
typeString = Converter.ToComType(primitiveTypeEnum);
type = Converter.ToType(primitiveTypeEnum);
break;
case BinaryTypeEnum.String:
type = Converter.s_typeofString;
break;
case BinaryTypeEnum.Object:
type = Converter.s_typeofObject;
isVariant = true;
break;
case BinaryTypeEnum.ObjectArray:
type = Converter.s_typeofObjectArray;
break;
case BinaryTypeEnum.StringArray:
type = Converter.s_typeofStringArray;
break;
case BinaryTypeEnum.PrimitiveArray:
primitiveTypeEnum = (InternalPrimitiveTypeE)typeInformation;
type = Converter.ToArrayType(primitiveTypeEnum);
break;
case BinaryTypeEnum.ObjectUser:
case BinaryTypeEnum.ObjectUrt:
if (typeInformation != null)
{
typeString = typeInformation.ToString();
type = objectReader.GetType(assemblyInfo, typeString);
if (ReferenceEquals(type, Converter.s_typeofObject))
{
isVariant = true;
}
}
break;
default:
throw new SerializationException(SR.Format(SR.Serialization_TypeRead, binaryTypeEnum.ToString()));
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//#define ENABLE_TRACING
//#define ENABLE_TRACING_VERBOSE
//#define ENABLE_CACHE
//#define ENABLE_MMU
//#define ENABLE_STACKEDMEMORY
//#define ENABLE_ABORTHANDLERS
namespace Microsoft.iMote2Loader
{
using System;
using System.Collections.Generic;
using RT = Microsoft.Zelig.Runtime;
using PXA27x = Microsoft.DeviceModels.Chipset.PXA27x;
using ARMv4 = Microsoft.Zelig.Runtime.TargetPlatform.ARMv4;
//
// Override stock bootstrap code, to avoid including most of the code.
//
[RT.ExtendClass(typeof(RT.Bootstrap))]
public static class BootstrapImpl
{
[RT.NoInline]
[RT.NoReturn]
private static void Initialization()
{
Processor.Instance.InitializeProcessor();
#if ENABLE_CACHE
ARMv4.Coprocessor15.InvalidateICache();
ARMv4.Coprocessor15.InvalidateDCache();
//
// Enable ICache
//
ARMv4.Coprocessor15.SetControlRegisterBits( ARMv4.Coprocessor15.c_ControlRegister__ICache );
#endif
PXA27x.ClockManager.Instance.InitializeClocks();
#if ENABLE_STACKEDMEMORY
PXA27x.MemoryController.Instance.InitializeStackedSDRAM();
PXA27x.MemoryController.Instance.InitializeStackedFLASH();
#endif
#if ENABLE_MMU
ConfigureMMU();
#endif
RT.Configuration.ExecuteApplication();
}
#if ENABLE_MMU
private static void ConfigureMMU()
{
ARMv4.MMUv4.ClearTLB();
const uint baseFlash = 0x80000000u;
const uint sizeFlash = 0x2000000;
ARMv4.MMUv4.AddUncacheableSection( 0, 0 + 256 * 1024, 0x5C000000 );
ARMv4.MMUv4.AddUncacheableSection( 0x5C000000, 0x5C000000 + 256 * 1024, 0x5C000000 );
ARMv4.MMUv4.AddUncacheableSection( baseFlash, baseFlash + sizeFlash, 0 );
ARMv4.MMUv4.EnableTLB();
}
#endif
#if ENABLE_ABORTHANDLERS
static uint fault_DFSR;
static uint fault_IFSR;
static uint fault_FAR;
[RT.NoInline]
[RT.NoReturn()]
[RT.HardwareExceptionHandler(RT.HardwareException.UndefinedInstruction)]
[RT.MemoryUsage(RT.MemoryUsage.Bootstrap)]
static void UndefinedInstruction()
{
fault_DFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 0 );
fault_IFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 1 );
fault_FAR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 6, 0, 0 );
Processor.Instance.Breakpoint();
}
[RT.NoInline]
[RT.NoReturn()]
[RT.HardwareExceptionHandler(RT.HardwareException.PrefetchAbort)]
[RT.MemoryUsage(RT.MemoryUsage.Bootstrap)]
static void PrefetchAbort()
{
fault_DFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 0 );
fault_IFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 1 );
fault_FAR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 6, 0, 0 );
Processor.Instance.Breakpoint();
}
[RT.NoInline]
[RT.NoReturn()]
[RT.HardwareExceptionHandler(RT.HardwareException.DataAbort)]
[RT.MemoryUsage(RT.MemoryUsage.Bootstrap)]
static void DataAbort()
{
fault_DFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 0 );
fault_IFSR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 5, 0, 1 );
fault_FAR = ARMv4.ProcessorARMv4.MoveFromCoprocessor( 15, 0, 6, 0, 0 );
Processor.Instance.Breakpoint();
}
#endif
}
[RT.ExtendClass(typeof(RT.TypeSystemManager),NoConstructors=true)]
public class TypeSystemManagerImpl
{
public void DeliverException( Exception obj )
{
}
}
class Loader
{
const uint cmd_Signature = 0xDEADC000;
const uint cmd_Mask = 0xFFFFFF00;
const byte cmd_Hello = 0x01;
const byte cmd_EnterCFI = 0x02; // Arg: Address
const byte cmd_ExitCFI = 0x03; // Arg: Address
const byte cmd_ReadMemory8 = 0x04; // Arg: Address, Size => <Size> values
const byte cmd_ReadMemory16 = 0x05; // Arg: Address, Size => <Size> values
const byte cmd_ReadMemory32 = 0x06; // Arg: Address, Size => <Size> values
const byte cmd_ChecksumMemory = 0x07; // Arg: Address, Size => CRC value, AND of all memory
const byte cmd_EraseSector = 0x08; // Arg: Address => Status value
const byte cmd_ProgramMemory = 0x09; // Arg: Address, Size, [32bits words] => Status value
const byte cmd_EndOfStream = 0xFF;
const uint FlashSize = 32 * 1024 * 1024;
const uint FlashMask = ~(FlashSize - 1);
const uint baseIRAM = 0x5C000000;
const uint blockSize = 64 * 1024;
const uint baseHostToDevice = baseIRAM + blockSize * 1;
const uint baseDeviceToHost = baseIRAM + blockSize * 2;
//--//
static unsafe uint* s_ptrInput;
static unsafe uint* s_ptrOutput;
//--//
[RT.DisableNullChecks()]
static unsafe void EnterCFI( ushort* baseAddress )
{
PXA27x.StackedFlashChip.EnterCFI( baseAddress );
}
[RT.DisableNullChecks()]
static unsafe void ExitCFI( ushort* baseAddress )
{
PXA27x.StackedFlashChip.ExitCFI( baseAddress );
}
[RT.DisableNullChecks()]
static unsafe void EraseSector( ushort* sectorStart )
{
PXA27x.StackedFlashChip.UnlockFlashSector( sectorStart );
PXA27x.StackedFlashChip.EraseFlashSector ( sectorStart );
}
[RT.DisableNullChecks()]
static unsafe void WriteWord( ushort* address ,
ushort value )
{
PXA27x.StackedFlashChip.UnlockFlashSector( address );
PXA27x.StackedFlashChip.ProgramFlashWord ( address, value );
}
//--//
static unsafe void RewindAndWait( bool fSetMarker )
{
s_ptrInput = (uint*)baseHostToDevice;
s_ptrOutput = (uint*)baseDeviceToHost;
if(fSetMarker)
{
*s_ptrOutput = cmd_Signature | cmd_EndOfStream;
}
System.Diagnostics.Debugger.Break();
}
static unsafe uint ReadInput()
{
return *s_ptrInput++;
}
static unsafe void WriteOutput( uint val )
{
*s_ptrOutput++ = val;
}
//--//
[System.Diagnostics.Conditional( "ENABLE_TRACING" )]
static void DebugInitialize()
{
PXA27x.UART.Instance.Configure( PXA27x.UART.Id.STUART, 115200 );
}
[System.Diagnostics.Conditional( "ENABLE_TRACING" )]
static void DebugPrint( string text )
{
PXA27x.UART.Instance.Ports[(int)PXA27x.UART.Id.STUART].DEBUG_WriteLine( text );
}
[System.Diagnostics.Conditional( "ENABLE_TRACING" )]
static void DebugPrint( string text ,
uint value )
{
PXA27x.UART.Instance.Ports[(int)PXA27x.UART.Id.STUART].DEBUG_WriteLine( text, value );
}
[System.Diagnostics.Conditional( "ENABLE_TRACING_VERBOSE" )]
static void DebugPrintVerbose( string text ,
uint value )
{
DebugPrint( text, value );
}
[System.Diagnostics.Conditional( "ENABLE_TRACING" )]
static void DebugChar( char c )
{
PXA27x.UART.Instance.Ports[(int)PXA27x.UART.Id.STUART].DEBUG_Write( c );
}
//--//
[RT.DisableNullChecks( ApplyRecursively=true )]
static unsafe void Main()
{
//// var clockControl = PXA27x.ClockManager.Instance;
////
//// clockControl.CKEN.EnOsTimer = true;
////
//// //--//
////
//// var timer = PXA27x.OSTimers.Instance;
////
//// uint* ptr2 = (uint*)0xA0000000;
////
//// uint last = timer.ReadCounter( 0 );
//// uint last2 = timer.ReadCounter( 0 );
////
//// for(uint i = 0; i < 1024; i++)
//// {
//// uint sum = 0;
////
//// for(int j = 0; j < 1024 * 16; j++)
//// {
//// sum += last;
//// }
////
//// uint val = timer.ReadCounter( 0 );
//// ptr2[i] = val - last2;
//// last2 = val;
////
//// last = sum;
//// }
DebugInitialize();
DebugPrint( "Hello World!\r\n" );
RewindAndWait( true );
while(true)
{
DebugPrint( "Waiting..." );
uint cmd = ReadInput();
DebugPrint( "Got data: ", cmd );
if((cmd & cmd_Mask) == cmd_Signature)
{
DebugPrint( "Got command: ", cmd );
switch((byte)cmd)
{
case cmd_EndOfStream:
WriteOutput( cmd );
RewindAndWait( false );
break;
case cmd_Hello:
WriteOutput( cmd );
break;
case cmd_EnterCFI:
EnterCFI( (ushort*)ReadInput() );
WriteOutput( cmd );
break;
case cmd_ExitCFI:
ExitCFI( (ushort*)ReadInput() );
WriteOutput( cmd );
break;
case cmd_ReadMemory8:
{
byte* ptr = (byte*)ReadInput();
uint len = ReadInput();
WriteOutput( cmd );
while(len > 0)
{
WriteOutput( *ptr++ );
len--;
}
}
break;
case cmd_ReadMemory16:
{
ushort* ptr = (ushort*)ReadInput();
uint len = ReadInput();
DebugPrint( "Address: ", (uint)ptr );
DebugPrint( "Length: ", len );
WriteOutput( cmd );
while(len > 0)
{
DebugPrint( "Data: ", (uint)*ptr );
WriteOutput( *ptr++ );
len--;
}
DebugPrint( "Done." );
}
break;
case cmd_ReadMemory32:
{
uint* ptr = (uint*)ReadInput();
uint len = ReadInput();
DebugPrint( "Address: ", (uint)ptr );
DebugPrint( "Length: ", len );
WriteOutput( cmd );
while(len > 0)
{
DebugPrint( "Data: ", (uint)*ptr );
WriteOutput( *ptr++ );
len--;
}
DebugPrint( "Done." );
}
break;
case cmd_ChecksumMemory:
{
uint* ptr = (uint*)ReadInput();
uint len = ReadInput();
uint sum = 0;
uint and = 0xFFFFFFFF;
WriteOutput( cmd );
DebugPrint( "Address: ", (uint)ptr );
DebugPrint( "Length: ", len );
while(len > 0)
{
uint val = *ptr;
sum = ((sum & 1) << 31) | (sum >> 1);
sum += val;
and &= val;
ptr++;
len--;
}
DebugPrint( "Sum: ", sum );
DebugPrint( "And: ", and );
WriteOutput( sum );
WriteOutput( and );
}
break;
case cmd_EraseSector:
EraseSector( (ushort*)ReadInput() );
WriteOutput( cmd );
WriteOutput( 0 );
break;
case cmd_ProgramMemory:
{
ushort* ptr = (ushort*)ReadInput();
uint len = ReadInput();
WriteOutput( cmd );
while(len > 0)
{
if(len >= 16)
{
PXA27x.StackedFlashChip.UnlockFlashSector ( ptr );
PXA27x.StackedFlashChip.StartBufferedProgramFlashWord( ptr, 32 );
for(int i = 0; i < 16; i++)
{
uint val = ReadInput();
PXA27x.StackedFlashChip.AddBufferedProgramFlashWord( ptr++, (ushort) val );
PXA27x.StackedFlashChip.AddBufferedProgramFlashWord( ptr++, (ushort)(val >> 16) );
DebugPrintVerbose( "Program Data: ", val );
}
PXA27x.StackedFlashChip.ConfirmProgramFlashWord( ptr - 32 );
len -= 16;
}
else
{
uint val = ReadInput();
WriteWord( ptr++, (ushort) val );
WriteWord( ptr++, (ushort)(val >> 16) );
len--;
}
}
WriteOutput( 0 );
}
break;
}
}
}
}
}
}
| |
/*
* 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.Core.Impl.Cache
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache.Expiry;
using Apache.Ignite.Core.Impl.Cache.Query;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Unmanaged;
/// <summary>
/// Native cache wrapper.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
internal class CacheImpl<TK, TV> : PlatformTarget, ICache<TK, TV>, ICacheInternal, ICacheLockInternal
{
/** Ignite instance. */
private readonly Ignite _ignite;
/** Flag: skip store. */
private readonly bool _flagSkipStore;
/** Flag: keep binary. */
private readonly bool _flagKeepBinary;
/** Flag: no-retries.*/
private readonly bool _flagNoRetries;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="flagSkipStore">Skip store flag.</param>
/// <param name="flagKeepBinary">Keep binary flag.</param>
/// <param name="flagNoRetries">No-retries mode flag.</param>
public CacheImpl(Ignite grid, IUnmanagedTarget target, Marshaller marsh,
bool flagSkipStore, bool flagKeepBinary, bool flagNoRetries) : base(target, marsh)
{
_ignite = grid;
_flagSkipStore = flagSkipStore;
_flagKeepBinary = flagKeepBinary;
_flagNoRetries = flagNoRetries;
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get { return _ignite; }
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task DoOutOpAsync<T1>(CacheOp op, T1 val1)
{
return DoOutOpAsync<object, T1>((int) op, val1);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task<TR> DoOutOpAsync<T1, TR>(CacheOp op, T1 val1)
{
return DoOutOpAsync<T1, TR>((int) op, val1);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task DoOutOpAsync<T1, T2>(CacheOp op, T1 val1, T2 val2)
{
return DoOutOpAsync<T1, T2, object>((int) op, val1, val2);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task<TR> DoOutOpAsync<T1, T2, TR>(CacheOp op, T1 val1, T2 val2)
{
return DoOutOpAsync<T1, T2, TR>((int) op, val1, val2);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task DoOutOpAsync(CacheOp op, Action<BinaryWriter> writeAction = null)
{
return DoOutOpAsync<object>(op, writeAction);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task<T> DoOutOpAsync<T>(CacheOp op, Action<BinaryWriter> writeAction = null,
Func<BinaryReader, T> convertFunc = null)
{
return DoOutOpAsync((int)op, writeAction, IsKeepBinary, convertFunc);
}
/** <inheritDoc /> */
public string Name
{
get { return DoInOp<string>((int)CacheOp.GetName); }
}
/** <inheritDoc /> */
public CacheConfiguration GetConfiguration()
{
return DoInOp((int) CacheOp.GetConfig, stream => new CacheConfiguration(Marshaller.StartUnmarshal(stream)));
}
/** <inheritDoc /> */
public bool IsEmpty()
{
return GetSize() == 0;
}
/** <inheritDoc /> */
public ICache<TK, TV> WithSkipStore()
{
if (_flagSkipStore)
return this;
return new CacheImpl<TK, TV>(_ignite, DoOutOpObject((int) CacheOp.WithSkipStore), Marshaller,
true, _flagKeepBinary, true);
}
/// <summary>
/// Skip store flag getter.
/// </summary>
internal bool IsSkipStore { get { return _flagSkipStore; } }
/** <inheritDoc /> */
public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_flagKeepBinary)
{
var result = this as ICache<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of binary cache. WithKeepBinary has been called on an instance of " +
"binary cache with incompatible generic arguments.");
return result;
}
return new CacheImpl<TK1, TV1>(_ignite, DoOutOpObject((int) CacheOp.WithKeepBinary), Marshaller,
_flagSkipStore, true, _flagNoRetries);
}
/** <inheritDoc /> */
public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
IgniteArgumentCheck.NotNull(plc, "plc");
var cache0 = DoOutOpObject((int)CacheOp.WithExpiryPolicy, w => ExpiryPolicySerializer.WritePolicy(w, plc));
return new CacheImpl<TK, TV>(_ignite, cache0, Marshaller, _flagSkipStore, _flagKeepBinary, _flagNoRetries);
}
/** <inheritDoc /> */
public bool IsKeepBinary
{
get { return _flagKeepBinary; }
}
/** <inheritDoc /> */
public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
DoOutInOpX((int) CacheOp.LoadCache, writer => WriteLoadCacheData(writer, p, args), ReadException);
}
/** <inheritDoc /> */
public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return DoOutOpAsync(CacheOp.LoadCacheAsync, writer => WriteLoadCacheData(writer, p, args));
}
/** <inheritDoc /> */
public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
DoOutInOpX((int) CacheOp.LocLoadCache, writer => WriteLoadCacheData(writer, p, args), ReadException);
}
/** <inheritDoc /> */
public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return DoOutOpAsync(CacheOp.LocLoadCacheAsync, writer => WriteLoadCacheData(writer, p, args));
}
/// <summary>
/// Writes the load cache data to the writer.
/// </summary>
private void WriteLoadCacheData(IBinaryRawWriter writer, ICacheEntryFilter<TK, TV> p, object[] args)
{
if (p != null)
{
var p0 = new CacheEntryFilterHolder(p, (k, v) => p.Invoke(new CacheEntry<TK, TV>((TK) k, (TV) v)),
Marshaller, IsKeepBinary);
writer.WriteObject(p0);
}
else
writer.WriteObject<CacheEntryFilterHolder>(null);
writer.WriteArray(args);
}
/** <inheritDoc /> */
public void LoadAll(IEnumerable<TK> keys, bool replaceExistingValues)
{
LoadAllAsync(keys, replaceExistingValues).Wait();
}
/** <inheritDoc /> */
public Task LoadAllAsync(IEnumerable<TK> keys, bool replaceExistingValues)
{
return DoOutOpAsync(CacheOp.LoadAll, writer =>
{
writer.WriteBoolean(replaceExistingValues);
WriteEnumerable(writer, keys);
});
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(CacheOp.ContainsKey, key);
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync<TK, bool>(CacheOp.ContainsKeyAsync, key);
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOp(CacheOp.ContainsKeys, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync<bool>(CacheOp.ContainsKeysAsync, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public TV LocalPeek(TK key, params CachePeekMode[] modes)
{
IgniteArgumentCheck.NotNull(key, "key");
TV res;
if (TryLocalPeek(key, out res))
return res;
throw GetKeyNotFoundException();
}
/** <inheritDoc /> */
public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes)
{
IgniteArgumentCheck.NotNull(key, "key");
var res = DoOutInOpX((int)CacheOp.Peek,
w =>
{
w.Write(key);
w.WriteInt(EncodePeekModes(modes));
},
(s, r) => r == True ? new CacheResult<TV>(Unmarshal<TV>(s)) : new CacheResult<TV>(),
ReadException);
value = res.Success ? res.Value : default(TV);
return res.Success;
}
/** <inheritDoc /> */
public TV this[TK key]
{
get
{
return Get(key);
}
set
{
Put(key, value);
}
}
/** <inheritDoc /> */
public TV Get(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpX((int) CacheOp.Get,
w => w.Write(key),
(stream, res) =>
{
if (res != True)
throw GetKeyNotFoundException();
return Unmarshal<TV>(stream);
}, ReadException);
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader =>
{
if (reader != null)
return reader.ReadObject<TV>();
throw GetKeyNotFoundException();
});
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
IgniteArgumentCheck.NotNull(key, "key");
var res = DoOutInOpNullable(CacheOp.Get, key);
value = res.Value;
return res.Success;
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader => GetCacheResult(reader));
}
/** <inheritDoc /> */
public IDictionary<TK, TV> GetAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpX((int) CacheOp.GetAll,
writer => WriteEnumerable(writer, keys),
(s, r) => r == True ? ReadGetAllDictionary(Marshaller.StartUnmarshal(s, _flagKeepBinary)) : null,
ReadException);
}
/** <inheritDoc /> */
public Task<IDictionary<TK, TV>> GetAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(CacheOp.GetAllAsync, w => WriteEnumerable(w, keys), r => ReadGetAllDictionary(r));
}
/** <inheritdoc /> */
public void Put(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
DoOutOp(CacheOp.Put, key, val);
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAsync(CacheOp.PutAsync, key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpNullable(CacheOp.GetAndPut, key, val);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAsync(CacheOp.GetAndPutAsync, w =>
{
w.WriteObject(key);
w.WriteObject(val);
}, r => GetCacheResult(r));
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpNullable(CacheOp.GetAndReplace, key, val);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAsync(CacheOp.GetAndReplaceAsync, w =>
{
w.WriteObject(key);
w.WriteObject(val);
}, r => GetCacheResult(r));
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpNullable(CacheOp.GetAndRemove, key);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.GetAndRemoveAsync, w => w.WriteObject(key), r => GetCacheResult(r));
}
/** <inheritdoc /> */
public bool PutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOp(CacheOp.PutIfAbsent, key, val);
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAsync<TK, TV, bool>(CacheOp.PutIfAbsentAsync, key, val);
}
/** <inheritdoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpNullable(CacheOp.GetAndPutIfAbsent, key, val);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAsync(CacheOp.GetAndPutIfAbsentAsync, w =>
{
w.WriteObject(key);
w.WriteObject(val);
}, r => GetCacheResult(r));
}
/** <inheritdoc /> */
public bool Replace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOp(CacheOp.Replace2, key, val);
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAsync<TK, TV, bool>(CacheOp.Replace2Async, key, val);
}
/** <inheritdoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
return DoOutOp(CacheOp.Replace3, key, oldVal, newVal);
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
return DoOutOpAsync<bool>(CacheOp.Replace3Async, w =>
{
w.WriteObject(key);
w.WriteObject(oldVal);
w.WriteObject(newVal);
});
}
/** <inheritdoc /> */
public void PutAll(IDictionary<TK, TV> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
DoOutOp(CacheOp.PutAll, writer => WriteDictionary(writer, vals));
}
/** <inheritDoc /> */
public Task PutAllAsync(IDictionary<TK, TV> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
return DoOutOpAsync(CacheOp.PutAllAsync, writer => WriteDictionary(writer, vals));
}
/** <inheritdoc /> */
public void LocalEvict(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.LocEvict, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public void Clear()
{
DoOutInOp((int) CacheOp.ClearCache);
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return DoOutOpAsync(CacheOp.ClearCacheAsync);
}
/** <inheritdoc /> */
public void Clear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOp(CacheOp.Clear, key);
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.ClearAsync, key);
}
/** <inheritdoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.ClearAll, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(CacheOp.ClearAllAsync, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public void LocalClear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOp(CacheOp.LocalClear, key);
}
/** <inheritdoc /> */
public void LocalClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.LocalClearAll, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public bool Remove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(CacheOp.RemoveObj, key);
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync<TK, bool>(CacheOp.RemoveObjAsync, key);
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOp(CacheOp.RemoveBool, key, val);
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAsync<TK, TV, bool>(CacheOp.RemoveBoolAsync, key, val);
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.RemoveAll, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(CacheOp.RemoveAllAsync, writer => WriteEnumerable(writer, keys));
}
/** <inheritDoc /> */
public void RemoveAll()
{
DoOutInOp((int) CacheOp.RemoveAll2);
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
return DoOutOpAsync(CacheOp.RemoveAll2Async);
}
/** <inheritDoc /> */
public int GetLocalSize(params CachePeekMode[] modes)
{
return Size0(true, modes);
}
/** <inheritDoc /> */
public int GetSize(params CachePeekMode[] modes)
{
return Size0(false, modes);
}
/** <inheritDoc /> */
public Task<int> GetSizeAsync(params CachePeekMode[] modes)
{
var modes0 = EncodePeekModes(modes);
return DoOutOpAsync<int>(CacheOp.SizeAsync, w => w.WriteInt(modes0));
}
/// <summary>
/// Internal size routine.
/// </summary>
/// <param name="loc">Local flag.</param>
/// <param name="modes">peek modes</param>
/// <returns>Size.</returns>
private int Size0(bool loc, params CachePeekMode[] modes)
{
var modes0 = EncodePeekModes(modes);
var op = loc ? CacheOp.SizeLoc : CacheOp.Size;
return (int) DoOutInOp((int) op, modes0);
}
/** <inheritDoc /> */
public void LocalPromote(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.LocPromote, writer => WriteEnumerable(writer, keys));
}
/** <inheritdoc /> */
public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(processor, "processor");
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutInOpX((int) CacheOp.Invoke,
writer =>
{
writer.Write(key);
writer.Write(holder);
},
(input, res) => res == True ? Unmarshal<TRes>(input) : default(TRes),
ReadException);
}
/** <inheritDoc /> */
public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(processor, "processor");
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutOpAsync(CacheOp.InvokeAsync, writer =>
{
writer.Write(key);
writer.Write(holder);
},
r =>
{
if (r == null)
return default(TRes);
var hasError = r.ReadBoolean();
if (hasError)
throw ReadException(r);
return r.ReadObject<TRes>();
});
}
/** <inheritdoc /> */
public IDictionary<TK, ICacheEntryProcessorResult<TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(keys, "keys");
IgniteArgumentCheck.NotNull(processor, "processor");
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutInOpX((int) CacheOp.InvokeAll,
writer =>
{
WriteEnumerable(writer, keys);
writer.Write(holder);
},
(input, res) => res == True ? ReadInvokeAllResults<TRes>(Marshaller.StartUnmarshal(input, IsKeepBinary)): null, ReadException);
}
/** <inheritDoc /> */
public Task<IDictionary<TK, ICacheEntryProcessorResult<TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(keys, "keys");
IgniteArgumentCheck.NotNull(processor, "processor");
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutOpAsync(CacheOp.InvokeAllAsync,
writer =>
{
WriteEnumerable(writer, keys);
writer.Write(holder);
},
input => ReadInvokeAllResults<TRes>(input));
}
/** <inheritDoc /> */
public T DoOutInOpExtension<T>(int extensionId, int opCode, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, T> readFunc)
{
return DoOutInOpX((int) CacheOp.Extension, writer =>
{
writer.WriteInt(extensionId);
writer.WriteInt(opCode);
writeAction(writer);
},
(input, res) => res == True
? readFunc(Marshaller.StartUnmarshal(input))
: default(T), ReadException);
}
/** <inheritdoc /> */
public ICacheLock Lock(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpX((int) CacheOp.Lock, w => w.Write(key),
(stream, res) => new CacheLock(stream.ReadInt(), this), ReadException);
}
/** <inheritdoc /> */
public ICacheLock LockAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpX((int) CacheOp.LockAll, w => WriteEnumerable(w, keys),
(stream, res) => new CacheLock(stream.ReadInt(), this), ReadException);
}
/** <inheritdoc /> */
public bool IsLocalLocked(TK key, bool byCurrentThread)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(CacheOp.IsLocalLocked, writer =>
{
writer.Write(key);
writer.WriteBoolean(byCurrentThread);
});
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics()
{
return DoInOp((int) CacheOp.GlobalMetrics, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return new CacheMetricsImpl(reader);
});
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics(IClusterGroup clusterGroup)
{
IgniteArgumentCheck.NotNull(clusterGroup, "clusterGroup");
var prj = clusterGroup as ClusterGroupImpl;
if (prj == null)
throw new ArgumentException("Unexpected IClusterGroup implementation: " + clusterGroup.GetType());
return prj.GetCacheMetrics(Name);
}
/** <inheritDoc /> */
public ICacheMetrics GetLocalMetrics()
{
return DoInOp((int) CacheOp.LocalMetrics, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return new CacheMetricsImpl(reader);
});
}
/** <inheritDoc /> */
public Task Rebalance()
{
return DoOutOpAsync(CacheOp.Rebalance);
}
/** <inheritDoc /> */
public ICache<TK, TV> WithNoRetries()
{
if (_flagNoRetries)
return this;
return new CacheImpl<TK, TV>(_ignite, DoOutOpObject((int) CacheOp.WithNoRetries), Marshaller,
_flagSkipStore, _flagKeepBinary, true);
}
#region Queries
/** <inheritDoc /> */
public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry)
{
return QueryFields(qry, ReadFieldsArrayList);
}
/// <summary>
/// Reads the fields array list.
/// </summary>
private static IList ReadFieldsArrayList(IBinaryRawReader reader, int count)
{
IList res = new ArrayList(count);
for (var i = 0; i < count; i++)
res.Add(reader.ReadObject<object>());
return res;
}
/** <inheritDoc /> */
public IQueryCursor<T> QueryFields<T>(SqlFieldsQuery qry, Func<IBinaryRawReader, int, T> readerFunc)
{
IgniteArgumentCheck.NotNull(qry, "qry");
IgniteArgumentCheck.NotNull(readerFunc, "readerFunc");
if (string.IsNullOrEmpty(qry.Sql))
throw new ArgumentException("Sql cannot be null or empty");
var cursor = DoOutOpObject((int) CacheOp.QrySqlFields, writer =>
{
writer.WriteBoolean(qry.Local);
writer.WriteString(qry.Sql);
writer.WriteInt(qry.PageSize);
WriteQueryArgs(writer, qry.Arguments);
writer.WriteBoolean(qry.EnableDistributedJoins);
writer.WriteBoolean(qry.EnforceJoinOrder);
});
return new FieldsQueryCursor<T>(cursor, Marshaller, _flagKeepBinary, readerFunc);
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
var cursor = DoOutOpObject((int) qry.OpId, writer => qry.Write(writer, IsKeepBinary));
return new QueryCursor<TK, TV>(cursor, Marshaller, _flagKeepBinary);
}
/// <summary>
/// Write query arguments.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="args">Arguments.</param>
private static void WriteQueryArgs(BinaryWriter writer, object[] args)
{
if (args == null)
writer.WriteInt(0);
else
{
writer.WriteInt(args.Length);
foreach (var arg in args)
{
// Write DateTime as TimeStamp always, otherwise it does not make sense
// Wrapped DateTime comparison does not work in SQL
var dt = arg as DateTime?; // Works with DateTime also
if (dt != null)
writer.WriteTimestamp(dt);
else
writer.WriteObject(arg);
}
}
}
/** <inheritdoc /> */
public IContinuousQueryHandle QueryContinuous(ContinuousQuery<TK, TV> qry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
return QueryContinuousImpl(qry, null);
}
/** <inheritdoc /> */
public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
IgniteArgumentCheck.NotNull(initialQry, "initialQry");
return QueryContinuousImpl(qry, initialQry);
}
/// <summary>
/// QueryContinuous implementation.
/// </summary>
private IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuousImpl(ContinuousQuery<TK, TV> qry,
QueryBase initialQry)
{
qry.Validate();
return new ContinuousQueryHandleImpl<TK, TV>(qry, Marshaller, _flagKeepBinary,
writeAction => DoOutOpObject((int) CacheOp.QryContinuous, writeAction), initialQry);
}
#endregion
#region Enumerable support
/** <inheritdoc /> */
public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(CachePeekMode[] peekModes)
{
return new CacheEnumerable<TK, TV>(this, EncodePeekModes(peekModes));
}
/** <inheritdoc /> */
public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator()
{
return new CacheEnumeratorProxy<TK, TV>(this, false, 0);
}
/** <inheritdoc /> */
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Create real cache enumerator.
/// </summary>
/// <param name="loc">Local flag.</param>
/// <param name="peekModes">Peek modes for local enumerator.</param>
/// <returns>Cache enumerator.</returns>
internal CacheEnumerator<TK, TV> CreateEnumerator(bool loc, int peekModes)
{
if (loc)
{
var target = DoOutOpObject((int) CacheOp.LocIterator, w => w.WriteInt(peekModes));
return new CacheEnumerator<TK, TV>(target, Marshaller, _flagKeepBinary);
}
return new CacheEnumerator<TK, TV>(DoOutOpObject((int) CacheOp.Iterator), Marshaller, _flagKeepBinary);
}
#endregion
/** <inheritDoc /> */
protected override T Unmarshal<T>(IBinaryStream stream)
{
return Marshaller.Unmarshal<T>(stream, _flagKeepBinary);
}
/// <summary>
/// Encodes the peek modes into a single int value.
/// </summary>
private static int EncodePeekModes(CachePeekMode[] modes)
{
int modesEncoded = 0;
if (modes != null)
{
foreach (var mode in modes)
modesEncoded |= (int) mode;
}
return modesEncoded;
}
/// <summary>
/// Reads results of InvokeAll operation.
/// </summary>
/// <typeparam name="T">The type of the result.</typeparam>
/// <param name="reader">Stream.</param>
/// <returns>Results of InvokeAll operation.</returns>
private IDictionary<TK, ICacheEntryProcessorResult<T>> ReadInvokeAllResults<T>(BinaryReader reader)
{
var count = reader.ReadInt();
if (count == -1)
return null;
var results = new Dictionary<TK, ICacheEntryProcessorResult<T>>(count);
for (var i = 0; i < count; i++)
{
var key = reader.ReadObject<TK>();
var hasError = reader.ReadBoolean();
results[key] = hasError
? new CacheEntryProcessorResult<T>(ReadException(reader))
: new CacheEntryProcessorResult<T>(reader.ReadObject<T>());
}
return results;
}
/// <summary>
/// Reads the exception.
/// </summary>
private Exception ReadException(IBinaryStream stream)
{
return ReadException(Marshaller.StartUnmarshal(stream));
}
/// <summary>
/// Reads the exception, either in binary wrapper form, or as a pair of strings.
/// </summary>
/// <param name="reader">The stream.</param>
/// <returns>Exception.</returns>
private Exception ReadException(BinaryReader reader)
{
var item = reader.ReadObject<object>();
var clsName = item as string;
if (clsName == null)
return new CacheEntryProcessorException((Exception) item);
var msg = reader.ReadObject<string>();
var trace = reader.ReadObject<string>();
var inner = reader.ReadBoolean() ? reader.ReadObject<Exception>() : null;
return ExceptionUtils.GetException(_ignite, clsName, msg, trace, reader, inner);
}
/// <summary>
/// Read dictionary returned by GET_ALL operation.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>Dictionary.</returns>
private static IDictionary<TK, TV> ReadGetAllDictionary(BinaryReader reader)
{
if (reader == null)
return null;
IBinaryStream stream = reader.Stream;
if (stream.ReadBool())
{
int size = stream.ReadInt();
IDictionary<TK, TV> res = new Dictionary<TK, TV>(size);
for (int i = 0; i < size; i++)
{
TK key = reader.ReadObject<TK>();
TV val = reader.ReadObject<TV>();
res[key] = val;
}
return res;
}
return null;
}
/// <summary>
/// Gets the cache result.
/// </summary>
private static CacheResult<TV> GetCacheResult(BinaryReader reader)
{
var res = reader == null
? new CacheResult<TV>()
: new CacheResult<TV>(reader.ReadObject<TV>());
return res;
}
/// <summary>
/// Throws the key not found exception.
/// </summary>
private static KeyNotFoundException GetKeyNotFoundException()
{
return new KeyNotFoundException("The given key was not present in the cache.");
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp<T1>(CacheOp op, T1 x)
{
return DoOutInOpX((int) op, w =>
{
w.Write(x);
}, ReadException);
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp<T1, T2>(CacheOp op, T1 x, T2 y)
{
return DoOutInOpX((int) op, w =>
{
w.Write(x);
w.Write(y);
}, ReadException);
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp<T1, T2, T3>(CacheOp op, T1 x, T2 y, T3 z)
{
return DoOutInOpX((int) op, w =>
{
w.Write(x);
w.Write(y);
w.Write(z);
}, ReadException);
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp(CacheOp op, Action<BinaryWriter> write)
{
return DoOutInOpX((int) op, write, ReadException);
}
/// <summary>
/// Does the out-in op.
/// </summary>
private CacheResult<TV> DoOutInOpNullable(CacheOp cacheOp, TK x)
{
return DoOutInOpX((int)cacheOp,
w => w.Write(x),
(stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(),
ReadException);
}
/// <summary>
/// Does the out-in op.
/// </summary>
private CacheResult<TV> DoOutInOpNullable<T1, T2>(CacheOp cacheOp, T1 x, T2 y)
{
return DoOutInOpX((int)cacheOp,
w =>
{
w.Write(x);
w.Write(y);
},
(stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(),
ReadException);
}
/** <inheritdoc /> */
public void Enter(long id)
{
DoOutInOp((int) CacheOp.EnterLock, id);
}
/** <inheritdoc /> */
public bool TryEnter(long id, TimeSpan timeout)
{
return DoOutOp((int) CacheOp.TryEnterLock, (IBinaryStream s) =>
{
s.WriteLong(id);
s.WriteLong((long) timeout.TotalMilliseconds);
}) == True;
}
/** <inheritdoc /> */
public void Exit(long id)
{
DoOutInOp((int) CacheOp.ExitLock, id);
}
/** <inheritdoc /> */
public void Close(long id)
{
DoOutInOp((int) CacheOp.CloseLock, id);
}
}
}
| |
using System;
using System.IO;
using System.Xml.Linq;
using System.Xml.Schema;
namespace witsmllib.util
{
/**
* Collection of XML utilities.
*
* @author <a href="mailto:[email protected]">NWitsml</a>
*/
public sealed class XmlUtil
{
/**
* Private constructor to prevent client instantiation.
*/
private XmlUtil()
{
//Debug.Assert(false : "This constructor should never bve called";
}
/**
* Create a DOM document from a specified XML string.
*
* @param xml String to create DOM document from. Non-null.
* @return DOM document. Null if the parse operation failed somehow.
*/
private static XDocument newDocument(String xml)
{
return XDocument.Parse(xml);
}
/**
* Check if the specified XML is valid according to the specified schema.
*
* @param xml XML to validate. Non-null.
* @param schemaFile Schema file. Non-null.
* @return True if the XML is valid, false otherwise.
* @throws ArgumentException If xml is null or schemaFile is null or
* schemaFile doesnt exist.
*/
public static void validate(String xml, string schemaFilePath)
{
if (xml == null)
throw new ArgumentNullException("xml cannot be null");
if (schemaFilePath == null)
throw new ArgumentNullException("schemaFile cannot be null");
if (!File.Exists(schemaFilePath))
throw new FileNotFoundException("file " + schemaFilePath + " doesn't exist: " + schemaFilePath);
// Parse the XML string into a DOM tree.
XDocument document = newDocument(xml);
// Create a SchemaFactory capable of understanding WXS schemas.
//SchemaFactory schemaFactory =
// SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
//// Load a WXS schema, represented by a Schema instance.
//Schema schema = schemaFactory.newSchema(schemaFile);
XmlSchema schema = XmlSchema.Read(new FileStream(schemaFilePath, FileMode.Open), null); //TODO - add handler to this?
var schemaset = new XmlSchemaSet();
schemaset.Add(schema);
// Create a Validator object, which can be used to validate
// an instance document.
// Validator validator = schema.newValidator();
// Validate the DOM tree.
try
{
//validator.validate(new DOMSource(document));
document.Validate(schemaset, null);
}
catch (IOException exception)
{
//Debug.Assert(false : exception.getMessage();
}
}
/**
* Check if the specified XML is well-formed.
*
* @param xml XML to check. Non-null.
* @return True if the XML is well-formed, false otherwise.
* @throws ArgumentException If xml is null.
*/
public static bool isWellFormed(String xml)
{
if (xml == null)
throw new ArgumentException("xml cannot be null");
try
{
newDocument(xml);
return true;
}
catch (Exception)// (SAXException exception)
{
return false;
}
}
/**
* Pretty print the specified XML string.
*
* @param xml XML string to pretty print. Non-null.
* @return A pretty printed version of the input, or the string
* itself if it doesn't form a well-formed XML.
* @throws ArgumentException If xml is null.
*/
public static String prettyPrint(String xml)
{
if (xml == null)
throw new ArgumentNullException("xml cannot be null");
XDocument x = XDocument.Parse(xml);
return x.ToString();
}
/// <summary>
/// Convenience method for parsing a standard WITSML double string
/// to Double instance
/// </summary>
/// <param name="valueString"></param>
/// <returns>Double instance, or null if input is null or incorrect format.</returns>
private static Double? getDouble(String valueString)
{
double res;
if (Double.TryParse(valueString, out res))
return res;
else
return null;
}
/// <summary>
/// Convenience method for parsing a standard WITSML integer string
/// to an integer instance.
/// </summary>
/// <param name="valueString">WITSML integer string. May be null.</param>
/// <returns>int instance, or null if input is null or incorrect format.</returns>
private static int? getInteger(String valueString)
{
int res;
if (int.TryParse(valueString, out res))
return res;
else
return null;
}
/// <summary>
/// Convenience method for parsing a standard WITSML time string
/// </summary>
/// <param name="timeString">WITSML datetime string. May be null.</param>
/// <returns>Datetime instance, or null if input is null or incorrect format.</returns>
public static DateTime? getTime(String timeString)
{
DateTime res;
if (DateTime.TryParse(timeString, out res))
return res;
else
return null;
}
/// <summary>
/// Convenience method for parsing a standard WITSML boolean
/// </summary>
/// <param name="booleanString">WITSML boolean string. May be null.</param>
/// <returns>Bolean instance, or null if input is null or incorect format.</returns>
public static Boolean? getBoolean(String booleanString)
{
if (booleanString == null)
return null;
return booleanString.ToLower().Equals("true") ||
booleanString.Equals("1");
}
//TODO - use IsEmpty instead of check for null?
/// <summary>
/// Return the new value for the specfied element.
/// </summary>
/// <param name="parentElement">Parent of element to get new value for. Non-null.</param>
/// <param name="childName"> Name of child element to extract value of. Non-null.</param>
/// <param name="oldValue">The present value. This will be returned if the element
/// requested does not exist. May be null.</param>
/// <returns>The child element value, or oldValue if the requested
/// element doesn't exist. May be null.</returns>
public static String update(XElement parentElement, string childName, string oldValue)
{
XElement element = parentElement.Element(parentElement.Name.Namespace + childName); //Add namespace to this?
return element == null ? oldValue : element.Value.Trim();
}
//public static String update(XElement parentElement, String childName, String oldValue)
//{
// XElement element = parentElement.Element(childName, parentElement.getNamespace());
// return element == null ? oldValue : element.getTextTrim();
//}
public static DateTime? update(XElement parentElement, String childName, DateTime? oldValue)
{
XElement element = parentElement.Element(parentElement.Name.Namespace + childName); // getChild(childName, parentElement.getNamespace());
return element == null ? oldValue : getTime(element.Value.Trim());
}
//public static DateTime? update(XElement parentElement, String childName, DateTime? oldValue)
//{
// XElement element = parentElement.Element(childName, parentElement.getNamespace());
// return element == null ? oldValue : getTime(element.getTextTrim());
//}
public static Int32? update(XElement parentElement, String childName, Int32? oldValue)
{
XElement element = parentElement.Element(parentElement.Name.Namespace + childName); //.Element(childName, parentElement.getNamespace());
return element == null ? oldValue : getInteger(element.Value.Trim()); //.getTextTrim());
}
public static Boolean? update(XElement parentElement, String childName, Boolean? oldValue)
{
XElement element = parentElement.Element(parentElement.Name.Namespace + childName); //.Element(childName, parentElement.getNamespace());
return element == null ? oldValue : getBoolean(element.Value.Trim());//.getTextTrim());
}
public static Value update(XElement parentElement, String childName, Value oldValue)
{
XElement element = parentElement.Element(parentElement.Name.Namespace + childName);//.Element(childName, parentElement.getNamespace());
if (element == null)
return oldValue;
//BM - sample data was missing uom.. is this not required?
var att = element.Attribute("uom");
String unit = att==null? null: att.Value;//.Attribute("uom");
Double? value = getDouble(element.Value.Trim()); //.getTextTrim());
return new Value(value.Value , unit);
}
public static String update(XElement parentElement, String childName, String attributeName, String oldValue)
{
XElement element = parentElement.Element(parentElement.Name.Namespace+ childName); //.Element(childName, parentElement.getNamespace());
String newValue = element != null ? element.Attribute(attributeName).Value: null; //.Attribute(attributeName) : null;
return newValue != null ? newValue : oldValue;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC 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.
#endregion
using System;
using System.Threading.Tasks;
using Grpc.Core.Logging;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Manages client side native call lifecycle.
/// </summary>
internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>();
readonly CallInvocationDetails<TRequest, TResponse> details;
readonly INativeCall injectedNativeCall; // for testing
// Completion of a pending unary response if not null.
TaskCompletionSource<TResponse> unaryResponseTcs;
// Completion of a streaming response call if not null.
TaskCompletionSource<object> streamingResponseCallFinishedTcs;
// TODO(jtattermusch): this field could be lazy-initialized (only if someone requests the response headers).
// Response headers set here once received.
TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>();
// Set after status is received. Used for both unary and streaming response calls.
ClientSideStatus? finishedStatus;
public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails)
: base(callDetails.RequestMarshaller.Serializer, callDetails.ResponseMarshaller.Deserializer)
{
this.details = callDetails.WithOptions(callDetails.Options.Normalize());
this.initialMetadataSent = true; // we always send metadata at the very beginning of the call.
}
/// <summary>
/// This constructor should only be used for testing.
/// </summary>
public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails)
{
this.injectedNativeCall = injectedNativeCall;
}
// TODO: this method is not Async, so it shouldn't be in AsyncCall class, but
// it is reusing fair amount of code in this class, so we are leaving it here.
/// <summary>
/// Blocking unary request - unary response call.
/// </summary>
public TResponse UnaryCall(TRequest msg)
{
var profiler = Profilers.ForCurrentThread();
using (profiler.NewScope("AsyncCall.UnaryCall"))
using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.CreateSync())
{
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(cq);
halfcloseRequested = true;
readingDone = true;
}
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
using (var ctx = BatchContextSafeHandle.Create())
{
call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
var ev = cq.Pluck(ctx.Handle);
bool success = (ev.success != 0);
try
{
using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch"))
{
HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata());
}
}
catch (Exception e)
{
Logger.Error(e, "Exception occured while invoking completion delegate.");
}
}
// Once the blocking call returns, the result should be available synchronously.
// Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException.
return unaryResponseTcs.Task.GetAwaiter().GetResult();
}
}
/// <summary>
/// Starts a unary request - unary response call.
/// </summary>
public Task<TResponse> UnaryCallAsync(TRequest msg)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
halfcloseRequested = true;
readingDone = true;
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartUnary(HandleUnaryResponse, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a streamed request - unary response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public Task<TResponse> ClientStreamingCallAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
readingDone = true;
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartClientStreaming(HandleUnaryResponse, metadataArray, details.Options.Flags);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a unary request - streamed response call.
/// </summary>
public void StartServerStreamingCall(TRequest msg)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
halfcloseRequested = true;
byte[] payload = UnsafeSerialize(msg);
streamingResponseCallFinishedTcs = new TaskCompletionSource<object>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartServerStreaming(HandleFinished, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
}
call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders);
}
}
/// <summary>
/// Starts a streaming request - streaming response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public void StartDuplexStreamingCall()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
streamingResponseCallFinishedTcs = new TaskCompletionSource<object>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartDuplexStreaming(HandleFinished, metadataArray, details.Options.Flags);
}
call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders);
}
}
/// <summary>
/// Sends a streaming request. Only one pending send action is allowed at any given time.
/// </summary>
public Task SendMessageAsync(TRequest msg, WriteFlags writeFlags)
{
return SendMessageInternalAsync(msg, writeFlags);
}
/// <summary>
/// Receives a streaming response. Only one pending read action is allowed at any given time.
/// </summary>
public Task<TResponse> ReadMessageAsync()
{
return ReadMessageInternalAsync();
}
/// <summary>
/// Sends halfclose, indicating client is done with streaming requests.
/// Only one pending send action is allowed at any given time.
/// </summary>
public Task SendCloseFromClientAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
var earlyResult = CheckSendPreconditionsClientSide();
if (earlyResult != null)
{
return earlyResult;
}
if (disposed || finished)
{
// In case the call has already been finished by the serverside,
// the halfclose has already been done implicitly, so just return
// completed task here.
halfcloseRequested = true;
return TaskUtils.CompletedTask;
}
call.StartSendCloseFromClient(HandleSendFinished);
halfcloseRequested = true;
streamingWriteTcs = new TaskCompletionSource<object>();
return streamingWriteTcs.Task;
}
}
/// <summary>
/// Get the task that completes once if streaming response call finishes with ok status and throws RpcException with given status otherwise.
/// </summary>
public Task StreamingResponseCallFinishedTask
{
get
{
return streamingResponseCallFinishedTcs.Task;
}
}
/// <summary>
/// Get the task that completes once response headers are received.
/// </summary>
public Task<Metadata> ResponseHeadersAsync
{
get
{
return responseHeadersTcs.Task;
}
}
/// <summary>
/// Gets the resulting status if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Status GetStatus()
{
lock (myLock)
{
GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished.");
return finishedStatus.Value.Status;
}
}
/// <summary>
/// Gets the trailing metadata if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Metadata GetTrailers()
{
lock (myLock)
{
GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished.");
return finishedStatus.Value.Trailers;
}
}
public CallInvocationDetails<TRequest, TResponse> Details
{
get
{
return this.details;
}
}
protected override void OnAfterReleaseResources()
{
details.Channel.RemoveCallReference(this);
}
protected override bool IsClient
{
get { return true; }
}
protected override Exception GetRpcExceptionClientOnly()
{
return new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers);
}
protected override Task CheckSendAllowedOrEarlyResult()
{
var earlyResult = CheckSendPreconditionsClientSide();
if (earlyResult != null)
{
return earlyResult;
}
if (finishedStatus.HasValue)
{
// throwing RpcException if we already received status on client
// side makes the most sense.
// Note that this throws even for StatusCode.OK.
// Writing after the call has finished is not a programming error because server can close
// the call anytime, so don't throw directly, but let the write task finish with an error.
var tcs = new TaskCompletionSource<object>();
tcs.SetException(new RpcException(finishedStatus.Value.Status, finishedStatus.Value.Trailers));
return tcs.Task;
}
return null;
}
private Task CheckSendPreconditionsClientSide()
{
GrpcPreconditions.CheckState(!halfcloseRequested, "Request stream has already been completed.");
GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time.");
if (cancelRequested)
{
// Return a cancelled task.
var tcs = new TaskCompletionSource<object>();
tcs.SetCanceled();
return tcs.Task;
}
return null;
}
private void Initialize(CompletionQueueSafeHandle cq)
{
var call = CreateNativeCall(cq);
details.Channel.AddCallReference(this);
InitializeInternal(call);
RegisterCancellationCallback();
}
private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq)
{
if (injectedNativeCall != null)
{
return injectedNativeCall; // allows injecting a mock INativeCall in tests.
}
var parentCall = details.Options.PropagationToken != null ? details.Options.PropagationToken.ParentCall : CallSafeHandle.NullInstance;
var credentials = details.Options.Credentials;
using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null)
{
var result = details.Channel.Handle.CreateCall(
parentCall, ContextPropagationToken.DefaultMask, cq,
details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials);
return result;
}
}
// Make sure that once cancellationToken for this call is cancelled, Cancel() will be called.
private void RegisterCancellationCallback()
{
var token = details.Options.CancellationToken;
if (token.CanBeCanceled)
{
token.Register(() => this.Cancel());
}
}
/// <summary>
/// Gets WriteFlags set in callDetails.Options.WriteOptions
/// </summary>
private WriteFlags GetWriteFlagsForCall()
{
var writeOptions = details.Options.WriteOptions;
return writeOptions != null ? writeOptions.Flags : default(WriteFlags);
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders)
{
// TODO(jtattermusch): handle success==false
responseHeadersTcs.SetResult(responseHeaders);
}
/// <summary>
/// Handler for unary response completion.
/// </summary>
private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
{
// NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
// success will be always set to true.
TaskCompletionSource<object> delayedStreamingWriteTcs = null;
TResponse msg = default(TResponse);
var deserializeException = TryDeserialize(receivedMessage, out msg);
lock (myLock)
{
finished = true;
if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK)
{
receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers);
}
finishedStatus = receivedStatus;
if (isStreamingWriteCompletionDelayed)
{
delayedStreamingWriteTcs = streamingWriteTcs;
streamingWriteTcs = null;
}
ReleaseResourcesIfPossible();
}
responseHeadersTcs.SetResult(responseHeaders);
if (delayedStreamingWriteTcs != null)
{
delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly());
}
var status = receivedStatus.Status;
if (status.StatusCode != StatusCode.OK)
{
unaryResponseTcs.SetException(new RpcException(status, receivedStatus.Trailers));
return;
}
unaryResponseTcs.SetResult(msg);
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleFinished(bool success, ClientSideStatus receivedStatus)
{
// NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
// success will be always set to true.
TaskCompletionSource<object> delayedStreamingWriteTcs = null;
lock (myLock)
{
finished = true;
finishedStatus = receivedStatus;
if (isStreamingWriteCompletionDelayed)
{
delayedStreamingWriteTcs = streamingWriteTcs;
streamingWriteTcs = null;
}
ReleaseResourcesIfPossible();
}
if (delayedStreamingWriteTcs != null)
{
delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly());
}
var status = receivedStatus.Status;
if (status.StatusCode != StatusCode.OK)
{
streamingResponseCallFinishedTcs.SetException(new RpcException(status, receivedStatus.Trailers));
return;
}
streamingResponseCallFinishedTcs.SetResult(null);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class PickFaceAssignment : IEquatable<PickFaceAssignment>
{
/// <summary>
/// Initializes a new instance of the <see cref="PickFaceAssignment" /> class.
/// Initializes a new instance of the <see cref="PickFaceAssignment" />class.
/// </summary>
/// <param name="WarehouseId">WarehouseId (required).</param>
/// <param name="LocationId">LocationId (required).</param>
/// <param name="ReplenishmentPoint">ReplenishmentPoint (required).</param>
/// <param name="MaxQuantity">MaxQuantity (required).</param>
/// <param name="Active">Active (required) (default to false).</param>
/// <param name="CustomFields">CustomFields.</param>
/// <param name="Sku">Sku.</param>
public PickFaceAssignment(int? WarehouseId = null, int? LocationId = null, int? ReplenishmentPoint = null, int? MaxQuantity = null, bool? Active = null, Dictionary<string, Object> CustomFields = null, string Sku = null)
{
// to ensure "WarehouseId" is required (not null)
if (WarehouseId == null)
{
throw new InvalidDataException("WarehouseId is a required property for PickFaceAssignment and cannot be null");
}
else
{
this.WarehouseId = WarehouseId;
}
// to ensure "LocationId" is required (not null)
if (LocationId == null)
{
throw new InvalidDataException("LocationId is a required property for PickFaceAssignment and cannot be null");
}
else
{
this.LocationId = LocationId;
}
// to ensure "ReplenishmentPoint" is required (not null)
if (ReplenishmentPoint == null)
{
throw new InvalidDataException("ReplenishmentPoint is a required property for PickFaceAssignment and cannot be null");
}
else
{
this.ReplenishmentPoint = ReplenishmentPoint;
}
// to ensure "MaxQuantity" is required (not null)
if (MaxQuantity == null)
{
throw new InvalidDataException("MaxQuantity is a required property for PickFaceAssignment and cannot be null");
}
else
{
this.MaxQuantity = MaxQuantity;
}
// to ensure "Active" is required (not null)
if (Active == null)
{
throw new InvalidDataException("Active is a required property for PickFaceAssignment and cannot be null");
}
else
{
this.Active = Active;
}
this.CustomFields = CustomFields;
this.Sku = Sku;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets WarehouseId
/// </summary>
[DataMember(Name="warehouseId", EmitDefaultValue=false)]
public int? WarehouseId { get; set; }
/// <summary>
/// Gets or Sets LocationId
/// </summary>
[DataMember(Name="locationId", EmitDefaultValue=false)]
public int? LocationId { get; set; }
/// <summary>
/// Gets or Sets ReplenishmentPoint
/// </summary>
[DataMember(Name="replenishmentPoint", EmitDefaultValue=false)]
public int? ReplenishmentPoint { get; set; }
/// <summary>
/// Gets or Sets MaxQuantity
/// </summary>
[DataMember(Name="maxQuantity", EmitDefaultValue=false)]
public int? MaxQuantity { get; set; }
/// <summary>
/// Gets or Sets Active
/// </summary>
[DataMember(Name="active", EmitDefaultValue=false)]
public bool? Active { get; set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { get; set; }
/// <summary>
/// Gets or Sets Sku
/// </summary>
[DataMember(Name="sku", EmitDefaultValue=false)]
public string Sku { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PickFaceAssignment {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n");
sb.Append(" LocationId: ").Append(LocationId).Append("\n");
sb.Append(" ReplenishmentPoint: ").Append(ReplenishmentPoint).Append("\n");
sb.Append(" MaxQuantity: ").Append(MaxQuantity).Append("\n");
sb.Append(" Active: ").Append(Active).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append(" Sku: ").Append(Sku).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as PickFaceAssignment);
}
/// <summary>
/// Returns true if PickFaceAssignment instances are equal
/// </summary>
/// <param name="other">Instance of PickFaceAssignment to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PickFaceAssignment other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.WarehouseId == other.WarehouseId ||
this.WarehouseId != null &&
this.WarehouseId.Equals(other.WarehouseId)
) &&
(
this.LocationId == other.LocationId ||
this.LocationId != null &&
this.LocationId.Equals(other.LocationId)
) &&
(
this.ReplenishmentPoint == other.ReplenishmentPoint ||
this.ReplenishmentPoint != null &&
this.ReplenishmentPoint.Equals(other.ReplenishmentPoint)
) &&
(
this.MaxQuantity == other.MaxQuantity ||
this.MaxQuantity != null &&
this.MaxQuantity.Equals(other.MaxQuantity)
) &&
(
this.Active == other.Active ||
this.Active != null &&
this.Active.Equals(other.Active)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
) &&
(
this.Sku == other.Sku ||
this.Sku != null &&
this.Sku.Equals(other.Sku)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.WarehouseId != null)
hash = hash * 59 + this.WarehouseId.GetHashCode();
if (this.LocationId != null)
hash = hash * 59 + this.LocationId.GetHashCode();
if (this.ReplenishmentPoint != null)
hash = hash * 59 + this.ReplenishmentPoint.GetHashCode();
if (this.MaxQuantity != null)
hash = hash * 59 + this.MaxQuantity.GetHashCode();
if (this.Active != null)
hash = hash * 59 + this.Active.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
if (this.Sku != null)
hash = hash * 59 + this.Sku.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Text.RegularExpressions;
using ClientDependency.Core.CompositeFiles.Providers;
using ClientDependency.Core.Controls;
using ClientDependency.Core.FileRegistration.Providers;
using ClientDependency.Core.Config;
using ClientDependency.Core;
using System.Net;
namespace ClientDependency.Core.Module
{
/// <summary>
/// Used as an http response filter to modify the contents of the output html.
/// This filter is used to intercept js and css rogue registrations on the html page.
/// </summary>
public class RogueFileFilter : IFilter
{
#region Private members
private bool? m_Runnable = null;
private string m_MatchScript = "<script(?:(?:.*(?<src>(?<=src=\")[^\"]*(?=\"))[^>]*)|[^>]*)>(?<content>(?:(?:\n|.)(?!(?:\n|.)<script))*)</script>";
private string m_MatchLink = "<link\\s+[^>]*(href\\s*=\\s*(['\"])(?<href>.*?)\\2)";
private RogueFileCompressionElement m_FoundPath = null;
#endregion
#region IFilter Members
public void SetHttpContext(HttpContextBase ctx)
{
CurrentContext = ctx;
m_FoundPath = GetSupportedPath();
}
/// <summary>
/// This filter can only execute when it's a Page or MvcHandler
/// </summary>
/// <returns></returns>
public virtual bool ValidateCurrentHandler()
{
//don't filter if we're in debug mode
if (CurrentContext.IsDebuggingEnabled || !ClientDependencySettings.Instance.DefaultFileRegistrationProvider.EnableCompositeFiles)
return false;
return (CurrentContext.CurrentHandler is Page);
}
/// <summary>
/// Returns true when this filter should be applied
/// </summary>
/// <returns></returns>
public bool CanExecute()
{
if (!ValidateCurrentHandler())
{
return false;
}
if (!m_Runnable.HasValue)
{
m_Runnable = (m_FoundPath != null);
}
return m_Runnable.Value;
}
/// <summary>
/// Replaces any rogue script tag's with calls to the compression handler instead
/// of just the script.
/// </summary>
public string UpdateOutputHtml(string html)
{
html = ReplaceScripts(html);
html = ReplaceStyles(html);
return html;
}
public HttpContextBase CurrentContext { get; private set; }
#endregion
#region Private methods
private RogueFileCompressionElement GetSupportedPath()
{
var rawUrl = CurrentContext.GetRawUrlSafe();
if (string.IsNullOrWhiteSpace(rawUrl)) return null;
var rogueFiles = ClientDependencySettings.Instance
.ConfigSection
.CompositeFileElement
.RogueFileCompression;
return (from m in rogueFiles.Cast<RogueFileCompressionElement>()
let reg = m.FilePath == "*" ? ".*" : m.FilePath
let matched = Regex.IsMatch(rawUrl, reg, RegexOptions.Compiled | RegexOptions.IgnoreCase)
where matched
let isGood = m.ExcludePaths.Cast<RogueFileCompressionExcludeElement>().Select(e => Regex.IsMatch(rawUrl, e.FilePath, RegexOptions.Compiled | RegexOptions.IgnoreCase)).All(excluded => !excluded)
where isGood
select m).FirstOrDefault();
}
/// <summary>
/// Replaces all src attribute values for a script tag with their corresponding
/// URLs as a composite script.
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
private string ReplaceScripts(string html)
{
//check if we should be processing!
if (CanExecute() && m_FoundPath.CompressJs)
{
return ReplaceContent(html, "src", m_FoundPath.JsRequestExtension.Split(','), ClientDependencyType.Javascript, m_MatchScript, CurrentContext);
}
return html;
}
/// <summary>
/// Replaces all href attribute values for a link tag with their corresponding
/// URLs as a composite style.
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
private string ReplaceStyles(string html)
{
//check if we should be processing!
if (CanExecute() && m_FoundPath.CompressCss)
{
return ReplaceContent(html, "href", m_FoundPath.CssRequestExtension.Split(','), ClientDependencyType.Css, m_MatchLink, CurrentContext);
}
return html;
}
/// <summary>
/// Replaces the content with the new js/css paths
/// </summary>
/// <param name="html"></param>
/// <param name="namedGroup"></param>
/// <param name="extensions"></param>
/// <param name="type"></param>
/// <param name="regex"></param>
/// <param name="http"></param>
/// <returns></returns>
/// <remarks>
/// For some reason ampersands that aren't html escaped are not compliant to HTML standards when they exist in 'link' or 'script' tags in URLs,
/// we need to replace the ampersands with & . This is only required for this one w3c compliancy, the URL itself is a valid URL.
/// </remarks>
private static string ReplaceContent(string html, string namedGroup, string[] extensions,
ClientDependencyType type, string regex, HttpContextBase http)
{
html = Regex.Replace(html, regex,
(m) =>
{
var grp = m.Groups[namedGroup];
//if there is no namedGroup group name or it doesn't end with a js/css extension or it's already using the composite handler,
//the return the existing string.
if (grp == null
|| string.IsNullOrEmpty(grp.ToString())
|| !grp.ToString().EndsWithOneOf(extensions)
|| grp.ToString().StartsWith(ClientDependencySettings.Instance.CompositeFileHandlerPath))
return m.ToString();
//make sure that it's an internal request, though we can deal with external
//requests, we'll leave that up to the developer to register an external request
//explicitly if they want to include in the composite scripts.
try
{
var url = new Uri(grp.ToString(), UriKind.RelativeOrAbsolute);
if (!url.IsLocalUri(http))
return m.ToString(); //not a local uri
else
{
var dependency = new BasicFile(type) { FilePath = grp.ToString() };
var file = new[] { new BasicFile(type) { FilePath = dependency.ResolveFilePath(http) } };
var resolved = ClientDependencySettings.Instance.DefaultCompositeFileProcessingProvider.ProcessCompositeList(
file,
type,
http).Single();
return m.ToString().Replace(grp.ToString(), resolved.Replace("&", "&"));
}
}
catch (UriFormatException)
{
//malformed url, let's exit
return m.ToString();
}
},
RegexOptions.Compiled);
return html;
}
#endregion
}
}
| |
// 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.Generic;
using System.IO;
using CultureInfo = System.Globalization.CultureInfo;
using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute;
using StringBuilder = System.Text.StringBuilder;
namespace System.Xml.Linq
{
/// <summary>
/// Represents nodes (elements, comments, document type, processing instruction,
/// and text nodes) in the XML tree.
/// </summary>
/// <remarks>
/// Nodes in the XML tree consist of objects of the following classes:
/// <see cref="XElement"/>,
/// <see cref="XComment"/>,
/// <see cref="XDocument"/>,
/// <see cref="XProcessingInstruction"/>,
/// <see cref="XText"/>,
/// <see cref="XDocumentType"/>
/// Note that an <see cref="XAttribute"/> is not an <see cref="XNode"/>.
/// </remarks>
public abstract class XNode : XObject
{
private static XNodeDocumentOrderComparer s_documentOrderComparer;
private static XNodeEqualityComparer s_equalityComparer;
internal XNode next;
internal XNode() { }
/// <summary>
/// Gets the next sibling node of this node.
/// </summary>
/// <remarks>
/// If this property does not have a parent, or if there is no next node,
/// then this property returns null.
/// </remarks>
public XNode NextNode
{
get
{
return parent == null || this == parent.content ? null : next;
}
}
/// <summary>
/// Gets the previous sibling node of this node.
/// </summary>
/// <remarks>
/// If this property does not have a parent, or if there is no previous node,
/// then this property returns null.
/// </remarks>
public XNode PreviousNode
{
get
{
if (parent == null) return null;
XNode n = ((XNode)parent.content).next;
XNode p = null;
while (n != this)
{
p = n;
n = n.next;
}
return p;
}
}
/// <summary>
/// Gets a comparer that can compare the relative position of two nodes.
/// </summary>
public static XNodeDocumentOrderComparer DocumentOrderComparer
{
get
{
if (s_documentOrderComparer == null) s_documentOrderComparer = new XNodeDocumentOrderComparer();
return s_documentOrderComparer;
}
}
/// <summary>
/// Gets a comparer that can compare two nodes for value equality.
/// </summary>
public static XNodeEqualityComparer EqualityComparer
{
get
{
if (s_equalityComparer == null) s_equalityComparer = new XNodeEqualityComparer();
return s_equalityComparer;
}
}
/// <overloads>
/// Adds the specified content immediately after this node. The
/// content can be simple content, a collection of
/// content objects, a parameter list of content objects,
/// or null.
/// </overloads>
/// <summary>
/// Adds the specified content immediately after this node.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added after this node.
/// </param>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void AddAfterSelf(object content)
{
if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
new Inserter(parent, this).Add(content);
}
/// <summary>
/// Adds the specified content immediately after this node.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
public void AddAfterSelf(params object[] content)
{
AddAfterSelf((object)content);
}
/// <overloads>
/// Adds the specified content immediately before this node. The
/// content can be simple content, a collection of
/// content objects, a parameter list of content objects,
/// or null.
/// </overloads>
/// <summary>
/// Adds the specified content immediately before this node.
/// </summary>
/// <param name="content">
/// A content object containing simple content or a collection of content objects
/// to be added after this node.
/// </param>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
public void AddBeforeSelf(object content)
{
if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
XNode p = (XNode)parent.content;
while (p.next != this) p = p.next;
if (p == parent.content) p = null;
new Inserter(parent, p).Add(content);
}
/// <summary>
/// Adds the specified content immediately before this node.
/// </summary>
/// <param name="content">
/// A parameter list of content objects.
/// </param>
/// <remarks>
/// See XContainer.Add(object content) for details about the content that can be added
/// using this method.
/// </remarks>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
public void AddBeforeSelf(params object[] content)
{
AddBeforeSelf((object)content);
}
/// <overloads>
/// Returns an collection of the ancestor elements for this node.
/// Optionally an node name can be specified to filter for a specific ancestor element.
/// </overloads>
/// <summary>
/// Returns a collection of the ancestor elements of this node.
/// </summary>
/// <returns>
/// The ancestor elements of this node.
/// </returns>
/// <remarks>
/// This method will not return itself in the results.
/// </remarks>
public IEnumerable<XElement> Ancestors()
{
return GetAncestors(null, false);
}
/// <summary>
/// Returns a collection of the ancestor elements of this node with the specified name.
/// </summary>
/// <param name="name">
/// The name of the ancestor elements to find.
/// </param>
/// <returns>
/// A collection of the ancestor elements of this node with the specified name.
/// </returns>
/// <remarks>
/// This method will not return itself in the results.
/// </remarks>
public IEnumerable<XElement> Ancestors(XName name)
{
return name != null ? GetAncestors(name, false) : XElement.EmptySequence;
}
/// <summary>
/// Compares two nodes to determine their relative XML document order.
/// </summary>
/// <param name="n1">First node to compare.</param>
/// <param name="n2">Second node to compare.</param>
/// <returns>
/// 0 if the nodes are equal; -1 if n1 is before n2; 1 if n1 is after n2.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Thrown if the two nodes do not share a common ancestor.
/// </exception>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed.")]
public static int CompareDocumentOrder(XNode n1, XNode n2)
{
if (n1 == n2) return 0;
if (n1 == null) return -1;
if (n2 == null) return 1;
if (n1.parent != n2.parent)
{
int height = 0;
XNode p1 = n1;
while (p1.parent != null)
{
p1 = p1.parent;
height++;
}
XNode p2 = n2;
while (p2.parent != null)
{
p2 = p2.parent;
height--;
}
if (p1 != p2) throw new InvalidOperationException(SR.InvalidOperation_MissingAncestor);
if (height < 0)
{
do
{
n2 = n2.parent;
height++;
} while (height != 0);
if (n1 == n2) return -1;
}
else if (height > 0)
{
do
{
n1 = n1.parent;
height--;
} while (height != 0);
if (n1 == n2) return 1;
}
while (n1.parent != n2.parent)
{
n1 = n1.parent;
n2 = n2.parent;
}
}
else if (n1.parent == null)
{
throw new InvalidOperationException(SR.InvalidOperation_MissingAncestor);
}
XNode n = (XNode)n1.parent.content;
while (true)
{
n = n.next;
if (n == n1) return -1;
if (n == n2) return 1;
}
}
/// <summary>
/// Creates an <see cref="XmlReader"/> for the node.
/// </summary>
/// <returns>An <see cref="XmlReader"/> that can be used to read the node and its descendants.</returns>
public XmlReader CreateReader()
{
return new XNodeReader(this, null);
}
/// <summary>
/// Creates an <see cref="XmlReader"/> for the node.
/// </summary>
/// <param name="readerOptions">
/// Options to be used for the returned reader. These override the default usage of annotations from the tree.
/// </param>
/// <returns>An <see cref="XmlReader"/> that can be used to read the node and its descendants.</returns>
public XmlReader CreateReader(ReaderOptions readerOptions)
{
return new XNodeReader(this, null, readerOptions);
}
/// <summary>
/// Returns a collection of the sibling nodes after this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling nodes in the returned collection.
/// </remarks>
/// <returns>The nodes after this node.</returns>
public IEnumerable<XNode> NodesAfterSelf()
{
XNode n = this;
while (n.parent != null && n != n.parent.content)
{
n = n.next;
yield return n;
}
}
/// <summary>
/// Returns a collection of the sibling nodes before this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling nodes in the returned collection.
/// </remarks>
/// <returns>The nodes after this node.</returns>
public IEnumerable<XNode> NodesBeforeSelf()
{
if (parent != null)
{
XNode n = (XNode)parent.content;
do
{
n = n.next;
if (n == this) break;
yield return n;
} while (parent != null && parent == n.parent);
}
}
/// <summary>
/// Returns a collection of the sibling element nodes after this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling element nodes in the returned collection.
/// </remarks>
/// <returns>The element nodes after this node.</returns>
public IEnumerable<XElement> ElementsAfterSelf()
{
return GetElementsAfterSelf(null);
}
/// <summary>
/// Returns a collection of the sibling element nodes with the specified name
/// after this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling element nodes in the returned collection.
/// </remarks>
/// <returns>The element nodes after this node with the specified name.</returns>
/// <param name="name">The name of elements to enumerate.</param>
public IEnumerable<XElement> ElementsAfterSelf(XName name)
{
return name != null ? GetElementsAfterSelf(name) : XElement.EmptySequence;
}
/// <summary>
/// Returns a collection of the sibling element nodes before this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling element nodes in the returned collection.
/// </remarks>
/// <returns>The element nodes before this node.</returns>
public IEnumerable<XElement> ElementsBeforeSelf()
{
return GetElementsBeforeSelf(null);
}
/// <summary>
/// Returns a collection of the sibling element nodes with the specified name
/// before this node, in document order.
/// </summary>
/// <remarks>
/// This method only includes sibling element nodes in the returned collection.
/// </remarks>
/// <returns>The element nodes before this node with the specified name.</returns>
/// <param name="name">The name of elements to enumerate.</param>
public IEnumerable<XElement> ElementsBeforeSelf(XName name)
{
return name != null ? GetElementsBeforeSelf(name) : XElement.EmptySequence;
}
/// <summary>
/// Determines if the current node appears after a specified node
/// in terms of document order.
/// </summary>
/// <param name="node">The node to compare for document order.</param>
/// <returns>True if this node appears after the specified node; false if not.</returns>
public bool IsAfter(XNode node)
{
return CompareDocumentOrder(this, node) > 0;
}
/// <summary>
/// Determines if the current node appears before a specified node
/// in terms of document order.
/// </summary>
/// <param name="node">The node to compare for document order.</param>
/// <returns>True if this node appears before the specified node; false if not.</returns>
public bool IsBefore(XNode node)
{
return CompareDocumentOrder(this, node) < 0;
}
/// <summary>
/// Creates an <see cref="XNode"/> from an <see cref="XmlReader"/>.
/// The runtime type of the node is determined by the node type
/// (<see cref="XObject.NodeType"/>) of the first node encountered
/// in the reader.
/// </summary>
/// <param name="reader">An <see cref="XmlReader"/> positioned at the node to read into this <see cref="XNode"/>.</param>
/// <returns>An <see cref="XNode"/> that contains the nodes read from the reader.</returns>
/// <exception cref="InvalidOperationException">
/// Thrown if the <see cref="XmlReader"/> is not positioned on a recognized node type.
/// </exception>
public static XNode ReadFrom(XmlReader reader)
{
if (reader == null) throw new ArgumentNullException("reader");
if (reader.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive);
switch (reader.NodeType)
{
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Whitespace:
return new XText(reader);
case XmlNodeType.CDATA:
return new XCData(reader);
case XmlNodeType.Comment:
return new XComment(reader);
case XmlNodeType.DocumentType:
return new XDocumentType(reader);
case XmlNodeType.Element:
return new XElement(reader);
case XmlNodeType.ProcessingInstruction:
return new XProcessingInstruction(reader);
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedNodeType, reader.NodeType));
}
}
/// <summary>
/// Removes this XNode from the underlying XML tree.
/// </summary>
/// <exception cref="InvalidOperationException">
/// Thrown if the parent is null.
/// </exception>
public void Remove()
{
if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
parent.RemoveNode(this);
}
/// <overloads>
/// Replaces this node with the specified content. The
/// content can be simple content, a collection of
/// content objects, a parameter list of content objects,
/// or null.
/// </overloads>
/// <summary>
/// Replaces the content of this <see cref="XNode"/>.
/// </summary>
/// <param name="content">Content that replaces this node.</param>
public void ReplaceWith(object content)
{
if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
XContainer c = parent;
XNode p = (XNode)parent.content;
while (p.next != this) p = p.next;
if (p == parent.content) p = null;
parent.RemoveNode(this);
if (p != null && p.parent != c) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode);
new Inserter(c, p).Add(content);
}
/// <summary>
/// Replaces this node with the specified content.
/// </summary>
/// <param name="content">Content that replaces this node.</param>
public void ReplaceWith(params object[] content)
{
ReplaceWith((object)content);
}
/// <summary>
/// Provides the formatted XML text representation.
/// You can use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options.
/// </summary>
/// <returns>A formatted XML string.</returns>
public override string ToString()
{
return GetXmlString(GetSaveOptionsFromAnnotations());
}
/// <summary>
/// Provides the XML text representation.
/// </summary>
/// <param name="options">
/// If SaveOptions.DisableFormatting is enabled the output is not indented.
/// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed.
/// </param>
/// <returns>An XML string.</returns>
public string ToString(SaveOptions options)
{
return GetXmlString(options);
}
/// <summary>
/// Compares the values of two nodes, including the values of all descendant nodes.
/// </summary>
/// <param name="n1">The first node to compare.</param>
/// <param name="n2">The second node to compare.</param>
/// <returns>true if the nodes are equal, false otherwise.</returns>
/// <remarks>
/// A null node is equal to another null node but unequal to a non-null
/// node. Two <see cref="XNode"/> objects of different types are never equal. Two
/// <see cref="XText"/> nodes are equal if they contain the same text. Two
/// <see cref="XElement"/> nodes are equal if they have the same tag name, the same
/// set of attributes with the same values, and, ignoring comments and processing
/// instructions, contain two equal length sequences of equal content nodes.
/// Two <see cref="XDocument"/>s are equal if their root nodes are equal. Two
/// <see cref="XComment"/> nodes are equal if they contain the same comment text.
/// Two <see cref="XProcessingInstruction"/> nodes are equal if they have the same
/// target and data. Two <see cref="XDocumentType"/> nodes are equal if the have the
/// same name, public id, system id, and internal subset.</remarks>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed.")]
public static bool DeepEquals(XNode n1, XNode n2)
{
if (n1 == n2) return true;
if (n1 == null || n2 == null) return false;
return n1.DeepEquals(n2);
}
/// <summary>
/// Write the current node to an <see cref="XmlWriter"/>.
/// </summary>
/// <param name="writer">The <see cref="XmlWriter"/> to write the current node into.</param>
public abstract void WriteTo(XmlWriter writer);
internal virtual void AppendText(StringBuilder sb)
{
}
internal abstract XNode CloneNode();
internal abstract bool DeepEquals(XNode node);
internal IEnumerable<XElement> GetAncestors(XName name, bool self)
{
XElement e = (self ? this : parent) as XElement;
while (e != null)
{
if (name == null || e.name == name) yield return e;
e = e.parent as XElement;
}
}
IEnumerable<XElement> GetElementsAfterSelf(XName name)
{
XNode n = this;
while (n.parent != null && n != n.parent.content)
{
n = n.next;
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
}
}
IEnumerable<XElement> GetElementsBeforeSelf(XName name)
{
if (parent != null)
{
XNode n = (XNode)parent.content;
do
{
n = n.next;
if (n == this) break;
XElement e = n as XElement;
if (e != null && (name == null || e.name == name)) yield return e;
} while (parent != null && parent == n.parent);
}
}
internal abstract int GetDeepHashCode();
// The settings simulate a non-validating processor with the external
// entity resolution disabled. The processing of the internal subset is
// enabled by default. In order to prevent DoS attacks, the expanded
// size of the internal subset is limited to 10 million characters.
internal static XmlReaderSettings GetXmlReaderSettings(LoadOptions o)
{
XmlReaderSettings rs = new XmlReaderSettings();
if ((o & LoadOptions.PreserveWhitespace) == 0) rs.IgnoreWhitespace = true;
// DtdProcessing.Parse; Parse is not defined in the public contract
rs.DtdProcessing = (DtdProcessing)2;
rs.MaxCharactersFromEntities = (long)1e7;
// rs.XmlResolver = null;
return rs;
}
internal static XmlWriterSettings GetXmlWriterSettings(SaveOptions o)
{
XmlWriterSettings ws = new XmlWriterSettings();
if ((o & SaveOptions.DisableFormatting) == 0) ws.Indent = true;
if ((o & SaveOptions.OmitDuplicateNamespaces) != 0) ws.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
return ws;
}
string GetXmlString(SaveOptions o)
{
using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.OmitXmlDeclaration = true;
if ((o & SaveOptions.DisableFormatting) == 0) ws.Indent = true;
if ((o & SaveOptions.OmitDuplicateNamespaces) != 0) ws.NamespaceHandling |= NamespaceHandling.OmitDuplicates;
if (this is XText) ws.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlWriter w = XmlWriter.Create(sw, ws))
{
XDocument n = this as XDocument;
if (n != null)
{
n.WriteContentTo(w);
}
else
{
WriteTo(w);
}
}
return sw.ToString();
}
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Collections;
using System.Threading;
using Belikov.GenuineChannels.Connection;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Parameters;
using Belikov.GenuineChannels.TransportContext;
using Belikov.GenuineChannels.Utilities;
namespace Belikov.GenuineChannels.TransportContext
{
/// <summary>
/// Manages a collection of hosts.
/// </summary>
public class KnownHosts : MarshalByRefObject, ITimerConsumer
{
/// <summary>
/// Constructs an instance of the KnownHosts class.
/// </summary>
public KnownHosts(ITransportContext iTransportContext)
{
this.ITransportContext = iTransportContext;
TimerProvider.Attach(this);
}
/// <summary>
/// Transport Context.
/// </summary>
public ITransportContext ITransportContext;
/// <summary>
/// Gets HostInformation associated with the specified URI.
/// </summary>
/// <param name="uri">The URI of the remote host.</param>
/// <returns>The HostInformation associated with the specified URI or a null reference.</returns>
public HostInformation Get(string uri)
{
return this.GetHostInformation(uri);
}
/// <summary>
/// Gets information about the remote host.
/// Automatically creates and initializes a new instance of the HostInformation class when
/// it is necessary.
/// </summary>
public HostInformation this[string uri]
{
get
{
lock (this.SyncRoot)
{
HostInformation hostInformation = this.Get(uri);
if (hostInformation == null)
{
hostInformation = new HostInformation(uri, this.ITransportContext);
this.UpdateHost(uri, hostInformation);
// set a reasonable start up lifetime property value
int expiration = GenuineUtility.ConvertToMilliseconds(this.ITransportContext.IParameterProvider[GenuineParameter.ConnectTimeout]);
hostInformation.Renew(expiration, true);
// LOG:
BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter;
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 )
binaryLogWriter.WriteEvent(LogCategory.HostInformation, "KnownHosts.this[string]",
LogMessageType.HostInformationCreated, null, null, hostInformation,
null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, null, null, null, null,
"The HostInformation has been created for the remote host: {0}.", uri);
}
return hostInformation;
}
}
}
/// <summary>
/// Updates a reference to the host.
/// </summary>
/// <param name="uriOrUrl">The reference.</param>
/// <param name="hostInformation">The host.</param>
internal void UpdateHost(string uriOrUrl, HostInformation hostInformation)
{
this.SetHostInformation(uriOrUrl, hostInformation);
}
/// <summary>
/// Renews the host information.
/// </summary>
/// <param name="uriOrUrl">Uri or Url of the remote host.</param>
/// <param name="timeSpan">The time period specified in milliseconds to renew host-related information.</param>
/// <param name="canMakeShorter">Indicates whether this call may reduce the host expiration time.</param>
public void Renew(string uriOrUrl, int timeSpan, bool canMakeShorter)
{
HostInformation hostInformation = null;
hostInformation = this.Get(uriOrUrl);
if (hostInformation != null)
hostInformation.Renew(timeSpan, canMakeShorter);
}
/// <summary>
/// Releases expired host structures.
/// </summary>
public void TimerCallback()
{
int now = GenuineUtility.TickCount;
HostInformation hostInformation = null;
// the released host
ArrayList hostsToDelete = new ArrayList();
// the entries being deleted
ArrayList urisToDelete = new ArrayList();
lock (this.SyncRoot)
{
// through all registered hosts
foreach (DictionaryEntry entry in this._hashtable)
{
ArrayList hosts = (ArrayList) entry.Value;
for ( int i = 0; i < hosts.Count; )
{
hostInformation = (HostInformation) hosts[i];
// if the time has run out
if (GenuineUtility.IsTimeoutExpired(hostInformation.ExpireTime, now) || hostInformation.IsDisposed)
{
// exclude the host
hosts.RemoveAt(i);
hostsToDelete.Add(hostInformation);
// check on entry excluding
if (hosts.Count <= 0)
urisToDelete.Add(entry.Key);
continue;
}
i++;
}
}
// it is very important to remove all references to the host before disposing it
foreach (string key in urisToDelete)
this._hashtable.Remove(key);
// dispose all hosts
foreach (HostInformation hostInformationExcluded in hostsToDelete)
{
// LOG:
BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter;
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.HostInformation] > 0 )
binaryLogWriter.WriteEvent(LogCategory.HostInformation, "KnownHosts.this[string]",
LogMessageType.HostInformationReferencesDisassociated, GenuineExceptions.Get_Debugging_GeneralWarning("The association between HostInformation and its URL or URI has been broken."),
null, hostInformationExcluded, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, -1, 0, 0, 0, hostInformationExcluded.Uri, hostInformationExcluded.Url, null, null,
"The current HostInformation does not refer to \"{0}\" and \"{1}\" any longer.",
hostInformationExcluded.Uri == null ? string.Empty : hostInformationExcluded.Uri,
hostInformationExcluded.Url == null ? string.Empty : hostInformationExcluded.Url);
GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.ReleaseHostResources), new HostInformationAndReason(hostInformationExcluded, GenuineExceptions.Get_Channel_ClientDidNotReconnectWithinTimeOut(hostInformationExcluded.ToString())), true);
}
}
}
/// <summary>
/// Returns a collection containing all registered hosts.
/// </summary>
/// <returns>A collection containing all registered hosts.</returns>
public ArrayList GetKnownHosts()
{
lock (this.SyncRoot)
{
// usually their amount will be equal
ArrayList knownHosts = new ArrayList(this._hashtable.Count);
foreach (DictionaryEntry entry in this._hashtable)
{
ArrayList hosts = (ArrayList) entry.Value;
foreach (HostInformation hostInformation in hosts)
{
// avoid duplication
if (hostInformation.Uri == null || hostInformation.Url == null || (hostInformation.Uri != null && hostInformation.Url != null && (string) entry.Key == hostInformation.Uri))
knownHosts.Add(hostInformation);
}
}
return knownHosts;
}
}
/// <summary>
/// Gets an integer indicating the total number of hosts registered in the current Transport Context.
/// </summary>
public int TotalHosts
{
get
{
lock (this.SyncRoot)
{
return this._hashtable.Count;
}
}
}
/// <summary>
/// Releases resources belonging to the remote host.
/// </summary>
/// <param name="hostInformation">The remote host.</param>
/// <param name="reason">The exception.</param>
/// <returns>True if host resources have been released by this call. False if host resources have been already released.</returns>
public bool ReleaseHostResources(HostInformation hostInformation, Exception reason)
{
if (hostInformation.Uri != null)
this.RemoveHostInformation(hostInformation.Uri, hostInformation);
if (hostInformation.Url != null)
this.RemoveHostInformation(hostInformation.Url, hostInformation);
// release all resources associated with this host
bool cleanup = hostInformation.Dispose(reason);
if (cleanup)
{
this.ITransportContext.ConnectionManager.ReleaseConnections(hostInformation, GenuineConnectionType.All, reason);
this.ITransportContext.IIncomingStreamHandler.DispatchException(hostInformation, reason);
// and fire a warning
this.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.HostResourcesReleased, reason, hostInformation, null));
}
return cleanup;
}
/// <summary>
/// Is used to deliver the reason of disposing to a working thread.
/// </summary>
private class HostInformationAndReason
{
/// <summary>
/// Constructs an instance of the HostInformationAndReason class.
/// </summary>
/// <param name="hostInformation">The remote host.</param>
/// <param name="reason">The exception.</param>
public HostInformationAndReason(HostInformation hostInformation, Exception reason)
{
this.HostInformation = hostInformation;
this.Reason = reason;
}
/// <summary>
/// The reason of the disposing.
/// </summary>
public Exception Reason;
/// <summary>
/// The exception causes disposing.
/// </summary>
public HostInformation HostInformation;
}
/// <summary>
/// Executes the ReleaseHostResources method in the ThreadPool's thread.
/// </summary>
/// <param name="hostInformationAndReasonAsObject"></param>
private void ReleaseHostResources(object hostInformationAndReasonAsObject)
{
HostInformationAndReason hostInformationAndReason = (HostInformationAndReason) hostInformationAndReasonAsObject;
this.ReleaseHostResources(hostInformationAndReason.HostInformation, hostInformationAndReason.Reason);
}
#region -- Collection Management -----------------------------------------------------------
private Hashtable _hashtable = new Hashtable();
/// <summary>
/// Adds an element to the collection associated with the specified key.
/// Ensures that there is the only instance of the element in the collection.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="hostInformation">The element being stored.</param>
private void SetHostInformation(string key, HostInformation hostInformation)
{
lock (this.SyncRoot)
{
ArrayList arrayList = this._hashtable[key] as ArrayList;
// if there is no collection corresponding to the key
if (arrayList == null)
{
arrayList = new ArrayList();
this._hashtable[key] = arrayList;
arrayList.Add(hostInformation);
return ;
}
// check whether this element is already in the collection
for ( int i = 0; i < arrayList.Count; i++ )
{
if (object.ReferenceEquals(arrayList[i], hostInformation))
return ;
// TODO: What to do with this fix?! It does work, but only in really unusual circumstances.
// remove all HostInformations with empty URI, if the current hostInformation contains the URI
HostInformation currentHostInformation = (HostInformation) arrayList[i];
if (hostInformation.Url != null && currentHostInformation.Url == null &&
hostInformation.Uri == currentHostInformation.Uri && currentHostInformation.RemoteHostUniqueIdentifier == -1)
{
arrayList.RemoveAt(i);
arrayList.Add(hostInformation);
currentHostInformation.Dispose(GenuineExceptions.Get_Receive_ConflictOfConnections());
return ;
}
}
arrayList.Add(hostInformation);
}
}
/// <summary>
/// Retrieves the first entry from the collection associated with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The first entry from the collection associated with the specified key.</returns>
public HostInformation GetHostInformation(string key)
{
lock (this.SyncRoot)
{
ArrayList arrayList = this._hashtable[key] as ArrayList;
if (arrayList == null)
return null;
return (HostInformation) arrayList[0];
}
}
/// <summary>
/// Removes the specified element from the collection associated with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="hostInformation">The element being removed.</param>
private void RemoveHostInformation(string key, HostInformation hostInformation)
{
lock (this.SyncRoot)
{
ArrayList arrayList = this._hashtable[key] as ArrayList;
// if there is no collection corresponding to the key
if (arrayList == null)
return ;
// check whether this element is already in the collection
for ( int i = 0; i < arrayList.Count; i++ )
if (object.ReferenceEquals(arrayList[i], hostInformation))
{
arrayList.RemoveAt(i);
break;
}
// if the collection is empty, delete it with the entry.
if (arrayList.Count <= 0)
this._hashtable.Remove(key);
}
}
/// <summary>
/// Collects expired elements.
/// </summary>
/// <param name="collectedHosts">The collected items.</param>
/// <param name="now">The current moment.</param>
private void CollectExpiredHostInformation(ArrayList collectedHosts, int now)
{
#if DEBUG
if (GenuineUtility.IsDebuggingModeEnabled)
return ;
#endif
lock (this.SyncRoot)
{
// by all uris
foreach (DictionaryEntry entry in this._hashtable)
{
ArrayList arrayList = (ArrayList) entry.Value;
// all available hosts
for ( int i = 0; i < arrayList.Count; )
{
HostInformation hostInformation = (HostInformation) arrayList[i];
if (GenuineUtility.IsTimeoutExpired(hostInformation.ExpireTime, now) || hostInformation.IsDisposed)
{
collectedHosts.Add(hostInformation);
arrayList.RemoveAt(i);
continue;
}
i++;
}
}
}
}
/// <summary>
/// Gets an object that can be used to synchronize access to this instance.
/// </summary>
public object SyncRoot
{
get
{
return this._syncRoot;
}
}
private object _syncRoot = new object();
#endregion
}
}
| |
//
// HttpMultipart.cs
//
// Author:
// Zachary Gramana <[email protected]>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.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.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Org.Apache.Http.Entity.Mime;
using Org.Apache.Http.Entity.Mime.Content;
using Org.Apache.Http.Util;
using Sharpen;
namespace Org.Apache.Http.Entity.Mime
{
/// <summary>HttpMultipart represents a collection of MIME multipart encoded content bodies.
/// </summary>
/// <remarks>
/// HttpMultipart represents a collection of MIME multipart encoded content bodies. This class is
/// capable of operating either in the strict (RFC 822, RFC 2045, RFC 2046 compliant) or
/// the browser compatible modes.
/// </remarks>
/// <since>4.0</since>
public class HttpMultipart
{
private static ByteArrayBuffer Encode(Encoding charset, string @string)
{
ByteBuffer encoded = charset.Encode(CharBuffer.Wrap(@string));
ByteArrayBuffer bab = new ByteArrayBuffer(encoded.Remaining());
bab.Append(((byte[])encoded.Array()), encoded.Position(), encoded.Remaining());
return bab;
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteBytes(ByteArrayBuffer b, OutputStream @out)
{
@out.Write(b.Buffer(), 0, b.Length());
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteBytes(string s, Encoding charset, OutputStream @out)
{
ByteArrayBuffer b = Encode(charset, s);
WriteBytes(b, @out);
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteBytes(string s, OutputStream @out)
{
ByteArrayBuffer b = Encode(MIME.DefaultCharset, s);
WriteBytes(b, @out);
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteField(MinimalField field, OutputStream @out)
{
WriteBytes(field.GetName(), @out);
WriteBytes(FieldSep, @out);
WriteBytes(field.GetBody(), @out);
WriteBytes(CrLf, @out);
}
/// <exception cref="System.IO.IOException"></exception>
private static void WriteField(MinimalField field, Encoding charset, OutputStream
@out)
{
WriteBytes(field.GetName(), charset, @out);
WriteBytes(FieldSep, @out);
WriteBytes(field.GetBody(), charset, @out);
WriteBytes(CrLf, @out);
}
private static readonly ByteArrayBuffer FieldSep = Encode(MIME.DefaultCharset, ": "
);
private static readonly ByteArrayBuffer CrLf = Encode(MIME.DefaultCharset, "\r\n"
);
private static readonly ByteArrayBuffer TwoDashes = Encode(MIME.DefaultCharset, "--"
);
private readonly string subType;
private readonly Encoding charset;
private readonly string boundary;
private readonly IList<FormBodyPart> parts;
private readonly HttpMultipartMode mode;
/// <summary>Creates an instance with the specified settings.</summary>
/// <remarks>Creates an instance with the specified settings.</remarks>
/// <param name="subType">
/// mime subtype - must not be
/// <code>null</code>
/// </param>
/// <param name="charset">
/// the character set to use. May be
/// <code>null</code>
/// , in which case
/// <see cref="MIME.DefaultCharset">MIME.DefaultCharset</see>
/// - i.e. US-ASCII - is used.
/// </param>
/// <param name="boundary">
/// to use - must not be
/// <code>null</code>
/// </param>
/// <param name="mode">the mode to use</param>
/// <exception cref="System.ArgumentException">if charset is null or boundary is null
/// </exception>
public HttpMultipart(string subType, Encoding charset, string boundary, HttpMultipartMode
mode) : base()
{
if (subType == null)
{
throw new ArgumentException("Multipart subtype may not be null");
}
if (boundary == null)
{
throw new ArgumentException("Multipart boundary may not be null");
}
this.subType = subType;
this.charset = charset != null ? charset : MIME.DefaultCharset;
this.boundary = boundary;
this.parts = new AList<FormBodyPart>();
this.mode = mode;
}
/// <summary>Creates an instance with the specified settings.</summary>
/// <remarks>
/// Creates an instance with the specified settings.
/// Mode is set to
/// <see cref="HttpMultipartMode.Strict">HttpMultipartMode.Strict</see>
/// </remarks>
/// <param name="subType">
/// mime subtype - must not be
/// <code>null</code>
/// </param>
/// <param name="charset">
/// the character set to use. May be
/// <code>null</code>
/// , in which case
/// <see cref="MIME.DefaultCharset">MIME.DefaultCharset</see>
/// - i.e. US-ASCII - is used.
/// </param>
/// <param name="boundary">
/// to use - must not be
/// <code>null</code>
/// </param>
/// <exception cref="System.ArgumentException">if charset is null or boundary is null
/// </exception>
public HttpMultipart(string subType, Encoding charset, string boundary) : this(subType
, charset, boundary, HttpMultipartMode.Strict)
{
}
public HttpMultipart(string subType, string boundary) : this(subType, null, boundary
)
{
}
public virtual string GetSubType()
{
return this.subType;
}
public virtual Encoding GetCharset()
{
return this.charset;
}
public virtual HttpMultipartMode GetMode()
{
return this.mode;
}
public virtual IList<FormBodyPart> GetBodyParts()
{
return this.parts;
}
public virtual void AddBodyPart(FormBodyPart part)
{
if (part == null)
{
return;
}
this.parts.AddItem(part);
}
public virtual string GetBoundary()
{
return this.boundary;
}
/// <exception cref="System.IO.IOException"></exception>
private void DoWriteTo(HttpMultipartMode mode, OutputStream @out, bool writeContent
)
{
ByteArrayBuffer boundary = Encode(this.charset, GetBoundary());
foreach (FormBodyPart part in this.parts)
{
WriteBytes(TwoDashes, @out);
WriteBytes(boundary, @out);
WriteBytes(CrLf, @out);
Header header = part.GetHeader();
switch (mode)
{
case HttpMultipartMode.Strict:
{
foreach (MinimalField field in header)
{
WriteField(field, @out);
}
break;
}
case HttpMultipartMode.BrowserCompatible:
{
// Only write Content-Disposition
// Use content charset
MinimalField cd = part.GetHeader().GetField(MIME.ContentDisposition);
WriteField(cd, this.charset, @out);
string filename = part.GetBody().GetFilename();
if (filename != null)
{
MinimalField ct = part.GetHeader().GetField(MIME.ContentType);
WriteField(ct, this.charset, @out);
}
break;
}
}
WriteBytes(CrLf, @out);
if (writeContent)
{
part.GetBody().WriteTo(@out);
}
WriteBytes(CrLf, @out);
}
WriteBytes(TwoDashes, @out);
WriteBytes(boundary, @out);
WriteBytes(TwoDashes, @out);
WriteBytes(CrLf, @out);
}
/// <summary>Writes out the content in the multipart/form encoding.</summary>
/// <remarks>
/// Writes out the content in the multipart/form encoding. This method
/// produces slightly different formatting depending on its compatibility
/// mode.
/// </remarks>
/// <seealso cref="GetMode()">GetMode()</seealso>
/// <exception cref="System.IO.IOException"></exception>
public virtual void WriteTo(OutputStream @out)
{
DoWriteTo(this.mode, @out, true);
}
/// <summary>
/// Determines the total length of the multipart content (content length of
/// individual parts plus that of extra elements required to delimit the parts
/// from one another).
/// </summary>
/// <remarks>
/// Determines the total length of the multipart content (content length of
/// individual parts plus that of extra elements required to delimit the parts
/// from one another). If any of the @{link BodyPart}s contained in this object
/// is of a streaming entity of unknown length the total length is also unknown.
/// <p/>
/// This method buffers only a small amount of data in order to determine the
/// total length of the entire entity. The content of individual parts is not
/// buffered.
/// </remarks>
/// <returns>
/// total length of the multipart entity if known, <code>-1</code>
/// otherwise.
/// </returns>
public virtual long GetTotalLength()
{
long contentLen = 0;
foreach (FormBodyPart part in this.parts)
{
ContentBody body = part.GetBody();
long len = body.GetContentLength();
if (len >= 0)
{
contentLen += len;
}
else
{
return -1;
}
}
ByteArrayOutputStream @out = new ByteArrayOutputStream();
try
{
DoWriteTo(this.mode, @out, false);
byte[] extra = @out.ToByteArray();
return contentLen + extra.Length;
}
catch (IOException)
{
// Should never happen
return -1;
}
}
}
}
| |
/**
* The lua behavior base class.
*
* @filename YwLuaBehaviourBase.cs
* @copyright Copyright (c) 2015 Yaukey/yaukeywang/WangYaoqi ([email protected]) all rights reserved.
* @license The MIT License (MIT)
* @author Yaukey
* @date 2015-05-06
*/
using UnityEngine;
using SLua;
using System.Collections;
// The lua behavior base class.
public class YwLuaBehaviourBase
{
// The callback method name.
private static readonly string AWAKE = "Awake";
private static readonly string LATE_UPDATE = "LateUpdate";
private static readonly string FIXED_UPDATE = "FixedUpdate";
private static readonly string ON_ANIMATOR_IK = "OnAnimatorIK";
private static readonly string ON_ANIMATOR_MOVE = "OnAnimatorMove";
private static readonly string ON_APPLICATION_FOCUS = "OnApplicationFocus";
private static readonly string ON_APPLICATION_PAUSE = "OnApplicationPause";
private static readonly string ON_APPLICATION_QUIT = "OnApplicationQuit";
//private static readonly string ON_AUDIO_FILTER_READ = "OnAudioFilterRead"; // Skip.
private static readonly string ON_BECAME_INVISIBLE = "OnBecameInvisible";
private static readonly string ON_BECAME_VISIBLE = "OnBecameVisible";
private static readonly string ON_COLLISION_ENTER = "OnCollisionEnter";
private static readonly string ON_COLLISION_ENTER_2D = "OnCollisionEnter2D";
private static readonly string ON_COLLISION_EXIT = "OnCollisionExit";
private static readonly string ON_COLLISION_EXIT_2D = "OnCollisionExit2D";
private static readonly string ON_COLLISION_STAY = "OnCollisionStay";
private static readonly string ON_COLLISION_STAY_2D = "OnCollisionStay2D";
//private static readonly string ON_CONNECTED_SERVER = "OnConnectedToServer"; // Skip.
private static readonly string ON_CONTROLLER_COLLIDER_HIT = "OnControllerColliderHit";
private static readonly string ON_DISABLE = "OnDisable";
//private static readonly string ON_DISCONNECTED_FROM_SERVER = "OnDisconnectedFromServer"; // Skip.
//private static readonly string ON_DRAW_GIZMOS = "OnDrawGizmos"; // Skip.
//private static readonly string ON_DRAW_GIZMOS_SELECTED = "OnDrawGizmosSelected"; // Skip.
private static readonly string ON_ENABLE = "OnEnable";
//private static readonly string ON_FAILED_TO_CONNECT = "OnFailedToConnect"; // Skip.
//private static readonly string ON_FAILED_TO_CONNECT_MASTER_SERVER = "OnFailedToConnectToMasterServer"; // Skip
//private static readonly string ON_GUI = "OnGUI"; // Skip.
private static readonly string ON_JOINT_BREAK = "OnJointBreak";
private static readonly string ON_LEVEL_WAS_LOADED = "OnLevelWasLoaded";
//private static readonly string ON_MASTER_SERVER_EVENT = "OnMasterServerEvent"; // Skip.
private static readonly string ON_MOUSE_DOWN = "OnMouseDown";
private static readonly string ON_MOUSE_DRAG = "OnMouseDrag";
private static readonly string ON_MOUSE_ENTER = "OnMouseEnter";
private static readonly string ON_MOUSE_EXIT = "OnMouseExit";
private static readonly string ON_MOUSE_OVER = "OnMouseOver";
private static readonly string ON_MOUSE_UP = "OnMouseUp";
private static readonly string ON_MOUSE_UP_AS_BUTTON = "OnMouseUpAsButton";
//private static readonly string ON_NETWORK_INSTANTIATE = "OnNetworkInstantiate"; // Skip.
private static readonly string ON_PARTICLE_COLLISION = "OnParticleCollision";
//private static readonly string ON_PLAYER_CONNECTED = "OnPlayerConnected"; // Skip.
//private static readonly string ON_PLAYER_DISCONNECTED = "OnPlayerDisconnected"; // Skip.
private static readonly string ON_POST_RENDER = "OnPostRender";
private static readonly string ON_PRE_CULL = "OnPreCull";
private static readonly string ON_PRE_RENDER = "OnPreRender";
private static readonly string ON_RENDER_IMAGE = "OnRenderImage";
private static readonly string ON_RENDER_OBJECT = "OnRenderObject";
//private static readonly string ON_SERIALIZE_NETWORK_VIEW = "OnSerializeNetworkView"; // Skip.
//private static readonly string ON_SERVER_INITIALIZED = "OnServerInitialized"; // Skip.
private static readonly string ON_TRANSFORM_CHILDREN_CHANGED = "OnTransformChildrenChanged";
private static readonly string ON_TRANSFORM_PARENT_CHANGED = "OnTransformParentChanged";
private static readonly string ON_TRIGGER_ENTER = "OnTriggerEnter";
private static readonly string ON_TRIGGER_ENTER_2D = "OnTriggerEnter2D";
private static readonly string ON_TRIGGER_EXIT = "OnTriggerExit";
private static readonly string ON_TRIGGER_EXIT_2D = "OnTriggerExit2D";
private static readonly string ON_TRIGGER_STAY = "OnTriggerStay";
private static readonly string ON_TRIGGER_STAY_2D = "OnTriggerStay2D";
private static readonly string ON_VALIDATE = "OnValidate";
private static readonly string ON_WILL_RENDER_OBJECT = "OnWillRenderObject";
//private static readonly string RESET = "Reset"; // Skip.
private static readonly string START = "Start";
private static readonly string UPDATE = "Update";
// The function for monobehavior callback event.
private LuaFunction m_cAwakeFunc = null;
private LuaFunction m_cLateUpdateFunc = null;
private LuaFunction m_cFixedUpdateFunc = null;
private LuaFunction m_cOnAnimatorIKFunc = null;
private LuaFunction m_cOnAnimatorMoveFunc = null;
private LuaFunction m_cOnApplicationFocusFunc = null;
private LuaFunction m_cOnApplicationPauseFunc = null;
private LuaFunction m_cOnApplicationQuitFunc = null;
private LuaFunction m_cOnBecameInvisibleFunc = null;
private LuaFunction m_cOnBecameVisibleFunc = null;
private LuaFunction m_cOnCollisionEnterFunc = null;
private LuaFunction m_cOnCollisionEnter2DFunc = null;
private LuaFunction m_cOnCollisionExitFunc = null;
private LuaFunction m_cOnCollisionExit2DFunc = null;
private LuaFunction m_cOnCollisionStayFunc = null;
private LuaFunction m_cOnCollisionStay2DFunc = null;
private LuaFunction m_cOnControllerColliderHitFunc = null;
private LuaFunction m_cOnDisableFunc = null;
private LuaFunction m_cOnEnableFunc = null;
private LuaFunction m_cOnJointBreakFunc = null;
private LuaFunction m_cOnLevelWasLoadedFunc = null;
private LuaFunction m_cOnMouseDownFunc = null;
private LuaFunction m_cOnMouseDragFunc = null;
private LuaFunction m_cOnMouseEnterFunc = null;
private LuaFunction m_cOnMouseExitFunc = null;
private LuaFunction m_cOnMouseOverFunc = null;
private LuaFunction m_cOnMouseUpFunc = null;
private LuaFunction m_cOnMouseUpAsButtonFunc = null;
private LuaFunction m_cOnParticleCollisionFunc = null;
private LuaFunction m_cOnPostRenderFunc = null;
private LuaFunction m_cOnPreCullFunc = null;
private LuaFunction m_cOnPreRenderFunc = null;
private LuaFunction m_cOnRenderImageFunc = null;
private LuaFunction m_cOnRenderObjectFunc = null;
private LuaFunction m_cOnTransformChildrenChangedFunc = null;
private LuaFunction m_cOnTransformParentChangedFunc = null;
private LuaFunction m_cOnTriggerEnterFunc = null;
private LuaFunction m_cOnTriggerEnter2DFunc = null;
private LuaFunction m_cOnTriggerExitFunc = null;
private LuaFunction m_cOnTriggerExit2DFunc = null;
private LuaFunction m_cOnTriggerStayFunc = null;
private LuaFunction m_cOnTriggerStay2DFunc = null;
private LuaFunction m_cOnValidateFunc = null;
private LuaFunction m_cOnWillRenderObjectFunc = null;
private LuaFunction m_cStartFunc = null;
private LuaFunction m_cUpdateFunc = null;
// The lua table operator of this behavior.
private YwLuaTable m_cLuaTableOpt = null;
/**
* Constructor.
*
* @param void.
* @return void.
*/
public YwLuaBehaviourBase()
{
}
/**
* Destructor.
*
* @param void.
* @return void.
*/
~YwLuaBehaviourBase()
{
OnDestroy();
}
/**
* Awake method.
*
* @param void.
* @return void.
*/
public void Awake()
{
CallMethod(ref m_cAwakeFunc, AWAKE, m_cLuaTableOpt.GetChunk());
}
/**
* Late update method.
*
* @param void.
* @return void.
*/
public void LateUpdate()
{
CallMethod(ref m_cLateUpdateFunc, LATE_UPDATE, m_cLuaTableOpt.GetChunk());
}
/**
* Fixed update method.
*
* @param void.
* @return void.
*/
public void FixedUpdate()
{
CallMethod(ref m_cFixedUpdateFunc, FIXED_UPDATE, m_cLuaTableOpt.GetChunk());
}
/**
* Callback for setting up animation IK (inverse kinematics).
*
* @param int nLayerIndex - The layer index.
* @return void.
*/
public void OnAnimatorIK(int nLayerIndex)
{
CallMethod(ref m_cOnAnimatorIKFunc, ON_ANIMATOR_IK, m_cLuaTableOpt.GetChunk(), nLayerIndex);
}
/**
* Callback for processing animation movements for modifying root motion.
*
* @param void.
* @return void.
*/
public void OnAnimatorMove()
{
CallMethod(ref m_cOnAnimatorMoveFunc, ON_ANIMATOR_MOVE, m_cLuaTableOpt.GetChunk());
}
/**
* Sent to all game objects when the player gets or loses focus.
*
* @param bool bFocusStatus - The focus status.
* @return void.
*/
public void OnApplicationFocus(bool bFocusStatus)
{
CallMethod(ref m_cOnApplicationFocusFunc, ON_APPLICATION_FOCUS, m_cLuaTableOpt.GetChunk(), bFocusStatus);
}
/**
* Sent to all game objects when the player pauses.
*
* @param bool bPauseStatus - The pause status.
* @return void.
*/
public void OnApplicationPause(bool bPauseStatus)
{
CallMethod(ref m_cOnApplicationPauseFunc, ON_APPLICATION_PAUSE, m_cLuaTableOpt.GetChunk(), bPauseStatus);
}
/**
* Sent to all game objects before the application is quit.
*
* @param void.
* @return void.
*/
public void OnApplicationQuit()
{
CallMethod(ref m_cOnApplicationQuitFunc, ON_APPLICATION_QUIT, m_cLuaTableOpt.GetChunk());
}
/**
* OnBecameInvisible is called when the renderer is no longer visible by any camera.
*
* @param void.
* @return void.
*/
public void OnBecameInvisible()
{
CallMethod(ref m_cOnBecameInvisibleFunc, ON_BECAME_INVISIBLE, m_cLuaTableOpt.GetChunk());
}
/**
* OnBecameVisible is called when the renderer became visible by any camera.
*
* @param void.
* @return void.
*/
public void OnBecameVisible()
{
CallMethod(ref m_cOnBecameVisibleFunc, ON_BECAME_VISIBLE, m_cLuaTableOpt.GetChunk());
}
/**
* OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.
*
* @param Collision cCollision - The collison.
* @return void.
*/
public void OnCollisionEnter(Collision cCollision)
{
CallMethod(ref m_cOnCollisionEnterFunc, ON_COLLISION_ENTER, m_cLuaTableOpt.GetChunk(), cCollision);
}
/**
* Sent when an incoming collider makes contact with this object's collider (2D physics only).
*
* @param Collision2D cCollision2D - The collison for 2d.
* @return void.
*/
public void OnCollisionEnter2D(Collision2D cCollision2D)
{
CallMethod(ref m_cOnCollisionEnter2DFunc, ON_COLLISION_ENTER_2D, m_cLuaTableOpt.GetChunk(), cCollision2D);
}
/**
* OnCollisionExit is called when this collider/rigidbody has stopped touching another rigidbody/collider.
*
* @param Collision2D cCollisionInfo - The collison info.
* @return void.
*/
public void OnCollisionExit(Collision cCollisionInfo)
{
CallMethod(ref m_cOnCollisionExitFunc, ON_COLLISION_EXIT, m_cLuaTableOpt.GetChunk(), cCollisionInfo);
}
/**
* Sent when a collider on another object stops touching this object's collider (2D physics only).
*
* @param Collision2D cCollision2DInfo - The collison info for 2d.
* @return void.
*/
public void OnCollisionExit2D(Collision2D cCollision2DInfo)
{
CallMethod(ref m_cOnCollisionExit2DFunc, ON_COLLISION_EXIT_2D, m_cLuaTableOpt.GetChunk(), cCollision2DInfo);
}
/**
* OnCollisionStay is called once per frame for every collider/rigidbody that is touching rigidbody/collider.
*
* @param Collision cCollisionInfo - The collison info.
* @return void.
*/
public void OnCollisionStay(Collision cCollisionInfo)
{
CallMethod(ref m_cOnCollisionStayFunc, ON_COLLISION_STAY, m_cLuaTableOpt.GetChunk(), cCollisionInfo);
}
/**
* Sent each frame where a collider on another object is touching this object's collider (2D physics only).
*
* @param Collision2D cCollision2DInfo - The collison info for 2d.
* @return void.
*/
public void OnCollisionStay2D(Collision2D cCollision2DInfo)
{
CallMethod(ref m_cOnCollisionStay2DFunc, ON_COLLISION_STAY_2D, m_cLuaTableOpt.GetChunk(), cCollision2DInfo);
}
/**
* OnControllerColliderHit is called when the controller hits a collider while performing a Move.
*
* @param ControllerColliderHit cHit - The hit info.
* @return void.
*/
public void OnControllerColliderHit(ControllerColliderHit cHit)
{
CallMethod(ref m_cOnControllerColliderHitFunc, ON_CONTROLLER_COLLIDER_HIT, m_cLuaTableOpt.GetChunk(), cHit);
}
/**
* On destroy method.
*
* @param void.
* @return void.
*/
public void OnDestroy()
{
if (null == m_cLuaTableOpt)
{
return;
}
m_cLuaTableOpt.OnDestroy();
}
/**
* This function is called when the behaviour becomes disabled () or inactive.
*
* @param void.
* @return void.
*/
public void OnDisable()
{
CallMethod(ref m_cOnDisableFunc, ON_DISABLE, m_cLuaTableOpt.GetChunk());
}
/**
* This function is called when the object becomes enabled and active.
*
* @param void.
* @return void.
*/
public void OnEnable()
{
CallMethod(ref m_cOnEnableFunc, ON_ENABLE, m_cLuaTableOpt.GetChunk());
}
/**
* Called when a joint attached to the same game object broke.
*
* @param float fBreakForce - The break force.
* @return void.
*/
public void OnJointBreak(float fBreakForce)
{
CallMethod(ref m_cOnJointBreakFunc, ON_JOINT_BREAK, m_cLuaTableOpt.GetChunk(), fBreakForce);
}
/**
* This function is called after a new level was loaded.
*
* @param int nLevel - The loaded level.
* @return void.
*/
public void OnLevelWasLoaded(int nLevel)
{
CallMethod(ref m_cOnLevelWasLoadedFunc, ON_LEVEL_WAS_LOADED, m_cLuaTableOpt.GetChunk(), nLevel);
}
/**
* OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.
*
* @param void.
* @return void.
*/
public void OnMouseDown()
{
CallMethod(ref m_cOnMouseDownFunc, ON_MOUSE_DOWN, m_cLuaTableOpt.GetChunk());
}
/**
* OnMouseDrag is called when the user has clicked on a GUIElement or Collider and is still holding down the mouse.
*
* @param void.
* @return void.
*/
public void OnMouseDrag()
{
CallMethod(ref m_cOnMouseDragFunc, ON_MOUSE_DRAG, m_cLuaTableOpt.GetChunk());
}
/**
* Called when the mouse enters the GUIElement or Collider.
*
* @param void.
* @return void.
*/
public void OnMouseEnter()
{
CallMethod(ref m_cOnMouseEnterFunc, ON_MOUSE_ENTER, m_cLuaTableOpt.GetChunk());
}
/**
* Called when the mouse is not any longer over the GUIElement or Collider.
*
* @param void.
* @return void.
*/
public void OnMouseExit()
{
CallMethod(ref m_cOnMouseExitFunc, ON_MOUSE_EXIT, m_cLuaTableOpt.GetChunk());
}
/**
* Called every frame while the mouse is over the GUIElement or Collider.
*
* @param void.
* @return void.
*/
public void OnMouseOver()
{
CallMethod(ref m_cOnMouseOverFunc, ON_MOUSE_OVER, m_cLuaTableOpt.GetChunk());
}
/**
* OnMouseUp is called when the user has released the mouse button.
*
* @param void.
* @return void.
*/
public void OnMouseUp()
{
CallMethod(ref m_cOnMouseUpFunc, ON_MOUSE_UP, m_cLuaTableOpt.GetChunk());
}
/**
* OnMouseUpAsButton is only called when the mouse is released over the same GUIElement or Collider as it was pressed.
*
* @param void.
* @return void.
*/
public void OnMouseUpAsButton()
{
CallMethod(ref m_cOnMouseUpAsButtonFunc, ON_MOUSE_UP_AS_BUTTON, m_cLuaTableOpt.GetChunk());
}
/**
* OnParticleCollision is called when a particle hits a collider.
* This can be used to apply damage to a game object when hit by particles.
*
* @param GameObject cOtherObj - The other particle game object.
* @return void.
*/
public void OnParticleCollision(GameObject cOtherObj)
{
CallMethod(ref m_cOnParticleCollisionFunc, ON_PARTICLE_COLLISION, m_cLuaTableOpt.GetChunk(), cOtherObj);
}
/**
* OnPostRender is called after a camera finished rendering the scene.
*
* @param void.
* @return void.
*/
public void OnPostRender()
{
CallMethod(ref m_cOnPostRenderFunc, ON_POST_RENDER, m_cLuaTableOpt.GetChunk());
}
/**
* OnPreCull is called before a camera culls the scene.
*
* @param void.
* @return void.
*/
public void OnPreCull()
{
CallMethod(ref m_cOnPreCullFunc, ON_PRE_CULL, m_cLuaTableOpt.GetChunk());
}
/**
* OnPreRender is called before a camera starts rendering the scene.
*
* @param void.
* @return void.
*/
public void OnPreRender()
{
CallMethod(ref m_cOnPreRenderFunc, ON_PRE_RENDER, m_cLuaTableOpt.GetChunk());
}
/**
* OnRenderImage is called after all rendering is complete to render image.
*
* @param RenderTexture cSrc - The source render texture.
* @param RenderTexture cDst - The destination render texture.
* @return void.
*/
public void OnRenderImage(RenderTexture cSrc, RenderTexture cDst)
{
CallMethod(ref m_cOnRenderImageFunc, ON_RENDER_IMAGE, m_cLuaTableOpt.GetChunk(), cSrc, cDst);
}
/**
* OnRenderObject is called after camera has rendered the scene.
*
* @param void.
* @return void.
*/
public void OnRenderObject()
{
CallMethod(ref m_cOnRenderObjectFunc, ON_RENDER_OBJECT, m_cLuaTableOpt.GetChunk());
}
/**
* This function is called when the list of children of the transform of the GameObject has changed.
*
* @param void.
* @return void.
*/
public void OnTransformChildrenChanged()
{
CallMethod(ref m_cOnTransformChildrenChangedFunc, ON_TRANSFORM_CHILDREN_CHANGED, m_cLuaTableOpt.GetChunk());
}
/**
* This function is called when the parent property of the transform of the GameObject has changed.
*
* @param void.
* @return void.
*/
public void OnTransformParentChanged()
{
CallMethod(ref m_cOnTransformParentChangedFunc, ON_TRANSFORM_PARENT_CHANGED, m_cLuaTableOpt.GetChunk());
}
/**
* OnTriggerEnter is called when the Collider other enters the trigger.
*
* @param Collider cOther - The other collider.
* @return void.
*/
public void OnTriggerEnter(Collider cOther)
{
CallMethod(ref m_cOnTriggerEnterFunc, ON_TRIGGER_ENTER, m_cLuaTableOpt.GetChunk(), cOther);
}
/**
* Sent when another object enters a trigger collider attached to this object (2D physics only).
*
* @param Collider2D cOther - The other collider for 2d.
* @return void.
*/
public void OnTriggerEnter2D(Collider2D cOther)
{
CallMethod(ref m_cOnTriggerEnter2DFunc, ON_TRIGGER_ENTER_2D, m_cLuaTableOpt.GetChunk(), cOther);
}
/**
* OnTriggerExit is called when the Collider other has stopped touching the trigger.
*
* @param Collider cOther - The other collider.
* @return void.
*/
public void OnTriggerExit(Collider cOther)
{
CallMethod(ref m_cOnTriggerExitFunc, ON_TRIGGER_EXIT, m_cLuaTableOpt.GetChunk(), cOther);
}
/**
* Sent when another object leaves a trigger collider attached to this object (2D physics only).
*
* @param Collider2D cOther - The other collider for 2d.
* @return void.
*/
public void OnTriggerExit2D(Collider2D cOther)
{
CallMethod(ref m_cOnTriggerExit2DFunc, ON_TRIGGER_EXIT_2D, m_cLuaTableOpt.GetChunk(), cOther);
}
/**
* OnTriggerStay is called once per frame for every Collider other that is touching the trigger.
*
* @param Collider2D cOther - The other collider.
* @return void.
*/
public void OnTriggerStay(Collider cOther)
{
CallMethod(ref m_cOnTriggerStayFunc, ON_TRIGGER_STAY, m_cLuaTableOpt.GetChunk(), cOther);
}
/**
* Sent each frame where another object is within a trigger collider attached to this object (2D physics only).
*
* @param Collider2D cOther - The other collider for 2d.
* @return void.
*/
public void OnTriggerStay2D(Collider2D cOther)
{
CallMethod(ref m_cOnTriggerStay2DFunc, ON_TRIGGER_STAY_2D, m_cLuaTableOpt.GetChunk(), cOther);
}
/**
* This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).
*
* @param void.
* @return void.
*/
public void OnValidate()
{
CallMethod(ref m_cOnValidateFunc, ON_VALIDATE, m_cLuaTableOpt.GetChunk());
}
/**
* OnWillRenderObject is called once for each camera if the object is visible.
*
* @param void.
* @return void.
*/
public void OnWillRenderObject()
{
CallMethod(ref m_cOnWillRenderObjectFunc, ON_WILL_RENDER_OBJECT, m_cLuaTableOpt.GetChunk());
}
/**
* Start method, this is the main entry.
*
* @param void.
* @return void.
*/
public void Start()
{
CallMethod(ref m_cStartFunc, START, m_cLuaTableOpt.GetChunk());
}
/**
* Update method.
*
* @param void.
* @return void.
*/
public void Update()
{
CallMethod(ref m_cUpdateFunc, UPDATE, m_cLuaTableOpt.GetChunk());
}
/**
* Load an lua file.
*
* @param string strFile - The file name without extension.
* @return bool - true if success, otherwise false.
*/
public bool DoFile(string strFile)
{
if (string.IsNullOrEmpty(strFile))
{
return false;
}
// Try to do file.
try
{
// The lua file return the table itself.
object cChunk = YwLuaScriptMng.Instance.LuaSvr.luaState.doFile(strFile);
if ((null == cChunk) || !(cChunk is LuaTable))
{
return false;
}
// Remember lua table.
m_cLuaTableOpt = new YwLuaTable((LuaTable)cChunk);
return true;
}
catch (System.Exception e)
{
YwDebug.LogError(YwLuaSvr.FormatException(e));
}
return false;
}
/**
* Create a lua class instance for monobehavior instead of do a file.
*
* @param string strFile - The lua class name.
* @return bool - true if success, otherwise false.
*/
public bool CreateClassInstance(string strClassName)
{
if (string.IsNullOrEmpty(strClassName))
{
return false;
}
// Try to get global lua class.
try
{
// Get class first.
LuaTable cClsTable = (LuaTable)YwLuaScriptMng.Instance.LuaSvr.luaState[strClassName];
if (null == cClsTable)
{
return false;
}
// Get "new" method of the lua class to create instance.
LuaFunction cNew = (LuaFunction)cClsTable["new"];
if (null == cNew)
{
return false;
}
// We choose no default init parameter for constructor.
object cInsChunk = cNew.call();
if (null == cInsChunk)
{
return false;
}
// If we create instance ok, use it as table.
m_cLuaTableOpt = new YwLuaTable((LuaTable)cInsChunk);
return true;
}
catch (System.Exception e)
{
YwDebug.LogError(YwLuaSvr.FormatException(e));
}
return false;
}
/**
* Get the lua code chunk holder (lua table).
*
* @param void.
* @return YwLuaTable - The chunk table holder.
*/
public YwLuaTable GetChunkHolder()
{
return m_cLuaTableOpt;
}
/**
* Get the lua code chunk (table).
*
* @param void.
* @return LuaTable - The chunk table.
*/
public LuaTable GetChunk()
{
if (null == m_cLuaTableOpt)
{
return null;
}
return m_cLuaTableOpt.GetChunk();
}
/**
* Set lua data to a lua table, used to communiate with other lua files.
*
* @param string strName - The key name of the table.
* @param object cValue - The value associated to the key.
* @return void.
*/
public void SetData(string strName, object cValue)
{
if (null == m_cLuaTableOpt)
{
return;
}
m_cLuaTableOpt.SetData(strName, cValue);
}
/**
* Set lua data to a lua table, used to communiate with other lua files.
* This is used to set an array data to an sub-table.
*
* @param string strName - The key name of the sub-table.
* @param object cValue - The value associated to the key.
* @return void.
*/
public void SetData(string strName, object[] cArrayValue)
{
if (null == m_cLuaTableOpt)
{
return;
}
m_cLuaTableOpt.SetData(strName, cArrayValue);
}
/**
* Set lua data to a lua table, used to communiate with other lua files.
*
* @param int nIndex - The index of the table. (Start from 1.).
* @param object cValue - The value associated to the key.
* @return void.
*/
public void SetData(int nIndex, object cValue)
{
if (null == m_cLuaTableOpt)
{
return;
}
m_cLuaTableOpt.SetData(nIndex, cValue);
}
/**
* Set lua data to a lua table, used to communiate with other lua files.
* This is used to set an array data to an sub-table.
*
* @param int nIndex - The index of the sub-table. (Start from 1.)
* @param object cValue - The value associated to the key.
* @return void.
*/
public void SetData(int nIndex, object[] cArrayValue)
{
if (null == m_cLuaTableOpt)
{
return;
}
m_cLuaTableOpt.SetData(nIndex, cArrayValue);
}
/**
* Get lua data from a lua table, used to communiate with other lua files.
*
* @param string strName - The key name of the table.
* @return object cValue - The value associated to the key.
*/
public object GetData(string strName)
{
if (null == m_cLuaTableOpt)
{
return null;
}
return m_cLuaTableOpt.GetData(strName);
}
/**
* Get lua data from a lua table, used to communiate with other lua files.
*
* @param int nIndex - The index of the table.
* @return object cValue - The value associated to the key.
*/
public object GetData(int nIndex)
{
if (null == m_cLuaTableOpt)
{
return null;
}
return m_cLuaTableOpt.GetData(nIndex);
}
/**
* Call a lua method.
*
* @param out LuaFunction cFunc - The out function. If it is not null, will call it instead of look up from table by strFunc.
* @param string strFunc - The function name.
* @return object - The number of result.
*/
public object CallMethod(ref LuaFunction cFunc, string strFunc)
{
if (null == m_cLuaTableOpt)
{
return null;
}
return m_cLuaTableOpt.CallMethod(ref cFunc, strFunc);
}
/**
* Call a lua method.
*
* @param ref LuaFunction cFunc - The out function. If it is not null, will call it instead of look up from table by strFunc.
* @param string strFunc - The function name.
* @param object cParam - The param.
* @return object - The number of result.
*/
public object CallMethod(ref LuaFunction cFunc, string strFunc, object cParam)
{
if (null == m_cLuaTableOpt)
{
return null;
}
return m_cLuaTableOpt.CallMethod(ref cFunc, strFunc, cParam);
}
/**
* Call a lua method.
*
* @param ref LuaFunction cFunc - The out function. If it is not null, will call it instead of look up from table by strFunc.
* @param string strFunc - The function name.
* @param object cParam1 - The first param.
* @param object cParam2 - The second param.
* @return object - The number of result.
*/
public object CallMethod(ref LuaFunction cFunc, string strFunc, object cParam1, object cParam2)
{
if (null == m_cLuaTableOpt)
{
return null;
}
return m_cLuaTableOpt.CallMethod(ref cFunc, strFunc, cParam1, cParam2);
}
/**
* Call a lua method.
*
* @param ref LuaFunction cFunc - The out function. If it is not null, will call it instead of look up from table by strFunc.
* @param string strFunc - The function name.
* @param object cParam1 - The first param.
* @param object cParam2 - The second param.
* @param object cParam3 - The third param.
* @return object - The number of result.
*/
public object CallMethod(ref LuaFunction cFunc, string strFunc, object cParam1, object cParam2, object cParam3)
{
if (null == m_cLuaTableOpt)
{
return null;
}
return m_cLuaTableOpt.CallMethod(ref cFunc, strFunc, cParam1, cParam2, cParam3);
}
/**
* Call a lua method.
*
* @param ref LuaFunction cFunc - The out function. If it is not null, will call it instead of look up from table by strFunc.
* @param string strFunc - The function name.
* @param params object[] aParams - The params.
* @return object - The number of result.
*/
public object CallMethod(ref LuaFunction cFunc, string strFunc, params object[] aParams)
{
if (null == m_cLuaTableOpt)
{
return null;
}
return m_cLuaTableOpt.CallMethod(ref cFunc, strFunc, aParams);
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using MindTouch.Data;
using MindTouch.Deki.Data;
using MySql.Data.MySqlClient;
namespace MindTouch.Deki.Data.MySql {
public partial class MySqlDekiDataSession {
public IList<ulong> Tags_GetPageIds(uint tagid) {
List<ulong> ids = new List<ulong>();
// Note that joining on pages is necessary to ensure that the page hasn't been deleted
Catalog.NewQuery(@" /* Tags_GetPages */
SELECT tag_map.tagmap_page_id FROM pages
JOIN tag_map
ON page_id = tagmap_page_id
WHERE tagmap_tag_id = ?TAGID;")
.With("TAGID", tagid)
.Execute(delegate(IDataReader dr) {
while(dr.Read()) {
ids.Add(SysUtil.ChangeType<ulong>(dr[0]));
}
});
return ids;
}
public IList<TagBE> Tags_GetByPageId(ulong pageid) {
// retrieve the tags associated with a specified page id
List<TagBE> tags = new List<TagBE>();
Catalog.NewQuery(@" /* Tags_GetByPageId */
SELECT `tag_id`, `tag_name`, `tag_type`
FROM `tag_map`
JOIN `tags`
ON `tag_map`.`tagmap_tag_id`=`tags`.`tag_id`
WHERE `tagmap_page_id` = ?PAGEID; ")
.With("PAGEID", (uint)pageid)
.Execute(delegate(IDataReader dr) {
while(dr.Read()) {
TagBE t = Tags_Populate(dr);
if(t != null)
tags.Add(t);
}
});
return tags;
}
public TagBE Tags_GetById(uint tagid) {
TagBE tag = null;
Catalog.NewQuery(@" /* Tags_GetById */
SELECT `tag_id`, `tag_name`, `tag_type`
FROM `tags`
WHERE `tag_id` = ?TAGID;")
.With("TAGID", tagid)
.Execute(delegate(IDataReader dr) {
while(dr.Read()) {
tag = Tags_Populate(dr);
}
});
return tag;
}
public TagBE Tags_GetByNameAndType(string tagName, TagType type) {
TagBE tag = null;
Catalog.NewQuery(@" /* Tags_GetByNameAndType */
SELECT `tag_id`, `tag_name`, `tag_type`
FROM `tags`
WHERE `tag_name` = ?TAGNAME
AND `tag_type` = ?TAGTYPE;")
.With("TAGNAME", tagName)
.With("TAGTYPE", type)
.Execute(delegate(IDataReader dr) {
while(dr.Read()) {
tag = Tags_Populate(dr);
}
});
return tag;
}
public bool Tags_ValidateDefineTagMapping(TagBE tag) {
if(tag == null) {
throw new ArgumentNullException("tag");
}
if(tag.Type != TagType.DEFINE) {
throw new ArgumentException("Tag has to be of type DEFINE");
}
return Catalog.NewQuery(@" /* Tags_ValidateDefineTagMapping */
DELETE FROM tag_map WHERE tagmap_tag_id = ?TAGID AND (SELECT COUNT(*) FROM pages WHERE page_id = tagmap_page_id) = 0;
SELECT COUNT(*) FROM tag_map WHERE tagmap_tag_id = ?TAGID;")
.With("TAGID", tag.Id).ReadAsInt() > 0;
}
public IList<TagBE> Tags_GetByQuery(string partialName, TagType type, DateTime from, DateTime to) {
// retrieve the tags associated with a specified page id
List<TagBE> tags = new List<TagBE>();
bool hasWhere = false;
StringBuilder query = new StringBuilder();
query.Append(@" /* Tags_GetByQuery */
SELECT `tag_id`, `tag_name`, `tag_type`
FROM tags ");
if(!string.IsNullOrEmpty(partialName)) {
query.AppendFormat("WHERE tag_name LIKE '{0}%' ", DataCommand.MakeSqlSafe(partialName));
hasWhere = true;
}
if(type != TagType.ALL) {
if(hasWhere)
query.Append("AND ");
else
query.Append("WHERE ");
query.AppendFormat(" tag_type={0} ", (int)type);
hasWhere = true;
}
if((type == TagType.DATE) && (from != DateTime.MinValue)) {
if(hasWhere)
query.Append("AND ");
else
query.Append("WHERE ");
query.AppendFormat("tag_name >= '{0}' ", from.ToString("yyyy-MM-dd"));
hasWhere = true;
}
if((type == TagType.DATE) && (to != DateTime.MaxValue)) {
if(hasWhere)
query.Append("AND ");
else
query.Append("WHERE ");
query.AppendFormat("tag_name <= '{0}' ", to.ToString("yyyy-MM-dd"));
}
Catalog.NewQuery(query.ToString())
.Execute(delegate(IDataReader dr) {
while(dr.Read()) {
TagBE t = Tags_Populate(dr);
tags.Add(t);
}
});
return tags;
}
public Dictionary<uint, IList<PageBE>> Tags_GetRelatedPages(IList<uint> tagids) {
// retrieve a map of tag id to pages
// each define tag maps to a list of related pages and each text tag maps to its defining page (if one exists)
Dictionary<uint, IList<PageBE>> result = new Dictionary<uint, IList<PageBE>>();
if(0 < tagids.Count) {
string tagIdsText = string.Join(",", DbUtils.ConvertArrayToDelimittedString<uint>(',', tagids));
//TODO MaxM: This query is causing quite a bit of db load and needs to be optimized
Catalog.NewQuery(string.Format(@" /* Tags_GetRelatedPages */
SELECT requested_tag_id as tag_id, page_id, page_title, page_namespace, page_display_name
FROM pages
JOIN tag_map
ON page_id = tagmap_page_id
JOIN
(SELECT requestedtags.tag_id as requested_tag_id, tags.tag_id from tags
JOIN tags as requestedtags
ON tags.tag_name = requestedtags.tag_name
WHERE ( ((tags.tag_type = 3 AND requestedtags.tag_type = 0)
OR (tags.tag_type = 0 AND requestedtags.tag_type = 3))
AND requestedtags.tag_id IN ({0}))) relatedtags
ON tagmap_tag_id = tag_id;"
, tagIdsText))
.Execute(delegate(IDataReader dr) {
while(dr.Read()) {
// extract the tag to page mapping
uint tagid = DbUtils.Convert.To<UInt32>(dr["tag_id"], 0);
PageBE page = new PageBE();
page.ID = DbUtils.Convert.To<UInt32>(dr["page_id"], 0);
page.Title = DbUtils.TitleFromDataReader(dr, "page_namespace", "page_title", "page_display_name");
// add the mapping into the collection
IList<PageBE> relatedPages;
if(!result.TryGetValue(tagid, out relatedPages)) {
relatedPages = new List<PageBE>();
result[tagid] = relatedPages;
}
relatedPages.Add(page);
}
});
}
return result;
}
public uint Tags_Insert(TagBE tag) {
try {
return Catalog.NewQuery(@" /* Tags_Insert */
INSERT INTO tags (tag_name, tag_type) VALUES (?TAGNAME, ?TAGTYPE);
SELECT LAST_INSERT_ID();")
.With("TAGNAME", tag.Name)
.With("TAGTYPE", tag.Type)
.ReadAsUInt() ?? 0;
} catch(MySqlException e) {
if(e.Number == 1062) {
_log.DebugFormat("tag '{0}'({1}) already exists, returning 0",tag.Name,tag.Type);
return 0;
}
throw;
}
}
public void TagMapping_Delete(ulong pageId, IList<uint> tagids) {
// deletes the specified page to tag mappings and removes the tag if it is no longer used
if(0 < tagids.Count) {
string tagIdsText = string.Join(",", DbUtils.ConvertArrayToDelimittedString<uint>(',', tagids));
Catalog.NewQuery(String.Format(@" /* Tags_Delete */
DELETE FROM tag_map
WHERE tagmap_page_id = ?PAGEID AND tagmap_tag_id in ({0});
DELETE FROM tags
USING tags
LEFT JOIN tag_map tm ON tags.tag_id = tm.tagmap_tag_id
WHERE tm.tagmap_id IS NULL;", tagIdsText))
.With("PAGEID", pageId)
.Execute();
}
}
public void TagMapping_Insert(ulong pageId, uint tagId) {
Catalog.NewQuery(@" /* TagMapping_Insert */
REPLACE INTO tag_map (tagmap_page_id, tagmap_tag_id) VALUES (?PAGEID, ?TAGID);")
.With("PAGEID", pageId)
.With("TAGID", tagId)
.Execute();
}
private TagBE Tags_Populate(IDataReader dr) {
TagBE tag = new TagBE();
tag._Type = dr.Read<uint>("tag_type");
tag.Id = dr.Read<uint>("tag_id");
tag.Name = dr.Read<string>("tag_name");
return tag;
}
}
}
| |
/*
Copyright (c) 2004-2005 Jan Benda.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading.Tasks;
using System.Diagnostics;
namespace PHP.Core
{
#region PhpStream (partial) class
/// <summary>
/// Abstraction of streaming behavior for PHP.
/// PhpStreams are opened by StreamWrappers on a call to fopen().
/// </summary>
public abstract partial class PhpStream : PhpResource
{
public virtual bool CanReadWithoutLock()
{
return true;
}
public virtual bool CanWriteWithoutLock()
{
return true;
}
#region Stat (optional)
/// <include file='Doc/Streams.xml' path='docs/method[@name="Stat"]/*'/>
public virtual StatStruct Stat()
{
if (this.Wrapper != null)
{
return this.Wrapper.Stat(OpenedPath, StreamStatOptions.Empty, StreamContext.Default, true);
}
PhpException.Throw(PhpError.Warning, CoreResources.GetString("wrapper_op_unsupported", "Stat"));
StatStruct rv = new StatStruct();
rv.st_size = -1;
return rv;
}
#endregion
#region Opening utilities
/// <summary>
/// Merges the path with the current working directory
/// to get a canonicalized absolute pathname representing the same file.
/// </summary>
/// <remarks>
/// This method is an analogy of <c>main/safe_mode.c: php_checkuid</c>.
/// Looks for the file in the <c>include_path</c> and checks for <c>open_basedir</c> restrictions.
/// </remarks>
/// <param name="path">An absolute or relative path to a file.</param>
/// <param name="wrapper">The wrapper found for the specified file or <c>null</c> if the path resolution fails.</param>
/// <param name="mode">The checking mode of the <see cref="CheckAccess"/> method (file, directory etc.).</param>
/// <param name="options">Additional options for the <see cref="CheckAccess"/> method.</param>
/// <returns><c>true</c> if all the resolution and checking passed without an error, <b>false</b> otherwise.</returns>
/// <exception cref="PhpException">Security violation - when the target file
/// lays outside the tree defined by <c>open_basedir</c> configuration option.</exception>
public static bool ResolvePath(ref string path, out StreamWrapper wrapper, CheckAccessMode mode, CheckAccessOptions options)
{
// Path will contain the absolute path without file:// or the complete URL; filename is the relative path.
string filename, scheme = GetSchemeInternal(path, out filename);
wrapper = StreamWrapper.GetWrapper(scheme, (StreamOptions)options);
if (wrapper == null) return false;
if (wrapper.IsUrl)
{
// Note: path contains the whole URL, filename the same without the scheme:// portion.
// What to check more?
}
else if (scheme != "php")
{
try
{
// Filename contains the original path without the scheme:// portion, check for include path.
bool isInclude = false;
if ((options & CheckAccessOptions.UseIncludePath) > 0)
{
isInclude = CheckIncludePath(filename, ref path);
}
// Path will now contain an absolute path (either to an include or actual directory).
if (!isInclude)
{
path = Path.GetFullPath(Path.Combine(ScriptContext.CurrentContext.WorkingDirectory, filename));
}
}
catch (Exception)
{
if ((options & CheckAccessOptions.Quiet) == 0)
PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_filename_invalid",
FileSystemUtils.StripPassword(path)));
return false;
}
GlobalConfiguration global_config = Configuration.Global;
// Note: extensions check open_basedir too -> double check..
if (!global_config.SafeMode.IsPathAllowed(path))
{
if ((options & CheckAccessOptions.Quiet) == 0)
PhpException.Throw(PhpError.Warning, CoreResources.GetString("open_basedir_effect",
path, global_config.SafeMode.GetAllowedPathPrefixesJoin()));
return false;
}
// Replace all '/' with '\'.
// path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
Debug.Assert(
path.IndexOf(Path.AltDirectorySeparatorChar) == -1 ||
(Path.AltDirectorySeparatorChar == Path.DirectorySeparatorChar), // on Mono, so ignore it
string.Format("'{0}' should not contain '{1}' char.", path, Path.AltDirectorySeparatorChar));
// The file wrapper expects an absolute path w/o the scheme, others expect the scheme://url.
if (scheme != "file")
{
path = String.Format("{0}://{1}", scheme, path);
}
}
return true;
}
/// <summary>
/// Check if the path lays inside of the directory tree specified
/// by the <c>open_basedir</c> configuration option and return the resulting <paramref name="absolutePath"/>.
/// </summary>
/// <param name="relativePath">The filename to search for.</param>
/// <param name="absolutePath">The combined absolute path (either in the working directory
/// or in an include path wherever it has been found first).</param>
/// <returns><c>true</c> if the file was found in an include path.</returns>
private static bool CheckIncludePath(string relativePath, ref string absolutePath)
{
// Note: If the absolutePath exists, it overtakse the include_path search.
if (Path.IsPathRooted(relativePath)) return false;
if (File.Exists(absolutePath)) return false;
string paths = ScriptContext.CurrentContext.Config.FileSystem.IncludePaths;
if (paths == null) return false;
foreach (string s in paths.Split(new char[] { Path.PathSeparator }))
{
if ((s == null) || (s == string.Empty)) continue;
string abs = Path.GetFullPath(Path.Combine(s, relativePath));
if (File.Exists(abs))
{
absolutePath = abs;
return true;
}
}
return false;
}
/// <summary>
/// Performs all checks on a path passed to a PHP function.
/// </summary>
/// <remarks>
/// <para>
/// This method performs a check similar to <c>safe_mode.c: php_checkuid_ex()</c>
/// together with <c>open_basedir</c> check.
/// </para>
/// <para>
/// The <paramref name="filename"/> may be one of the following:
/// <list type="bullet">
/// <item>A relative path. The path is resolved regarding the <c>include_path</c> too if required
/// and checking continues as in the next case.</item>
/// <item>An absolute path. The file or directory is checked for existence and for access permissions<sup>1</sup>
/// according to the given <paramref name="mode"/>.</item>
/// </list>
/// <sup>1</sup> Regarding the <c>open_basedir</c> configuration option.
/// File access permissions are checked at the time of file manipulation
/// (opening, copying etc.).
/// </para>
/// </remarks>
/// <param name="filename">A resolved path. Must be an absolute path to a local file.</param>
/// <param name="mode">One of the <see cref="CheckAccessMode"/>.</param>
/// <param name="options"><c>true</c> to suppress error messages.</param>
/// <returns><c>true</c> if the function may continue with file access,
/// <c>false</c>to fail.</returns>
/// <exception cref="PhpException">If the file can not be accessed
/// and the <see cref="CheckAccessOptions.Quiet"/> is not set.</exception>
public static bool CheckAccess(string filename, CheckAccessMode mode, CheckAccessOptions options)
{
Debug.Assert(Path.IsPathRooted(filename));
string url = FileSystemUtils.StripPassword(filename);
bool quiet = (options & CheckAccessOptions.Quiet) > 0;
switch (mode)
{
case CheckAccessMode.FileMayExist:
break;
case CheckAccessMode.FileExists:
if (!File.Exists(filename))
{
if (!quiet) PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_not_exists", url));
return false;
}
break;
case CheckAccessMode.FileNotExists:
if (File.Exists(filename))
{
if (!quiet) PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_exists", url));
return false;
}
break;
case CheckAccessMode.FileOrDirectory:
if ((!Directory.Exists(filename)) && (!File.Exists(filename)))
{
if (!quiet) PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_path_not_exists", url));
return false;
}
break;
case CheckAccessMode.Directory:
if (!Directory.Exists(filename))
{
if (!quiet) PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_directory_not_exists", url));
return false;
}
break;
default:
Debug.Assert(false);
return false;
}
return true;
}
#endregion
}
#endregion
#region SocketStream class
/// <summary>
/// An implementation of <see cref="PhpStream"/> as an encapsulation
/// of System.Net.Socket transports.
/// </summary>
public class SocketStream : PhpStream
{
public override bool CanReadWithoutLock()
{
return socket.Available > 0 && (currentTask == null || currentTask.IsCompleted);
}
public override bool CanWriteWithoutLock()
{
return currentTask == null || currentTask.IsCompleted;
}
/// <summary>
/// The encapsulated network socket.
/// </summary>
protected Socket socket;
/// <summary>
/// Result of the last read/write operation.
/// </summary>
protected bool eof;
private bool isAsync;
private Task currentTask;
#region PhpStream overrides
public SocketStream(Socket socket, string openedPath, StreamContext context, bool isAsync = false)
: base(null, StreamAccessOptions.Read | StreamAccessOptions.Write, openedPath, context)
{
Debug.Assert(socket != null);
this.socket = socket;
this.IsWriteBuffered = false;
this.eof = false;
this.isAsync = isAsync;
this.IsReadBuffered = false;
}
/// <summary>
/// PhpResource.FreeManaged overridden to get rid of the contained context on Dispose.
/// </summary>
protected override void FreeManaged()
{
base.FreeManaged();
socket.Close();
socket = null;
}
#endregion
#region Raw byte access (mandatory)
/// <include file='Doc/Streams.xml' path='docs/method[@name="RawRead"]/*'/>
protected override int RawRead(byte[] buffer, int offset, int count)
{
if (currentTask != null)
currentTask.Wait();
try
{
int rv = socket.Receive(buffer, offset, count, SocketFlags.None);
eof = rv == 0;
return rv;
}
catch (Exception e)
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_socket_error", e.Message));
return 0;
}
}
/// <include file='Doc/Streams.xml' path='docs/method[@name="RawWrite"]/*'/>
protected override int RawWrite(byte[] buffer, int offset, int count)
{
try
{
if (isAsync)
{
if (currentTask != null)
currentTask.Wait();
currentTask = new Task(() =>
{
int rv = socket.Send(buffer, offset, count, SocketFlags.None);
eof = rv == 0;
});
currentTask.Start();
return count;
}
else
{
int rv = socket.Send(buffer, offset, count, SocketFlags.None);
eof = rv == 0;
return rv;
}
}
catch (Exception e)
{
PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_socket_error", e.Message));
return 0;
}
}
/// <include file='Doc/Streams.xml' path='docs/method[@name="RawFlush"]/*'/>
protected override bool RawFlush()
{
return true;
}
/// <include file='Doc/Streams.xml' path='docs/property[@name="RawEof"]/*'/>
protected override bool RawEof
{
get
{
return eof;
}
}
public override bool SetParameter(StreamParameterOptions option, object value)
{
if (option == StreamParameterOptions.ReadTimeout)
{
int timeout = (int)(Convert.ObjectToDouble(value) * 1000.0);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout);
return true;
}
return base.SetParameter(option, value);
}
#endregion
#region Conversion to .NET native Stream (NS)
/// <include file='Doc/Streams.xml' path='docs/property[@name="RawStream"]/*'/>
public override Stream RawStream
{
get
{
throw new NotImplementedException();
}
}
#endregion
new public static SocketStream GetValid(PhpResource handle)
{
SocketStream result = handle as SocketStream;
if (result == null)
PhpException.Throw(PhpError.Warning, CoreResources.GetString("invalid_socket_stream_resource"));
return result;
}
}
#endregion
}
| |
namespace System.Web.Services.Discovery {
internal class DiscoveryDocumentSerializationWriter : System.Xml.Serialization.XmlSerializationWriter {
public void Write10_discovery(object o) {
WriteStartDocument();
if (o == null) {
WriteNullTagLiteral(@"discovery", @"http://schemas.xmlsoap.org/disco/");
return;
}
TopLevelElement();
Write9_DiscoveryDocument(@"discovery", @"http://schemas.xmlsoap.org/disco/", ((global::System.Web.Services.Discovery.DiscoveryDocument)o), true, false);
}
void Write9_DiscoveryDocument(string n, string ns, global::System.Web.Services.Discovery.DiscoveryDocument o, bool isNullable, bool needType) {
if ((object)o == null) {
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType) {
System.Type t = o.GetType();
if (t == typeof(global::System.Web.Services.Discovery.DiscoveryDocument)) {
}
else {
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"DiscoveryDocument", @"http://schemas.xmlsoap.org/disco/");
{
global::System.Collections.IList a = (global::System.Collections.IList)o.@References;
if (a != null) {
for (int ia = 0; ia < ((System.Collections.ICollection)a).Count; ia++) {
global::System.Object ai = (global::System.Object)a[ia];
{
if (ai is global::System.Web.Services.Discovery.SchemaReference) {
Write7_SchemaReference(@"schemaRef", @"http://schemas.xmlsoap.org/disco/schema/", ((global::System.Web.Services.Discovery.SchemaReference)ai), false, false);
}
else if (ai is global::System.Web.Services.Discovery.ContractReference) {
Write5_ContractReference(@"contractRef", @"http://schemas.xmlsoap.org/disco/scl/", ((global::System.Web.Services.Discovery.ContractReference)ai), false, false);
}
else if (ai is global::System.Web.Services.Discovery.DiscoveryDocumentReference) {
Write3_DiscoveryDocumentReference(@"discoveryRef", @"http://schemas.xmlsoap.org/disco/", ((global::System.Web.Services.Discovery.DiscoveryDocumentReference)ai), false, false);
}
else if (ai is global::System.Web.Services.Discovery.SoapBinding) {
Write8_SoapBinding(@"soap", @"http://schemas.xmlsoap.org/disco/soap/", ((global::System.Web.Services.Discovery.SoapBinding)ai), false, false);
}
else {
if (ai != null) {
throw CreateUnknownTypeException(ai);
}
}
}
}
}
}
WriteEndElement(o);
}
void Write8_SoapBinding(string n, string ns, global::System.Web.Services.Discovery.SoapBinding o, bool isNullable, bool needType) {
if ((object)o == null) {
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType) {
System.Type t = o.GetType();
if (t == typeof(global::System.Web.Services.Discovery.SoapBinding)) {
}
else {
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"SoapBinding", @"http://schemas.xmlsoap.org/disco/soap/");
WriteAttribute(@"address", @"", ((global::System.String)o.@Address));
WriteAttribute(@"binding", @"", FromXmlQualifiedName(((global::System.Xml.XmlQualifiedName)o.@Binding)));
WriteEndElement(o);
}
void Write3_DiscoveryDocumentReference(string n, string ns, global::System.Web.Services.Discovery.DiscoveryDocumentReference o, bool isNullable, bool needType) {
if ((object)o == null) {
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType) {
System.Type t = o.GetType();
if (t == typeof(global::System.Web.Services.Discovery.DiscoveryDocumentReference)) {
}
else {
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"DiscoveryDocumentReference", @"http://schemas.xmlsoap.org/disco/");
WriteAttribute(@"ref", @"", ((global::System.String)o.@Ref));
WriteEndElement(o);
}
void Write5_ContractReference(string n, string ns, global::System.Web.Services.Discovery.ContractReference o, bool isNullable, bool needType) {
if ((object)o == null) {
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType) {
System.Type t = o.GetType();
if (t == typeof(global::System.Web.Services.Discovery.ContractReference)) {
}
else {
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"ContractReference", @"http://schemas.xmlsoap.org/disco/scl/");
WriteAttribute(@"ref", @"", ((global::System.String)o.@Ref));
WriteAttribute(@"docRef", @"", ((global::System.String)o.@DocRef));
WriteEndElement(o);
}
void Write7_SchemaReference(string n, string ns, global::System.Web.Services.Discovery.SchemaReference o, bool isNullable, bool needType) {
if ((object)o == null) {
if (isNullable) WriteNullTagLiteral(n, ns);
return;
}
if (!needType) {
System.Type t = o.GetType();
if (t == typeof(global::System.Web.Services.Discovery.SchemaReference)) {
}
else {
throw CreateUnknownTypeException(o);
}
}
WriteStartElement(n, ns, o, false, null);
if (needType) WriteXsiType(@"SchemaReference", @"http://schemas.xmlsoap.org/disco/schema/");
WriteAttribute(@"ref", @"", ((global::System.String)o.@Ref));
WriteAttribute(@"targetNamespace", @"", ((global::System.String)o.@TargetNamespace));
WriteEndElement(o);
}
protected override void InitCallbacks() {
}
}
internal class DiscoveryDocumentSerializationReader : System.Xml.Serialization.XmlSerializationReader {
public object Read10_discovery() {
object o = null;
Reader.MoveToContent();
if (Reader.NodeType == System.Xml.XmlNodeType.Element) {
if (((object) Reader.LocalName == (object)id1_discovery && (object) Reader.NamespaceURI == (object)id2_Item)) {
o = Read9_DiscoveryDocument(true, true);
}
else {
throw CreateUnknownNodeException();
}
}
else {
UnknownNode(null, @"http://schemas.xmlsoap.org/disco/:discovery");
}
return (object)o;
}
global::System.Web.Services.Discovery.DiscoveryDocument Read9_DiscoveryDocument(bool isNullable, bool checkType) {
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType) {
if (xsiType == null || ((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id3_DiscoveryDocument && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) {
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::System.Web.Services.Discovery.DiscoveryDocument o;
o = new global::System.Web.Services.Discovery.DiscoveryDocument();
global::System.Collections.IList a_0 = (global::System.Collections.IList)o.@References;
bool[] paramsRead = new bool[1];
while (Reader.MoveToNextAttribute()) {
if (!IsXmlnsAttribute(Reader.Name)) {
UnknownNode((object)o);
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement) {
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations0 = 0;
int readerCount0 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) {
if (Reader.NodeType == System.Xml.XmlNodeType.Element) {
if (((object) Reader.LocalName == (object)id4_discoveryRef && (object) Reader.NamespaceURI == (object)id2_Item)) {
if ((object)(a_0) == null) Reader.Skip(); else a_0.Add(Read3_DiscoveryDocumentReference(false, true));
}
else if (((object) Reader.LocalName == (object)id5_contractRef && (object) Reader.NamespaceURI == (object)id6_Item)) {
if ((object)(a_0) == null) Reader.Skip(); else a_0.Add(Read5_ContractReference(false, true));
}
else if (((object) Reader.LocalName == (object)id7_schemaRef && (object) Reader.NamespaceURI == (object)id8_Item)) {
if ((object)(a_0) == null) Reader.Skip(); else a_0.Add(Read7_SchemaReference(false, true));
}
else if (((object) Reader.LocalName == (object)id9_soap && (object) Reader.NamespaceURI == (object)id10_Item)) {
if ((object)(a_0) == null) Reader.Skip(); else a_0.Add(Read8_SoapBinding(false, true));
}
else {
UnknownNode((object)o, @"http://schemas.xmlsoap.org/disco/:discoveryRef, http://schemas.xmlsoap.org/disco/scl/:contractRef, http://schemas.xmlsoap.org/disco/schema/:schemaRef, http://schemas.xmlsoap.org/disco/soap/:soap");
}
}
else {
UnknownNode((object)o, @"http://schemas.xmlsoap.org/disco/:discoveryRef, http://schemas.xmlsoap.org/disco/scl/:contractRef, http://schemas.xmlsoap.org/disco/schema/:schemaRef, http://schemas.xmlsoap.org/disco/soap/:soap");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations0, ref readerCount0);
}
ReadEndElement();
return o;
}
global::System.Web.Services.Discovery.SoapBinding Read8_SoapBinding(bool isNullable, bool checkType) {
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType) {
if (xsiType == null || ((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id11_SoapBinding && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id10_Item)) {
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::System.Web.Services.Discovery.SoapBinding o;
o = new global::System.Web.Services.Discovery.SoapBinding();
bool[] paramsRead = new bool[2];
while (Reader.MoveToNextAttribute()) {
if (!paramsRead[0] && ((object) Reader.LocalName == (object)id12_address && (object) Reader.NamespaceURI == (object)id13_Item)) {
o.@Address = Reader.Value;
paramsRead[0] = true;
}
else if (!paramsRead[1] && ((object) Reader.LocalName == (object)id14_binding && (object) Reader.NamespaceURI == (object)id13_Item)) {
o.@Binding = ToXmlQualifiedName(Reader.Value);
paramsRead[1] = true;
}
else if (!IsXmlnsAttribute(Reader.Name)) {
UnknownNode((object)o, @":address, :binding");
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement) {
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations1 = 0;
int readerCount1 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) {
if (Reader.NodeType == System.Xml.XmlNodeType.Element) {
UnknownNode((object)o, @"");
}
else {
UnknownNode((object)o, @"");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations1, ref readerCount1);
}
ReadEndElement();
return o;
}
global::System.Web.Services.Discovery.SchemaReference Read7_SchemaReference(bool isNullable, bool checkType) {
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType) {
if (xsiType == null || ((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id15_SchemaReference && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id8_Item)) {
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::System.Web.Services.Discovery.SchemaReference o;
o = new global::System.Web.Services.Discovery.SchemaReference();
bool[] paramsRead = new bool[2];
while (Reader.MoveToNextAttribute()) {
if (!paramsRead[0] && ((object) Reader.LocalName == (object)id16_ref && (object) Reader.NamespaceURI == (object)id13_Item)) {
o.@Ref = Reader.Value;
paramsRead[0] = true;
}
else if (!paramsRead[1] && ((object) Reader.LocalName == (object)id17_targetNamespace && (object) Reader.NamespaceURI == (object)id13_Item)) {
o.@TargetNamespace = Reader.Value;
paramsRead[1] = true;
}
else if (!IsXmlnsAttribute(Reader.Name)) {
UnknownNode((object)o, @":ref, :targetNamespace");
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement) {
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations2 = 0;
int readerCount2 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) {
if (Reader.NodeType == System.Xml.XmlNodeType.Element) {
UnknownNode((object)o, @"");
}
else {
UnknownNode((object)o, @"");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations2, ref readerCount2);
}
ReadEndElement();
return o;
}
global::System.Web.Services.Discovery.ContractReference Read5_ContractReference(bool isNullable, bool checkType) {
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType) {
if (xsiType == null || ((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id18_ContractReference && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id6_Item)) {
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::System.Web.Services.Discovery.ContractReference o;
o = new global::System.Web.Services.Discovery.ContractReference();
bool[] paramsRead = new bool[2];
while (Reader.MoveToNextAttribute()) {
if (!paramsRead[0] && ((object) Reader.LocalName == (object)id16_ref && (object) Reader.NamespaceURI == (object)id13_Item)) {
o.@Ref = Reader.Value;
paramsRead[0] = true;
}
else if (!paramsRead[1] && ((object) Reader.LocalName == (object)id19_docRef && (object) Reader.NamespaceURI == (object)id13_Item)) {
o.@DocRef = Reader.Value;
paramsRead[1] = true;
}
else if (!IsXmlnsAttribute(Reader.Name)) {
UnknownNode((object)o, @":ref, :docRef");
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement) {
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations3 = 0;
int readerCount3 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) {
if (Reader.NodeType == System.Xml.XmlNodeType.Element) {
UnknownNode((object)o, @"");
}
else {
UnknownNode((object)o, @"");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations3, ref readerCount3);
}
ReadEndElement();
return o;
}
global::System.Web.Services.Discovery.DiscoveryDocumentReference Read3_DiscoveryDocumentReference(bool isNullable, bool checkType) {
System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null;
bool isNull = false;
if (isNullable) isNull = ReadNull();
if (checkType) {
if (xsiType == null || ((object) ((System.Xml.XmlQualifiedName)xsiType).Name == (object)id20_DiscoveryDocumentReference && (object) ((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)id2_Item)) {
}
else
throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType);
}
if (isNull) return null;
global::System.Web.Services.Discovery.DiscoveryDocumentReference o;
o = new global::System.Web.Services.Discovery.DiscoveryDocumentReference();
bool[] paramsRead = new bool[1];
while (Reader.MoveToNextAttribute()) {
if (!paramsRead[0] && ((object) Reader.LocalName == (object)id16_ref && (object) Reader.NamespaceURI == (object)id13_Item)) {
o.@Ref = Reader.Value;
paramsRead[0] = true;
}
else if (!IsXmlnsAttribute(Reader.Name)) {
UnknownNode((object)o, @":ref");
}
}
Reader.MoveToElement();
if (Reader.IsEmptyElement) {
Reader.Skip();
return o;
}
Reader.ReadStartElement();
Reader.MoveToContent();
int whileIterations4 = 0;
int readerCount4 = ReaderCount;
while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) {
if (Reader.NodeType == System.Xml.XmlNodeType.Element) {
UnknownNode((object)o, @"");
}
else {
UnknownNode((object)o, @"");
}
Reader.MoveToContent();
CheckReaderCount(ref whileIterations4, ref readerCount4);
}
ReadEndElement();
return o;
}
protected override void InitCallbacks() {
}
string id1_discovery;
string id4_discoveryRef;
string id19_docRef;
string id8_Item;
string id14_binding;
string id20_DiscoveryDocumentReference;
string id17_targetNamespace;
string id5_contractRef;
string id10_Item;
string id13_Item;
string id7_schemaRef;
string id3_DiscoveryDocument;
string id9_soap;
string id12_address;
string id16_ref;
string id11_SoapBinding;
string id18_ContractReference;
string id2_Item;
string id15_SchemaReference;
string id6_Item;
protected override void InitIDs() {
id1_discovery = Reader.NameTable.Add(@"discovery");
id4_discoveryRef = Reader.NameTable.Add(@"discoveryRef");
id19_docRef = Reader.NameTable.Add(@"docRef");
id8_Item = Reader.NameTable.Add(@"http://schemas.xmlsoap.org/disco/schema/");
id14_binding = Reader.NameTable.Add(@"binding");
id20_DiscoveryDocumentReference = Reader.NameTable.Add(@"DiscoveryDocumentReference");
id17_targetNamespace = Reader.NameTable.Add(@"targetNamespace");
id5_contractRef = Reader.NameTable.Add(@"contractRef");
id10_Item = Reader.NameTable.Add(@"http://schemas.xmlsoap.org/disco/soap/");
id13_Item = Reader.NameTable.Add(@"");
id7_schemaRef = Reader.NameTable.Add(@"schemaRef");
id3_DiscoveryDocument = Reader.NameTable.Add(@"DiscoveryDocument");
id9_soap = Reader.NameTable.Add(@"soap");
id12_address = Reader.NameTable.Add(@"address");
id16_ref = Reader.NameTable.Add(@"ref");
id11_SoapBinding = Reader.NameTable.Add(@"SoapBinding");
id18_ContractReference = Reader.NameTable.Add(@"ContractReference");
id2_Item = Reader.NameTable.Add(@"http://schemas.xmlsoap.org/disco/");
id15_SchemaReference = Reader.NameTable.Add(@"SchemaReference");
id6_Item = Reader.NameTable.Add(@"http://schemas.xmlsoap.org/disco/scl/");
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using FluentAssertions;
using IdentityServer.UnitTests.Common;
using IdentityServer4;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using IdentityServer4.Stores.Serialization;
using Xunit;
namespace IdentityServer.UnitTests.Stores.Default
{
public class DefaultPersistedGrantStoreTests
{
private InMemoryPersistedGrantStore _store = new InMemoryPersistedGrantStore();
private IAuthorizationCodeStore _codes;
private IRefreshTokenStore _refreshTokens;
private IReferenceTokenStore _referenceTokens;
private IUserConsentStore _userConsent;
private StubHandleGenerationService _stubHandleGenerationService = new StubHandleGenerationService();
private ClaimsPrincipal _user = new IdentityServerUser("123").CreatePrincipal();
public DefaultPersistedGrantStoreTests()
{
_codes = new DefaultAuthorizationCodeStore(_store,
new PersistentGrantSerializer(),
_stubHandleGenerationService,
TestLogger.Create<DefaultAuthorizationCodeStore>());
_refreshTokens = new DefaultRefreshTokenStore(_store,
new PersistentGrantSerializer(),
_stubHandleGenerationService,
TestLogger.Create<DefaultRefreshTokenStore>());
_referenceTokens = new DefaultReferenceTokenStore(_store,
new PersistentGrantSerializer(),
_stubHandleGenerationService,
TestLogger.Create<DefaultReferenceTokenStore>());
_userConsent = new DefaultUserConsentStore(_store,
new PersistentGrantSerializer(),
_stubHandleGenerationService,
TestLogger.Create<DefaultUserConsentStore>());
}
[Fact]
public async Task StoreAuthorizationCodeAsync_should_persist_grant()
{
var code1 = new AuthorizationCode()
{
ClientId = "test",
CreationTime = DateTime.UtcNow,
Lifetime = 10,
Subject = _user,
CodeChallenge = "challenge",
RedirectUri = "http://client/cb",
Nonce = "nonce",
RequestedScopes = new string[] { "scope1", "scope2" }
};
var handle = await _codes.StoreAuthorizationCodeAsync(code1);
var code2 = await _codes.GetAuthorizationCodeAsync(handle);
code1.ClientId.Should().Be(code2.ClientId);
code1.CreationTime.Should().Be(code2.CreationTime);
code1.Lifetime.Should().Be(code2.Lifetime);
code1.Subject.GetSubjectId().Should().Be(code2.Subject.GetSubjectId());
code1.CodeChallenge.Should().Be(code2.CodeChallenge);
code1.RedirectUri.Should().Be(code2.RedirectUri);
code1.Nonce.Should().Be(code2.Nonce);
code1.RequestedScopes.Should().BeEquivalentTo(code2.RequestedScopes);
}
[Fact]
public async Task RemoveAuthorizationCodeAsync_should_remove_grant()
{
var code1 = new AuthorizationCode()
{
ClientId = "test",
CreationTime = DateTime.UtcNow,
Lifetime = 10,
Subject = _user,
CodeChallenge = "challenge",
RedirectUri = "http://client/cb",
Nonce = "nonce",
RequestedScopes = new string[] { "scope1", "scope2" }
};
var handle = await _codes.StoreAuthorizationCodeAsync(code1);
await _codes.RemoveAuthorizationCodeAsync(handle);
var code2 = await _codes.GetAuthorizationCodeAsync(handle);
code2.Should().BeNull();
}
[Fact]
public async Task StoreRefreshTokenAsync_should_persist_grant()
{
var token1 = new RefreshToken()
{
CreationTime = DateTime.UtcNow,
Lifetime = 10,
AccessToken = new Token
{
ClientId = "client",
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Type = "type",
Claims = new List<Claim>
{
new Claim("sub", "123"),
new Claim("scope", "foo")
}
},
Version = 1
};
var handle = await _refreshTokens.StoreRefreshTokenAsync(token1);
var token2 = await _refreshTokens.GetRefreshTokenAsync(handle);
token1.ClientId.Should().Be(token2.ClientId);
token1.CreationTime.Should().Be(token2.CreationTime);
token1.Lifetime.Should().Be(token2.Lifetime);
token1.Subject.GetSubjectId().Should().Be(token2.Subject.GetSubjectId());
token1.Version.Should().Be(token2.Version);
token1.AccessToken.Audiences.Count.Should().Be(1);
token1.AccessToken.Audiences.First().Should().Be("aud");
token1.AccessToken.ClientId.Should().Be(token2.AccessToken.ClientId);
token1.AccessToken.CreationTime.Should().Be(token2.AccessToken.CreationTime);
token1.AccessToken.Type.Should().Be(token2.AccessToken.Type);
}
[Fact]
public async Task RemoveRefreshTokenAsync_should_remove_grant()
{
var token1 = new RefreshToken()
{
CreationTime = DateTime.UtcNow,
Lifetime = 10,
AccessToken = new Token
{
ClientId = "client",
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Type = "type",
Claims = new List<Claim>
{
new Claim("sub", "123"),
new Claim("scope", "foo")
}
},
Version = 1
};
var handle = await _refreshTokens.StoreRefreshTokenAsync(token1);
await _refreshTokens.RemoveRefreshTokenAsync(handle);
var token2 = await _refreshTokens.GetRefreshTokenAsync(handle);
token2.Should().BeNull();
}
[Fact]
public async Task RemoveRefreshTokenAsync_by_sub_and_client_should_remove_grant()
{
var token1 = new RefreshToken()
{
CreationTime = DateTime.UtcNow,
Lifetime = 10,
AccessToken = new Token
{
ClientId = "client",
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Type = "type",
Claims = new List<Claim>
{
new Claim("sub", "123"),
new Claim("scope", "foo")
}
},
Version = 1
};
var handle1 = await _refreshTokens.StoreRefreshTokenAsync(token1);
var handle2 = await _refreshTokens.StoreRefreshTokenAsync(token1);
await _refreshTokens.RemoveRefreshTokensAsync("123", "client");
var token2 = await _refreshTokens.GetRefreshTokenAsync(handle1);
token2.Should().BeNull();
token2 = await _refreshTokens.GetRefreshTokenAsync(handle2);
token2.Should().BeNull();
}
[Fact]
public async Task StoreReferenceTokenAsync_should_persist_grant()
{
var token1 = new Token()
{
ClientId = "client",
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Lifetime = 10,
Type = "type",
Claims = new List<Claim>
{
new Claim("sub", "123"),
new Claim("scope", "foo")
},
Version = 1
};
var handle = await _referenceTokens.StoreReferenceTokenAsync(token1);
var token2 = await _referenceTokens.GetReferenceTokenAsync(handle);
token1.ClientId.Should().Be(token2.ClientId);
token1.Audiences.Count.Should().Be(1);
token1.Audiences.First().Should().Be("aud");
token1.CreationTime.Should().Be(token2.CreationTime);
token1.Type.Should().Be(token2.Type);
token1.Lifetime.Should().Be(token2.Lifetime);
token1.Version.Should().Be(token2.Version);
}
[Fact]
public async Task RemoveReferenceTokenAsync_should_remove_grant()
{
var token1 = new Token()
{
ClientId = "client",
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Type = "type",
Claims = new List<Claim>
{
new Claim("sub", "123"),
new Claim("scope", "foo")
},
Version = 1
};
var handle = await _referenceTokens.StoreReferenceTokenAsync(token1);
await _referenceTokens.RemoveReferenceTokenAsync(handle);
var token2 = await _referenceTokens.GetReferenceTokenAsync(handle);
token2.Should().BeNull();
}
[Fact]
public async Task RemoveReferenceTokenAsync_by_sub_and_client_should_remove_grant()
{
var token1 = new Token()
{
ClientId = "client",
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Type = "type",
Claims = new List<Claim>
{
new Claim("sub", "123"),
new Claim("scope", "foo")
},
Version = 1
};
var handle1 = await _referenceTokens.StoreReferenceTokenAsync(token1);
var handle2 = await _referenceTokens.StoreReferenceTokenAsync(token1);
await _referenceTokens.RemoveReferenceTokensAsync("123", "client");
var token2 = await _referenceTokens.GetReferenceTokenAsync(handle1);
token2.Should().BeNull();
token2 = await _referenceTokens.GetReferenceTokenAsync(handle2);
token2.Should().BeNull();
}
[Fact]
public async Task StoreUserConsentAsync_should_persist_grant()
{
var consent1 = new Consent()
{
CreationTime = DateTime.UtcNow,
ClientId = "client",
SubjectId = "123",
Scopes = new string[] { "foo", "bar" }
};
await _userConsent.StoreUserConsentAsync(consent1);
var consent2 = await _userConsent.GetUserConsentAsync("123", "client");
consent2.ClientId.Should().Be(consent1.ClientId);
consent2.SubjectId.Should().Be(consent1.SubjectId);
consent2.Scopes.Should().BeEquivalentTo(new string[] { "bar", "foo" });
}
[Fact]
public async Task RemoveUserConsentAsync_should_remove_grant()
{
var consent1 = new Consent()
{
CreationTime = DateTime.UtcNow,
ClientId = "client",
SubjectId = "123",
Scopes = new string[] { "foo", "bar" }
};
await _userConsent.StoreUserConsentAsync(consent1);
await _userConsent.RemoveUserConsentAsync("123", "client");
var consent2 = await _userConsent.GetUserConsentAsync("123", "client");
consent2.Should().BeNull();
}
[Fact]
public async Task same_key_for_different_grant_types_should_not_interfere_with_each_other()
{
_stubHandleGenerationService.Handle = "key";
await _referenceTokens.StoreReferenceTokenAsync(new Token()
{
ClientId = "client1",
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Lifetime = 10,
Type = "type",
Claims = new List<Claim>
{
new Claim("sub", "123"),
new Claim("scope", "bar1"),
new Claim("scope", "bar2")
}
});
await _refreshTokens.StoreRefreshTokenAsync(new RefreshToken()
{
CreationTime = DateTime.UtcNow,
Lifetime = 20,
AccessToken = new Token
{
ClientId = "client1",
Audiences = { "aud" },
CreationTime = DateTime.UtcNow,
Type = "type",
Claims = new List<Claim>
{
new Claim("sub", "123"),
new Claim("scope", "baz1"),
new Claim("scope", "baz2")
}
},
Version = 1
});
await _codes.StoreAuthorizationCodeAsync(new AuthorizationCode()
{
ClientId = "client1",
CreationTime = DateTime.UtcNow,
Lifetime = 30,
Subject = _user,
CodeChallenge = "challenge",
RedirectUri = "http://client/cb",
Nonce = "nonce",
RequestedScopes = new string[] { "quux1", "quux2" }
});
(await _codes.GetAuthorizationCodeAsync("key")).Lifetime.Should().Be(30);
(await _refreshTokens.GetRefreshTokenAsync("key")).Lifetime.Should().Be(20);
(await _referenceTokens.GetReferenceTokenAsync("key")).Lifetime.Should().Be(10);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Framework.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using OSD = OpenMetaverse.StructuredData.OSD;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.Framework.Scenes
{
public delegate void RemoveKnownRegionsFromAvatarList(UUID avatarID, List<ulong> regionlst);
/// <summary>
/// Class that Region communications runs through
/// </summary>
public class SceneCommunicationService //one instance per region
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static string LogHeader = "[SCENE COMMUNICATION SERVICE]";
protected RegionInfo m_regionInfo;
protected Scene m_scene;
public void SetScene(Scene s)
{
m_scene = s;
m_regionInfo = s.RegionInfo;
}
public delegate void InformNeighbourThatRegionUpDelegate(INeighbourService nService, RegionInfo region, ulong regionhandle);
private void InformNeighborsThatRegionisUpCompleted(IAsyncResult iar)
{
InformNeighbourThatRegionUpDelegate icon = (InformNeighbourThatRegionUpDelegate)iar.AsyncState;
icon.EndInvoke(iar);
}
/// <summary>
/// Asynchronous call to information neighbouring regions that this region is up
/// </summary>
/// <param name="region"></param>
/// <param name="regionhandle"></param>
private void InformNeighboursThatRegionIsUpAsync(INeighbourService neighbourService, RegionInfo region, ulong regionhandle)
{
uint x = 0, y = 0;
Utils.LongToUInts(regionhandle, out x, out y);
GridRegion neighbour = null;
if (neighbourService != null)
neighbour = neighbourService.HelloNeighbour(regionhandle, region);
else
m_log.ErrorFormat("{0} No neighbour service provided for region {1} to inform neigbhours of status", LogHeader, m_scene.Name);
if (neighbour != null)
{
m_log.DebugFormat("{0} Region {1} successfully informed neighbour {2} at {3}-{4} that it is up",
LogHeader, m_scene.Name, neighbour.RegionName, Util.WorldToRegionLoc(x), Util.WorldToRegionLoc(y));
m_scene.EventManager.TriggerOnRegionUp(neighbour);
}
else
{
m_log.WarnFormat(
"[SCENE COMMUNICATION SERVICE]: Region {0} failed to inform neighbour at {1}-{2} that it is up.",
m_scene.Name, Util.WorldToRegionLoc(x), Util.WorldToRegionLoc(y));
}
}
public void InformNeighborsThatRegionisUp(INeighbourService neighbourService, RegionInfo region)
{
//m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending InterRegion Notification that region is up " + region.RegionName);
List<GridRegion> neighbours
= m_scene.GridService.GetNeighbours(m_scene.RegionInfo.ScopeID, m_scene.RegionInfo.RegionID);
List<GridRegion> onlineNeighbours = new List<GridRegion>();
foreach (GridRegion n in neighbours)
{
OpenSim.Framework.RegionFlags? regionFlags = n.RegionFlags;
// m_log.DebugFormat(
// "{0}: Region flags for {1} as seen by {2} are {3}",
// LogHeader, n.RegionName, m_scene.Name, regionFlags != null ? regionFlags.ToString() : "not present");
// Robust services before 2015-01-14 do not return the regionFlags information. In this case, we could
// make a separate RegionFlags call but this would involve a network call for each neighbour.
if (regionFlags != null)
{
if ((regionFlags & OpenSim.Framework.RegionFlags.RegionOnline) != 0)
onlineNeighbours.Add(n);
}
else
{
onlineNeighbours.Add(n);
}
}
m_log.DebugFormat(
"{0} Informing {1} neighbours that region {2} is up",
LogHeader, onlineNeighbours.Count, m_scene.Name);
foreach (GridRegion n in onlineNeighbours)
{
InformNeighbourThatRegionUpDelegate d = InformNeighboursThatRegionIsUpAsync;
d.BeginInvoke(neighbourService, region, n.RegionHandle,
InformNeighborsThatRegionisUpCompleted,
d);
}
}
public delegate void SendChildAgentDataUpdateDelegate(AgentPosition cAgentData, UUID scopeID, GridRegion dest);
/// <summary>
/// This informs all neighboring regions about the settings of it's child agent.
/// Calls an asynchronous method to do so.. so it doesn't lag the sim.
///
/// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc.
///
/// </summary>
private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, UUID scopeID, GridRegion dest)
{
//m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName);
try
{
m_scene.SimulationService.UpdateAgent(dest, cAgentData);
}
catch
{
// Ignore; we did our best
}
}
private void SendChildAgentDataUpdateCompleted(IAsyncResult iar)
{
SendChildAgentDataUpdateDelegate icon = (SendChildAgentDataUpdateDelegate)iar.AsyncState;
icon.EndInvoke(iar);
}
public void SendChildAgentDataUpdate(AgentPosition cAgentData, ScenePresence presence)
{
// m_log.DebugFormat(
// "[SCENE COMMUNICATION SERVICE]: Sending child agent position updates for {0} in {1}",
// presence.Name, m_scene.Name);
// This assumes that we know what our neighbors are.
try
{
uint x = 0, y = 0;
List<string> simulatorList = new List<string>();
foreach (ulong regionHandle in presence.KnownRegionHandles)
{
if (regionHandle != m_regionInfo.RegionHandle)
{
// we only want to send one update to each simulator; the simulator will
// hand it off to the regions where a child agent exists, this does assume
// that the region position is cached or performance will degrade
Util.RegionHandleToWorldLoc(regionHandle, out x, out y);
GridRegion dest = m_scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
if (dest == null)
continue;
if (!simulatorList.Contains(dest.ServerURI))
{
// we havent seen this simulator before, add it to the list
// and send it an update
simulatorList.Add(dest.ServerURI);
// Let move this to sync. Mono definitely does not like async networking.
m_scene.SimulationService.UpdateAgent(dest, cAgentData);
// Leaving this here as a reminder that we tried, and it sucks.
//SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync;
//d.BeginInvoke(cAgentData, m_regionInfo.ScopeID, dest,
// SendChildAgentDataUpdateCompleted,
// d);
}
}
}
}
catch (InvalidOperationException)
{
// We're ignoring a collection was modified error because this data gets old and outdated fast.
}
}
public delegate void SendCloseChildAgentDelegate(UUID agentID, ulong regionHandle);
/// <summary>
/// This Closes child agents on neighboring regions
/// Calls an asynchronous method to do so.. so it doesn't lag the sim.
/// </summary>
protected void SendCloseChildAgent(UUID agentID, ulong regionHandle, string auth_token)
{
// let's do our best, but there's not much we can do if the neighbour doesn't accept.
//m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID);
uint x = 0, y = 0;
Util.RegionHandleToWorldLoc(regionHandle, out x, out y);
GridRegion destination = m_scene.GridService.GetRegionByPosition(m_regionInfo.ScopeID, (int)x, (int)y);
if (destination == null)
{
m_log.DebugFormat(
"[SCENE COMMUNICATION SERVICE]: Sending close agent ID {0} FAIL, region with handle {1} not found", agentID, regionHandle);
return;
}
m_log.DebugFormat(
"[SCENE COMMUNICATION SERVICE]: Sending close agent ID {0} to {1}", agentID, destination.RegionName);
m_scene.SimulationService.CloseAgent(destination, agentID, auth_token);
}
/// <summary>
/// Closes a child agents in a collection of regions. Does so asynchronously
/// so that the caller doesn't wait.
/// </summary>
/// <param name="agentID"></param>
/// <param name="regionslst"></param>
public void SendCloseChildAgentConnections(UUID agentID, string auth_code, List<ulong> regionslst)
{
if (regionslst.Count == 0)
return;
// use a single thread job for all
Util.FireAndForget(o =>
{
foreach (ulong handle in regionslst)
{
SendCloseChildAgent(agentID, handle, auth_code);
}
}, null, "SceneCommunicationService.SendCloseChildAgentConnections");
}
public List<GridRegion> RequestNamedRegions(string name, int maxNumber)
{
return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber);
}
}
}
| |
//
// Copyright (c) 2004-2016 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.
//
#if !SILVERLIGHT && !MONO
namespace NLog.UnitTests.Targets
{
using System.Diagnostics;
using NLog.Config;
using NLog.Targets;
using System;
using System.Linq;
using Xunit;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using NLog.Layouts;
using Xunit.Extensions;
public class EventLogTargetTests : NLogTestBase
{
[Fact]
public void MaxMessageLengthShouldBe16384_WhenNotSpecifyAnyOption()
{
const int expectedMaxMessageLength = 16384;
LoggingConfiguration c = CreateConfigurationFromString(@"
<nlog ThrowExceptions='true'>
<targets>
<target type='EventLog' name='eventLog1' layout='${message}' />
</targets>
<rules>
<logger name='*' writeTo='eventLog1'>
</logger>
</rules>
</nlog>");
var eventLog1 = c.FindTargetByName<EventLogTarget>("eventLog1");
Assert.Equal(expectedMaxMessageLength, eventLog1.MaxMessageLength);
}
[Fact]
public void MaxMessageLengthShouldBeAsSpecifiedOption()
{
const int expectedMaxMessageLength = 1000;
LoggingConfiguration c = CreateConfigurationFromString(string.Format(@"
<nlog ThrowExceptions='true'>
<targets>
<target type='EventLog' name='eventLog1' layout='${{message}}' maxmessagelength='{0}' />
</targets>
<rules>
<logger name='*' writeTo='eventLog1'>
</logger>
</rules>
</nlog>", expectedMaxMessageLength));
var eventLog1 = c.FindTargetByName<EventLogTarget>("eventLog1");
Assert.Equal(expectedMaxMessageLength, eventLog1.MaxMessageLength);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void ConfigurationShouldThrowException_WhenMaxMessageLengthIsNegativeOrZero(int maxMessageLength)
{
string configrationText = string.Format(@"
<nlog ThrowExceptions='true'>
<targets>
<target type='EventLog' name='eventLog1' layout='${{message}}' maxmessagelength='{0}' />
</targets>
<rules>
<logger name='*' writeTo='eventLog1'>
</logger>
</rules>
</nlog>", maxMessageLength);
NLogConfigurationException ex = Assert.Throws<NLogConfigurationException>(() => CreateConfigurationFromString(configrationText));
Assert.Equal("MaxMessageLength cannot be zero or negative.", ex.InnerException.InnerException.Message);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void ShouldThrowException_WhenMaxMessageLengthSetNegativeOrZero(int maxMessageLength)
{
ArgumentException ex = Assert.Throws<ArgumentException>(() =>
{
var target = new EventLogTarget();
target.MaxMessageLength = maxMessageLength;
});
Assert.Equal("MaxMessageLength cannot be zero or negative.", ex.Message);
}
private void AssertMessageAndLogLevelForTruncatedMessages(LogLevel loglevel, EventLogEntryType expectedEventLogEntryType, string expectedMessage, Layout entryTypeLayout)
{
const int expectedEntryCount = 1;
var eventRecords = Write(loglevel, expectedEventLogEntryType, expectedMessage, entryTypeLayout, EventLogTargetOverflowAction.Truncate).ToList();
Assert.Equal(expectedEntryCount, eventRecords.Count);
AssertWrittenMessage(eventRecords, expectedMessage);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsTrace()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Trace, EventLogEntryType.Information, "TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsTrace", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsDebug()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Debug, EventLogEntryType.Information, "TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsDebug", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsInfo()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Info, EventLogEntryType.Information, "TruncatedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsInfo", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtWarningLevel_WhenNLogLevelIsWarn()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Warn, EventLogEntryType.Warning, "TruncatedMessagesShouldBeWrittenAtWarningLevel_WhenNLogLevelIsWarn", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsError()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Error, EventLogEntryType.Error, "TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsError", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsFatal()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Fatal, EventLogEntryType.Error, "TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsFatal", null);
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Warn, EventLogEntryType.SuccessAudit, "TruncatedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit", new SimpleLayout("SuccessAudit"));
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit_Uppercase()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Warn, EventLogEntryType.SuccessAudit, "TruncatedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit_Uppercase", new SimpleLayout("SUCCESSAUDIT"));
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtFailureAuditLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Debug, EventLogEntryType.FailureAudit, "TruncatedMessagesShouldBeWrittenAtFailureAuditLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit", new SimpleLayout("FailureAudit"));
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenEntryTypeLayoutSpecifiedAsError()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Debug, EventLogEntryType.Error, "TruncatedMessagesShouldBeWrittenAtErrorLevel_WhenEntryTypeLayoutSpecifiedAsError", new SimpleLayout("error"));
}
[Fact]
public void TruncatedMessagesShouldBeWrittenAtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied()
{
AssertMessageAndLogLevelForTruncatedMessages(LogLevel.Warn, EventLogEntryType.Warning, "TruncatedMessagesShouldBeWrittenAtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied", new SimpleLayout("fallback to auto determined"));
}
private void AssertMessageCountAndLogLevelForSplittedMessages(LogLevel loglevel, EventLogEntryType expectedEventLogEntryType, Layout entryTypeLayout)
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 2;
string messagePart1 = string.Join("", Enumerable.Repeat("l", maxMessageLength));
string messagePart2 = "this part must be splitted";
string testMessage = messagePart1 + messagePart2;
var entries = Write(loglevel, expectedEventLogEntryType, testMessage, entryTypeLayout, EventLogTargetOverflowAction.Split, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsTrace()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Trace, EventLogEntryType.Information, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsDebug()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Debug, EventLogEntryType.Information, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtInformationLevel_WhenNLogLevelIsInfo()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Info, EventLogEntryType.Information, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtWarningLevel_WhenNLogLevelIsWarn()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Warn, EventLogEntryType.Warning, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsError()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Error, EventLogEntryType.Error, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtErrorLevel_WhenNLogLevelIsFatal()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Fatal, EventLogEntryType.Error, null);
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtSuccessAuditLevel_WhenEntryTypeLayoutSpecifiedAsSuccessAudit()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Debug, EventLogEntryType.SuccessAudit, new SimpleLayout("SuccessAudit"));
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtFailureLevel_WhenEntryTypeLayoutSpecifiedAsFailureAudit()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Debug, EventLogEntryType.FailureAudit, new SimpleLayout("FailureAudit"));
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtErrorLevel_WhenEntryTypeLayoutSpecifiedAsError()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Debug, EventLogEntryType.Error, new SimpleLayout("error"));
}
[Fact]
public void SplittedMessagesShouldBeWrittenAtSpecifiedNLogLevel_WhenWrongEntryTypeLayoutSupplied()
{
AssertMessageCountAndLogLevelForSplittedMessages(LogLevel.Info, EventLogEntryType.Information, new SimpleLayout("wrong entry type level"));
}
[Fact]
public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowTruncate_TruncatesTheMessage()
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 1;
string expectedMessage = string.Join("", Enumerable.Repeat("t", maxMessageLength));
string expectedToTruncateMessage = " this part will be truncated";
string testMessage = expectedMessage + expectedToTruncateMessage;
var entries = Write(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Truncate, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
AssertWrittenMessage(entries, expectedMessage);
}
[Fact]
public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowTruncate_TheMessageIsNotTruncated()
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 1;
string expectedMessage = string.Join("", Enumerable.Repeat("t", maxMessageLength));
var entries = Write(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Truncate, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
AssertWrittenMessage(entries, expectedMessage);
}
[Fact]
public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowSplitEntries_TheMessageShouldBeSplitted()
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 5;
string messagePart1 = string.Join("", Enumerable.Repeat("a", maxMessageLength));
string messagePart2 = string.Join("", Enumerable.Repeat("b", maxMessageLength));
string messagePart3 = string.Join("", Enumerable.Repeat("c", maxMessageLength));
string messagePart4 = string.Join("", Enumerable.Repeat("d", maxMessageLength));
string messagePart5 = "this part must be splitted too";
string testMessage = messagePart1 + messagePart2 + messagePart3 + messagePart4 + messagePart5;
var entries = Write(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Split, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
AssertWrittenMessage(entries, messagePart1);
AssertWrittenMessage(entries, messagePart2);
AssertWrittenMessage(entries, messagePart3);
AssertWrittenMessage(entries, messagePart4);
AssertWrittenMessage(entries, messagePart5);
}
[Fact]
public void WriteEventLogEntryEqual2MaxMessageLengthWithOverflowSplitEntries_TheMessageShouldBeSplittedInTwoChunk()
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 2;
string messagePart1 = string.Join("", Enumerable.Repeat("a", maxMessageLength));
string messagePart2 = string.Join("", Enumerable.Repeat("b", maxMessageLength));
string testMessage = messagePart1 + messagePart2;
var entries = Write(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Split, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
AssertWrittenMessage(entries, messagePart1);
AssertWrittenMessage(entries, messagePart2);
}
[Fact]
public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowSplitEntries_TheMessageIsNotSplit()
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 1;
string expectedMessage = string.Join("", Enumerable.Repeat("a", maxMessageLength));
var entries = Write(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Split, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
AssertWrittenMessage(entries, expectedMessage);
}
[Fact]
public void WriteEventLogEntryEqualToMaxMessageLengthWithOverflowDiscard_TheMessageIsWritten()
{
const int maxMessageLength = 16384;
const int expectedEntryCount = 1;
string expectedMessage = string.Join("", Enumerable.Repeat("a", maxMessageLength));
var entries = Write(LogLevel.Info, EventLogEntryType.Information, expectedMessage, null, EventLogTargetOverflowAction.Discard, maxMessageLength).ToList();
Assert.Equal(expectedEntryCount, entries.Count);
AssertWrittenMessage(entries, expectedMessage);
}
[Fact]
public void WriteEventLogEntryLargerThanMaxMessageLengthWithOverflowDiscard_TheMessageIsNotWritten()
{
const int maxMessageLength = 16384;
string messagePart1 = string.Join("", Enumerable.Repeat("a", maxMessageLength));
string messagePart2 = "b";
string testMessage = messagePart1 + messagePart2;
bool wasWritten = Write(LogLevel.Info, EventLogEntryType.Information, testMessage, null, EventLogTargetOverflowAction.Discard, maxMessageLength).Any();
Assert.False(wasWritten);
}
[Fact]
public void WriteEventLogEntryWithDynamicSource()
{
const int maxMessageLength = 10;
string expectedMessage = string.Join("", Enumerable.Repeat("a", maxMessageLength));
var target = CreateEventLogTarget(null, "NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Split, maxMessageLength);
target.Layout = new SimpleLayout("${message}");
target.Source = new SimpleLayout("${event-properties:item=DynamicSource}");
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
var logger = LogManager.GetLogger("WriteEventLogEntry");
var sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N");
var logEvent = CreateLogEventWithDynamicSource(expectedMessage, LogLevel.Trace, "DynamicSource", sourceName);
logger.Log(logEvent);
var eventLog = new EventLog(target.Log);
var entries = GetEventRecords(eventLog.Log).ToList();
entries = entries.Where(a => a.ProviderName == sourceName).ToList();
Assert.Equal(1, entries.Count);
AssertWrittenMessage(entries, expectedMessage);
sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N");
expectedMessage = string.Join("", Enumerable.Repeat("b", maxMessageLength));
logEvent = CreateLogEventWithDynamicSource(expectedMessage, LogLevel.Trace, "DynamicSource", sourceName);
logger.Log(logEvent);
entries = GetEventRecords(eventLog.Log).ToList();
entries = entries.Where(a => a.ProviderName == sourceName).ToList();
Assert.Equal(1, entries.Count);
AssertWrittenMessage(entries, expectedMessage);
}
private static IEnumerable<EventRecord> Write(LogLevel logLevel, EventLogEntryType expectedEventLogEntryType, string logMessage, Layout entryType = null, EventLogTargetOverflowAction overflowAction = EventLogTargetOverflowAction.Truncate, int maxMessageLength = 16384)
{
var target = CreateEventLogTarget(entryType, "NLog.UnitTests" + Guid.NewGuid().ToString("N"), overflowAction, maxMessageLength);
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
var logger = LogManager.GetLogger("WriteEventLogEntry");
logger.Log(logLevel, logMessage);
var eventLog = new EventLog(target.Log);
var entries = GetEventRecords(eventLog.Log).ToList();
var expectedSource = target.GetFixedSource();
var filteredEntries = entries.Where(entry =>
entry.ProviderName == expectedSource &&
HasEntryType(entry, expectedEventLogEntryType)
);
if (overflowAction == EventLogTargetOverflowAction.Discard && logMessage.Length > maxMessageLength)
{
Assert.False(filteredEntries.Any(), string.Format("No message is expected. But {0} message(s) found entry of type '{1}' from source '{2}'.", filteredEntries.Count(), expectedEventLogEntryType, expectedSource));
}
else
{
Assert.True(filteredEntries.Any(), string.Format("Failed to find entry of type '{0}' from source '{1}'", expectedEventLogEntryType, expectedSource));
}
return filteredEntries;
}
private void AssertWrittenMessage(IEnumerable<EventRecord> eventLogs, string expectedMessage)
{
var messages = eventLogs.Where(entry => entry.Properties.Any(prop => Convert.ToString(prop.Value) == expectedMessage));
Assert.True(messages.Any(), string.Format("Event records has not the expected message: '{0}'", expectedMessage));
}
private static EventLogTarget CreateEventLogTarget(Layout entryType, string sourceName, EventLogTargetOverflowAction overflowAction, int maxMessageLength)
{
var target = new EventLogTarget();
//The Log to write to is intentionally lower case!!
target.Log = "application";
// set the source explicitly to prevent random AppDomain name being used as the source name
target.Source = sourceName;
//Be able to check message length and content, the Layout is intentionally only ${message}.
target.Layout = new SimpleLayout("${message}");
if (entryType != null)
{
//set only when not default
target.EntryType = entryType;
}
target.OnOverflow = overflowAction;
target.MaxMessageLength = maxMessageLength;
return target;
}
private LogEventInfo CreateLogEventWithDynamicSource(string message, LogLevel level, string propertyKey, string proertyValue)
{
var logEvent = new LogEventInfo();
logEvent.Message = message;
logEvent.Level = level;
logEvent.Properties[propertyKey] = proertyValue;
return logEvent;
}
private static IEnumerable<EventRecord> GetEventRecords(string logName)
{
var query = new EventLogQuery(logName, PathType.LogName) { ReverseDirection = true };
using (var reader = new EventLogReader(query))
for (var eventInstance = reader.ReadEvent(); eventInstance != null; eventInstance = reader.ReadEvent())
yield return eventInstance;
}
private static bool HasEntryType(EventRecord eventRecord, EventLogEntryType entryType)
{
var keywords = (StandardEventKeywords)(eventRecord.Keywords ?? 0);
var level = (StandardEventLevel)(eventRecord.Level ?? 0);
bool isClassicEvent = keywords.HasFlag(StandardEventKeywords.EventLogClassic);
switch (entryType)
{
case EventLogEntryType.Error:
return isClassicEvent && level == StandardEventLevel.Error;
case EventLogEntryType.Warning:
return isClassicEvent && level == StandardEventLevel.Warning;
case EventLogEntryType.Information:
return isClassicEvent && level == StandardEventLevel.Informational;
case EventLogEntryType.SuccessAudit:
return keywords.HasFlag(StandardEventKeywords.AuditSuccess);
case EventLogEntryType.FailureAudit:
return keywords.HasFlag(StandardEventKeywords.AuditFailure);
}
return false;
}
}
}
#endif
| |
using Discord.Commands.Builders;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace Discord.Commands
{
[DebuggerDisplay("{Name,nq}")]
public class CommandInfo
{
private static readonly System.Reflection.MethodInfo _convertParamsMethod = typeof(CommandInfo).GetTypeInfo().GetDeclaredMethod(nameof(ConvertParamsList));
private static readonly ConcurrentDictionary<Type, Func<IEnumerable<object>, object>> _arrayConverters = new ConcurrentDictionary<Type, Func<IEnumerable<object>, object>>();
private readonly Func<ICommandContext, object[], IServiceProvider, CommandInfo, Task> _action;
public ModuleInfo Module { get; }
public string Name { get; }
public string Summary { get; }
public string Remarks { get; }
public int Priority { get; }
public bool HasVarArgs { get; }
public RunMode RunMode { get; }
public IReadOnlyList<string> Aliases { get; }
public IReadOnlyList<ParameterInfo> Parameters { get; }
public IReadOnlyList<PreconditionAttribute> Preconditions { get; }
public IReadOnlyList<Attribute> Attributes { get; }
internal CommandInfo(CommandBuilder builder, ModuleInfo module, CommandService service)
{
Module = module;
Name = builder.Name;
Summary = builder.Summary;
Remarks = builder.Remarks;
RunMode = (builder.RunMode == RunMode.Default ? service._defaultRunMode : builder.RunMode);
Priority = builder.Priority;
Aliases = module.Aliases
.Permutate(builder.Aliases, (first, second) =>
{
if (first == "")
return second;
else if (second == "")
return first;
else
return first + service._separatorChar + second;
})
.Select(x => service._caseSensitive ? x : x.ToLowerInvariant())
.ToImmutableArray();
Preconditions = builder.Preconditions.ToImmutableArray();
Attributes = builder.Attributes.ToImmutableArray();
Parameters = builder.Parameters.Select(x => x.Build(this)).ToImmutableArray();
HasVarArgs = builder.Parameters.Count > 0 ? builder.Parameters[builder.Parameters.Count - 1].IsMultiple : false;
_action = builder.Callback;
}
public async Task<PreconditionResult> CheckPreconditionsAsync(ICommandContext context, IServiceProvider services = null)
{
services = services ?? EmptyServiceProvider.Instance;
async Task<PreconditionResult> CheckGroups(IEnumerable<PreconditionAttribute> preconditions, string type)
{
foreach (IGrouping<string, PreconditionAttribute> preconditionGroup in preconditions.GroupBy(p => p.Group, StringComparer.Ordinal))
{
if (preconditionGroup.Key == null)
{
foreach (PreconditionAttribute precondition in preconditionGroup)
{
var result = await precondition.CheckPermissions(context, this, services).ConfigureAwait(false);
if (!result.IsSuccess)
return result;
}
}
else
{
var results = new List<PreconditionResult>();
foreach (PreconditionAttribute precondition in preconditionGroup)
results.Add(await precondition.CheckPermissions(context, this, services).ConfigureAwait(false));
if (!results.Any(p => p.IsSuccess))
return PreconditionGroupResult.FromError($"{type} precondition group {preconditionGroup.Key} failed.", results);
}
}
return PreconditionGroupResult.FromSuccess();
}
var moduleResult = await CheckGroups(Module.Preconditions, "Module");
if (!moduleResult.IsSuccess)
return moduleResult;
var commandResult = await CheckGroups(Preconditions, "Command");
if (!commandResult.IsSuccess)
return commandResult;
return PreconditionResult.FromSuccess();
}
public async Task<ParseResult> ParseAsync(ICommandContext context, int startIndex, SearchResult searchResult, PreconditionResult preconditionResult = null, IServiceProvider services = null)
{
services = services ?? EmptyServiceProvider.Instance;
if (!searchResult.IsSuccess)
return ParseResult.FromError(searchResult);
if (preconditionResult != null && !preconditionResult.IsSuccess)
return ParseResult.FromError(preconditionResult);
string input = searchResult.Text.Substring(startIndex);
return await CommandParser.ParseArgs(this, context, services, input, 0).ConfigureAwait(false);
}
public Task<IResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services)
{
if (!parseResult.IsSuccess)
return Task.FromResult((IResult)ExecuteResult.FromError(parseResult));
var argList = new object[parseResult.ArgValues.Count];
for (int i = 0; i < parseResult.ArgValues.Count; i++)
{
if (!parseResult.ArgValues[i].IsSuccess)
return Task.FromResult((IResult)ExecuteResult.FromError(parseResult.ArgValues[i]));
argList[i] = parseResult.ArgValues[i].Values.First().Value;
}
var paramList = new object[parseResult.ParamValues.Count];
for (int i = 0; i < parseResult.ParamValues.Count; i++)
{
if (!parseResult.ParamValues[i].IsSuccess)
return Task.FromResult((IResult)ExecuteResult.FromError(parseResult.ParamValues[i]));
paramList[i] = parseResult.ParamValues[i].Values.First().Value;
}
return ExecuteAsync(context, argList, paramList, services);
}
public async Task<IResult> ExecuteAsync(ICommandContext context, IEnumerable<object> argList, IEnumerable<object> paramList, IServiceProvider services)
{
services = services ?? EmptyServiceProvider.Instance;
try
{
object[] args = GenerateArgs(argList, paramList);
for (int position = 0; position < Parameters.Count; position++)
{
var parameter = Parameters[position];
object argument = args[position];
var result = await parameter.CheckPreconditionsAsync(context, argument, services).ConfigureAwait(false);
if (!result.IsSuccess)
return ExecuteResult.FromError(result);
}
switch (RunMode)
{
case RunMode.Sync: //Always sync
return await ExecuteAsyncInternal(context, args, services).ConfigureAwait(false);
case RunMode.Async: //Always async
var t2 = Task.Run(async () =>
{
await ExecuteAsyncInternal(context, args, services).ConfigureAwait(false);
});
break;
}
return ExecuteResult.FromSuccess();
}
catch (Exception ex)
{
return ExecuteResult.FromError(ex);
}
}
private async Task<IResult> ExecuteAsyncInternal(ICommandContext context, object[] args, IServiceProvider services)
{
await Module.Service._cmdLogger.DebugAsync($"Executing {GetLogText(context)}").ConfigureAwait(false);
try
{
var task = _action(context, args, services, this);
if (task is Task<IResult> resultTask)
{
var result = await resultTask.ConfigureAwait(false);
await Module.Service._commandExecutedEvent.InvokeAsync(this, context, result).ConfigureAwait(false);
if (result is RuntimeResult execResult)
return execResult;
}
else if (task is Task<ExecuteResult> execTask)
{
var result = await execTask.ConfigureAwait(false);
await Module.Service._commandExecutedEvent.InvokeAsync(this, context, result).ConfigureAwait(false);
return result;
}
else
await task.ConfigureAwait(false);
var executeResult = ExecuteResult.FromSuccess();
await Module.Service._commandExecutedEvent.InvokeAsync(this, context, executeResult).ConfigureAwait(false);
return executeResult;
}
catch (Exception ex)
{
var originalEx = ex;
while (ex is TargetInvocationException) //Happens with void-returning commands
ex = ex.InnerException;
var wrappedEx = new CommandException(this, context, ex);
await Module.Service._cmdLogger.ErrorAsync(wrappedEx).ConfigureAwait(false);
if (Module.Service._throwOnError)
{
if (ex == originalEx)
throw;
else
ExceptionDispatchInfo.Capture(ex).Throw();
}
return ExecuteResult.FromError(CommandError.Exception, ex.Message);
}
finally
{
await Module.Service._cmdLogger.VerboseAsync($"Executed {GetLogText(context)}").ConfigureAwait(false);
}
}
private object[] GenerateArgs(IEnumerable<object> argList, IEnumerable<object> paramsList)
{
int argCount = Parameters.Count;
var array = new object[Parameters.Count];
if (HasVarArgs)
argCount--;
int i = 0;
foreach (object arg in argList)
{
if (i == argCount)
throw new InvalidOperationException("Command was invoked with too many parameters");
array[i++] = arg;
}
if (i < argCount)
throw new InvalidOperationException("Command was invoked with too few parameters");
if (HasVarArgs)
{
var func = _arrayConverters.GetOrAdd(Parameters[Parameters.Count - 1].Type, t =>
{
var method = _convertParamsMethod.MakeGenericMethod(t);
return (Func<IEnumerable<object>, object>)method.CreateDelegate(typeof(Func<IEnumerable<object>, object>));
});
array[i] = func(paramsList);
}
return array;
}
private static T[] ConvertParamsList<T>(IEnumerable<object> paramsList)
=> paramsList.Cast<T>().ToArray();
internal string GetLogText(ICommandContext context)
{
if (context.Guild != null)
return $"\"{Name}\" for {context.User} in {context.Guild}/{context.Channel}";
else
return $"\"{Name}\" for {context.User} in {context.Channel}";
}
}
}
| |
//
// SocketAbstractions/UnmanagedSocket.cs: Provides a wrapper around an unmanaged
// socket.
//
// Author:
// Brian Nickel ([email protected])
//
// Copyright (C) 2007 Brian Nickel
//
// 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 Mono.Unix.Native;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Socket = Mono.FastCgi.Socket;
namespace Mono.WebServer.FastCgi.Sockets {
class UnmanagedSocket : Socket {
[DllImport ("libc", SetLastError=true, EntryPoint="close")]
extern static int close (IntPtr s);
readonly IntPtr socket;
bool connected;
public override IntPtr Handle {
get { return socket; }
}
unsafe public UnmanagedSocket (IntPtr socket)
{
if (!supports_libc)
throw new NotSupportedException (Strings.UnmanagedSocket_NotSupported);
if ((int) socket < 0)
throw new ArgumentException ("Invalid socket.",
"socket");
var address = new byte [1024];
int size = 1024;
fixed (byte* ptr = address)
if (getsockname (socket, ptr, ref size) != 0)
throw GetException ();
this.socket = socket;
}
unsafe public UnmanagedSocket (IntPtr socket, bool connected)
{
if (!supports_libc)
throw new NotSupportedException (Strings.UnmanagedSocket_NotSupported);
if ((int) socket < 0)
throw new ArgumentException ("Invalid socket.", "socket");
var address = new byte [1024];
int size = 1024;
fixed (byte* ptr = address)
if (getsockname (socket, ptr, ref size) != 0)
throw GetException ();
this.socket = socket;
this.connected = connected;
}
public override void Connect ()
{
throw new NotSupportedException ();
}
public override void Close ()
{
connected = false;
if (shutdown (socket, (int) System.Net.Sockets.SocketShutdown.Both) != 0)
throw GetException ();
/* lighttpd makes the assumption that the FastCGI handler will close the unix socket */
close(socket);
}
unsafe public override int Receive (byte [] buffer, int offset,
int size,
System.Net.Sockets.SocketFlags flags)
{
if (!connected)
return 0;
int value;
fixed (byte* ptr = buffer)
value = recv (socket, ptr + offset, size, (int) flags);
if (value >= 0)
return value;
connected = false;
throw GetException ();
}
unsafe public override int Send (byte [] data, int offset,
int size,
System.Net.Sockets.SocketFlags flags)
{
if (!connected)
return 0;
int value;
fixed (byte* ptr = data)
value = send (socket, ptr + offset, size,
(int) flags);
if (value >= 0)
return value;
connected = false;
throw GetException ();
}
public override void Listen (int backlog)
{
listen (socket, backlog);
}
public override IAsyncResult BeginAccept (AsyncCallback callback,
object state)
{
var s = new SockAccept (socket, callback, state);
ThreadPool.QueueUserWorkItem (s.Run);
return s;
}
public override Socket EndAccept (IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
var s = asyncResult as SockAccept;
if (s == null || s.Socket != socket)
throw new ArgumentException (
"Result was not produced by current instance.",
"asyncResult");
if (!s.IsCompleted)
s.AsyncWaitHandle.WaitOne ();
if (s.Except != null)
throw s.Except;
return new UnmanagedSocket (s.Accepted) {connected = true};
}
public override bool Connected {
get {return connected;}
}
[DllImport ("libc", SetLastError=true, EntryPoint="shutdown")]
extern static int shutdown (IntPtr s, int how);
[DllImport ("libc", SetLastError=true, EntryPoint="send")]
unsafe extern static int send (IntPtr s, byte *buffer, int len,
int flags);
[DllImport ("libc", SetLastError=true, EntryPoint="recv")]
unsafe extern static int recv (IntPtr s, byte *buffer, int len,
int flags);
[DllImport ("libc", SetLastError=true, EntryPoint="accept")]
unsafe extern static IntPtr accept (IntPtr s, byte *addr,
ref int addrlen);
[DllImport("libc", SetLastError=true, EntryPoint="getsockname")]
unsafe static extern int getsockname(IntPtr s, byte *addr,
ref int namelen);
[DllImport ("libc", SetLastError=true, EntryPoint="listen")]
extern static int listen (IntPtr s, int count);
class SockAccept : IAsyncResult
{
bool completed;
readonly object waithandle_lock = new object ();
ManualResetEvent waithandle;
readonly AsyncCallback callback;
readonly object state;
public readonly IntPtr Socket;
public IntPtr Accepted;
public System.Net.Sockets.SocketException Except;
public SockAccept (IntPtr socket, AsyncCallback callback,
object state)
{
Socket = socket;
this.callback = callback;
this.state = state;
}
unsafe public void Run (object state)
{
var address = new byte [1024];
int size = 1024;
Errno errno;
fixed (byte* ptr = address)
do {
Accepted = accept (Socket, ptr,
ref size);
errno = Stdlib.GetLastError ();
} while ((int) Accepted == -1 &&
errno == Errno.EINTR);
if ((int) Accepted == -1)
Except = GetException (errno);
completed = true;
if (waithandle != null)
waithandle.Set ();
if (callback != null)
callback (this);
}
public bool IsCompleted {
get {return completed;}
}
public bool CompletedSynchronously {
get {return false;}
}
public WaitHandle AsyncWaitHandle {
get {
lock (waithandle_lock)
if (waithandle == null)
waithandle = new ManualResetEvent (completed);
return waithandle;
}
}
public object AsyncState {
get {return state;}
}
}
static readonly bool supports_libc;
static UnmanagedSocket ()
{
try {
string os = File.ReadAllText("/proc/sys/kernel/ostype");
supports_libc = os.StartsWith ("Linux");
} catch {
}
}
static System.Net.Sockets.SocketException GetException ()
{
return GetException (Stdlib.GetLastError ());
}
static System.Net.Sockets.SocketException GetException (Errno error)
{
if (error == Errno.EAGAIN ||
error == Errno.EWOULDBLOCK) // WSAEWOULDBLOCK
return new System.Net.Sockets.SocketException (10035);
if (error == Errno.EBADF ||
error == Errno.ENOTSOCK) // WSAENOTSOCK
return new System.Net.Sockets.SocketException (10038);
if (error == Errno.ECONNABORTED) // WSAENETDOWN
return new System.Net.Sockets.SocketException (10050);
if (error == Errno.EINVAL) // WSAEINVAL
return new System.Net.Sockets.SocketException (10022);
return new System.Net.Sockets.SocketException ();
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Collections;
using System.Linq;
namespace NLog.Internal
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Text;
using NLog.Common;
using NLog.Conditions;
using NLog.Config;
using NLog.Layouts;
using NLog.Targets;
/// <summary>
/// Reflection helpers for accessing properties.
/// </summary>
internal static class PropertyHelper
{
private static Dictionary<Type, Dictionary<string, PropertyInfo>> parameterInfoCache = new Dictionary<Type, Dictionary<string, PropertyInfo>>();
/// <summary>
/// Set value parsed from string.
/// </summary>
/// <param name="obj">object instance to set with property <paramref name="propertyName"/></param>
/// <param name="propertyName">name of the property on <paramref name="obj"/></param>
/// <param name="value">The value to be parsed.</param>
/// <param name="configurationItemFactory"></param>
internal static void SetPropertyFromString(object obj, string propertyName, string value, ConfigurationItemFactory configurationItemFactory)
{
InternalLogger.Debug("Setting '{0}.{1}' to '{2}'", obj.GetType().Name, propertyName, value);
PropertyInfo propInfo;
if (!TryGetPropertyInfo(obj, propertyName, out propInfo))
{
throw new NotSupportedException("Parameter " + propertyName + " not supported on " + obj.GetType().Name);
}
try
{
if (propInfo.IsDefined(typeof(ArrayParameterAttribute), false))
{
throw new NotSupportedException("Parameter " + propertyName + " of " + obj.GetType().Name + " is an array and cannot be assigned a scalar value.");
}
object newValue;
Type propertyType = propInfo.PropertyType;
propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType;
if (!(TryNLogSpecificConversion(propertyType, value, out newValue, configurationItemFactory)
|| TryGetEnumValue(propertyType, value, out newValue, true)
|| TryImplicitConversion(propertyType, value, out newValue)
|| TrySpecialConversion(propertyType, value, out newValue)
|| TryFlatListConversion(propertyType, value, out newValue)
|| TryTypeConverterConversion(propertyType, value, out newValue)))
newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
propInfo.SetValue(obj, newValue, null);
}
catch (TargetInvocationException ex)
{
throw new NLogConfigurationException("Error when setting property '" + propInfo.Name + "' on " + obj, ex.InnerException);
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "Error when setting property '{0}' on '{1}'", propInfo.Name, obj);
if (exception.MustBeRethrownImmediately())
{
throw;
}
throw new NLogConfigurationException("Error when setting property '" + propInfo.Name + "' on " + obj, exception);
}
}
/// <summary>
/// Is the property of array-type?
/// </summary>
/// <param name="t">Type which has the property <paramref name="propertyName"/></param>
/// <param name="propertyName">name of the property.</param>
/// <returns></returns>
internal static bool IsArrayProperty(Type t, string propertyName)
{
PropertyInfo propInfo;
if (!TryGetPropertyInfo(t, propertyName, out propInfo))
{
throw new NotSupportedException("Parameter " + propertyName + " not supported on " + t.Name);
}
return propInfo.IsDefined(typeof(ArrayParameterAttribute), false);
}
/// <summary>
/// Get propertyinfo
/// </summary>
/// <param name="obj">object which could have property <paramref name="propertyName"/></param>
/// <param name="propertyName">propertyname on <paramref name="obj"/></param>
/// <param name="result">result when success.</param>
/// <returns>success.</returns>
internal static bool TryGetPropertyInfo(object obj, string propertyName, out PropertyInfo result)
{
PropertyInfo propInfo = obj.GetType().GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propInfo != null)
{
result = propInfo;
return true;
}
lock (parameterInfoCache)
{
Type targetType = obj.GetType();
Dictionary<string, PropertyInfo> cache;
if (!parameterInfoCache.TryGetValue(targetType, out cache))
{
cache = BuildPropertyInfoDictionary(targetType);
parameterInfoCache[targetType] = cache;
}
return cache.TryGetValue(propertyName, out result);
}
}
internal static Type GetArrayItemType(PropertyInfo propInfo)
{
var arrayParameterAttribute = (ArrayParameterAttribute)Attribute.GetCustomAttribute(propInfo, typeof(ArrayParameterAttribute));
if (arrayParameterAttribute != null)
{
return arrayParameterAttribute.ItemType;
}
return null;
}
internal static IEnumerable<PropertyInfo> GetAllReadableProperties(Type type)
{
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
internal static void CheckRequiredParameters(object o)
{
foreach (PropertyInfo propInfo in PropertyHelper.GetAllReadableProperties(o.GetType()))
{
if (propInfo.IsDefined(typeof(RequiredParameterAttribute), false))
{
object value = propInfo.GetValue(o, null);
if (value == null)
{
throw new NLogConfigurationException(
"Required parameter '" + propInfo.Name + "' on '" + o + "' was not specified.");
}
}
}
}
private static bool TryImplicitConversion(Type resultType, string value, out object result)
{
MethodInfo operatorImplicitMethod = resultType.GetMethod("op_Implicit", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
if (operatorImplicitMethod == null)
{
result = null;
return false;
}
result = operatorImplicitMethod.Invoke(null, new object[] { value });
return true;
}
private static bool TryNLogSpecificConversion(Type propertyType, string value, out object newValue, ConfigurationItemFactory configurationItemFactory)
{
if (propertyType == typeof(Layout) || propertyType == typeof(SimpleLayout))
{
newValue = new SimpleLayout(value, configurationItemFactory);
return true;
}
if (propertyType == typeof(ConditionExpression))
{
newValue = ConditionParser.ParseExpression(value, configurationItemFactory);
return true;
}
newValue = null;
return false;
}
private static bool TryGetEnumValue(Type resultType, string value, out object result, bool flagsEnumAllowed)
{
if (!resultType.IsEnum)
{
result = null;
return false;
}
if (flagsEnumAllowed && resultType.IsDefined(typeof(FlagsAttribute), false))
{
ulong union = 0;
foreach (string v in value.Split(','))
{
FieldInfo enumField = resultType.GetField(v.Trim(), BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public);
if (enumField == null)
{
throw new NLogConfigurationException("Invalid enumeration value '" + value + "'.");
}
union |= Convert.ToUInt64(enumField.GetValue(null), CultureInfo.InvariantCulture);
}
result = Convert.ChangeType(union, Enum.GetUnderlyingType(resultType), CultureInfo.InvariantCulture);
result = Enum.ToObject(resultType, result);
return true;
}
else
{
FieldInfo enumField = resultType.GetField(value, BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public);
if (enumField == null)
{
throw new NLogConfigurationException("Invalid enumeration value '" + value + "'.");
}
result = enumField.GetValue(null);
return true;
}
}
private static bool TrySpecialConversion(Type type, string value, out object newValue)
{
if (type == typeof(Encoding))
{
value = value.Trim();
newValue = Encoding.GetEncoding(value);
return true;
}
if (type == typeof(CultureInfo))
{
value = value.Trim();
newValue = new CultureInfo(value);
return true;
}
if (type == typeof(Type))
{
value = value.Trim();
newValue = Type.GetType(value, true);
return true;
}
newValue = null;
return false;
}
/// <summary>
/// Try parse of string to (Generic) list, comma separated.
/// </summary>
/// <remarks>
/// If there is a comma in the value, then (single) quote the value. For single quotes, use the backslash as escape
/// </remarks>
/// <param name="type"></param>
/// <param name="valueRaw"></param>
/// <param name="newValue"></param>
/// <returns></returns>
private static bool TryFlatListConversion(Type type, string valueRaw, out object newValue)
{
if (type.IsGenericType)
{
var typeDefinition = type.GetGenericTypeDefinition();
#if NET3_5
var isSet = typeDefinition == typeof(HashSet<>);
#else
var isSet = typeDefinition == typeof(ISet<>) || typeDefinition == typeof(HashSet<>);
#endif
//not checking "implements" interface as we are creating HashSet<T> or List<T> and also those checks are expensive
if (isSet || typeDefinition == typeof(List<>) || typeDefinition == typeof(IList<>) || typeDefinition == typeof(IEnumerable<>)) //set or list/array etc
{
//note: type.GenericTypeArguments is .NET 4.5+
var propertyType = type.GetGenericArguments()[0];
var listType = isSet ? typeof(HashSet<>) : typeof(List<>);
var genericArgs = propertyType;
var concreteType = listType.MakeGenericType(genericArgs);
var newList = Activator.CreateInstance(concreteType);
//no support for array
if (newList == null)
{
throw new NLogConfigurationException("Cannot create instance of {0} for value {1}", type.ToString(), valueRaw);
}
var values = valueRaw.SplitQuoted(',', '\'', '\\');
var collectionAddMethod = concreteType.GetMethod("Add", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (collectionAddMethod == null)
{
throw new NLogConfigurationException("Add method on type {0} for value {1} not found", type.ToString(), valueRaw);
}
foreach (var value in values)
{
if (!(TryGetEnumValue(propertyType, value, out newValue, false)
|| TryImplicitConversion(propertyType, value, out newValue)
|| TrySpecialConversion(propertyType, value, out newValue)
|| TryTypeConverterConversion(propertyType, value, out newValue)))
{
newValue = Convert.ChangeType(value, propertyType, CultureInfo.InvariantCulture);
}
collectionAddMethod.Invoke(newList, new object[] { newValue });
}
newValue = newList;
return true;
}
}
newValue = null;
return false;
}
private static bool TryTypeConverterConversion(Type type, string value, out object newValue)
{
#if !SILVERLIGHT
var converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertFrom(typeof(string)))
{
newValue = converter.ConvertFromInvariantString(value);
return true;
}
#else
if (type == typeof(LineEndingMode))
{
newValue = LineEndingMode.FromString(value);
return true;
}
else if (type == typeof(Uri))
{
newValue = new Uri(value);
return true;
}
#endif
newValue = null;
return false;
}
private static bool TryGetPropertyInfo(Type targetType, string propertyName, out PropertyInfo result)
{
if (!string.IsNullOrEmpty(propertyName))
{
PropertyInfo propInfo = targetType.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propInfo != null)
{
result = propInfo;
return true;
}
}
lock (parameterInfoCache)
{
Dictionary<string, PropertyInfo> cache;
if (!parameterInfoCache.TryGetValue(targetType, out cache))
{
cache = BuildPropertyInfoDictionary(targetType);
parameterInfoCache[targetType] = cache;
}
return cache.TryGetValue(propertyName, out result);
}
}
private static Dictionary<string, PropertyInfo> BuildPropertyInfoDictionary(Type t)
{
var retVal = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
foreach (PropertyInfo propInfo in GetAllReadableProperties(t))
{
var arrayParameterAttribute = (ArrayParameterAttribute)Attribute.GetCustomAttribute(propInfo, typeof(ArrayParameterAttribute));
if (arrayParameterAttribute != null)
{
retVal[arrayParameterAttribute.ElementName] = propInfo;
}
else
{
retVal[propInfo.Name] = propInfo;
}
if (propInfo.IsDefined(typeof(DefaultParameterAttribute), false))
{
// define a property with empty name
retVal[string.Empty] = propInfo;
}
}
return retVal;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="StashPanel.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultAE.GUI
{
using Properties;
using System;
using System.Drawing;
using System.Globalization;
using System.Text;
using System.Windows.Forms;
using Tooltip;
using TQVaultData;
/// <summary>
/// Class for handling the stash panel ui functions
/// </summary>
public class StashPanel : VaultPanel
{
#region StashPanel Fields
/// <summary>
/// Localized tab names
/// </summary>
private static string[] buttonNames =
{
Resources.StashPanelBtn1,
Resources.StashPanelBtn2,
Resources.StashPanelBtn3
};
/// <summary>
/// Stash file instance
/// </summary>
private Stash stash;
/// <summary>
/// Transfer stash file instance
/// </summary>
private Stash transferStash;
/// <summary>
/// background bitmap
/// </summary>
private Bitmap background;
/// <summary>
/// Currently selected bag
/// </summary>
private int currentBag;
/// <summary>
/// Maximum size of the panel. Uses the initial constructor size.
/// </summary>
private Size maxPanelSize;
/// <summary>
/// Equipment Panel instance
/// </summary>
private EquipmentPanel equipmentPanel;
/// <summary>
/// Background image for the equipment panel
/// </summary>
private Bitmap equipmentBackground;
/// <summary>
/// Background image for the stash vault panels
/// </summary>
private Bitmap stashBackground;
#endregion StashPanel Fields
/// <summary>
/// Initializes a new instance of the StashPanel class. Hard coded to 3 stash buttons and no autosort buttons.
/// </summary>
/// <param name="dragInfo">ItemDragInfo instance</param>
/// <param name="panelSize">Size of the panel in cells</param>
/// <param name="tooltip">ToolTip instance</param>
public StashPanel(ItemDragInfo dragInfo, Size panelSize, TTLib tooltip) : base(dragInfo, 3, panelSize, tooltip, 0, AutoMoveLocation.Stash)
{
this.equipmentPanel = new EquipmentPanel(10, 14, dragInfo, AutoMoveLocation.Stash);
this.Controls.Add(this.equipmentPanel);
this.equipmentPanel.OnNewItemHighlighted += new EventHandler<SackPanelEventArgs>(this.NewItemHighlightedCallback);
this.equipmentPanel.OnAutoMoveItem += new EventHandler<SackPanelEventArgs>(this.AutoMoveItemCallback);
this.equipmentPanel.OnActivateSearch += new EventHandler<SackPanelEventArgs>(this.ActivateSearchCallback);
this.equipmentPanel.OnItemSelected += new EventHandler<SackPanelEventArgs>(this.ItemSelectedCallback);
this.equipmentPanel.OnClearAllItemsSelected += new EventHandler<SackPanelEventArgs>(this.ClearAllItemsSelectedCallback);
this.equipmentPanel.OnResizeForm += new EventHandler<ResizeEventArgs>(this.ResizeFormCallback);
this.Text = Resources.StashPanelText;
this.NoPlayerString = Resources.StashPanelText;
this.Size = new Size(
(panelSize.Width * Database.DB.ItemUnitSize) + Convert.ToInt32(10.0F * Database.DB.Scale) + BorderPad,
(panelSize.Height * Database.DB.ItemUnitSize) + Convert.ToInt32(60.0F * Database.DB.Scale) + BorderPad);
this.Paint += new PaintEventHandler(this.PaintCallback);
this.BagSackPanel.SetLocation(new Point(BorderPad, this.Size.Height - (this.BagSackPanel.Size.Height + BorderPad)));
this.BagSackPanel.MaxSacks = 1;
this.BagSackPanel.Anchor = AnchorStyles.None;
this.EquipmentBackground = Resources.Equipment_bg_new;
this.StashBackground = Resources.caravan_bg;
// Set up the inital font size
if (Database.DB.Scale != 1.0F)
{
this.Font = new Font(this.Font.Name, this.Font.SizeInPoints * Database.DB.Scale, this.Font.Style);
}
this.background = Resources.Equipment_bg_new;
// Now that the buttons are set we can move the panel
this.BagSackPanel.SetLocation(new Point(
BorderPad,
this.BagButtons[0].Location.Y + this.BagButtons[0].Size.Height + Database.DB.HalfUnitSize));
int offsetX = (panelSize.Width - this.equipmentPanel.SackSize.Width) * Database.DB.HalfUnitSize;
if (offsetX < 0)
{
offsetX = 0;
}
int offsetY = (panelSize.Height - this.equipmentPanel.SackSize.Height) * Database.DB.HalfUnitSize;
if (offsetY < 0)
{
offsetY = 0;
}
this.equipmentPanel.SetLocation(new Point(
offsetX,
this.BagButtons[0].Location.Y + this.BagButtons[0].Size.Height + offsetY));
this.maxPanelSize = panelSize;
this.BagSackPanel.Visible = false;
this.BagSackPanel.Enabled = false;
}
#region StashPanel Properties
/// <summary>
/// Gets or sets the stash instance
/// </summary>
public Stash Stash
{
get
{
return this.stash;
}
set
{
this.stash = value;
this.Text = Resources.StashPanelText;
this.AssignSacks();
}
}
/// <summary>
/// Gets or sets the transfer stash instance
/// </summary>
public Stash TransferStash
{
get
{
return this.transferStash;
}
set
{
this.transferStash = value;
this.Text = Resources.StashPanelText;
this.AssignSacks();
}
}
/// <summary>
/// Gets the SackPanel instance
/// </summary>
public new SackPanel SackPanel
{
get
{
if (this.CurrentBag == 0 && this.equipmentPanel != null)
{
return this.equipmentPanel;
}
return this.BagSackPanel;
}
}
/// <summary>
/// Gets or sets the background image for the equipment panel scaled by the panel size
/// </summary>
public Bitmap EquipmentBackground
{
get
{
if (Database.DB.Scale != 1.0F)
{
// We need to scale this since we use it to redraw the background.
return new Bitmap(
this.equipmentBackground,
(this.maxPanelSize.Width * Database.DB.ItemUnitSize) + (Convert.ToInt32(SackPanel.BorderWidth) * 2),
(this.maxPanelSize.Height * Database.DB.ItemUnitSize) + (Convert.ToInt32(SackPanel.BorderWidth) * 2));
}
return this.equipmentBackground;
}
set
{
this.equipmentBackground = value;
}
}
/// <summary>
/// Gets or sets the bitmap for the stash panel background scaled by the panel size.
/// </summary>
public Bitmap StashBackground
{
get
{
if (Database.DB.Scale != 1.0F)
{
// We need to scale this since we use it to redraw the background.
return new Bitmap(
this.stashBackground,
(this.maxPanelSize.Width * Database.DB.ItemUnitSize) + (Convert.ToInt32(SackPanel.BorderWidth) * 2),
(this.maxPanelSize.Height * Database.DB.ItemUnitSize) + (Convert.ToInt32(SackPanel.BorderWidth) * 2));
}
return this.stashBackground;
}
set
{
this.stashBackground = value;
}
}
/// <summary>
/// Gets or sets the currently selected bag id
/// </summary>
public new int CurrentBag
{
get
{
return this.currentBag;
}
set
{
int bagID = value;
// figure out the current bag to use
if (bagID < 0)
{
bagID = 0;
}
if (bagID >= 3)
{
bagID = 2;
}
if (bagID != this.currentBag)
{
// turn off the current bag and turn on the new bag
this.BagButtons[this.currentBag].IsOn = false;
this.BagButtons[bagID].IsOn = true;
this.currentBag = bagID;
BagButtonBase button = this.BagButtons[this.currentBag];
int buttonOffsetY = button.Location.Y + button.Size.Height;
if (this.currentBag == 0)
{
// Equipment Panel
if (this.Player == null)
{
this.equipmentPanel.Sack = null;
}
else
{
this.equipmentPanel.Sack = this.Player.EquipmentSack;
}
this.background = this.EquipmentBackground;
this.equipmentPanel.Visible = true;
this.equipmentPanel.Enabled = true;
this.BagSackPanel.Visible = false;
this.BagSackPanel.Enabled = false;
}
else if (this.currentBag == 1)
{
// Transfer Stash
this.background = this.StashBackground;
this.BagSackPanel.Sack = this.transferStash.Sack;
this.BagSackPanel.SackType = SackType.Stash;
this.BagSackPanel.ResizeSackPanel(this.transferStash.Width, this.transferStash.Height);
// Adjust location based on size.
int offsetX = Math.Max(0, (this.maxPanelSize.Width - this.transferStash.Width) * Database.DB.HalfUnitSize);
int offsetY = Math.Max(0, (this.maxPanelSize.Height - this.transferStash.Height) * Database.DB.HalfUnitSize);
this.BagSackPanel.Location = new Point(BorderPad + offsetX, buttonOffsetY + offsetY);
this.equipmentPanel.Visible = false;
this.equipmentPanel.Enabled = false;
this.BagSackPanel.Visible = true;
this.BagSackPanel.Enabled = true;
}
else if (this.currentBag == 2)
{
// Stash
this.background = this.StashBackground;
this.BagSackPanel.Sack = this.stash.Sack;
this.BagSackPanel.SackType = SackType.Stash;
this.BagSackPanel.ResizeSackPanel(this.stash.Width, this.stash.Height);
// Adjust location based on size so it will be centered.
int offsetX = Math.Max(0, (this.maxPanelSize.Width - this.stash.Width) * Database.DB.HalfUnitSize);
int offsetY = Math.Max(0, (this.maxPanelSize.Height - Math.Max(15, this.stash.Height)) * Database.DB.HalfUnitSize);
this.BagSackPanel.Location = new Point(BorderPad + offsetX, buttonOffsetY + offsetY);
this.equipmentPanel.Visible = false;
this.equipmentPanel.Enabled = false;
this.BagSackPanel.Visible = true;
this.BagSackPanel.Enabled = true;
}
this.Refresh();
}
}
}
#endregion StashPanel Properties
/// <summary>
/// Sets the equipment panel background image and cursor background image.
/// </summary>
/// <param name="background">Bitmap which is to be used for the background.</param>
public void SetEquipmentBackground(Bitmap background)
{
this.EquipmentBackground = background;
this.background = background;
}
#region StashPanel Protected Methods
/// <summary>
/// Override of ScaleControl which supports scaling of the fonts and internal items.
/// </summary>
/// <param name="factor">SizeF for the scale factor</param>
/// <param name="specified">BoundsSpecified value.</param>
protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
{
base.ScaleControl(factor, specified);
// This should really only be set for the equipment panel.
}
/// <summary>
/// Creates a new stash button
/// </summary>
/// <param name="bagNumber">The bag number for button that is being created.</param>
/// <param name="numberOfBags">The total number of bags which is used for scaling.</param>
/// <returns>The new StashButton that is created.</returns>
protected StashButton CreateBagButton(int bagNumber, int numberOfBags)
{
StashButton button = new StashButton(bagNumber, new GetToolTip(this.GetSackToolTip), this.Tooltip);
float buttonWidth = (float)Resources.StashTabUp.Width;
float buttonHeight = (float)Resources.StashTabUp.Height;
float pad = 2.0F;
float slotWidth = buttonWidth + (2.0F * pad);
// we need to scale down the button size depending on the # we have
float scale = this.GetBagButtonScale(slotWidth, numberOfBags);
float bagSlotWidth = scale * slotWidth;
// We are using tabs so only scale horizontally
button.Size = new Size((int)Math.Round(scale * buttonWidth), Convert.ToInt32(buttonHeight * Database.DB.Scale));
float offset = (bagSlotWidth * bagNumber) + ((bagSlotWidth - button.Width) / 2.0F);
button.Location = new Point(this.SackPanel.Location.X + (int)Math.Round(offset), this.SackPanel.Location.Y - button.Height);
button.Visible = false;
button.MouseDown += new MouseEventHandler(this.BagButtonClick);
button.ButtonText = buttonNames[bagNumber];
return button;
}
/// <summary>
/// Creates all of the stash buttons.
/// </summary>
/// <param name="numberOfBags">The total number of buttons to create.</param>
/// <remarks>We need this override since the CreateBagButton() method above has a different return type than the base class.</remarks>
protected override void CreateBagButtons(int numberOfBags)
{
for (int i = 0; i < numberOfBags; ++i)
{
this.BagButtons.Insert(i, this.CreateBagButton(i, numberOfBags));
this.Controls.Add(this.BagButtons[i]);
}
}
/// <summary>
/// Updates the text for the group box. Override the base method since we do not need to change it based on the player name.
/// </summary>
protected override void UpdateText()
{
this.Text = string.Empty;
if (this.DrawAsGroupBox)
{
this.Text = Resources.StashPanelText;
}
}
/// <summary>
/// Assigns sacks to bag buttons
/// </summary>
protected override void AssignSacks()
{
// figure out the current bag to use
if (this.currentBag < 0)
{
this.currentBag = 0;
}
if (this.currentBag >= 3)
{
this.currentBag = 2;
}
// hide/show bag buttons and assign initial bitmaps
int buttonOffset = 0;
foreach (StashButton button in this.BagButtons)
{
button.Visible = buttonOffset < 3;
button.IsOn = buttonOffset == this.currentBag;
++buttonOffset;
}
if ((this.stash == null) || (this.stash.NumberOfSacks < 1))
{
this.BagButtons[2].Visible = false;
}
if ((this.transferStash == null) || (this.transferStash.NumberOfSacks < 1))
{
this.BagButtons[1].Visible = false;
}
if (this.currentBag == 0)
{
if (this.Player == null)
{
this.SackPanel.Sack = null;
}
else
{
this.SackPanel.Sack = this.Player.EquipmentSack;
}
}
else if (this.currentBag == 1)
{
// Assign the transfer stash
if ((this.transferStash == null) || (this.transferStash.NumberOfSacks < 1))
{
this.SackPanel.Sack = null;
}
else
{
if (this.transferStash.NumberOfSacks > 0)
{
this.SackPanel.Sack = this.transferStash.Sack;
}
else
{
this.SackPanel.Sack = null;
}
}
}
else if (this.currentBag == 2)
{
if ((this.stash == null) || (this.stash.NumberOfSacks < 1))
{
this.SackPanel.Sack = null;
}
else
{
if (this.stash.NumberOfSacks > 0)
{
this.SackPanel.Sack = this.stash.Sack;
}
else
{
this.SackPanel.Sack = null;
}
}
}
}
/// <summary>
/// Handler for clicking on a bag button
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">EventArgs data</param>
protected override void BagButtonClick(object sender, MouseEventArgs e)
{
BagButtonBase button = (BagButtonBase)sender;
int bagID = button.ButtonNumber;
// filter the bagID
if (bagID < 0)
{
bagID = 0;
}
if (bagID >= 3)
{
bagID = 2;
}
if (bagID != this.currentBag)
{
// turn off the current bag and turn on the new bag
this.BagButtons[this.currentBag].IsOn = false;
this.BagButtons[bagID].IsOn = true;
// set the current bag to the selected bag
this.CurrentBag = bagID;
this.SackPanel.ClearSelectedItems();
}
}
/// <summary>
/// Paint callback
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="e">PaintEventArgs data</param>
protected new void PaintCallback(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(this.background, this.GetBackgroundRect());
base.PaintCallback(sender, e);
}
#endregion StashPanel Protected Methods
#region StashPanel Private Methods
/// <summary>
/// Gets the tooltip for a sack. Summarizes the items within the sack
/// </summary>
/// <param name="button">button the mouse is over. Corresponds to a sack</param>
/// <returns>string to be displayed in the tooltip</returns>
private string GetSackToolTip(BagButtonBase button)
{
// Get the list of items and return them as a string
int bagID = button.ButtonNumber;
SackCollection sack;
if (bagID == 0)
{
if (this.Player == null)
{
sack = null;
}
else
{
sack = this.Player.EquipmentSack;
}
}
else if (bagID == 1)
{
sack = this.transferStash.Sack;
}
else
{
sack = this.stash.Sack;
}
if (sack == null || sack.IsEmpty)
{
return null;
}
StringBuilder answer = new StringBuilder();
answer.Append(Database.DB.TooltipTitleTag);
bool first = true;
foreach (Item item in sack)
{
if (this.DragInfo.IsActive && item == this.DragInfo.Item)
{
// skip the item being dragged
continue;
}
if (item.BaseItemId.Length == 0)
{
// skip empty items
continue;
}
if (!first)
{
answer.Append("<br>");
}
first = false;
string text = Database.MakeSafeForHtml(item.ToString());
Color color = item.GetColorTag(text);
text = Item.ClipColorTag(text);
string htmlcolor = Database.HtmlColor(color);
string htmlLine = string.Format(CultureInfo.CurrentCulture, "<font color={0}><b>{1}</b></font>", htmlcolor, text);
answer.Append(htmlLine);
}
return answer.ToString();
}
/// <summary>
/// Gets a rectangle scaled by the size of the child vault panels.
/// </summary>
/// <returns>Rectangle containg the size and position of the child vault panel.</returns>
private Rectangle GetBackgroundRect()
{
if (this.BagButtons == null || this.BagButtons.Count == 0)
{
return Rectangle.Empty;
}
return new Rectangle(
BorderPad,
this.BagButtons[0].Location.Y + this.BagButtons[0].Size.Height,
this.Width - (BorderPad * 2),
this.Height - (this.BagButtons[0].Location.Y + this.BagButtons[0].Size.Height + BorderPad));
}
#endregion StashPanel Private Methods
}
}
| |
namespace Manssiere.Core.Graphics.VertexArayUtility
{
using System.Linq;
using Buffers;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using System;
using System.Collections.Generic;
public class VertexArray : VertexArrayObject<Vector3, Vector3, Vector2, uint, uint, uint>
{
public VertexArray() { }
public VertexArray(BeginMode geometry) { Geometry = geometry; }
}
public class VertexArrayObject<TVertexStruct, TNormalStruct, TExCoordStruct, TElementStruct, TColorStruct, TAttribStruct> : IDisposable
where TVertexStruct : struct
where TNormalStruct : struct
where TExCoordStruct : struct
where TElementStruct : struct
where TColorStruct : struct
where TAttribStruct : struct
{
// static bool supportsFrameBufferObjects = GL.SupportsFunction("glBufferData");
// static bool supportsVertexArrayObjects = GL.SupportsFunction("glBindVertexArray");
~VertexArrayObject() { Dispose(false); }
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
// If disposing, dispose all managed and unmanaged resources.
if (disposing)
{
// Dispose managed resources
// Unhook events
foreach (TexCoordBufferObject<TExCoordStruct> texCoords in _texCoordsArray)
{
if (texCoords == null) continue;
texCoords.Dispose();
}
if (Attributes != null) Attributes.Dispose();
if (Colors != null) Colors.Dispose();
if (SecondaryColors != null) SecondaryColors.Dispose();
if (Normals != null) Normals.Dispose();
if (Vertices != null) Vertices.Dispose();
foreach (ElementBufferObject<TElementStruct> elementBuffer in _elementBuffersArray)
{
elementBuffer.Dispose();
}
//if (vertexArrayObjectID != 0)
//{
// GL.DeleteVertexArrays(1, ref vertexArrayObjectID);
// vertexArrayObjectID = 0;
//}
}
// Dispose of unmanaged resources
for (int i = 0; i < _texCoordsArray.Length; i++)
{
_texCoordsArray[i] = null;
}
for (int i = 0; i < _elementBuffersArray.Count; i++)
{
_elementBuffersArray[i] = null;
}
// Set fields to null
Attributes = null;
Colors = null;
SecondaryColors = null;
Normals = null;
Vertices = null;
}
public VertexAttribBufferObject<TAttribStruct> Attributes
{
get { return _vertexAttribs; }
set
{
if( _vertexAttribs == value ) return;
if (_vertexAttribs != null)
{
_vertexAttribs.NeedsUpdate -= SetBufferUpdateNeeded;
}
_vertexAttribs = value;
if (_vertexAttribs != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _vertexAttribs.Dirty;
_vertexAttribs.NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
VertexAttribBufferObject<TAttribStruct> _vertexAttribs;
public ColorBufferObject<TColorStruct> Colors
{
get { return _colors; }
set
{
if (_colors == value) return;
if (_colors != null)
{
_colors.NeedsUpdate -= SetBufferUpdateNeeded;
}
_colors = value;
if (_colors != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _colors.Dirty;
_colors.NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
ColorBufferObject<TColorStruct> _colors;
public ColorBufferObject<TColorStruct> SecondaryColors
{
get { return _secondaryColors; }
set
{
if (_secondaryColors == value) return;
if (_secondaryColors != null)
{
_secondaryColors.NeedsUpdate -= SetBufferUpdateNeeded;
}
_secondaryColors = value;
if (_secondaryColors != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _secondaryColors.Dirty;
_secondaryColors.NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
ColorBufferObject<TColorStruct> _secondaryColors;
public TexCoordBufferObject<TExCoordStruct> TexCoords
{
get { return _texCoordsArray[0]; }
set
{
if (_texCoordsArray[0] == value) return;
if (_texCoordsArray[0] != null)
{
_texCoordsArray[0].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[0] = value;
if (_texCoordsArray[0] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[0].Dirty;
_texCoordsArray[0].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords1
{
get { return _texCoordsArray[1]; }
set
{
if (_texCoordsArray[1] == value) return;
if (_texCoordsArray[1] != null)
{
_texCoordsArray[1].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[1] = value;
if (_texCoordsArray[1] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[1].Dirty;
_texCoordsArray[1].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords2
{
get { return _texCoordsArray[2]; }
set
{
if (_texCoordsArray[2] == value) return;
if (_texCoordsArray[2] != null)
{
_texCoordsArray[2].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[2] = value;
if (_texCoordsArray[2] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[2].Dirty;
_texCoordsArray[2].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords3
{
get { return _texCoordsArray[3]; }
set
{
if (_texCoordsArray[3] == value) return;
if (_texCoordsArray[3] != null)
{
_texCoordsArray[3].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[3] = value;
if (_texCoordsArray[3] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[3].Dirty;
_texCoordsArray[3].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords4
{
get { return _texCoordsArray[4]; }
set
{
if (_texCoordsArray[4] == value) return;
if (_texCoordsArray[4] != null)
{
_texCoordsArray[4].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[4] = value;
if (_texCoordsArray[4] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[4].Dirty;
_texCoordsArray[4].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords5
{
get { return _texCoordsArray[5]; }
set
{
if (_texCoordsArray[5] == value) return;
if (_texCoordsArray[5] != null)
{
_texCoordsArray[5].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[5] = value;
if (_texCoordsArray[5] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[5].Dirty;
_texCoordsArray[5].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords6
{
get { return _texCoordsArray[6]; }
set
{
if (_texCoordsArray[6] == value) return;
if (_texCoordsArray[6] != null)
{
_texCoordsArray[6].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[6] = value;
if (_texCoordsArray[6] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[6].Dirty;
_texCoordsArray[6].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords7
{
get { return _texCoordsArray[7]; }
set
{
if (_texCoordsArray[7] == value) return;
if (_texCoordsArray[7] != null)
{
_texCoordsArray[7].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[7] = value;
if (_texCoordsArray[7] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[7].Dirty;
_texCoordsArray[7].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords8
{
get { return _texCoordsArray[8]; }
set
{
if (_texCoordsArray[8] == value) return;
if (_texCoordsArray[8] != null)
{
_texCoordsArray[8].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[8] = value;
if (_texCoordsArray[8] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[8].Dirty;
_texCoordsArray[8].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords9
{
get { return _texCoordsArray[9]; }
set
{
if (_texCoordsArray[9] == value) return;
if (_texCoordsArray[9] != null)
{
_texCoordsArray[9].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[9] = value;
if (_texCoordsArray[9] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[9].Dirty;
_texCoordsArray[9].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords10
{
get { return _texCoordsArray[10]; }
set
{
if (_texCoordsArray[10] == value) return;
if (_texCoordsArray[10] != null)
{
_texCoordsArray[10].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[10] = value;
if (_texCoordsArray[10] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[10].Dirty;
_texCoordsArray[10].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords11
{
get { return _texCoordsArray[11]; }
set
{
if (_texCoordsArray[11] == value) return;
if (_texCoordsArray[11] != null)
{
_texCoordsArray[11].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[11] = value;
if (_texCoordsArray[11] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[11].Dirty;
_texCoordsArray[11].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords12
{
get { return _texCoordsArray[12]; }
set
{
if (_texCoordsArray[12] == value) return;
if (_texCoordsArray[12] != null)
{
_texCoordsArray[12].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[12] = value;
if (_texCoordsArray[12] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[12].Dirty;
_texCoordsArray[12].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords13
{
get { return _texCoordsArray[13]; }
set
{
if (_texCoordsArray[13] == value) return;
if (_texCoordsArray[13] != null)
{
_texCoordsArray[13].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[13] = value;
if (_texCoordsArray[13] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[13].Dirty;
_texCoordsArray[13].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords14
{
get { return _texCoordsArray[14]; }
set
{
if (_texCoordsArray[14] == value) return;
if (_texCoordsArray[14] != null)
{
_texCoordsArray[14].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[14] = value;
if (_texCoordsArray[14] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[14].Dirty;
_texCoordsArray[14].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords15
{
get { return _texCoordsArray[15]; }
set
{
if (_texCoordsArray[15] == value) return;
if (_texCoordsArray[15] != null)
{
_texCoordsArray[15].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[15] = value;
if (_texCoordsArray[15] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[15].Dirty;
_texCoordsArray[15].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords16
{
get { return _texCoordsArray[16]; }
set
{
if (_texCoordsArray[16] == value) return;
if (_texCoordsArray[16] != null)
{
_texCoordsArray[16].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[16] = value;
if (_texCoordsArray[16] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[16].Dirty;
_texCoordsArray[16].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords17
{
get { return _texCoordsArray[17]; }
set
{
if (_texCoordsArray[17] == value) return;
if (_texCoordsArray[17] != null)
{
_texCoordsArray[17].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[17] = value;
if (_texCoordsArray[17] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[17].Dirty;
_texCoordsArray[17].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords18
{
get { return _texCoordsArray[18]; }
set
{
if (_texCoordsArray[18] == value) return;
if (_texCoordsArray[18] != null)
{
_texCoordsArray[18].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[18] = value;
if (_texCoordsArray[18] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[18].Dirty;
_texCoordsArray[18].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords19
{
get { return _texCoordsArray[19]; }
set
{
if (_texCoordsArray[19] == value) return;
if (_texCoordsArray[19] != null)
{
_texCoordsArray[19].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[19] = value;
if (_texCoordsArray[19] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[19].Dirty;
_texCoordsArray[19].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords20
{
get { return _texCoordsArray[20]; }
set
{
if (_texCoordsArray[20] == value) return;
if (_texCoordsArray[20] != null)
{
_texCoordsArray[20].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[20] = value;
if (_texCoordsArray[20] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[20].Dirty;
_texCoordsArray[20].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords21
{
get { return _texCoordsArray[21]; }
set
{
if (_texCoordsArray[21] == value) return;
if (_texCoordsArray[21] != null)
{
_texCoordsArray[21].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[21] = value;
if (_texCoordsArray[21] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[21].Dirty;
_texCoordsArray[21].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords22
{
get { return _texCoordsArray[22]; }
set
{
if (_texCoordsArray[22] == value) return;
if (_texCoordsArray[22] != null)
{
_texCoordsArray[22].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[22] = value;
if (_texCoordsArray[22] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[22].Dirty;
_texCoordsArray[22].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords23
{
get { return _texCoordsArray[23]; }
set
{
if (_texCoordsArray[23] == value) return;
if (_texCoordsArray[23] != null)
{
_texCoordsArray[23].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[23] = value;
if (_texCoordsArray[23] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[23].Dirty;
_texCoordsArray[23].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords24
{
get { return _texCoordsArray[24]; }
set
{
if (_texCoordsArray[24] == value) return;
if (_texCoordsArray[24] != null)
{
_texCoordsArray[24].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[24] = value;
if (_texCoordsArray[24] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[24].Dirty;
_texCoordsArray[24].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords25
{
get { return _texCoordsArray[25]; }
set
{
if (_texCoordsArray[25] == value) return;
if (_texCoordsArray[25] != null)
{
_texCoordsArray[25].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[25] = value;
if (_texCoordsArray[25] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[25].Dirty;
_texCoordsArray[25].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords26
{
get { return _texCoordsArray[26]; }
set
{
if (_texCoordsArray[26] == value) return;
if (_texCoordsArray[26] != null)
{
_texCoordsArray[26].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[26] = value;
if (_texCoordsArray[26] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[26].Dirty;
_texCoordsArray[26].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords27
{
get { return _texCoordsArray[27]; }
set
{
if (_texCoordsArray[27] == value) return;
if (_texCoordsArray[27] != null)
{
_texCoordsArray[27].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[27] = value;
if (_texCoordsArray[27] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[27].Dirty;
_texCoordsArray[27].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords28
{
get { return _texCoordsArray[28]; }
set
{
if (_texCoordsArray[28] == value) return;
if (_texCoordsArray[28] != null)
{
_texCoordsArray[28].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[28] = value;
if (_texCoordsArray[28] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[28].Dirty;
_texCoordsArray[28].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords29
{
get { return _texCoordsArray[29]; }
set
{
if (_texCoordsArray[29] == value) return;
if (_texCoordsArray[29] != null)
{
_texCoordsArray[29].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[29] = value;
if (_texCoordsArray[29] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[29].Dirty;
_texCoordsArray[29].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords30
{
get { return _texCoordsArray[30]; }
set
{
if (_texCoordsArray[30] == value) return;
if (_texCoordsArray[30] != null)
{
_texCoordsArray[30].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[30] = value;
if (_texCoordsArray[30] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[30].Dirty;
_texCoordsArray[30].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
public TexCoordBufferObject<TExCoordStruct> TexCoords31
{
get { return _texCoordsArray[31]; }
set
{
if (_texCoordsArray[31] == value) return;
if (_texCoordsArray[31] != null)
{
_texCoordsArray[31].NeedsUpdate -= SetBufferUpdateNeeded;
}
_texCoordsArray[31] = value;
if (_texCoordsArray[31] != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _texCoordsArray[31].Dirty;
_texCoordsArray[31].NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
readonly TexCoordBufferObject<TExCoordStruct>[] _texCoordsArray = new TexCoordBufferObject<TExCoordStruct>[(int)TextureUnit.Texture31 - (int)TextureUnit.Texture0 + 1];
public NormalBufferObject<TNormalStruct> Normals
{
get { return _normals; }
set
{
if (_normals == value) return;
if (_normals != null)
{
_normals.NeedsUpdate -= SetBufferUpdateNeeded;
}
_normals = value;
if (_normals != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _normals.Dirty;
_normals.NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
NormalBufferObject<TNormalStruct> _normals;
public VertexBufferObject<TVertexStruct> Vertices
{
get { return _vertices; }
set
{
if (_vertices == value) return;
if (_vertices != null)
{
_vertices.NeedsUpdate -= SetBufferUpdateNeeded;
}
_vertices = value;
if (_vertices != null)
{
if (!_bufferUpdateNeeded) _bufferUpdateNeeded = _vertices.Dirty;
_vertices.NeedsUpdate += SetBufferUpdateNeeded;
}
_vertexArrayObjectUpdateNeeded = true;
}
}
VertexBufferObject<TVertexStruct> _vertices;
public ElementBufferObject<TElementStruct> Elements
{
get
{
if (_elementBuffersArray.Count == 0) return null;
return _elementBuffersArray[0];
}
set
{
if (Elements == value) return;
if (Elements != null)
{
Elements.NeedsUpdate -= SetBufferUpdateNeeded;
_elementBuffersArray.RemoveAt(0);
}
if (value != null)
{
_elementBuffersArray.Insert(0, value);
if (!_bufferUpdateNeeded) if (Elements != null) _bufferUpdateNeeded = Elements.Dirty;
if (Elements != null) Elements.NeedsUpdate += SetBufferUpdateNeeded;
}
}
}
readonly List<ElementBufferObject<TElementStruct>> _elementBuffersArray = new List<ElementBufferObject<TElementStruct>>();
bool _bufferUpdateNeeded;
void SetBufferUpdateNeeded() { _bufferUpdateNeeded = true; }
bool _vertexArrayObjectUpdateNeeded;
protected void Update()
{
if (!_bufferUpdateNeeded)
{
return;
}
foreach (var texCoords in _texCoordsArray.TakeWhile(texCoords => texCoords != null))
{
texCoords.Update();
}
if (_colors != null) _colors.Update();
if (_secondaryColors != null) _secondaryColors.Update();
if (_normals != null) _normals.Update();
if (_vertexAttribs != null) _vertexAttribs.Update();
if (_vertices != null) _vertices.Update();
foreach (var elementBuffer in _elementBuffersArray)
{
elementBuffer.Update();
}
}
public BeginMode Geometry
{
get { return _geometry; }
set { _geometry = value; }
}
BeginMode _geometry = BeginMode.Triangles;
public int Instances { get; set; }
public VertexArrayObject()
{
Instances = 1;
}
void SetupBuffers()
{
int texCoordIndex = 0;
foreach (var texCoords in _texCoordsArray.TakeWhile(texCoords => texCoords != null))
{
texCoords.TextureUnit = TextureUnit.Texture0 + texCoordIndex;
texCoords.Enable();
texCoordIndex++;
}
if (_colors != null)
{
_colors.IsSecondary = false;
_colors.Enable();
}
if (_secondaryColors != null)
{
_secondaryColors.IsSecondary = true;
_secondaryColors.Enable();
}
if (_normals != null) _normals.Enable();
if (_vertexAttribs != null) _vertexAttribs.Enable();
if (_vertices != null) _vertices.Enable();
}
public void Render()
{
GL.PushClientAttrib(ClientAttribMask.ClientVertexArrayBit);
Update();
if (_vertexArrayObjectUpdateNeeded)
{
_vertexArrayObjectUpdateNeeded = false;
SetupBuffers();
}
else
{
SetupBuffers();
}
if (_elementBuffersArray.Count != 0)
{
foreach (var elementBuffer in _elementBuffersArray)
{
elementBuffer.Enable();
if (Instances <= 1)
{
elementBuffer.DrawElements(_geometry);
}
else
{
elementBuffer.DrawElementsInstanced(_geometry, Instances);
}
}
}
else
{
if (Instances <= 1)
{
GL.DrawArrays(_geometry, 0, _vertices.Count);
}
else
{
GL.DrawArraysInstanced(_geometry, 0, _vertices.Count, Instances);
}
}
GL.PopClientAttrib();
}
}
}
| |
namespace ZetaResourceEditor.Code;
using ExtendedControlsLibrary.Skinning;
using Properties;
using RuntimeBusinessLogic.Projects;
using UI.Helper.ErrorHandling;
using UI.Main;
using Zeta.VoyagerLibrary.Tools.Miscellaneous;
using Zeta.VoyagerLibrary.Tools.Storage;
internal sealed class Host
{
private static readonly IDictionary<string, Assembly> _additional =
new Dictionary<string, Assembly>();
private static ZlpDirectoryInfo _cacheForCurrentUserStorageBaseFolderPath;
[STAThread]
private static void Main()
{
try
{
BindingRedirectsHelper.Initialize();
LogCentral.Current.ConfigureLogging();
// --
// Register extension.
try
{
var info =
new FileExtensionRegistration.RegistrationInformation
{
ApplicationFilePath = typeof(Host).Assembly.Location,
Extension = Project.ProjectFileExtension,
ClassName = @"ZetaResourceEditorDocument",
Description = Resources.SR_Host_Main_ZetaResourceEditorProjectFile
};
FileExtensionRegistration.Register(info);
}
catch (Exception x)
{
// May fail if no permissions, silently eat.
LogCentral.Current.LogError(x);
}
// --
var persistentStorage =
new PersistentXmlFilePairStorage
{
FilePath =
ZlpPathHelper.Combine(
CurrentUserStorageBaseFolderPath.FullName,
@"zeta-resource-editor-settings.xml")
};
persistentStorage.Error += storageError;
PersistanceHelper.Storage = persistentStorage;
// --
// http://community.devexpress.com/forums/t/80133.aspx
SkinHelper.InitializeAll();
// --
AppDomain.CurrentDomain.UnhandledException += currentDomainUnhandledException;
Application.ThreadException += applicationThreadException;
// --
// http://stackoverflow.com/a/9180843/107625
var dir = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location ?? string.Empty);
foreach (var assemblyName in Directory.GetFiles(dir ?? string.Empty, @"*.dll"))
{
try
{
var assembly = Assembly.LoadFile(assemblyName);
_additional.Add(assembly.GetName().Name, assembly);
}
catch (BadImageFormatException)
{
// Ignorieren.
}
}
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ResolveAssembly;
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_ResolveAssembly;
// --
test();
initializeLanguage();
Application.Run(new MainForm());
}
catch (Exception x)
{
doHandleException(x);
}
}
private static Assembly CurrentDomain_ResolveAssembly(object sender, ResolveEventArgs e)
{
// Hier mache ich quasi mein eigenes, automatisches, Binding-Redirect.
// (z.B. Newtonsoft.Json 6.0.0.0 nach 9.0.0.0).
if (e.Name.IndexOf(',') < 0) return null;
var name = e.Name.Substring(0, e.Name.IndexOf(','));
_additional.TryGetValue(name, out var res);
return res;
}
public static void ApplyLanguageSettingsToCurrentThread()
{
foreach (var e in Environment.GetCommandLineArgs())
{
if (e.StartsWith(@"-language") || e.StartsWith(@"/language"))
{
var f = e.Replace(@"language", string.Empty);
f = f.Trim(' ', '\t', '=', '/', '-').ToLowerInvariant();
if (f.StartsWith(@"de"))
{
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture =
Application.CurrentCulture = new CultureInfo(@"de-DE");
}
else if (f.StartsWith(@"en"))
{
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture =
Application.CurrentCulture = new CultureInfo(@"en-US");
}
}
}
}
private static void initializeLanguage()
{
ApplyLanguageSettingsToCurrentThread();
}
private static void test()
{
}
private static void currentDomainUnhandledException(
object sender,
UnhandledExceptionEventArgs e)
{
doHandleException(e.ExceptionObject as Exception);
}
private static void applicationThreadException(
object sender,
ThreadExceptionEventArgs e)
{
doHandleException(e.Exception);
}
public static void NotifyAboutException(
Exception e)
{
doHandleException(e);
}
private static void doHandleException(
Exception e)
{
LogCentral.Current.Warn(e);
bool handleException;
switch (e)
{
case MessageBoxException exception:
{
var mbx = exception;
XtraMessageBox.Show(
mbx.Parent,
mbx.Message,
@"Zeta Resource Editor",
mbx.Buttons,
mbx.Icon);
handleException = false;
break;
}
case PersistentPairStorageException _:
{
// 2009-06-22, Uwe Keim:
// http://zeta-producer.de/Pages/AdvancedForumIndex.aspx?DataID=9514
LogCentral.Current.LogWarn(
@"PersistentPairStorageException occurred.", e);
switch (e.InnerException)
{
case null:
handleException = true;
break;
case UnauthorizedAccessException:
case IOException:
handleException = false;
break;
default:
handleException = true;
break;
}
break;
}
default:
handleException = true;
break;
}
// --
if (handleException)
{
LogCentral.Current.LogError(@"Exception occurred.", e);
// Do not allow recursive exceptions, since the
// Application.ThreadException would eat them anyway.
try
{
using var form = new ErrorForm();
form.Initialize(e);
var result = form.ShowDialog(Form.ActiveForm);
if (result == DialogResult.Abort)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
Application.Exit();
}
}
catch (Exception x)
{
LogCentral.Current.LogError(
@"Exception occurred during exception handling.",
x);
XtraMessageBox.Show(
Form.ActiveForm,
string.Format(@"{0}{1}{1}{2}",
x.Message,
Environment.NewLine,
e.Message),
@"Zeta Resource Editor",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private static void storageError(
object sender,
PersistentPairStorageErrorEventArgs args)
{
if (args.RetryCount <= 2)
{
Application.DoEvents();
Thread.Sleep(0);
args.Result = CheckHandleExceptionResult.Retry;
}
else
{
args.Result = CheckHandleExceptionResult.Ignore;
}
}
public static ZlpDirectoryInfo CurrentUserStorageBaseFolderPath
{
get
{
if (_cacheForCurrentUserStorageBaseFolderPath == null)
{
const string folderName = @"Zeta Resource Editor";
var result = new ZlpDirectoryInfo(
ZlpPathHelper.Combine(
Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData),
folderName));
_cacheForCurrentUserStorageBaseFolderPath = result.CheckCreate();
}
return _cacheForCurrentUserStorageBaseFolderPath;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.PrinterSettings.cs
//
// Authors:
// Dennis Hayes ([email protected])
// Herve Poussineau ([email protected])
// Andreas Nahr ([email protected])
//
// (C) 2002 Ximian, Inc
// Copyright (C) 2004,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.Runtime.InteropServices;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Drawing.Imaging;
namespace System.Drawing.Printing
{
[Serializable]
public class PrinterSettings : ICloneable
{
private string printer_name;
private string print_filename;
private short copies;
private int maximum_page;
private int minimum_page;
private int from_page;
private int to_page;
private bool collate;
private PrintRange print_range;
internal int maximum_copies;
internal bool can_duplex;
internal bool supports_color;
internal int landscape_angle;
private bool print_tofile;
internal PrinterSettings.PrinterResolutionCollection printer_resolutions;
internal PrinterSettings.PaperSizeCollection paper_sizes;
internal PrinterSettings.PaperSourceCollection paper_sources;
private PageSettings default_pagesettings;
private Duplex duplex;
internal bool is_plotter;
internal NameValueCollection printer_capabilities; // this stores a list of all the printer options. Used only in cups, but might come in handy on win too.
public PrinterSettings()
{
printer_name = PrintingServices.DefaultPrinter;
ResetToDefaults();
PrintingServices.LoadPrinterSettings(printer_name, this);
}
private void ResetToDefaults()
{
printer_resolutions = null;
paper_sizes = null;
paper_sources = null;
default_pagesettings = null;
maximum_page = 9999;
copies = 1;
collate = true;
}
//properties
public bool CanDuplex
{
get { return can_duplex; }
}
public bool Collate
{
get { return collate; }
set { collate = value; }
}
public short Copies
{
get { return copies; }
set
{
if (value < 0)
throw new ArgumentException("The value of the Copies property is less than zero.");
copies = value;
}
}
public PageSettings DefaultPageSettings
{
get
{
if (default_pagesettings == null)
{
default_pagesettings = new PageSettings(this,
SupportsColor,
false,
// Real defaults are set by LoadPrinterSettings
new PaperSize("A4", 827, 1169),
new PaperSource(PaperSourceKind.FormSource, "Tray"),
new PrinterResolution(PrinterResolutionKind.Medium, 200, 200));
}
return default_pagesettings;
}
}
public Duplex Duplex
{
get { return this.duplex; }
set { this.duplex = value; }
}
public int FromPage
{
get { return from_page; }
set
{
if (value < 0)
throw new ArgumentException("The value of the FromPage property is less than zero");
from_page = value;
}
}
public static PrinterSettings.StringCollection InstalledPrinters
{
get { return PrintingServices.InstalledPrinters; }
}
public bool IsDefaultPrinter
{
get { return (printer_name == PrintingServices.DefaultPrinter); }
}
public bool IsPlotter
{
get { return is_plotter; }
}
public bool IsValid
{
get { return PrintingServices.IsPrinterValid(this.printer_name); }
}
public int LandscapeAngle
{
get { return landscape_angle; }
}
public int MaximumCopies
{
get { return maximum_copies; }
}
public int MaximumPage
{
get { return maximum_page; }
set
{
// This not documented but behaves like MinimumPage
if (value < 0)
throw new ArgumentException("The value of the MaximumPage property is less than zero");
maximum_page = value;
}
}
public int MinimumPage
{
get { return minimum_page; }
set
{
if (value < 0)
throw new ArgumentException("The value of the MaximumPage property is less than zero");
minimum_page = value;
}
}
public PrinterSettings.PaperSizeCollection PaperSizes
{
get
{
if (!this.IsValid)
throw new InvalidPrinterException(this);
return paper_sizes;
}
}
public PrinterSettings.PaperSourceCollection PaperSources
{
get
{
if (!this.IsValid)
throw new InvalidPrinterException(this);
return paper_sources;
}
}
public
string PrintFileName
{
get { return print_filename; }
set { print_filename = value; }
}
public string PrinterName
{
get { return printer_name; }
set
{
if (printer_name == value)
return;
printer_name = value;
PrintingServices.LoadPrinterSettings(printer_name, this);
}
}
public PrinterSettings.PrinterResolutionCollection PrinterResolutions
{
get
{
if (!this.IsValid)
throw new InvalidPrinterException(this);
if (printer_resolutions == null)
{
printer_resolutions = new PrinterSettings.PrinterResolutionCollection(new PrinterResolution[] { });
PrintingServices.LoadPrinterResolutions(printer_name, this);
}
return printer_resolutions;
}
}
public PrintRange PrintRange
{
get { return print_range; }
set
{
if (value != PrintRange.AllPages && value != PrintRange.Selection &&
value != PrintRange.SomePages)
throw new InvalidEnumArgumentException("The value of the PrintRange property is not one of the PrintRange values");
print_range = value;
}
}
public bool PrintToFile
{
get { return print_tofile; }
set { print_tofile = value; }
}
public bool SupportsColor
{
get { return supports_color; }
}
public int ToPage
{
get { return to_page; }
set
{
if (value < 0)
throw new ArgumentException("The value of the ToPage property is less than zero");
to_page = value;
}
}
internal NameValueCollection PrinterCapabilities
{
get
{
if (this.printer_capabilities == null)
this.printer_capabilities = new NameValueCollection();
return this.printer_capabilities;
}
}
//methods
public object Clone()
{
PrinterSettings ps = new PrinterSettings();
return ps;
}
[MonoTODO("PrinterSettings.CreateMeasurementGraphics")]
public Graphics CreateMeasurementGraphics()
{
throw new NotImplementedException();
}
[MonoTODO("PrinterSettings.CreateMeasurementGraphics")]
public Graphics CreateMeasurementGraphics(bool honorOriginAtMargins)
{
throw new NotImplementedException();
}
[MonoTODO("PrinterSettings.CreateMeasurementGraphics")]
public Graphics CreateMeasurementGraphics(PageSettings pageSettings)
{
throw new NotImplementedException();
}
[MonoTODO("PrinterSettings.CreateMeasurementGraphics")]
public Graphics CreateMeasurementGraphics(PageSettings pageSettings, bool honorOriginAtMargins)
{
throw new NotImplementedException();
}
[MonoTODO("PrinterSettings.GetHdevmode")]
public IntPtr GetHdevmode()
{
throw new NotImplementedException();
}
[MonoTODO("PrinterSettings.GetHdevmode")]
public IntPtr GetHdevmode(PageSettings pageSettings)
{
throw new NotImplementedException();
}
[MonoTODO("PrinterSettings.GetHdevname")]
public IntPtr GetHdevnames()
{
throw new NotImplementedException();
}
[MonoTODO("IsDirectPrintingSupported")]
public bool IsDirectPrintingSupported(Image image)
{
throw new NotImplementedException();
}
[MonoTODO("IsDirectPrintingSupported")]
public bool IsDirectPrintingSupported(ImageFormat imageFormat)
{
throw new NotImplementedException();
}
[MonoTODO("PrinterSettings.SetHdevmode")]
public void SetHdevmode(IntPtr hdevmode)
{
throw new NotImplementedException();
}
[MonoTODO("PrinterSettings.SetHdevnames")]
public void SetHdevnames(IntPtr hdevnames)
{
throw new NotImplementedException();
}
public override string ToString()
{
return "Printer [PrinterSettings " + printer_name + " Copies=" + copies + " Collate=" + collate
+ " Duplex=" + can_duplex + " FromPage=" + from_page + " LandscapeAngle=" + landscape_angle
+ " MaximumCopies=" + maximum_copies + " OutputPort=" + " ToPage=" + to_page + "]";
}
// Public subclasses
#region Public Subclasses
public class PaperSourceCollection : ICollection, IEnumerable
{
ArrayList _PaperSources = new ArrayList();
public PaperSourceCollection(PaperSource[] array)
{
foreach (PaperSource ps in array)
_PaperSources.Add(ps);
}
public int Count { get { return _PaperSources.Count; } }
int ICollection.Count { get { return _PaperSources.Count; } }
bool ICollection.IsSynchronized { get { return false; } }
object ICollection.SyncRoot { get { return this; } }
[EditorBrowsable(EditorBrowsableState.Never)]
public int Add(PaperSource paperSource) { return _PaperSources.Add(paperSource); }
public void CopyTo(PaperSource[] paperSources, int index) { throw new NotImplementedException(); }
public virtual PaperSource this[int index]
{
get { return _PaperSources[index] as PaperSource; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return _PaperSources.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return _PaperSources.GetEnumerator();
}
void ICollection.CopyTo(Array array, int index)
{
_PaperSources.CopyTo(array, index);
}
internal void Clear()
{
_PaperSources.Clear();
}
}
public class PaperSizeCollection : ICollection, IEnumerable
{
ArrayList _PaperSizes = new ArrayList();
public PaperSizeCollection(PaperSize[] array)
{
foreach (PaperSize ps in array)
_PaperSizes.Add(ps);
}
public int Count { get { return _PaperSizes.Count; } }
int ICollection.Count { get { return _PaperSizes.Count; } }
bool ICollection.IsSynchronized { get { return false; } }
object ICollection.SyncRoot { get { return this; } }
[EditorBrowsable(EditorBrowsableState.Never)]
public int Add(PaperSize paperSize) { return _PaperSizes.Add(paperSize); }
public void CopyTo(PaperSize[] paperSizes, int index) { throw new NotImplementedException(); }
public virtual PaperSize this[int index]
{
get { return _PaperSizes[index] as PaperSize; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return _PaperSizes.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return _PaperSizes.GetEnumerator();
}
void ICollection.CopyTo(Array array, int index)
{
_PaperSizes.CopyTo(array, index);
}
internal void Clear()
{
_PaperSizes.Clear();
}
}
public class PrinterResolutionCollection : ICollection, IEnumerable
{
ArrayList _PrinterResolutions = new ArrayList();
public PrinterResolutionCollection(PrinterResolution[] array)
{
foreach (PrinterResolution pr in array)
_PrinterResolutions.Add(pr);
}
public int Count { get { return _PrinterResolutions.Count; } }
int ICollection.Count { get { return _PrinterResolutions.Count; } }
bool ICollection.IsSynchronized { get { return false; } }
object ICollection.SyncRoot { get { return this; } }
[EditorBrowsable(EditorBrowsableState.Never)]
public int Add(PrinterResolution printerResolution) { return _PrinterResolutions.Add(printerResolution); }
public void CopyTo(PrinterResolution[] printerResolutions, int index) { throw new NotImplementedException(); }
public virtual PrinterResolution this[int index]
{
get { return _PrinterResolutions[index] as PrinterResolution; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return _PrinterResolutions.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return _PrinterResolutions.GetEnumerator();
}
void ICollection.CopyTo(Array array, int index)
{
_PrinterResolutions.CopyTo(array, index);
}
internal void Clear()
{
_PrinterResolutions.Clear();
}
}
public class StringCollection : ICollection, IEnumerable
{
ArrayList _Strings = new ArrayList();
public StringCollection(string[] array)
{
foreach (string s in array)
_Strings.Add(s);
}
public int Count { get { return _Strings.Count; } }
int ICollection.Count { get { return _Strings.Count; } }
bool ICollection.IsSynchronized { get { return false; } }
object ICollection.SyncRoot { get { return this; } }
public virtual string this[int index]
{
get { return _Strings[index] as string; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public int Add(string value) { return _Strings.Add(value); }
public void CopyTo(string[] strings, int index) { throw new NotImplementedException(); }
IEnumerator IEnumerable.GetEnumerator()
{
return _Strings.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
return _Strings.GetEnumerator();
}
void ICollection.CopyTo(Array array, int index)
{
_Strings.CopyTo(array, index);
}
}
#endregion
/*
void GetPrintDialogInfo (string printer_name, ref string port, ref string type, ref string status, ref string comment)
{
printing_services.GetPrintDialogInfo (printer_name, ref port, ref type, ref status, ref comment);
}
*/
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Provisioning.Cloud.Async.WebJob.Job
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Orders;
namespace Nop.Services.Catalog
{
/// <summary>
/// Product service
/// </summary>
public partial interface IProductService
{
#region Products
/// <summary>
/// Delete a product
/// </summary>
/// <param name="product">Product</param>
void DeleteProduct(Product product);
/// <summary>
/// Gets all products displayed on the home page
/// </summary>
/// <returns>Product collection</returns>
IList<Product> GetAllProductsDisplayedOnHomePage();
/// <summary>
/// Gets product
/// </summary>
/// <param name="productId">Product identifier</param>
/// <returns>Product</returns>
Product GetProductById(int productId);
/// <summary>
/// Gets products by identifier
/// </summary>
/// <param name="productIds">Product identifiers</param>
/// <returns>Products</returns>
IList<Product> GetProductsByIds(int[] productIds);
/// <summary>
/// Inserts a product
/// </summary>
/// <param name="product">Product</param>
void InsertProduct(Product product);
/// <summary>
/// Updates the product
/// </summary>
/// <param name="product">Product</param>
void UpdateProduct(Product product);
/// <summary>
/// Get (visible) product number in certain category
/// </summary>
/// <param name="categoryIds">Category identifiers</param>
/// <param name="storeId">Store identifier; 0 to load all records</param>
/// <returns>Product number</returns>
int GetCategoryProductNumber(IList<int> categoryIds = null, int storeId = 0);
/// <summary>
/// Search products
/// </summary>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="categoryIds">Category identifiers</param>
/// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param>
/// <param name="storeId">Store identifier; 0 to load all records</param>
/// <param name="vendorId">Vendor identifier; 0 to load all records</param>
/// <param name="warehouseId">Warehouse identifier; 0 to load all records</param>
/// <param name="parentGroupedProductId">Parent product identifier (used with grouped products); 0 to load all records</param>
/// <param name="productType">Product type; 0 to load all records</param>
/// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param>
/// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and manufacturers). 0 to load featured products only, 1 to load not featured products only, null to load all products</param>
/// <param name="priceMin">Minimum price; null to load all records</param>
/// <param name="priceMax">Maximum price; null to load all records</param>
/// <param name="productTagId">Product tag identifier; 0 to load all records</param>
/// <param name="keywords">Keywords</param>
/// <param name="searchDescriptions">A value indicating whether to search by a specified "keyword" in product descriptions</param>
/// <param name="searchSku">A value indicating whether to search by a specified "keyword" in product SKU</param>
/// <param name="searchProductTags">A value indicating whether to search by a specified "keyword" in product tags</param>
/// <param name="languageId">Language identifier (search for text searching)</param>
/// <param name="filteredSpecs">Filtered product specification identifiers</param>
/// <param name="orderBy">Order by</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Products</returns>
IPagedList<Product> SearchProducts(
int pageIndex = 0,
int pageSize = int.MaxValue,
IList<int> categoryIds = null,
int manufacturerId = 0,
int storeId = 0,
int vendorId = 0,
int warehouseId = 0,
int parentGroupedProductId = 0,
ProductType? productType = null,
bool visibleIndividuallyOnly = false,
bool? featuredProducts = null,
decimal? priceMin = null,
decimal? priceMax = null,
int productTagId = 0,
string keywords = null,
bool searchDescriptions = false,
bool searchSku = true,
bool searchProductTags = false,
int languageId = 0,
IList<int> filteredSpecs = null,
ProductSortingEnum orderBy = ProductSortingEnum.Position,
bool showHidden = false);
/// <summary>
/// Search products
/// </summary>
/// <param name="filterableSpecificationAttributeOptionIds">The specification attribute option identifiers applied to loaded products (all pages)</param>
/// <param name="loadFilterableSpecificationAttributeOptionIds">A value indicating whether we should load the specification attribute option identifiers applied to loaded products (all pages)</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="categoryIds">Category identifiers</param>
/// <param name="manufacturerId">Manufacturer identifier; 0 to load all records</param>
/// <param name="storeId">Store identifier; 0 to load all records</param>
/// <param name="vendorId">Vendor identifier; 0 to load all records</param>
/// <param name="warehouseId">Warehouse identifier; 0 to load all records</param>
/// <param name="parentGroupedProductId">Parent product identifier (used with grouped products); 0 to load all records</param>
/// <param name="productType">Product type; 0 to load all records</param>
/// <param name="visibleIndividuallyOnly">A values indicating whether to load only products marked as "visible individually"; "false" to load all records; "true" to load "visible individually" only</param>
/// <param name="featuredProducts">A value indicating whether loaded products are marked as featured (relates only to categories and manufacturers). 0 to load featured products only, 1 to load not featured products only, null to load all products</param>
/// <param name="priceMin">Minimum price; null to load all records</param>
/// <param name="priceMax">Maximum price; null to load all records</param>
/// <param name="productTagId">Product tag identifier; 0 to load all records</param>
/// <param name="keywords">Keywords</param>
/// <param name="searchDescriptions">A value indicating whether to search by a specified "keyword" in product descriptions</param>
/// <param name="searchSku">A value indicating whether to search by a specified "keyword" in product SKU</param>
/// <param name="searchProductTags">A value indicating whether to search by a specified "keyword" in product tags</param>
/// <param name="languageId">Language identifier (search for text searching)</param>
/// <param name="filteredSpecs">Filtered product specification identifiers</param>
/// <param name="orderBy">Order by</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Products</returns>
IPagedList<Product> SearchProducts(
out IList<int> filterableSpecificationAttributeOptionIds,
bool loadFilterableSpecificationAttributeOptionIds = false,
int pageIndex = 0,
int pageSize = int.MaxValue,
IList<int> categoryIds = null,
int manufacturerId = 0,
int storeId = 0,
int vendorId = 0,
int warehouseId = 0,
int parentGroupedProductId = 0,
ProductType? productType = null,
bool visibleIndividuallyOnly = false,
bool? featuredProducts = null,
decimal? priceMin = null,
decimal? priceMax = null,
int productTagId = 0,
string keywords = null,
bool searchDescriptions = false,
bool searchSku = true,
bool searchProductTags = false,
int languageId = 0,
IList<int> filteredSpecs = null,
ProductSortingEnum orderBy = ProductSortingEnum.Position,
bool showHidden = false);
/// <summary>
/// Gets associated products
/// </summary>
/// <param name="parentGroupedProductId">Parent product identifier (used with grouped products)</param>
/// <param name="storeId">Store identifier; 0 to load all records</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Products</returns>
IList<Product> GetAssociatedProducts(int parentGroupedProductId,
int storeId = 0, bool showHidden = false);
/// <summary>
/// Update product review totals
/// </summary>
/// <param name="product">Product</param>
void UpdateProductReviewTotals(Product product);
/// <summary>
/// Get low stock products
/// </summary>
/// <param name="vendorId">Vendor identifier; 0 to load all records</param>
/// <param name="products">Low stock products</param>
/// <param name="combinations">Low stock attribute combinations</param>
void GetLowStockProducts(int vendorId,
out IList<Product> products,
out IList<ProductVariantAttributeCombination> combinations);
/// <summary>
/// Gets a product by SKU
/// </summary>
/// <param name="sku">SKU</param>
/// <returns>Product</returns>
Product GetProductBySku(string sku);
/// <summary>
/// Adjusts inventory
/// </summary>
/// <param name="product">Product</param>
/// <param name="decrease">A value indicating whether to increase or descrease product stock quantity</param>
/// <param name="quantity">Quantity</param>
/// <param name="attributesXml">Attributes in XML format</param>
void AdjustInventory(Product product, bool decrease,
int quantity, string attributesXml);
/// <summary>
/// Update HasTierPrices property (used for performance optimization)
/// </summary>
/// <param name="product">Product</param>
void UpdateHasTierPricesProperty(Product product);
/// <summary>
/// Update HasDiscountsApplied property (used for performance optimization)
/// </summary>
/// <param name="product">Product</param>
void UpdateHasDiscountsApplied(Product product);
#endregion
#region Related products
/// <summary>
/// Deletes a related product
/// </summary>
/// <param name="relatedProduct">Related product</param>
void DeleteRelatedProduct(RelatedProduct relatedProduct);
/// <summary>
/// Gets a related product collection by product identifier
/// </summary>
/// <param name="productId1">The first product identifier</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Related product collection</returns>
IList<RelatedProduct> GetRelatedProductsByProductId1(int productId1, bool showHidden = false);
/// <summary>
/// Gets a related product
/// </summary>
/// <param name="relatedProductId">Related product identifier</param>
/// <returns>Related product</returns>
RelatedProduct GetRelatedProductById(int relatedProductId);
/// <summary>
/// Inserts a related product
/// </summary>
/// <param name="relatedProduct">Related product</param>
void InsertRelatedProduct(RelatedProduct relatedProduct);
/// <summary>
/// Updates a related product
/// </summary>
/// <param name="relatedProduct">Related product</param>
void UpdateRelatedProduct(RelatedProduct relatedProduct);
#endregion
#region Cross-sell products
/// <summary>
/// Deletes a cross-sell product
/// </summary>
/// <param name="crossSellProduct">Cross-sell</param>
void DeleteCrossSellProduct(CrossSellProduct crossSellProduct);
/// <summary>
/// Gets a cross-sell product collection by product identifier
/// </summary>
/// <param name="productId1">The first product identifier</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Cross-sell product collection</returns>
IList<CrossSellProduct> GetCrossSellProductsByProductId1(int productId1, bool showHidden = false);
/// <summary>
/// Gets a cross-sell product
/// </summary>
/// <param name="crossSellProductId">Cross-sell product identifier</param>
/// <returns>Cross-sell product</returns>
CrossSellProduct GetCrossSellProductById(int crossSellProductId);
/// <summary>
/// Inserts a cross-sell product
/// </summary>
/// <param name="crossSellProduct">Cross-sell product</param>
void InsertCrossSellProduct(CrossSellProduct crossSellProduct);
/// <summary>
/// Updates a cross-sell product
/// </summary>
/// <param name="crossSellProduct">Cross-sell product</param>
void UpdateCrossSellProduct(CrossSellProduct crossSellProduct);
/// <summary>
/// Gets a cross-sells
/// </summary>
/// <param name="cart">Shopping cart</param>
/// <param name="numberOfProducts">Number of products to return</param>
/// <returns>Cross-sells</returns>
IList<Product> GetCrosssellProductsByShoppingCart(IList<ShoppingCartItem> cart, int numberOfProducts);
#endregion
#region Tier prices
/// <summary>
/// Deletes a tier price
/// </summary>
/// <param name="tierPrice">Tier price</param>
void DeleteTierPrice(TierPrice tierPrice);
/// <summary>
/// Gets a tier price
/// </summary>
/// <param name="tierPriceId">Tier price identifier</param>
/// <returns>Tier price</returns>
TierPrice GetTierPriceById(int tierPriceId);
/// <summary>
/// Inserts a tier price
/// </summary>
/// <param name="tierPrice">Tier price</param>
void InsertTierPrice(TierPrice tierPrice);
/// <summary>
/// Updates the tier price
/// </summary>
/// <param name="tierPrice">Tier price</param>
void UpdateTierPrice(TierPrice tierPrice);
#endregion
#region Product pictures
/// <summary>
/// Deletes a product picture
/// </summary>
/// <param name="productPicture">Product picture</param>
void DeleteProductPicture(ProductPicture productPicture);
/// <summary>
/// Gets a product pictures by product identifier
/// </summary>
/// <param name="productId">The product identifier</param>
/// <returns>Product pictures</returns>
IList<ProductPicture> GetProductPicturesByProductId(int productId);
/// <summary>
/// Gets a product picture
/// </summary>
/// <param name="productPictureId">Product picture identifier</param>
/// <returns>Product picture</returns>
ProductPicture GetProductPictureById(int productPictureId);
/// <summary>
/// Inserts a product picture
/// </summary>
/// <param name="productPicture">Product picture</param>
void InsertProductPicture(ProductPicture productPicture);
/// <summary>
/// Updates a product picture
/// </summary>
/// <param name="productPicture">Product picture</param>
void UpdateProductPicture(ProductPicture productPicture);
#endregion
#region Product reviews
/// <summary>
/// Gets all product reviews
/// </summary>
/// <param name="customerId">Customer identifier; 0 to load all records</param>
/// <param name="approved">A value indicating whether to content is approved; null to load all records</param>
/// <param name="fromUtc">Item creation from; null to load all records</param>
/// <param name="toUtc">Item item creation to; null to load all records</param>
/// <param name="message">Search title or review text; null to load all records</param>
/// <returns>Reviews</returns>
IList<ProductReview> GetAllProductReviews(int customerId, bool? approved,
DateTime? fromUtc = null, DateTime? toUtc = null,
string message = null);
/// <summary>
/// Gets product review
/// </summary>
/// <param name="productReviewId">Product review identifier</param>
/// <returns>Product review</returns>
ProductReview GetProductReviewById(int productReviewId);
/// <summary>
/// Deletes a product review
/// </summary>
/// <param name="productReview">Product review</param>
void DeleteProductReview(ProductReview productReview);
#endregion
}
}
| |
//
// XmlConfigurationClient.cs
//
// Author:
// Scott Peterson <[email protected]>
//
// Copyright (C) 2007-2008 Scott Peterson
//
// 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.IO;
using System.Timers;
using System.Xml;
using System.Xml.Serialization;
using Hyena;
using Banshee.Base;
namespace Banshee.Configuration
{
public class XmlConfigurationClient : IConfigurationClient
{
private const string null_namespace = "null";
private const string namespace_tag_name = "namespace";
private const string value_tag_name = "value";
private const string tag_identifier_attribute_name = "name";
private const string skel_path = "/etc/skel/.config/banshee-1/config.xml";
private static string file_path {
get {
return Path.Combine(Paths.ApplicationData, "config.xml");
}
}
private static XmlDocument xml_document;
private static System.Timers.Timer timer;
private static object timer_mutex = new object();
private static volatile bool delay_write;
public XmlConfigurationClient()
{
timer = new System.Timers.Timer(100); // a 10th of a second
timer.Elapsed += new ElapsedEventHandler(OnTimerElapsedEvent);
timer.AutoReset = true;
xml_document = new XmlDocument();
bool make_new_xml = true;
string load_path = null;
if (File.Exists (file_path)) {
load_path = file_path;
} else if (File.Exists (skel_path)) {
Hyena.Log.InformationFormat ("Restoring config.xml from {0}", skel_path);
load_path = skel_path;
}
if (load_path != null && File.Exists (load_path)) {
try {
xml_document.Load (load_path);
make_new_xml = false;
} catch { // TODO try recovery?
}
}
if(make_new_xml) {
xml_document.LoadXml("<configuration />");
}
}
public bool TryGet<T>(string namespce, string key, out T result)
{
lock(xml_document) {
XmlNode namespace_node = GetNamespaceNode(namespce == null
? new string [] {null_namespace}
: namespce.Split('.'), false);
if(namespace_node != null) {
foreach(XmlNode node in namespace_node.ChildNodes) {
if(node.Attributes[tag_identifier_attribute_name].Value == key && node.Name == value_tag_name) {
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (var reader = new StringReader(node.InnerXml) ) {
result = (T) serializer.Deserialize(reader);
return true;
}
}
}
}
result = default (T);
return false;
}
}
public void Set<T>(SchemaEntry<T> entry, T value)
{
Set(entry.Namespace, entry.Key, value);
}
public void Set<T>(string key, T value)
{
Set(null, key, value);
}
public void Set<T>(string namespce, string key, T value)
{
lock(xml_document) {
XmlSerializer serializer = new XmlSerializer(typeof(T));
var fragment = xml_document.CreateDocumentFragment();
using (var writer = new StringWriter()) {
serializer.Serialize(writer, value);
fragment.InnerXml = writer.ToString();
}
if(fragment.FirstChild is XmlDeclaration) {
fragment.RemoveChild(fragment.FirstChild); // This is only a problem with Microsoft's System.Xml
}
XmlNode namespace_node = GetNamespaceNode(namespce == null
? new string [] {null_namespace}
: namespce.Split('.'), true);
bool found = false;
foreach(XmlNode node in namespace_node.ChildNodes) {
if(node.Attributes[tag_identifier_attribute_name].Value == key && node.Name == value_tag_name) {
node.InnerXml = fragment.InnerXml;
found = true;
break;
}
}
if(!found) {
XmlNode new_node = xml_document.CreateElement(value_tag_name);
XmlAttribute attribute = xml_document.CreateAttribute(tag_identifier_attribute_name);
attribute.Value = key;
new_node.Attributes.Append(attribute);
new_node.AppendChild(fragment);
namespace_node.AppendChild(new_node);
}
QueueWrite();
}
}
private XmlNode GetNamespaceNode(string [] namespace_parts, bool create)
{
return GetNamespaceNode(xml_document.DocumentElement, namespace_parts, create);
}
private XmlNode GetNamespaceNode(XmlNode parent_node, string [] namespace_parts, bool create)
{
XmlNode node = parent_node.FirstChild ?? parent_node;
do {
if(node.Name == namespace_tag_name && node.Attributes[tag_identifier_attribute_name].Value == namespace_parts[0]) {
if(namespace_parts.Length > 1) {
string [] new_namespace_parts = new string[namespace_parts.Length - 1];
for(int i = 1; i < namespace_parts.Length; i++) {
new_namespace_parts[i - 1] = namespace_parts[i];
}
node = GetNamespaceNode(node, new_namespace_parts, create);
}
return node;
} else {
node = node.NextSibling;
}
} while(node != null);
if(create) {
XmlNode appending_node = parent_node;
foreach(string s in namespace_parts) {
XmlNode new_node = xml_document.CreateElement(namespace_tag_name);
XmlAttribute attribute = xml_document.CreateAttribute(tag_identifier_attribute_name);
attribute.Value = s;
new_node.Attributes.Append(attribute);
appending_node.AppendChild(new_node);
appending_node = new_node;
}
node = appending_node;
}
return node;
}
// Queue XML file writes to minimize disk access
private static void QueueWrite()
{
lock(timer_mutex) {
if(!timer.Enabled) {
timer.Start();
} else {
delay_write = true;
}
}
}
private static void OnTimerElapsedEvent(object o, ElapsedEventArgs args)
{
lock(timer_mutex) {
if(delay_write) {
delay_write = false;
} else {
xml_document.Save(file_path);
timer.Stop();
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataGridViewRowPostPaintEventArgs.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms
{
using System;
using System.Drawing;
using System.ComponentModel;
using System.Diagnostics;
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs"]/*' />
public class DataGridViewRowPostPaintEventArgs : EventArgs
{
private DataGridView dataGridView;
private Graphics graphics;
private Rectangle clipBounds;
private Rectangle rowBounds;
private DataGridViewCellStyle inheritedRowStyle;
private int rowIndex;
private DataGridViewElementStates rowState;
private string errorText;
private bool isFirstDisplayedRow;
private bool isLastVisibleRow;
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.DataGridViewRowPostPaintEventArgs"]/*' />
public DataGridViewRowPostPaintEventArgs(DataGridView dataGridView,
Graphics graphics,
Rectangle clipBounds,
Rectangle rowBounds,
int rowIndex,
DataGridViewElementStates rowState,
string errorText,
DataGridViewCellStyle inheritedRowStyle,
bool isFirstDisplayedRow,
bool isLastVisibleRow)
{
if (dataGridView == null)
{
throw new ArgumentNullException("dataGridView");
}
if (graphics == null)
{
throw new ArgumentNullException("graphics");
}
if (inheritedRowStyle == null)
{
throw new ArgumentNullException("inheritedRowStyle");
}
this.dataGridView = dataGridView;
this.graphics = graphics;
this.clipBounds = clipBounds;
this.rowBounds = rowBounds;
this.rowIndex = rowIndex;
this.rowState = rowState;
this.errorText = errorText;
this.inheritedRowStyle = inheritedRowStyle;
this.isFirstDisplayedRow = isFirstDisplayedRow;
this.isLastVisibleRow = isLastVisibleRow;
}
internal DataGridViewRowPostPaintEventArgs(DataGridView dataGridView)
{
Debug.Assert(dataGridView != null);
this.dataGridView = dataGridView;
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.ClipBounds"]/*' />
public Rectangle ClipBounds
{
get
{
return this.clipBounds;
}
set
{
this.clipBounds = value;
}
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.ErrorText"]/*' />
public string ErrorText
{
get
{
return this.errorText;
}
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.Graphics"]/*' />
public Graphics Graphics
{
get
{
return this.graphics;
}
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.InheritedRowStyle"]/*' />
public DataGridViewCellStyle InheritedRowStyle
{
get
{
return this.inheritedRowStyle;
}
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.IsFirstDisplayedRow"]/*' />
public bool IsFirstDisplayedRow
{
get
{
return this.isFirstDisplayedRow;
}
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.IsLastVisibleRow"]/*' />
public bool IsLastVisibleRow
{
get
{
return this.isLastVisibleRow;
}
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.RowBounds"]/*' />
public Rectangle RowBounds
{
get
{
return this.rowBounds;
}
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.RowIndex"]/*' />
public int RowIndex
{
get
{
return this.rowIndex;
}
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.State"]/*' />
public DataGridViewElementStates State
{
get
{
return this.rowState;
}
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.DrawFocus"]/*' />
public void DrawFocus(Rectangle bounds, bool cellsPaintSelectionBackground)
{
if (this.rowIndex < 0 || this.rowIndex >= this.dataGridView.Rows.Count)
{
throw new InvalidOperationException(SR.GetString(SR.DataGridViewElementPaintingEventArgs_RowIndexOutOfRange));
}
this.dataGridView.Rows.SharedRow(rowIndex).DrawFocus(this.graphics,
this.clipBounds,
bounds,
this.rowIndex,
this.rowState,
this.inheritedRowStyle,
cellsPaintSelectionBackground);
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.PaintCells"]/*' />
public void PaintCells(Rectangle clipBounds, DataGridViewPaintParts paintParts)
{
if (this.rowIndex < 0 || this.rowIndex >= this.dataGridView.Rows.Count)
{
throw new InvalidOperationException(SR.GetString(SR.DataGridViewElementPaintingEventArgs_RowIndexOutOfRange));
}
this.dataGridView.Rows.SharedRow(rowIndex).PaintCells(this.graphics,
clipBounds,
this.rowBounds,
this.rowIndex,
this.rowState,
this.isFirstDisplayedRow,
this.isLastVisibleRow,
paintParts);
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.PaintCellsBackground"]/*' />
public void PaintCellsBackground(Rectangle clipBounds, bool cellsPaintSelectionBackground)
{
if (this.rowIndex < 0 || this.rowIndex >= this.dataGridView.Rows.Count)
{
throw new InvalidOperationException(SR.GetString(SR.DataGridViewElementPaintingEventArgs_RowIndexOutOfRange));
}
DataGridViewPaintParts paintParts = DataGridViewPaintParts.Background | DataGridViewPaintParts.Border;
if (cellsPaintSelectionBackground)
{
paintParts |= DataGridViewPaintParts.SelectionBackground;
}
this.dataGridView.Rows.SharedRow(rowIndex).PaintCells(this.graphics,
clipBounds,
this.rowBounds,
this.rowIndex,
this.rowState,
this.isFirstDisplayedRow,
this.isLastVisibleRow,
paintParts);
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.PaintCellsContent"]/*' />
public void PaintCellsContent(Rectangle clipBounds)
{
if (this.rowIndex < 0 || this.rowIndex >= this.dataGridView.Rows.Count)
{
throw new InvalidOperationException(SR.GetString(SR.DataGridViewElementPaintingEventArgs_RowIndexOutOfRange));
}
this.dataGridView.Rows.SharedRow(rowIndex).PaintCells(this.graphics,
clipBounds,
this.rowBounds,
this.rowIndex,
this.rowState,
this.isFirstDisplayedRow,
this.isLastVisibleRow,
DataGridViewPaintParts.ContentBackground | DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.ErrorIcon);
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.PaintHeader1"]/*' />
public void PaintHeader(bool paintSelectionBackground)
{
DataGridViewPaintParts paintParts = DataGridViewPaintParts.Background | DataGridViewPaintParts.Border | DataGridViewPaintParts.ContentBackground | DataGridViewPaintParts.ContentForeground | DataGridViewPaintParts.ErrorIcon;
if (paintSelectionBackground)
{
paintParts |= DataGridViewPaintParts.SelectionBackground;
}
PaintHeader(paintParts);
}
/// <include file='doc\DataGridViewRowPostPaintEventArgs.uex' path='docs/doc[@for="DataGridViewRowPostPaintEventArgs.PaintHeader2"]/*' />
public void PaintHeader(DataGridViewPaintParts paintParts)
{
if (this.rowIndex < 0 || this.rowIndex >= this.dataGridView.Rows.Count)
{
throw new InvalidOperationException(SR.GetString(SR.DataGridViewElementPaintingEventArgs_RowIndexOutOfRange));
}
this.dataGridView.Rows.SharedRow(rowIndex).PaintHeader(this.graphics,
this.clipBounds,
this.rowBounds,
this.rowIndex,
this.rowState,
this.isFirstDisplayedRow,
this.isLastVisibleRow,
paintParts);
}
internal void SetProperties(Graphics graphics,
Rectangle clipBounds,
Rectangle rowBounds,
int rowIndex,
DataGridViewElementStates rowState,
string errorText,
DataGridViewCellStyle inheritedRowStyle,
bool isFirstDisplayedRow,
bool isLastVisibleRow)
{
Debug.Assert(graphics != null);
Debug.Assert(inheritedRowStyle != null);
this.graphics = graphics;
this.clipBounds = clipBounds;
this.rowBounds = rowBounds;
this.rowIndex = rowIndex;
this.rowState = rowState;
this.errorText = errorText;
this.inheritedRowStyle = inheritedRowStyle;
this.isFirstDisplayedRow = isFirstDisplayedRow;
this.isLastVisibleRow = isLastVisibleRow;
}
}
}
| |
using System.Threading.Tasks;
using LockStockAuth.Auth.Managers;
using LockStockAuth.Auth.Models;
namespace LockStockAuth.Auth.Controllers
{
[Authorize]
[RoutePrefix("/Account")]
public class AccountController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View("~/Auth/Views/Account/Login.cshtml");
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View("~/Auth/Views/Account/Login.cshtml", model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View("~/Auth/Views/Account/Login.cshtml", model);
}
}
//
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
{
// Require that the user has already logged in via username/password or external login
if (!await SignInManager.HasBeenVerifiedAsync())
{
return View("Error");
}
return View("~/Auth/Views/Account/VerifyCode.cshtml", new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View("~/Auth/Views/Account/VerifyCode.cshtml", model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(model.ReturnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid code.");
return View("~/Auth/Views/Account/VerifyCode.cshtml", model);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View("~/Auth/Views/Account/Register.cshtml");
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
SignInManager.SignIn(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View("~/Auth/Views/Account/Register.cshtml", model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View("~/Auth/Views/Account/ForgotPassword.cshtml");
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("~/Auth/Views/Account/ForgotPasswordConfirmation.cshtml");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View("~/Auth/Views/Account/ForgotPassword.cshtml", model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return View("~/Auth/Views/Account/ForgotPasswordConfirmation.cshtml");
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View("~/Auth/Views/Account/ResetPassword.cshtml");
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View("~/Auth/Views/Account/ResetPassword.cshtml", model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("Confirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View("~/Auth/Views/Account/ResetPassword.cshtml");
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return View("~/Auth/Views/Account/ResetPasswordConfirmation.cshtml");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View("~/Auth/Views/Account/SendCode.cshtml", new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View("~/Auth/Views/Account/SendCode.cshtml");
}
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return View("Error");
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("~/Auth/Views/Account/ExternalLoginConfirmation.cshtml", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("~/Auth/Views/Account/ExternalLoginFailure.cshtml");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View("~/Auth/Views/Account/ExternalLoginConfirmation.cshtml", model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View("~/Auth/Views/Account/ExternalLoginFailure.cshtml");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
if (_signInManager != null)
{
_signInManager.Dispose();
_signInManager = null;
}
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for ProjectImportElement class.</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Construction;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Tests for the ProjectImportElement class
/// </summary>
[TestClass]
public class ProjectImportElement_Tests
{
/// <summary>
/// Read project with no imports
/// </summary>
[TestMethod]
public void ReadNone()
{
ProjectRootElement project = ProjectRootElement.Create();
Assert.AreEqual(null, project.Imports.GetEnumerator().Current);
}
/// <summary>
/// Read import with no project attribute
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidMissingProject()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read import with empty project attribute
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidEmptyProject()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project=''/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read import with unexpected attribute
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidAttribute()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='p' X='Y'/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read basic valid imports
/// </summary>
[TestMethod]
public void ReadBasic()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='i1.proj' />
<Import Project='i2.proj' Condition='c'/>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
List<ProjectImportElement> imports = Helpers.MakeList(project.Imports);
Assert.AreEqual(2, imports.Count);
Assert.AreEqual("i1.proj", imports[0].Project);
Assert.AreEqual("i2.proj", imports[1].Project);
Assert.AreEqual("c", imports[1].Condition);
}
/// <summary>
/// Set valid project on import
/// </summary>
[TestMethod]
public void SetProjectValid()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='i1.proj' />
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectImportElement import = (ProjectImportElement)Helpers.GetFirst(project.Children);
import.Project = "i1b.proj";
Assert.AreEqual("i1b.proj", import.Project);
}
/// <summary>
/// Set invalid empty project value on import
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SetProjectInvalidEmpty()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='i1.proj' />
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectImportElement import = (ProjectImportElement)Helpers.GetFirst(project.Children);
import.Project = String.Empty;
}
/// <summary>
/// Setting the project attribute should dirty the project
/// </summary>
[TestMethod]
public void SettingProjectDirties()
{
string file1 = null;
string file2 = null;
try
{
file1 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement importProject1 = ProjectRootElement.Create();
importProject1.AddProperty("p", "v1");
importProject1.Save(file1);
file2 = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement importProject2 = ProjectRootElement.Create();
importProject2.AddProperty("p", "v2");
importProject2.Save(file2);
string content = String.Format
(
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='{0}'/>
</Project>",
file1
);
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectImportElement import = Helpers.GetFirst(project.Xml.Imports);
import.Project = file2;
Assert.AreEqual("v1", project.GetPropertyValue("p"));
project.ReevaluateIfNecessary();
Assert.AreEqual("v2", project.GetPropertyValue("p"));
}
finally
{
File.Delete(file1);
File.Delete(file2);
}
}
/// <summary>
/// Setting the condition should dirty the project
/// </summary>
[TestMethod]
public void SettingConditionDirties()
{
string file = null;
try
{
file = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement importProject = ProjectRootElement.Create();
importProject.AddProperty("p", "v1");
importProject.Save(file);
string content = String.Format
(
@"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='{0}'/>
</Project>",
file
);
Project project = new Project(XmlReader.Create(new StringReader(content)));
ProjectImportElement import = Helpers.GetFirst(project.Xml.Imports);
import.Condition = "false";
Assert.AreEqual("v1", project.GetPropertyValue("p"));
project.ReevaluateIfNecessary();
Assert.AreEqual(String.Empty, project.GetPropertyValue("p"));
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// Importing a project which has a relative path
/// </summary>
[TestMethod]
public void ImportWithRelativePath()
{
string tempPath = Path.GetTempPath();
string testTempPath = Path.Combine(tempPath, "UnitTestsPublicOm");
string projectfile = Path.Combine(testTempPath, "a.proj");
string targetsFile = Path.Combine(tempPath, "x.targets");
string projectfileContent = String.Format
(
@"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='{0}'/>
</Project>
",
testTempPath + "\\..\\x.targets"
);
string targetsfileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
</Project>
";
try
{
Directory.CreateDirectory(testTempPath);
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectfileContent)));
project.Save(projectfile);
project = ProjectRootElement.Create(XmlReader.Create(new StringReader(targetsfileContent)));
project.Save(targetsFile);
Project msbuildProject = new Project(projectfile);
}
finally
{
if (Directory.Exists(testTempPath))
{
Directory.Delete(testTempPath, true);
}
if (File.Exists(targetsFile))
{
File.Delete(targetsFile);
}
}
}
}
}
| |
#if UNITY_EDITOR
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus 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
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics;
[InitializeOnLoad]
class OVRPluginUpdater
{
enum PluginPlatform
{
Android,
AndroidUniversal,
OSXUniversal,
Win,
Win64,
}
class PluginPackage
{
public string RootPath;
public System.Version Version;
public Dictionary<PluginPlatform, string> Plugins = new Dictionary<PluginPlatform, string>();
public bool IsBundledPluginPackage()
{
return (RootPath == GetBundledPluginRootPath());
}
public bool IsEnabled()
{
// TODO: Check each individual platform rather than using the Win64 DLL status for the overall package status.
string path = "";
if (Plugins.TryGetValue(PluginPlatform.Win64, out path))
{
return File.Exists(path);
}
return false;
}
public bool IsAndroidUniversalEnabled()
{
string path = "";
if (Plugins.TryGetValue(PluginPlatform.AndroidUniversal, out path))
{
if (File.Exists(path))
{
string basePath = GetCurrentProjectPath();
string relPath = path.Substring(basePath.Length + 1);
PluginImporter pi = PluginImporter.GetAtPath(relPath) as PluginImporter;
if (pi != null)
{
return pi.GetCompatibleWithPlatform(BuildTarget.Android);
}
}
}
return false;
}
public bool IsAndroidUniversalPresent()
{
string path = "";
if (Plugins.TryGetValue(PluginPlatform.AndroidUniversal, out path))
{
string disabledPath = path + GetDisabledPluginSuffix();
if (File.Exists(path) || File.Exists(disabledPath))
{
return true;
}
}
return false;
}
}
private static bool restartPending = false;
private static bool unityVersionSupportsAndroidUniversal = false;
private static bool enableAndroidUniversalSupport = true;
static OVRPluginUpdater()
{
EditorApplication.delayCall += OnDelayCall;
}
static void OnDelayCall()
{
if (enableAndroidUniversalSupport)
{
#if UNITY_2018_1_OR_NEWER
// Temporarily disable the AndroidUniversal plugin because of a plugin copying error in Unity
unityVersionSupportsAndroidUniversal = false;
#endif
}
if (ShouldAttemptPluginUpdate())
{
AttemptPluginUpdate(true);
}
}
private static PluginPackage GetPluginPackage(string rootPath)
{
return new PluginPackage()
{
RootPath = rootPath,
Version = GetPluginVersion(rootPath),
Plugins = new Dictionary<PluginPlatform, string>()
{
{ PluginPlatform.Android, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.Android) },
{ PluginPlatform.AndroidUniversal, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.AndroidUniversal) },
{ PluginPlatform.OSXUniversal, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.OSXUniversal) },
{ PluginPlatform.Win, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.Win) },
{ PluginPlatform.Win64, rootPath + GetPluginBuildTargetSubPath(PluginPlatform.Win64) },
}
};
}
private static PluginPackage GetBundledPluginPackage()
{
return GetPluginPackage(GetBundledPluginRootPath());
}
private static List<PluginPackage> GetAllUtilitiesPluginPackages()
{
string pluginRootPath = GetUtilitiesPluginRootPath();
List<PluginPackage> packages = new List<PluginPackage>();
if (Directory.Exists(pluginRootPath))
{
var dirs = Directory.GetDirectories(pluginRootPath);
foreach(string dir in dirs)
{
packages.Add(GetPluginPackage(dir));
}
}
return packages;
}
private static string GetCurrentProjectPath()
{
return Directory.GetParent(Application.dataPath).FullName;
}
private static string GetUtilitiesPluginRootPath()
{
return GetUtilitiesRootPath() + @"/Plugins";
}
private static string GetUtilitiesRootPath()
{
var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string assetPath = AssetDatabase.GetAssetPath(script);
string editorDir = Directory.GetParent(assetPath).FullName;
string ovrDir = Directory.GetParent(editorDir).FullName;
return ovrDir;
}
private static string GetBundledPluginRootPath()
{
string basePath = EditorApplication.applicationContentsPath;
string pluginPath = @"/UnityExtensions/Unity/VR";
return basePath + pluginPath;
}
private static string GetPluginBuildTargetSubPath(PluginPlatform target)
{
string path = string.Empty;
switch (target)
{
case PluginPlatform.Android:
path = @"/Android/OVRPlugin.aar";
break;
case PluginPlatform.AndroidUniversal:
path = @"/AndroidUniversal/OVRPlugin.aar";
break;
case PluginPlatform.OSXUniversal:
path = @"/OSXUniversal/OVRPlugin.bundle";
break;
case PluginPlatform.Win:
path = @"/Win/OVRPlugin.dll";
break;
case PluginPlatform.Win64:
path = @"/Win64/OVRPlugin.dll";
break;
default:
throw new ArgumentException("Attempted GetPluginBuildTargetSubPath() for unsupported BuildTarget: " + target);
}
return path;
}
private static string GetDisabledPluginSuffix()
{
return @".disabled";
}
private static System.Version GetPluginVersion(string path)
{
System.Version invalidVersion = new System.Version("0.0.0");
System.Version pluginVersion = invalidVersion;
try
{
pluginVersion = new System.Version(Path.GetFileName(path));
}
catch
{
pluginVersion = invalidVersion;
}
if (pluginVersion == invalidVersion)
{
//Unable to determine version from path, fallback to Win64 DLL meta data
path += GetPluginBuildTargetSubPath(PluginPlatform.Win64);
if (!File.Exists(path))
{
path += GetDisabledPluginSuffix();
if (!File.Exists(path))
{
return invalidVersion;
}
}
FileVersionInfo pluginVersionInfo = FileVersionInfo.GetVersionInfo(path);
if (pluginVersionInfo == null || pluginVersionInfo.ProductVersion == null || pluginVersionInfo.ProductVersion == "")
{
return invalidVersion;
}
pluginVersion = new System.Version(pluginVersionInfo.ProductVersion);
}
return pluginVersion;
}
private static bool ShouldAttemptPluginUpdate()
{
return !UnitySupportsEnabledAndroidPlugin() || (autoUpdateEnabled && !restartPending && !Application.isPlaying);
}
private static void DisableAllUtilitiesPluginPackages()
{
List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();
foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
{
foreach(string path in pluginPkg.Plugins.Values)
{
if ((Directory.Exists(path)) || (File.Exists(path)))
{
string basePath = GetCurrentProjectPath();
string relPath = path.Substring(basePath.Length + 1);
string relDisabledPath = relPath + GetDisabledPluginSuffix();
AssetDatabase.MoveAsset(relPath, relDisabledPath);
AssetDatabase.ImportAsset(relDisabledPath, ImportAssetOptions.ForceUpdate);
}
}
}
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
private static void EnablePluginPackage(PluginPackage pluginPkg)
{
foreach(var kvp in pluginPkg.Plugins)
{
PluginPlatform platform = kvp.Key;
string path = kvp.Value;
if ((Directory.Exists(path + GetDisabledPluginSuffix())) || (File.Exists(path + GetDisabledPluginSuffix())))
{
string basePath = GetCurrentProjectPath();
string relPath = path.Substring(basePath.Length + 1);
string relDisabledPath = relPath + GetDisabledPluginSuffix();
AssetDatabase.MoveAsset(relDisabledPath, relPath);
AssetDatabase.ImportAsset(relPath, ImportAssetOptions.ForceUpdate);
PluginImporter pi = PluginImporter.GetAtPath(relPath) as PluginImporter;
if (pi == null)
{
continue;
}
// Disable support for all platforms, then conditionally enable desired support below
pi.SetCompatibleWithEditor(false);
pi.SetCompatibleWithAnyPlatform(false);
pi.SetCompatibleWithPlatform(BuildTarget.Android, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false);
#if UNITY_2017_3_OR_NEWER
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, false);
#else
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false);
#endif
switch (platform)
{
case PluginPlatform.Android:
pi.SetCompatibleWithPlatform(BuildTarget.Android, !unityVersionSupportsAndroidUniversal);
pi.SetPlatformData(BuildTarget.Android, "CPU", "ARMv7");
break;
case PluginPlatform.AndroidUniversal:
pi.SetCompatibleWithPlatform(BuildTarget.Android, unityVersionSupportsAndroidUniversal);
pi.SetPlatformData(BuildTarget.Android, "CPU", "ARM64");
break;
case PluginPlatform.OSXUniversal:
#if UNITY_2017_3_OR_NEWER
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSX, true);
#else
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, true);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, true);
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, true);
#endif
pi.SetCompatibleWithEditor(true);
pi.SetEditorData("CPU", "AnyCPU");
pi.SetEditorData("OS", "OSX");
pi.SetPlatformData("Editor", "CPU", "AnyCPU");
pi.SetPlatformData("Editor", "OS", "OSX");
break;
case PluginPlatform.Win:
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, true);
pi.SetCompatibleWithEditor(true);
pi.SetEditorData("CPU", "X86");
pi.SetEditorData("OS", "Windows");
pi.SetPlatformData("Editor", "CPU", "X86");
pi.SetPlatformData("Editor", "OS", "Windows");
break;
case PluginPlatform.Win64:
pi.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, true);
pi.SetCompatibleWithEditor(true);
pi.SetEditorData("CPU", "X86_64");
pi.SetEditorData("OS", "Windows");
pi.SetPlatformData("Editor", "CPU", "X86_64");
pi.SetPlatformData("Editor", "OS", "Windows");
break;
default:
throw new ArgumentException("Attempted EnablePluginPackage() for unsupported BuildTarget: " + platform);
}
AssetDatabase.ImportAsset(relPath, ImportAssetOptions.ForceUpdate);
}
}
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
private static readonly string autoUpdateEnabledKey = "Oculus_Utilities_OVRPluginUpdater_AutoUpdate_" + OVRManager.utilitiesVersion;
private static bool autoUpdateEnabled
{
get {
return PlayerPrefs.GetInt(autoUpdateEnabledKey, 1) == 1;
}
set {
PlayerPrefs.SetInt(autoUpdateEnabledKey, value ? 1 : 0);
}
}
[MenuItem("Tools/Oculus/Disable OVR Utilities Plugin")]
private static void AttemptPluginDisable()
{
PluginPackage bundledPluginPkg = GetBundledPluginPackage();
List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();
PluginPackage enabledUtilsPluginPkg = null;
foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
{
if (pluginPkg.IsEnabled())
{
if ((enabledUtilsPluginPkg == null) || (pluginPkg.Version > enabledUtilsPluginPkg.Version))
{
enabledUtilsPluginPkg = pluginPkg;
}
}
}
if (enabledUtilsPluginPkg == null)
{
if (EditorUtility.DisplayDialog("Disable Oculus Utilities Plugin", "The OVRPlugin included with Oculus Utilities is already disabled. The OVRPlugin bundled with the Unity Editor will continue to be used.\n\nBundled version: " + bundledPluginPkg.Version, "Ok", ""))
{
return;
}
}
else
{
if (EditorUtility.DisplayDialog("Disable Oculus Utilities Plugin", "Do you want to disable the OVRPlugin included with Oculus Utilities and revert to the OVRPlugin bundled with the Unity Editor?\n\nCurrent version: " + enabledUtilsPluginPkg.Version + "\nBundled version: " + bundledPluginPkg.Version, "Yes", "No"))
{
DisableAllUtilitiesPluginPackages();
if (EditorUtility.DisplayDialog("Restart Unity", "OVRPlugin has been updated to " + bundledPluginPkg.Version + ".\n\nPlease restart the Unity Editor to complete the update process. You may need to manually relaunch Unity if you are using Unity 5.6 and higher.", "Restart", "Not Now"))
{
RestartUnityEditor();
}
}
}
}
[MenuItem("Tools/Oculus/Update OVR Utilities Plugin")]
private static void RunPluginUpdate()
{
AttemptPluginUpdate(false);
}
private static void AttemptPluginUpdate(bool triggeredByAutoUpdate)
{
OVRPlugin.SendEvent("attempt_plugin_update_auto", triggeredByAutoUpdate.ToString());
autoUpdateEnabled = true;
PluginPackage bundledPluginPkg = GetBundledPluginPackage();
List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();
PluginPackage enabledUtilsPluginPkg = null;
PluginPackage newestUtilsPluginPkg = null;
foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
{
if ((newestUtilsPluginPkg == null) || (pluginPkg.Version > newestUtilsPluginPkg.Version))
{
newestUtilsPluginPkg = pluginPkg;
}
if (pluginPkg.IsEnabled())
{
if ((enabledUtilsPluginPkg == null) || (pluginPkg.Version > enabledUtilsPluginPkg.Version))
{
enabledUtilsPluginPkg = pluginPkg;
}
}
}
bool reenableCurrentPluginPkg = false;
PluginPackage targetPluginPkg = null;
if ((newestUtilsPluginPkg != null) && (newestUtilsPluginPkg.Version > bundledPluginPkg.Version))
{
if ((enabledUtilsPluginPkg == null) || (enabledUtilsPluginPkg.Version != newestUtilsPluginPkg.Version))
{
targetPluginPkg = newestUtilsPluginPkg;
}
}
else if ((enabledUtilsPluginPkg != null) && (enabledUtilsPluginPkg.Version < bundledPluginPkg.Version))
{
targetPluginPkg = bundledPluginPkg;
}
PluginPackage currentPluginPkg = (enabledUtilsPluginPkg != null) ? enabledUtilsPluginPkg : bundledPluginPkg;
if ((targetPluginPkg == null) && !UnitySupportsEnabledAndroidPlugin())
{
// Force reenabling the current package to configure the correct android plugin for this unity version.
reenableCurrentPluginPkg = true;
targetPluginPkg = currentPluginPkg;
}
if (targetPluginPkg == null)
{
if (!triggeredByAutoUpdate)
{
EditorUtility.DisplayDialog("Update Oculus Utilities Plugin", "OVRPlugin is already up to date.\n\nCurrent version: " + currentPluginPkg.Version + "\nBundled version: " + bundledPluginPkg.Version, "Ok", "");
}
return; // No update necessary.
}
System.Version targetVersion = targetPluginPkg.Version;
string dialogBody = "Oculus Utilities has detected that a newer OVRPlugin is available. Using the newest version is recommended. Do you want to enable it?\n\nCurrent version: "
+ currentPluginPkg.Version
+ "\nAvailable version: "
+ targetVersion;
if (reenableCurrentPluginPkg)
{
dialogBody = "Oculus Utilities has detected a configuration change that requires re-enabling the current OVRPlugin. Do you want to proceed?\n\nCurrent version: "
+ currentPluginPkg.Version;
}
int dialogResult = EditorUtility.DisplayDialogComplex("Update Oculus Utilities Plugin", dialogBody, "Yes", "No, Don't Ask Again", "No");
bool userAcceptsUpdate = false;
switch (dialogResult)
{
case 0: // "Yes"
userAcceptsUpdate = true;
break;
case 1: // "No, Don't Ask Again"
autoUpdateEnabled = false;
EditorUtility.DisplayDialog("Oculus Utilities OVRPlugin", "To manually update in the future, use the following menu option:\n\n[Tools -> Oculus -> Update OVR Utilities Plugin]", "Ok", "");
return;
case 2: // "No"
return;
}
if (userAcceptsUpdate)
{
DisableAllUtilitiesPluginPackages();
if (!targetPluginPkg.IsBundledPluginPackage())
{
EnablePluginPackage(targetPluginPkg);
}
if (EditorUtility.DisplayDialog("Restart Unity", "OVRPlugin has been updated to " + targetPluginPkg.Version + ".\n\nPlease restart the Unity Editor to complete the update process. You may need to manually relaunch Unity if you are using Unity 5.6 and higher.", "Restart", "Not Now"))
{
RestartUnityEditor();
}
}
}
private static bool UnitySupportsEnabledAndroidPlugin()
{
List<PluginPackage> allUtilsPluginPkgs = GetAllUtilitiesPluginPackages();
foreach(PluginPackage pluginPkg in allUtilsPluginPkgs)
{
if (pluginPkg.IsEnabled())
{
if (pluginPkg.IsAndroidUniversalEnabled() && !unityVersionSupportsAndroidUniversal)
{
// Android Universal should only be enabled on supported Unity versions since it can prevent app launch.
return false;
}
else if (!pluginPkg.IsAndroidUniversalEnabled() && pluginPkg.IsAndroidUniversalPresent() && unityVersionSupportsAndroidUniversal)
{
// Android Universal is present and should be enabled on supported Unity versions since ARM64 config will fail otherwise.
return false;
}
}
}
return true;
}
private static void RestartUnityEditor()
{
restartPending = true;
EditorApplication.OpenProject(GetCurrentProjectPath());
}
}
#endif
| |
namespace XenAdmin.TabPages
{
partial class PerformancePage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PerformancePage));
this.panel1 = new System.Windows.Forms.Panel();
this.GraphList = new XenAdmin.Controls.CustomDataGraph.GraphList();
this.DataEventList = new XenAdmin.Controls.CustomDataGraph.DataEventList();
this.DataPlotNav = new XenAdmin.Controls.CustomDataGraph.DataPlotNav();
this.EventsLabel = new System.Windows.Forms.Label();
this.gradientPanel2 = new XenAdmin.Controls.GradientPanel.VerticalGradientPanel();
this.panel3 = new System.Windows.Forms.Panel();
this.zoomButton = new System.Windows.Forms.Button();
this.moveDownButton = new System.Windows.Forms.Button();
this.moveUpButton = new System.Windows.Forms.Button();
this.graphActionsButton = new System.Windows.Forms.Button();
this.graphActionsMenuStrip = new XenAdmin.Controls.NonReopeningContextMenuStrip(this.components);
this.newGraphToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editGraphToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteGraphToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.restoreDefaultGraphsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.zoomMenuStrip = new XenAdmin.Controls.NonReopeningContextMenuStrip(this.components);
this.lastYearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastMonthToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastWeekToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastDayToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastHourToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastTenMinutesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.moveUpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.moveDownToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.actionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newGraphToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editGraphToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteGraphToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.restoreDefaultGraphsToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.zoomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastYearToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastMonthToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastWeekToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastDayToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastHourToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.lastTenMinutesToolStripContextMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pageContainerPanel.SuspendLayout();
this.panel1.SuspendLayout();
this.gradientPanel2.SuspendLayout();
this.panel3.SuspendLayout();
this.graphActionsMenuStrip.SuspendLayout();
this.zoomMenuStrip.SuspendLayout();
this.contextMenuStrip.SuspendLayout();
this.SuspendLayout();
//
// pageContainerPanel
//
this.pageContainerPanel.Controls.Add(this.panel3);
resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel");
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panel1.Controls.Add(this.GraphList);
this.panel1.Name = "panel1";
//
// GraphList
//
this.GraphList.ArchiveMaintainer = null;
resources.ApplyResources(this.GraphList, "GraphList");
this.GraphList.BackColor = System.Drawing.SystemColors.Window;
this.GraphList.DataEventList = this.DataEventList;
this.GraphList.DataPlotNav = this.DataPlotNav;
this.GraphList.Name = "GraphList";
this.GraphList.SelectedGraph = null;
this.GraphList.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.GraphList_MouseDoubleClick);
//
// DataEventList
//
resources.ApplyResources(this.DataEventList, "DataEventList");
this.DataEventList.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.DataEventList.FormattingEnabled = true;
this.DataEventList.Name = "DataEventList";
//
// DataPlotNav
//
resources.ApplyResources(this.DataPlotNav, "DataPlotNav");
this.DataPlotNav.ArchiveMaintainer = null;
this.DataPlotNav.DataEventList = this.DataEventList;
this.DataPlotNav.DisplayedUuids = ((System.Collections.Generic.List<string>)(resources.GetObject("DataPlotNav.DisplayedUuids")));
this.DataPlotNav.GraphOffset = System.TimeSpan.Parse("00:00:00");
this.DataPlotNav.GraphWidth = System.TimeSpan.Parse("00:09:59");
this.DataPlotNav.GridSpacing = System.TimeSpan.Parse("00:02:00");
this.DataPlotNav.MinimumSize = new System.Drawing.Size(410, 0);
this.DataPlotNav.Name = "DataPlotNav";
this.DataPlotNav.ScrollViewOffset = System.TimeSpan.Parse("00:00:00");
this.DataPlotNav.ScrollViewWidth = System.TimeSpan.Parse("02:00:00");
//
// EventsLabel
//
this.EventsLabel.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.EventsLabel, "EventsLabel");
this.EventsLabel.ForeColor = System.Drawing.SystemColors.ControlText;
this.EventsLabel.Name = "EventsLabel";
//
// gradientPanel2
//
resources.ApplyResources(this.gradientPanel2, "gradientPanel2");
this.gradientPanel2.Controls.Add(this.EventsLabel);
this.gradientPanel2.Name = "gradientPanel2";
//
// panel3
//
this.panel3.Controls.Add(this.zoomButton);
this.panel3.Controls.Add(this.moveDownButton);
this.panel3.Controls.Add(this.moveUpButton);
this.panel3.Controls.Add(this.graphActionsButton);
this.panel3.Controls.Add(this.gradientPanel2);
this.panel3.Controls.Add(this.DataPlotNav);
this.panel3.Controls.Add(this.panel1);
this.panel3.Controls.Add(this.DataEventList);
resources.ApplyResources(this.panel3, "panel3");
this.panel3.Name = "panel3";
//
// zoomButton
//
resources.ApplyResources(this.zoomButton, "zoomButton");
this.zoomButton.Image = global::XenAdmin.Properties.Resources.expanded_triangle;
this.zoomButton.Name = "zoomButton";
this.zoomButton.UseVisualStyleBackColor = true;
this.zoomButton.Click += new System.EventHandler(this.zoomButton_Click);
//
// moveDownButton
//
resources.ApplyResources(this.moveDownButton, "moveDownButton");
this.moveDownButton.Name = "moveDownButton";
this.moveDownButton.UseVisualStyleBackColor = true;
this.moveDownButton.Click += new System.EventHandler(this.moveDownButton_Click);
//
// moveUpButton
//
resources.ApplyResources(this.moveUpButton, "moveUpButton");
this.moveUpButton.Name = "moveUpButton";
this.moveUpButton.UseVisualStyleBackColor = true;
this.moveUpButton.Click += new System.EventHandler(this.moveUpButton_Click);
//
// graphActionsButton
//
this.graphActionsButton.Image = global::XenAdmin.Properties.Resources.expanded_triangle;
resources.ApplyResources(this.graphActionsButton, "graphActionsButton");
this.graphActionsButton.Name = "graphActionsButton";
this.graphActionsButton.UseVisualStyleBackColor = true;
this.graphActionsButton.Click += new System.EventHandler(this.graphActionsButton_Click);
//
// graphActionsMenuStrip
//
this.graphActionsMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newGraphToolStripMenuItem,
this.editGraphToolStripMenuItem,
this.deleteGraphToolStripMenuItem,
this.toolStripSeparator3,
this.restoreDefaultGraphsToolStripMenuItem});
this.graphActionsMenuStrip.Name = "saveMenuStrip";
resources.ApplyResources(this.graphActionsMenuStrip, "graphActionsMenuStrip");
this.graphActionsMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.graphActionsMenuStrip_Opening);
//
// newGraphToolStripMenuItem
//
this.newGraphToolStripMenuItem.Name = "newGraphToolStripMenuItem";
resources.ApplyResources(this.newGraphToolStripMenuItem, "newGraphToolStripMenuItem");
this.newGraphToolStripMenuItem.Click += new System.EventHandler(this.addGraphToolStripMenuItem_Click);
//
// editGraphToolStripMenuItem
//
this.editGraphToolStripMenuItem.Name = "editGraphToolStripMenuItem";
resources.ApplyResources(this.editGraphToolStripMenuItem, "editGraphToolStripMenuItem");
this.editGraphToolStripMenuItem.Click += new System.EventHandler(this.editGraphToolStripMenuItem_Click);
//
// deleteGraphToolStripMenuItem
//
this.deleteGraphToolStripMenuItem.Name = "deleteGraphToolStripMenuItem";
resources.ApplyResources(this.deleteGraphToolStripMenuItem, "deleteGraphToolStripMenuItem");
this.deleteGraphToolStripMenuItem.Click += new System.EventHandler(this.deleteGraphToolStripMenuItem_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// restoreDefaultGraphsToolStripMenuItem
//
this.restoreDefaultGraphsToolStripMenuItem.Name = "restoreDefaultGraphsToolStripMenuItem";
resources.ApplyResources(this.restoreDefaultGraphsToolStripMenuItem, "restoreDefaultGraphsToolStripMenuItem");
this.restoreDefaultGraphsToolStripMenuItem.Click += new System.EventHandler(this.restoreDefaultGraphsToolStripMenuItem_Click);
//
// zoomMenuStrip
//
this.zoomMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lastYearToolStripMenuItem,
this.lastMonthToolStripMenuItem,
this.lastWeekToolStripMenuItem,
this.lastDayToolStripMenuItem,
this.lastHourToolStripMenuItem,
this.lastTenMinutesToolStripMenuItem});
this.zoomMenuStrip.Name = "saveMenuStrip";
resources.ApplyResources(this.zoomMenuStrip, "zoomMenuStrip");
//
// lastYearToolStripMenuItem
//
this.lastYearToolStripMenuItem.Name = "lastYearToolStripMenuItem";
resources.ApplyResources(this.lastYearToolStripMenuItem, "lastYearToolStripMenuItem");
this.lastYearToolStripMenuItem.Click += new System.EventHandler(this.lastYearToolStripMenuItem_Click);
//
// lastMonthToolStripMenuItem
//
this.lastMonthToolStripMenuItem.Name = "lastMonthToolStripMenuItem";
resources.ApplyResources(this.lastMonthToolStripMenuItem, "lastMonthToolStripMenuItem");
this.lastMonthToolStripMenuItem.Click += new System.EventHandler(this.lastMonthToolStripMenuItem_Click);
//
// lastWeekToolStripMenuItem
//
this.lastWeekToolStripMenuItem.Name = "lastWeekToolStripMenuItem";
resources.ApplyResources(this.lastWeekToolStripMenuItem, "lastWeekToolStripMenuItem");
this.lastWeekToolStripMenuItem.Click += new System.EventHandler(this.lastWeekToolStripMenuItem_Click);
//
// lastDayToolStripMenuItem
//
this.lastDayToolStripMenuItem.Name = "lastDayToolStripMenuItem";
resources.ApplyResources(this.lastDayToolStripMenuItem, "lastDayToolStripMenuItem");
this.lastDayToolStripMenuItem.Click += new System.EventHandler(this.lastDayToolStripMenuItem_Click);
//
// lastHourToolStripMenuItem
//
this.lastHourToolStripMenuItem.Name = "lastHourToolStripMenuItem";
resources.ApplyResources(this.lastHourToolStripMenuItem, "lastHourToolStripMenuItem");
this.lastHourToolStripMenuItem.Click += new System.EventHandler(this.lastHourToolStripMenuItem_Click);
//
// lastTenMinutesToolStripMenuItem
//
this.lastTenMinutesToolStripMenuItem.Name = "lastTenMinutesToolStripMenuItem";
resources.ApplyResources(this.lastTenMinutesToolStripMenuItem, "lastTenMinutesToolStripMenuItem");
this.lastTenMinutesToolStripMenuItem.Click += new System.EventHandler(this.lastTenMinutesToolStripMenuItem_Click);
//
// contextMenuStrip
//
this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.moveUpToolStripMenuItem,
this.moveDownToolStripMenuItem,
this.toolStripSeparator1,
this.actionsToolStripMenuItem,
this.toolStripSeparator2,
this.zoomToolStripMenuItem});
this.contextMenuStrip.Name = "contextMenuStrip";
resources.ApplyResources(this.contextMenuStrip, "contextMenuStrip");
this.contextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip_Opening);
//
// moveUpToolStripMenuItem
//
this.moveUpToolStripMenuItem.Name = "moveUpToolStripMenuItem";
resources.ApplyResources(this.moveUpToolStripMenuItem, "moveUpToolStripMenuItem");
this.moveUpToolStripMenuItem.Click += new System.EventHandler(this.moveUpToolStripMenuItem_Click);
//
// moveDownToolStripMenuItem
//
this.moveDownToolStripMenuItem.Name = "moveDownToolStripMenuItem";
resources.ApplyResources(this.moveDownToolStripMenuItem, "moveDownToolStripMenuItem");
this.moveDownToolStripMenuItem.Click += new System.EventHandler(this.moveDownToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// actionsToolStripMenuItem
//
this.actionsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newGraphToolStripContextMenuItem,
this.editGraphToolStripContextMenuItem,
this.deleteGraphToolStripContextMenuItem,
this.toolStripSeparator4,
this.restoreDefaultGraphsToolStripContextMenuItem});
this.actionsToolStripMenuItem.Name = "actionsToolStripMenuItem";
resources.ApplyResources(this.actionsToolStripMenuItem, "actionsToolStripMenuItem");
//
// newGraphToolStripContextMenuItem
//
this.newGraphToolStripContextMenuItem.Name = "newGraphToolStripContextMenuItem";
resources.ApplyResources(this.newGraphToolStripContextMenuItem, "newGraphToolStripContextMenuItem");
this.newGraphToolStripContextMenuItem.Click += new System.EventHandler(this.newGraphToolStripContextMenuItem_Click);
//
// editGraphToolStripContextMenuItem
//
this.editGraphToolStripContextMenuItem.Name = "editGraphToolStripContextMenuItem";
resources.ApplyResources(this.editGraphToolStripContextMenuItem, "editGraphToolStripContextMenuItem");
this.editGraphToolStripContextMenuItem.Click += new System.EventHandler(this.editGraphToolStripContextMenuItem_Click);
//
// deleteGraphToolStripContextMenuItem
//
this.deleteGraphToolStripContextMenuItem.Name = "deleteGraphToolStripContextMenuItem";
resources.ApplyResources(this.deleteGraphToolStripContextMenuItem, "deleteGraphToolStripContextMenuItem");
this.deleteGraphToolStripContextMenuItem.Click += new System.EventHandler(this.deleteGraphToolStripContextMenuItem_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// restoreDefaultGraphsToolStripContextMenuItem
//
this.restoreDefaultGraphsToolStripContextMenuItem.Name = "restoreDefaultGraphsToolStripContextMenuItem";
resources.ApplyResources(this.restoreDefaultGraphsToolStripContextMenuItem, "restoreDefaultGraphsToolStripContextMenuItem");
this.restoreDefaultGraphsToolStripContextMenuItem.Click += new System.EventHandler(this.restoreDefaultGraphsToolStripContextMenuItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// zoomToolStripMenuItem
//
this.zoomToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.lastYearToolStripContextMenuItem,
this.lastMonthToolStripContextMenuItem,
this.lastWeekToolStripContextMenuItem,
this.lastDayToolStripContextMenuItem,
this.lastHourToolStripContextMenuItem,
this.lastTenMinutesToolStripContextMenuItem});
this.zoomToolStripMenuItem.Name = "zoomToolStripMenuItem";
resources.ApplyResources(this.zoomToolStripMenuItem, "zoomToolStripMenuItem");
//
// lastYearToolStripContextMenuItem
//
this.lastYearToolStripContextMenuItem.Name = "lastYearToolStripContextMenuItem";
resources.ApplyResources(this.lastYearToolStripContextMenuItem, "lastYearToolStripContextMenuItem");
this.lastYearToolStripContextMenuItem.Click += new System.EventHandler(this.lastYearToolStripContextMenuItem_Click);
//
// lastMonthToolStripContextMenuItem
//
this.lastMonthToolStripContextMenuItem.Name = "lastMonthToolStripContextMenuItem";
resources.ApplyResources(this.lastMonthToolStripContextMenuItem, "lastMonthToolStripContextMenuItem");
this.lastMonthToolStripContextMenuItem.Click += new System.EventHandler(this.lastMonthToolStripContextMenuItem_Click);
//
// lastWeekToolStripContextMenuItem
//
this.lastWeekToolStripContextMenuItem.Name = "lastWeekToolStripContextMenuItem";
resources.ApplyResources(this.lastWeekToolStripContextMenuItem, "lastWeekToolStripContextMenuItem");
this.lastWeekToolStripContextMenuItem.Click += new System.EventHandler(this.lastWeekToolStripContextMenuItem_Click);
//
// lastDayToolStripContextMenuItem
//
this.lastDayToolStripContextMenuItem.Name = "lastDayToolStripContextMenuItem";
resources.ApplyResources(this.lastDayToolStripContextMenuItem, "lastDayToolStripContextMenuItem");
this.lastDayToolStripContextMenuItem.Click += new System.EventHandler(this.lastDayToolStripContextMenuItem_Click);
//
// lastHourToolStripContextMenuItem
//
this.lastHourToolStripContextMenuItem.Name = "lastHourToolStripContextMenuItem";
resources.ApplyResources(this.lastHourToolStripContextMenuItem, "lastHourToolStripContextMenuItem");
this.lastHourToolStripContextMenuItem.Click += new System.EventHandler(this.lastHourToolStripContextMenuItem_Click);
//
// lastTenMinutesToolStripContextMenuItem
//
this.lastTenMinutesToolStripContextMenuItem.Name = "lastTenMinutesToolStripContextMenuItem";
resources.ApplyResources(this.lastTenMinutesToolStripContextMenuItem, "lastTenMinutesToolStripContextMenuItem");
this.lastTenMinutesToolStripContextMenuItem.Click += new System.EventHandler(this.lastTenMinutesToolStripContextMenuItem_Click);
//
// PerformancePage
//
resources.ApplyResources(this, "$this");
this.DoubleBuffered = true;
this.Name = "PerformancePage";
this.Controls.SetChildIndex(this.pageContainerPanel, 0);
this.pageContainerPanel.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.gradientPanel2.ResumeLayout(false);
this.panel3.ResumeLayout(false);
this.graphActionsMenuStrip.ResumeLayout(false);
this.zoomMenuStrip.ResumeLayout(false);
this.contextMenuStrip.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private XenAdmin.Controls.CustomDataGraph.DataEventList DataEventList;
private XenAdmin.Controls.CustomDataGraph.DataPlotNav DataPlotNav;
private XenAdmin.Controls.CustomDataGraph.GraphList GraphList;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label EventsLabel;
private XenAdmin.Controls.GradientPanel.GradientPanel gradientPanel2;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Button graphActionsButton;
private XenAdmin.Controls.NonReopeningContextMenuStrip graphActionsMenuStrip;
private System.Windows.Forms.ToolStripMenuItem newGraphToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editGraphToolStripMenuItem;
private System.Windows.Forms.Button moveDownButton;
private System.Windows.Forms.Button moveUpButton;
private XenAdmin.Controls.NonReopeningContextMenuStrip zoomMenuStrip;
private System.Windows.Forms.ToolStripMenuItem lastYearToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastMonthToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastWeekToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastDayToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastHourToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastTenMinutesToolStripMenuItem;
private System.Windows.Forms.Button zoomButton;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem moveUpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem moveDownToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem actionsToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripMenuItem zoomToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem newGraphToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem editGraphToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastYearToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastMonthToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastWeekToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastDayToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastHourToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem lastTenMinutesToolStripContextMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteGraphToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripMenuItem restoreDefaultGraphsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem deleteGraphToolStripContextMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ToolStripMenuItem restoreDefaultGraphsToolStripContextMenuItem;
}
}
| |
/*
* 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.Data
{
/// <summary>
/// Represents a rule that automatically handles incoming messages.
/// A rule consists of a set of conditions and exceptions that determine whether or
/// not a set of actions should be executed on incoming messages.
/// </summary>
public sealed class Rule : ComplexProperty
{
/// <summary>
/// The rule ID.
/// </summary>
private string ruleId;
/// <summary>
/// The rule display name.
/// </summary>
private string displayName;
/// <summary>
/// The rule priority.
/// </summary>
private int priority;
/// <summary>
/// The rule status of enabled or not.
/// </summary>
private bool isEnabled;
/// <summary>
/// The rule status of is supported or not.
/// </summary>
private bool isNotSupported;
/// <summary>
/// The rule status of in error or not.
/// </summary>
private bool isInError;
/// <summary>
/// The rule conditions.
/// </summary>
private RulePredicates conditions;
/// <summary>
/// The rule actions.
/// </summary>
private RuleActions actions;
/// <summary>
/// The rule exceptions.
/// </summary>
private RulePredicates exceptions;
/// <summary>
/// Initializes a new instance of the <see cref="Rule"/> class.
/// </summary>
public Rule()
: base()
{
//// New rule has priority as 0 by default
this.priority = 1;
//// New rule is enabled by default
this.isEnabled = true;
this.conditions = new RulePredicates();
this.actions = new RuleActions();
this.exceptions = new RulePredicates();
}
/// <summary>
/// Gets or sets the Id of this rule.
/// </summary>
public string Id
{
get
{
return this.ruleId;
}
set
{
this.SetFieldValue<string>(ref this.ruleId, value);
}
}
/// <summary>
/// Gets or sets the name of this rule as it should be displayed to the user.
/// </summary>
public string DisplayName
{
get
{
return this.displayName;
}
set
{
this.SetFieldValue<string>(ref this.displayName, value);
}
}
/// <summary>
/// Gets or sets the priority of this rule, which determines its execution order.
/// </summary>
public int Priority
{
get
{
return this.priority;
}
set
{
this.SetFieldValue<int>(ref this.priority, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether this rule is enabled.
/// </summary>
public bool IsEnabled
{
get
{
return this.isEnabled;
}
set
{
this.SetFieldValue<bool>(ref this.isEnabled, value);
}
}
/// <summary>
/// Gets a value indicating whether this rule can be modified via EWS.
/// If IsNotSupported is true, the rule cannot be modified via EWS.
/// </summary>
public bool IsNotSupported
{
get
{
return this.isNotSupported;
}
}
/// <summary>
/// Gets or sets a value indicating whether this rule has errors. A rule that is in error
/// cannot be processed unless it is updated and the error is corrected.
/// </summary>
public bool IsInError
{
get
{
return this.isInError;
}
set
{
this.SetFieldValue<bool>(ref this.isInError, value);
}
}
/// <summary>
/// Gets the conditions that determine whether or not this rule should be
/// executed against incoming messages.
/// </summary>
public RulePredicates Conditions
{
get
{
return this.conditions;
}
}
/// <summary>
/// Gets the actions that should be executed against incoming messages if the
/// conditions evaluate as true.
/// </summary>
public RuleActions Actions
{
get
{
return this.actions;
}
}
/// <summary>
/// Gets the exceptions that determine if this rule should be skipped even if
/// its conditions evaluate to true.
/// </summary>
public RulePredicates Exceptions
{
get
{
return this.exceptions;
}
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.DisplayName:
this.displayName = reader.ReadElementValue();
return true;
case XmlElementNames.RuleId:
this.ruleId = reader.ReadElementValue();
return true;
case XmlElementNames.Priority:
this.priority = reader.ReadElementValue<int>();
return true;
case XmlElementNames.IsEnabled:
this.isEnabled = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.IsNotSupported:
this.isNotSupported = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.IsInError:
this.isInError = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.Conditions:
this.conditions.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.Actions:
this.actions.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.Exceptions:
this.exceptions.LoadFromXml(reader, reader.LocalName);
return true;
default:
return false;
}
}
/// <summary>
/// Writes elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
if (!string.IsNullOrEmpty(this.Id))
{
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.RuleId,
this.Id);
}
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.DisplayName,
this.DisplayName);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.Priority,
this.Priority);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.IsEnabled,
this.IsEnabled);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.IsInError,
this.IsInError);
this.Conditions.WriteToXml(writer, XmlElementNames.Conditions);
this.Exceptions.WriteToXml(writer, XmlElementNames.Exceptions);
this.Actions.WriteToXml(writer, XmlElementNames.Actions);
}
/// <summary>
/// Validates this instance.
/// </summary>
internal override void InternalValidate()
{
base.InternalValidate();
EwsUtilities.ValidateParam(this.displayName, "DisplayName");
EwsUtilities.ValidateParam(this.conditions, "Conditions");
EwsUtilities.ValidateParam(this.exceptions, "Exceptions");
EwsUtilities.ValidateParam(this.actions, "Actions");
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.Collections;
namespace System.IO
{
/// <summary>
/// FileArchiver
/// </summary>
public class FileArchiver
{
/// <summary>
/// ArchiveEveryMode
/// </summary>
public enum ArchiveEveryMode
{
/// <summary>
///
/// </summary>
None,
/// <summary>
///
/// </summary>
Year,
/// <summary>
///
/// </summary>
Month,
/// <summary>
///
/// </summary>
Day,
/// <summary>
///
/// </summary>
Hour,
/// <summary>
///
/// </summary>
Minute
}
/// <summary>
/// ArchiveNumberingMode
/// </summary>
public enum ArchiveNumberingMode
{
/// <summary>
///
/// </summary>
Sequence,
/// <summary>
///
/// </summary>
Rolling
}
/// <summary>
/// Initializes a new instance of the <see cref="FileArchiver"/> class.
/// </summary>
public FileArchiver()
{
MaxArchiveFiles = 9;
ArchiveAboveSize = -1L;
ArchiveNumbering = ArchiveNumberingMode.Rolling;
}
/// <summary>
/// Gets or sets the max archive files.
/// </summary>
/// <value>The max archive files.</value>
public int MaxArchiveFiles { get; set; }
/// <summary>
/// Gets or sets the archive numbering.
/// </summary>
/// <value>The archive numbering.</value>
public ArchiveNumberingMode ArchiveNumbering { get; set; }
/// <summary>
/// Gets or sets the size of the archive above.
/// </summary>
/// <value>The size of the archive above.</value>
public long ArchiveAboveSize { get; set; }
/// <summary>
/// Gets or sets the archive every.
/// </summary>
/// <value>The archive every.</value>
public ArchiveEveryMode ArchiveEvery { get; set; }
/// <summary>
/// Gets the file info.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="lastWriteTime">The last write time.</param>
/// <param name="fileLength">Length of the file.</param>
/// <returns></returns>
private bool GetFileInfo(string fileName, out DateTime lastWriteTime, out long fileLength)
{
var info = new FileInfo(fileName);
if (info.Exists)
{
fileLength = info.Length;
lastWriteTime = info.LastWriteTime;
return true;
}
fileLength = -1L;
lastWriteTime = DateTime.MinValue;
return false;
}
/// <summary>
/// Shoulds the auto archive.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="upcomingWriteTime">The upcoming write time.</param>
/// <param name="upcomingWriteSize">Size of the upcoming write.</param>
/// <returns></returns>
public bool ShouldAutoArchive(string fileName, DateTime upcomingWriteTime, int upcomingWriteSize)
{
DateTime time;
long num;
string str;
if ((ArchiveAboveSize == -1L) && (ArchiveEvery == ArchiveEveryMode.None))
return false;
if (!GetFileInfo(fileName, out time, out num))
return false;
if ((ArchiveAboveSize != -1L) && ((num + upcomingWriteSize) > ArchiveAboveSize))
return true;
switch (ArchiveEvery)
{
case ArchiveEveryMode.Year:
str = "yyyy";
break;
case ArchiveEveryMode.Month:
str = "yyyyMM";
break;
case ArchiveEveryMode.Hour:
str = "yyyyMMddHH";
break;
case ArchiveEveryMode.Minute:
str = "yyyyMMddHHmm";
break;
case ArchiveEveryMode.None:
return false;
default:
str = "yyyyMMdd";
break;
}
string str2 = time.ToString(str);
string str3 = upcomingWriteTime.ToString(str);
if (str2 != str3)
return true;
return false;
}
/// <summary>
/// Res the scope path.
/// </summary>
/// <param name="directory">The directory.</param>
/// <param name="path">The path.</param>
/// <returns></returns>
public static string ReScopePath(string directory, string path)
{
return Path.GetFullPath(Path.Combine(Path.Combine(Path.GetDirectoryName(path), directory), Path.GetFileName(path)));
}
/// <summary>
/// Does the auto archive.
/// </summary>
/// <param name="fileName">Name of the file.</param>
public void DoAutoArchive(string archiveDirectory, string fileName)
{
var info = new FileInfo(fileName);
if (info.Exists)
{
string formattedMessage = Path.ChangeExtension(info.FullName, ".{#}" + Path.GetExtension(fileName));
if ((archiveDirectory != null) && (archiveDirectory.Length > 0))
formattedMessage = ReScopePath(archiveDirectory, formattedMessage);
switch (ArchiveNumbering)
{
case ArchiveNumberingMode.Sequence:
SequentialArchive(info.FullName, formattedMessage);
return;
case ArchiveNumberingMode.Rolling:
RecursiveRollingRename(info.FullName, formattedMessage, 0);
return;
}
}
}
/// <summary>
/// Recursives the rolling rename.
/// </summary>
/// <param name="archiveDirectory">The archive directory.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="pattern">The pattern.</param>
/// <param name="archiveNumber">The archive number.</param>
private void RecursiveRollingRename(string fileName, string pattern, int archiveNumber)
{
if ((MaxArchiveFiles != -1) && (archiveNumber >= MaxArchiveFiles))
File.Delete(fileName);
else if (File.Exists(fileName))
{
string str = ReplaceNumber(pattern, archiveNumber);
if (File.Exists(fileName))
RecursiveRollingRename(str, pattern, archiveNumber + 1);
try { File.Move(fileName, str); }
catch (DirectoryNotFoundException) { Directory.CreateDirectory(Path.GetDirectoryName(str)); File.Move(fileName, str); }
}
}
/// <summary>
/// Sequentials the archive.
/// </summary>
/// <param name="archiveDirectory">The archive directory.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="pattern">The pattern.</param>
private void SequentialArchive(string fileName, string pattern)
{
string str = Path.GetFileName(pattern);
int index = str.IndexOf("{#");
int startIndex = str.IndexOf("#}") + 2;
int num3 = str.Length - startIndex;
string searchPattern = str.Substring(0, index) + "*" + str.Substring(startIndex);
string directoryName = Path.GetDirectoryName(Path.GetFullPath(pattern));
int num4 = -1;
int num5 = -1;
var hashtable = new Hashtable();
try
{
foreach (string str4 in Directory.GetFiles(directoryName, searchPattern))
{
int num6;
string str5 = Path.GetFileName(str4);
string str6 = str5.Substring(index, (str5.Length - num3) - index);
try { num6 = Convert.ToInt32(str6); }
catch (FormatException) { continue; }
num4 = Math.Max(num4, num6);
num5 = (num5 != -1 ? Math.Min(num5, num6) : num6);
hashtable[num6] = str4;
}
num4++;
}
catch (DirectoryNotFoundException) { Directory.CreateDirectory(directoryName); num4 = 0; }
if ((MaxArchiveFiles != -1) && (num5 != -1))
{
int num7 = (num4 - MaxArchiveFiles) + 1;
for (int i = num5; i < num7; i++)
{
string path = (string)hashtable[i];
if (path != null)
File.Delete(path);
}
}
string destFileName = ReplaceNumber(pattern, num4);
File.Move(fileName, destFileName);
}
/// <summary>
/// Replaces the number.
/// </summary>
/// <param name="pattern">The pattern.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
private string ReplaceNumber(string pattern, int value)
{
int index = pattern.IndexOf("{#");
int startIndex = pattern.IndexOf("#}") + 2;
int totalWidth = (startIndex - index) - 2;
return (pattern.Substring(0, index) + Convert.ToString(value, 10).PadLeft(totalWidth, '0') + pattern.Substring(startIndex));
}
}
}
| |
using System;
using System.IO;
using System.Threading;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
using NUnit.Framework;
using ICSharpCode.SharpZipLib.Tests.TestSupport;
namespace ICSharpCode.SharpZipLib.Tests.GZip
{
/// <summary>
/// This class contains test cases for GZip compression
/// </summary>
[TestFixture]
public class GZipTestSuite
{
/// <summary>
/// Basic compress/decompress test
/// </summary>
[Test]
[Category("GZip")]
public void TestGZip()
{
MemoryStream ms = new MemoryStream();
GZipOutputStream outStream = new GZipOutputStream(ms);
byte[] buf = new byte[100000];
System.Random rnd = new Random();
rnd.NextBytes(buf);
outStream.Write(buf, 0, buf.Length);
outStream.Flush();
outStream.Finish();
ms.Seek(0, SeekOrigin.Begin);
GZipInputStream inStream = new GZipInputStream(ms);
byte[] buf2 = new byte[buf.Length];
int currentIndex = 0;
int count = buf2.Length;
while (true) {
int numRead = inStream.Read(buf2, currentIndex, count);
if (numRead <= 0) {
break;
}
currentIndex += numRead;
count -= numRead;
}
Assert.AreEqual(0, count);
for (int i = 0; i < buf.Length; ++i) {
Assert.AreEqual(buf2[i], buf[i]);
}
}
/// <summary>
/// Writing GZip headers is delayed so that this stream can be used with HTTP/IIS.
/// </summary>
[Test]
[Category("GZip")]
public void DelayedHeaderWriteNoData()
{
MemoryStream ms = new MemoryStream();
Assert.AreEqual(0, ms.Length);
using (GZipOutputStream outStream = new GZipOutputStream(ms)) {
Assert.AreEqual(0, ms.Length);
}
byte[] data = ms.ToArray();
Assert.IsTrue(data.Length > 0);
}
/// <summary>
/// Writing GZip headers is delayed so that this stream can be used with HTTP/IIS.
/// </summary>
[Test]
[Category("GZip")]
public void DelayedHeaderWriteWithData()
{
MemoryStream ms = new MemoryStream();
Assert.AreEqual(0, ms.Length);
using (GZipOutputStream outStream = new GZipOutputStream(ms)) {
Assert.AreEqual(0, ms.Length);
outStream.WriteByte(45);
// Should in fact contain header right now with
// 1 byte in the compression pipeline
Assert.AreEqual(10, ms.Length);
}
byte[] data = ms.ToArray();
Assert.IsTrue(data.Length > 0);
}
[Test]
[Category("GZip")]
public void ZeroLengthInputStream()
{
GZipInputStream gzi = new GZipInputStream(new MemoryStream());
bool exception = false;
try {
gzi.ReadByte();
}
catch {
exception = true;
}
Assert.IsTrue(exception, "reading from an empty stream should cause an exception");
}
[Test]
[Category("GZip")]
public void OutputStreamOwnership()
{
MemoryStreamEx memStream = new MemoryStreamEx();
GZipOutputStream s = new GZipOutputStream(memStream);
Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");
s.Close();
Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close");
Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close");
memStream = new MemoryStreamEx();
s = new GZipOutputStream(memStream);
Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");
s.IsStreamOwner = false;
s.Close();
Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close");
Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close");
}
[Test]
[Category("GZip")]
public void InputStreamOwnership()
{
MemoryStreamEx memStream = new MemoryStreamEx();
GZipInputStream s = new GZipInputStream(memStream);
Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");
s.Close();
Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close");
Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close");
memStream = new MemoryStreamEx();
s = new GZipInputStream(memStream);
Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");
s.IsStreamOwner = false;
s.Close();
Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close");
Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close");
}
[Test]
[Category("GZip")]
[Category("Long Running")]
public void BigStream()
{
window_ = new WindowedStream(0x3ffff);
outStream_ = new GZipOutputStream(window_);
inStream_ = new GZipInputStream(window_);
long target = 0x10000000;
readTarget_ = writeTarget_ = target;
Thread reader = new Thread(Reader);
reader.Name = "Reader";
reader.Start();
Thread writer = new Thread(Writer);
writer.Name = "Writer";
DateTime startTime = DateTime.Now;
writer.Start();
writer.Join();
reader.Join();
DateTime endTime = DateTime.Now;
TimeSpan span = endTime - startTime;
Console.WriteLine("Time {0} processes {1} KB/Sec", span, (target / 1024) / span.TotalSeconds);
}
void Reader()
{
const int Size = 8192;
int readBytes = 1;
byte[] buffer = new byte[Size];
long passifierLevel = readTarget_ - 0x10000000;
while ( (readTarget_ > 0) && (readBytes > 0) ) {
int count = Size;
if (count > readTarget_) {
count = (int)readTarget_;
}
readBytes = inStream_.Read(buffer, 0, count);
readTarget_ -= readBytes;
if (readTarget_ <= passifierLevel) {
Console.WriteLine("Reader {0} bytes remaining", readTarget_);
passifierLevel = readTarget_ - 0x10000000;
}
}
Assert.IsTrue(window_.IsClosed, "Window should be closed");
// This shouldnt read any data but should read the footer
readBytes = inStream_.Read(buffer, 0, 1);
Assert.AreEqual(0, readBytes, "Stream should be empty");
Assert.AreEqual(0, window_.Length, "Window should be closed");
inStream_.Close();
}
void Writer()
{
const int Size = 8192;
byte[] buffer = new byte[Size];
while (writeTarget_ > 0) {
int thisTime = Size;
if (thisTime > writeTarget_) {
thisTime = (int)writeTarget_;
}
outStream_.Write(buffer, 0, thisTime);
writeTarget_-= thisTime;
}
outStream_.Close();
}
WindowedStream window_;
GZipOutputStream outStream_;
GZipInputStream inStream_;
long readTarget_;
long writeTarget_;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Collections.ObjectModel
{
[Serializable]
[DebuggerTypeProxy(typeof(ICollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class ReadOnlyCollection<T> : IList<T>, IList, IReadOnlyList<T>
{
private IList<T> list; // Do not rename (binary serialization)
[NonSerialized]
private Object _syncRoot;
public ReadOnlyCollection(IList<T> list)
{
if (list == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
this.list = list;
}
public int Count
{
get { return list.Count; }
}
public T this[int index]
{
get { return list[index]; }
}
public bool Contains(T value)
{
return list.Contains(value);
}
public void CopyTo(T[] array, int index)
{
list.CopyTo(array, index);
}
public IEnumerator<T> GetEnumerator()
{
return list.GetEnumerator();
}
public int IndexOf(T value)
{
return list.IndexOf(value);
}
protected IList<T> Items
{
get
{
return list;
}
}
bool ICollection<T>.IsReadOnly
{
get { return true; }
}
T IList<T>.this[int index]
{
get { return list[index]; }
set
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
void ICollection<T>.Add(T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void ICollection<T>.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList<T>.Insert(int index, T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
bool ICollection<T>.Remove(T value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
void IList<T>.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)list).GetEnumerator();
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
ICollection c = list as ICollection;
if (c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0)
{
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < Count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
T[] items = array as T[];
if (items != null)
{
list.CopyTo(items, index);
}
else
{
//
// Catch the obvious case assignment will fail.
// We can't find all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType)))
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if (objects == null)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = list.Count;
try
{
for (int i = 0; i < count; i++)
{
objects[index++] = list[i];
}
}
catch (ArrayTypeMismatchException)
{
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
bool IList.IsFixedSize
{
get { return true; }
}
bool IList.IsReadOnly
{
get { return true; }
}
object IList.this[int index]
{
get { return list[index]; }
set
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
int IList.Add(object value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return -1;
}
void IList.Clear()
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
private static bool IsCompatibleObject(object value)
{
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
bool IList.Contains(object value)
{
if (IsCompatibleObject(value))
{
return Contains((T)value);
}
return false;
}
int IList.IndexOf(object value)
{
if (IsCompatibleObject(value))
{
return IndexOf((T)value);
}
return -1;
}
void IList.Insert(int index, object value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList.Remove(object value)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
void IList.RemoveAt(int index)
{
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>CustomerLabel</c> resource.</summary>
public sealed partial class CustomerLabelName : gax::IResourceName, sys::IEquatable<CustomerLabelName>
{
/// <summary>The possible contents of <see cref="CustomerLabelName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/customerLabels/{label_id}</c>.
/// </summary>
CustomerLabel = 1,
}
private static gax::PathTemplate s_customerLabel = new gax::PathTemplate("customers/{customer_id}/customerLabels/{label_id}");
/// <summary>Creates a <see cref="CustomerLabelName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CustomerLabelName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomerLabelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomerLabelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomerLabelName"/> with the pattern
/// <c>customers/{customer_id}/customerLabels/{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CustomerLabelName"/> constructed from the provided ids.</returns>
public static CustomerLabelName FromCustomerLabel(string customerId, string labelId) =>
new CustomerLabelName(ResourceNameType.CustomerLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerLabelName"/> with pattern
/// <c>customers/{customer_id}/customerLabels/{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerLabelName"/> with pattern
/// <c>customers/{customer_id}/customerLabels/{label_id}</c>.
/// </returns>
public static string Format(string customerId, string labelId) => FormatCustomerLabel(customerId, labelId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomerLabelName"/> with pattern
/// <c>customers/{customer_id}/customerLabels/{label_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CustomerLabelName"/> with pattern
/// <c>customers/{customer_id}/customerLabels/{label_id}</c>.
/// </returns>
public static string FormatCustomerLabel(string customerId, string labelId) =>
s_customerLabel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerLabelName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customerLabels/{label_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="customerLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomerLabelName"/> if successful.</returns>
public static CustomerLabelName Parse(string customerLabelName) => Parse(customerLabelName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomerLabelName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customerLabels/{label_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CustomerLabelName"/> if successful.</returns>
public static CustomerLabelName Parse(string customerLabelName, bool allowUnparsed) =>
TryParse(customerLabelName, allowUnparsed, out CustomerLabelName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerLabelName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customerLabels/{label_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="customerLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerLabelName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerLabelName, out CustomerLabelName result) =>
TryParse(customerLabelName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomerLabelName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/customerLabels/{label_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customerLabelName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomerLabelName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customerLabelName, bool allowUnparsed, out CustomerLabelName result)
{
gax::GaxPreconditions.CheckNotNull(customerLabelName, nameof(customerLabelName));
gax::TemplatedResourceName resourceName;
if (s_customerLabel.TryParseName(customerLabelName, out resourceName))
{
result = FromCustomerLabel(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customerLabelName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomerLabelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string labelId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
LabelId = labelId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomerLabelName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/customerLabels/{label_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param>
public CustomerLabelName(string customerId, string labelId) : this(ResourceNameType.CustomerLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>Label</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LabelId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerLabel: return s_customerLabel.Expand(CustomerId, LabelId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CustomerLabelName);
/// <inheritdoc/>
public bool Equals(CustomerLabelName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomerLabelName a, CustomerLabelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomerLabelName a, CustomerLabelName b) => !(a == b);
}
public partial class CustomerLabel
{
/// <summary>
/// <see cref="CustomerLabelName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CustomerLabelName ResourceNameAsCustomerLabelName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CustomerLabelName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CustomerName"/>-typed view over the <see cref="Customer"/> resource name property.
/// </summary>
internal CustomerName CustomerAsCustomerName
{
get => string.IsNullOrEmpty(Customer) ? null : CustomerName.Parse(Customer, allowUnparsed: true);
set => Customer = value?.ToString() ?? "";
}
/// <summary><see cref="LabelName"/>-typed view over the <see cref="Label"/> resource name property.</summary>
internal LabelName LabelAsLabelName
{
get => string.IsNullOrEmpty(Label) ? null : LabelName.Parse(Label, allowUnparsed: true);
set => Label = value?.ToString() ?? "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Collections.Tests
{
public class ReadOnlyCollectionBaseTests
{
private static MyReadOnlyCollectionBase CreateCollection()
{
var fooArray = new Foo[100];
for (int i = 0; i < 100; i++)
{
fooArray[i] = new Foo(i, i.ToString());
}
return new MyReadOnlyCollectionBase(fooArray);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // Changed behavior
public static void SyncRoot()
{
MyReadOnlyCollectionBase collection = CreateCollection();
Assert.True(collection.SyncRoot is ArrayList);
Assert.Same(collection.SyncRoot, collection.SyncRoot);
}
[Fact]
public static void AddRange_Count()
{
MyReadOnlyCollectionBase collection = CreateCollection();
Assert.Equal(100, collection.Count);
}
[Fact]
public static void CopyTo_ZeroIndex()
{
MyReadOnlyCollectionBase collection = CreateCollection();
var copyArray = new Foo[100];
collection.CopyTo(copyArray, 0);
Assert.Equal(100, copyArray.Length);
for (int i = 0; i < 100; i++)
{
Assert.Equal(i, copyArray[i].IntValue);
Assert.Equal(i.ToString(), copyArray[i].StringValue);
}
}
[Fact]
public static void CopyTo_NonZeroIndex()
{
MyReadOnlyCollectionBase collection = CreateCollection();
var copyArray = new Foo[200];
collection.CopyTo(copyArray, 100);
Assert.Equal(200, copyArray.Length);
for (int i = 0; i < 100; i++)
{
Assert.Equal(i, copyArray[100 + i].IntValue);
Assert.Equal(i.ToString(), copyArray[100 + i].StringValue);
}
}
[Fact]
public static void CopyTo_Invalid()
{
MyReadOnlyCollectionBase collection = CreateCollection();
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => collection.CopyTo(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("destinationArray", string.Empty, () => collection.CopyTo(new Foo[100], 50)); // Index + collection.Count > array.Length
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => collection.CopyTo(new Foo[100], -1)); // Index < 0
}
[Fact]
public static void GetEnumerator()
{
MyReadOnlyCollectionBase collection = CreateCollection();
IEnumerator enumerator = collection.GetEnumerator();
// Calling current should throw when the enumerator has not started enumerating
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
int counter = 0;
while (enumerator.MoveNext())
{
Foo current = (Foo)enumerator.Current;
Assert.Equal(counter, current.IntValue);
Assert.Equal(counter.ToString(), current.StringValue);
counter++;
}
Assert.Equal(collection.Count, counter);
// Calling current should throw when the enumerator has finished enumerating
Assert.Throws<InvalidOperationException>(() => (Foo)enumerator.Current);
// Calling current should throw when the enumerator is reset
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => (Foo)enumerator.Current);
}
[Fact]
public static void IsSynchronized()
{
MyReadOnlyCollectionBase collection = CreateCollection();
Assert.False(((ICollection)collection).IsSynchronized);
}
[Fact]
public static void IListMethods()
{
MyReadOnlyCollectionBase collection = CreateCollection();
for (int i = 0; i < 100; i++)
{
Assert.Equal(i, collection[i].IntValue);
Assert.Equal(i.ToString(), collection[i].StringValue);
Assert.Equal(i, collection.IndexOf(new Foo(i, i.ToString())));
Assert.True(collection.Contains(new Foo(i, i.ToString())));
}
}
[Fact]
public static void IListProperties()
{
MyReadOnlyCollectionBase collection = CreateCollection();
Assert.True(collection.IsFixedSize);
Assert.True(collection.IsReadOnly);
}
[Fact]
public static void VirtualMethods()
{
VirtualTestReadOnlyCollection collectionBase = new VirtualTestReadOnlyCollection();
Assert.Equal(collectionBase.Count, int.MinValue);
Assert.Null(collectionBase.GetEnumerator());
}
// ReadOnlyCollectionBase is provided to be used as the base class for strongly typed collections.
// Let's use one of our own here for the type Foo.
private class MyReadOnlyCollectionBase : ReadOnlyCollectionBase
{
public MyReadOnlyCollectionBase(Foo[] values)
{
InnerList.AddRange(values);
}
public Foo this[int indx]
{
get { return (Foo)InnerList[indx]; }
}
public void CopyTo(Array array, int index) => ((ICollection)this).CopyTo(array, index);
public virtual object SyncRoot
{
get { return ((ICollection)this).SyncRoot; }
}
public int IndexOf(Foo f) => ((IList)InnerList).IndexOf(f);
public bool Contains(Foo f) => ((IList)InnerList).Contains(f);
public bool IsFixedSize
{
get { return true; }
}
public bool IsReadOnly
{
get { return true; }
}
}
private class VirtualTestReadOnlyCollection : ReadOnlyCollectionBase
{
public override int Count
{
get { return int.MinValue; }
}
public override IEnumerator GetEnumerator() => null;
}
private class Foo
{
public Foo()
{
}
public Foo(int intValue, string stringValue)
{
IntValue = intValue;
StringValue = stringValue;
}
public int IntValue { get; set; }
public string StringValue { get; set; }
public override bool Equals(object obj)
{
Foo foo = obj as Foo;
if (obj == null)
return false;
return foo.IntValue == IntValue && foo.StringValue == StringValue;
}
public override int GetHashCode() => IntValue;
}
}
}
| |
// 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.Collections.Generic;
using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class InvocationExpressionSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new InvocationExpressionSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationAfterCloseParen()
{
var markup = @"
class C
{
int Foo(int x)
{
[|Foo(Foo(x)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("int C.Foo(int x)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationInsideLambda()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Console.WriteLine(i)$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationInsideLambda2()
{
var markup = @"
using System;
class C
{
void Foo(Action<int> f)
{
[|Foo(i => Con$$sole.WriteLine(i)|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(Action<int> f)", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParameters()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo
/// </summary>
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo", null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn1()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo($$a, b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param a", currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class C
{
/// <summary>
/// Summary for Foo
/// </summary>
/// <param name=" + "\"a\">Param a</param>" + @"
/// <param name=" + "\"b\">Param b</param>" + @"
void Foo(int a, int b)
{
[|Foo(a, $$b|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", "Summary for Foo", "Param b", currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParen()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParenWithParameters()
{
var markup =
@"class C
{
void Foo(int a, int b)
{
[|Foo($$a, b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithoutClosingParenWithParametersOn2()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(a, $$b
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnLambda()
{
var markup = @"
using System;
class C
{
void Foo()
{
Action<int> f = (i) => Console.WriteLine(i);
[|f($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Action<int>(int obj)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnMemberAccessExpression()
{
var markup = @"
class C
{
static void Bar(int a)
{
}
void Foo()
{
[|C.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Bar(int a)", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestExtensionMethod1()
{
var markup = @"
using System;
class C
{
void Method()
{
string s = ""Text"";
[|s.ExtensionMethod($$
|]}
}
public static class MyExtension
{
public static int ExtensionMethod(this string s, int x)
{
return s.Length;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) int string.ExtensionMethod(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
// TODO: Once we do the work to allow extension methods in nested types, we should change this.
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestOptionalParameters()
{
var markup = @"
class Class1
{
void Test()
{
Foo($$
}
void Foo(int a = 42)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Class1.Foo([int a = 42])", string.Empty, string.Empty, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnEventNotInCurrentClass()
{
var markup = @"
using System;
class C
{
void Foo()
{
D d;
[|d.evt($$
|]}
}
public class D
{
public event Action evt;
}";
Test(markup);
}
[WorkItem(539712)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnNamedType()
{
var markup = @"
class Program
{
void Main()
{
C.Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x)", string.Empty, string.Empty, currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(539712)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnInstance()
{
var markup = @"
class Program
{
void Main()
{
new C().Foo($$
}
}
class C
{
public static double Foo(double x)
{
return x;
}
public double Foo(double x, double y)
{
return x + y;
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("double C.Foo(double x, double y)", string.Empty, string.Empty, currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(545118)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestStatic1()
{
var markup = @"
class C
{
static void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(545118)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestStatic2()
{
var markup = @"
class C
{
void Foo()
{
Bar($$
}
static void Bar()
{
}
void Bar(int i)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C.Bar()", currentParameterIndex: 0),
new SignatureHelpTestItem("void C.Bar(int i)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(543117)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnAnonymousType()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var foo = new { Name = string.Empty, Age = 30 };
Foo(foo).Add($$);
}
static List<T> Foo<T>(T t)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
$@"void List<'a>.Add('a item)
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: $@"
{FeaturesResources.AnonymousTypes}
'a {FeaturesResources.Is} new {{ string Name, int Age }}")
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_Overridden()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnThisExpression_ProtectedAccessibility_AbstractBase_Overridden()
{
var markup = @"
using System;
public abstract class Base
{
protected abstract void Foo(int x);
}
public class Derived : Base
{
void Test()
{
this.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Derived.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_ProtectedInternalAccessibility()
{
var markup = @"
using System;
public class Base
{
protected internal void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
@"void Base.Foo(int x)",
methodDocumentation: string.Empty,
parameterDocumentation: string.Empty,
currentParameterIndex: 0,
description: string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseMember_ProtectedAccessibility_ThroughType()
{
var markup = @"
using System;
public class Base
{
protected virtual void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
new Base().Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
Test(markup, null);
}
[WorkItem(968188)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnBaseExpression_PrivateAccessibility()
{
var markup = @"
using System;
public class Base
{
private void Foo(int x) { }
}
public class Derived : Base
{
void Test()
{
base.Foo($$);
}
protected override void Foo(int x)
{
throw new NotImplementedException();
}
}";
Test(markup, null);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestCurrentParameterName()
{
var markup = @"
class C
{
void Foo(int someParameter, bool something)
{
Foo(something: false, someParameter: $$)
}
}";
VerifyCurrentParameterName(markup, "someParameter");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerParens()
{
var markup = @"
class C
{
void Foo()
{
[|Foo($$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationOnTriggerComma()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23,$$|]);
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1));
Test(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestNoInvocationOnSpace()
{
var markup = @"
class C
{
void Foo(int a, int b)
{
[|Foo(23, $$|]);
}
}";
Test(markup, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
Foo.Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Bar()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_Method_Overloads_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Foo().Bar($$
}
}";
var referencedCode = @"
public class Foo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}";
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar()", string.Empty, null, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void Foo.Bar(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void OverriddenSymbolsFilteredFromSigHelp()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
public class B
{
public virtual void Foo(int original)
{
}
}
public class D : B
{
public override void Foo(int derived)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void D.Foo(int derived)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass()
{
var markup = @"
class Program
{
void M()
{
new C().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class C
{
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass()
{
var markup = @"
class Program
{
void M()
{
new D().Foo($$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class B
{
public void Foo()
{
}
}
public class D : B
{
public void Foo(int x)
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0),
new SignatureHelpTestItem("void D.Foo(int x)", string.Empty, string.Empty, currentParameterIndex: 0),
};
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_BrowsableStateNeverMethodsInBaseClass()
{
var markup = @"
class Program : B
{
void M()
{
Foo($$
}
}";
var referencedCode = @"
public class B
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo()
{
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void B.Foo()", string.Empty, null, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int>().Foo($$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(int i) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int>.Foo(int i)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
public void Foo(U u) { }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C<int, int>().Foo($$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo(U u) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int t)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItems.Add(new SignatureHelpTestItem("void C<int, int>.Foo(int u)", string.Empty, string.Empty, currentParameterIndex: 0));
TestSignatureHelpInEditorBrowsableContexts(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
#region "Awaitable tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void AwaitableMethod()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void AwaitableMethod2()
{
var markup = @"
using System.Threading.Tasks;
class C
{
async Task<Task<int>> Foo()
{
[|Foo($$|]);
}
}";
var description = $@"
{WorkspacesResources.Usage}
Task<int> x = await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Awaitable}) Task<Task<int>> C.Foo()", methodDocumentation: description, currentParameterIndex: 0));
TestSignatureHelpWithMscorlib45(markup, expectedOrderedItems, "C#");
}
#endregion
[WorkItem(13849, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestSpecificity1()
{
var markup = @"
class Class1
{
static void Main()
{
var obj = new C<int>();
[|obj.M($$|])
}
}
class C<T>
{
/// <param name=""t"">Generic t</param>
public void M(T t) { }
/// <param name=""t"">Real t</param>
public void M(int t) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void C<int>.M(int t)", string.Empty, "Real t", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(530017)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void LongSignature()
{
var markup = @"
class C
{
void Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)
{
[|Foo($$|])
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem(
signature: "void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j, string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u, string v, string w, string x, string y, string z)",
prettyPrintedSignature: @"void C.Foo(string a, string b, string c, string d, string e, string f, string g, string h, string i, string j,
string k, string l, string m, string n, string o, string p, string q, string r, string s, string t, string u,
string v, string w, string x, string y, string z)",
currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void GenericExtensionMethod()
{
var markup = @"
interface IFoo
{
void Bar<T>();
}
static class FooExtensions
{
public static void Bar<T1, T2>(this IFoo foo) { }
}
class Program
{
static void Main()
{
IFoo f = null;
[|f.Bar($$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
Test(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestInvocationWithCrefXmlComments()
{
var markup = @"
class C
{
/// <summary>
/// Summary for foo. See method <see cref=""Bar"" />
/// </summary>
void Foo()
{
[|Foo($$|]);
}
void Bar() { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo()", "Summary for foo. See method C.Bar()", null, currentParameterIndex: 0));
Test(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
void foo()
{
bar($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
void bar()
{
}
#endif
#if BAR
void foo()
{
bar($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.bar()\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown1()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown2()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$"");
}
}
class Foo
{
public void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown3()
{
var markup = @"
class C
{
Foo Foo;
void M()
{
Foo.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void Foo.Bar(int x)", currentParameterIndex: 0),
new SignatureHelpTestItem("void Foo.Bar(string s)", currentParameterIndex: 0)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown4()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems);
}
[WorkItem(768697)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InstanceAndStaticMethodsShown5()
{
var markup = @"
class C
{
void M()
{
Foo x;
x.Bar($$
}
}
class x { }
class Foo
{
public static void Bar(int x) { }
public static void Bar(string s) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
Test(markup, expectedOrderedItems);
}
[WorkItem(1067933)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void InvokedWithNoToken()
{
var markup = @"
// foo($$";
Test(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public void MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
this.Do($$
}
}]]></Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"void C.Do(int x)", currentParameterIndex: 0);
VerifyItemWithReferenceWorker(markup, new[] { expectedDescription }, false);
}
[WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")]
[WorkItem(1068424)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestGenericParameters1()
{
var markup = @"
class C
{
void M()
{
Foo(""""$$);
}
void Foo<T>(T a) { }
void Foo<T, U>(T a, U b) { }
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>()
{
new SignatureHelpTestItem("void C.Foo<string>(string a)", string.Empty, string.Empty, currentParameterIndex: 0),
new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty)
};
Test(markup, expectedOrderedItems);
}
[WorkItem(699, "https://github.com/dotnet/roslyn/issues/699")]
[WorkItem(1068424)]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestGenericParameters2()
{
var markup = @"
class C
{
void M()
{
Foo("""", $$);
}
void Foo<T>(T a) { }
void Foo<T, U>(T a, U b) { }
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>()
{
new SignatureHelpTestItem("void C.Foo<T>(T a)", string.Empty),
new SignatureHelpTestItem("void C.Foo<T, U>(T a, U b)", string.Empty, string.Empty, currentParameterIndex: 1)
};
Test(markup, expectedOrderedItems);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Globalization;
using TestLibrary;
// ToString_str.cs
// Tests TimeSpan.ToString(str)
// The desktop changes 2009/04/21 KatyK are ported 2009/06/08 DidemG
public class TimeSpanTest
{
static bool verbose = false;
static int iCountTestcases = 0;
static int iCountErrors = 0;
public static int Main(String[] args)
{
try
{
// for SL, String.ToLower(InvariantCulture)
if ((args.Length > 0) && args[0].ToLower() == "true")
verbose = true;
Logging.WriteLine("CurrentCulture: " + Utilities.CurrentCulture.Name);
Logging.WriteLine("CurrentUICulture: " + Utilities.CurrentCulture.Name);
RunTests();
}
catch (Exception e)
{
iCountErrors++;
Logging.WriteLine("Unexpected exception!! " + e.ToString());
}
if (iCountErrors == 0)
{
Logging.WriteLine("Pass. iCountTestcases=="+iCountTestcases);
return 100;
}
else
{
Logging.WriteLine("FAIL! iCountTestcases=="+iCountTestcases+", iCountErrors=="+iCountErrors);
return 1;
}
}
public static void RunTests()
{
// The current implementation uses the same character as the default NumberDecimalSeparator
// for a culture, but this is an implementation detail and could change. No user overrides
// are respected.
String GDecimalSeparator = Utilities.CurrentCulture.NumberFormat.NumberDecimalSeparator;
// Standard formats
foreach (TimeSpan ts in Support.InterestingTimeSpans)
{
String defaultFormat = Support.CFormat(ts);
VerifyToString(ts, defaultFormat); // no regressions
VerifyToString(ts, "c", defaultFormat);
VerifyToString(ts, "t", defaultFormat);
VerifyToString(ts, "T", defaultFormat);
VerifyToString(ts, null, defaultFormat);
VerifyToString(ts, "", defaultFormat);
VerifyToString(ts, "g", Support.gFormat(ts, GDecimalSeparator));
VerifyToString(ts, "G", Support.GFormat(ts, GDecimalSeparator));
}
// Custom formats
TimeSpan ts1 = new TimeSpan(1, 2, 3, 4, 56);
VerifyToString(ts1, "d'-'", "1-");
VerifyToString(ts1, "%d", "1");
VerifyToString(ts1, "dd", "01");
VerifyToString(ts1, "ddd", "001");
VerifyToString(ts1, "dddd", "0001");
VerifyToString(ts1, "ddddd", "00001");
VerifyToString(ts1, "dddddd", "000001");
VerifyToString(ts1, "ddddddd", "0000001");
VerifyToString(ts1, "dddddddd", "00000001");
VerifyToString(ts1, "h'-'", "2-");
VerifyToString(ts1, "%h", "2");
VerifyToString(ts1, "hh", "02");
VerifyToString(ts1, "m'-'", "3-");
VerifyToString(ts1, "%m", "3");
VerifyToString(ts1, "mm", "03");
VerifyToString(ts1, "s'-'", "4-");
VerifyToString(ts1, "%s", "4");
VerifyToString(ts1, "ss", "04");
VerifyToString(ts1, "f'-'", "0-");
VerifyToString(ts1, "ff", "05");
VerifyToString(ts1, "fff", "056");
VerifyToString(ts1, "ffff", "0560");
VerifyToString(ts1, "fffff", "05600");
VerifyToString(ts1, "ffffff", "056000");
VerifyToString(ts1, "fffffff", "0560000");
VerifyToString(ts1, "F'-'", "-");
VerifyToString(ts1, "FF", "05");
VerifyToString(ts1, "FFF", "056");
VerifyToString(ts1, "FFFF", "056");
VerifyToString(ts1, "FFFFF", "056");
VerifyToString(ts1, "FFFFFF", "056");
VerifyToString(ts1, "FFFFFFF", "056");
VerifyToString(ts1, "hhmmss", "020304");
ts1 = new TimeSpan(-1, -2, -3, -4, -56);
VerifyToString(ts1, "d'-'", "1-");
VerifyToString(ts1, "%d", "1");
VerifyToString(ts1, "dd", "01");
VerifyToString(ts1, "ddd", "001");
VerifyToString(ts1, "dddd", "0001");
VerifyToString(ts1, "ddddd", "00001");
VerifyToString(ts1, "dddddd", "000001");
VerifyToString(ts1, "ddddddd", "0000001");
VerifyToString(ts1, "dddddddd", "00000001");
VerifyToString(ts1, "h'-'", "2-");
VerifyToString(ts1, "%h", "2");
VerifyToString(ts1, "hh", "02");
VerifyToString(ts1, "m'-'", "3-");
VerifyToString(ts1, "%m", "3");
VerifyToString(ts1, "mm", "03");
VerifyToString(ts1, "s'-'", "4-");
VerifyToString(ts1, "%s", "4");
VerifyToString(ts1, "ss", "04");
VerifyToString(ts1, "f'-'", "0-");
VerifyToString(ts1, "ff", "05");
VerifyToString(ts1, "fff", "056");
VerifyToString(ts1, "ffff", "0560");
VerifyToString(ts1, "fffff", "05600");
VerifyToString(ts1, "ffffff", "056000");
VerifyToString(ts1, "fffffff", "0560000");
VerifyToString(ts1, "F'-'", "-");
VerifyToString(ts1, "FF", "05");
VerifyToString(ts1, "FFF", "056");
VerifyToString(ts1, "FFFF", "056");
VerifyToString(ts1, "FFFFF", "056");
VerifyToString(ts1, "FFFFFF", "056");
VerifyToString(ts1, "FFFFFFF", "056");
VerifyToString(ts1, "hhmmss", "020304");
ts1 = new TimeSpan(1, 2, 3, 4, 56).Add(new TimeSpan(78));
VerifyToString(ts1, "'.'F", ".");
VerifyToString(ts1, "FF", "05");
VerifyToString(ts1, "FFF", "056");
VerifyToString(ts1, "FFFF", "056");
VerifyToString(ts1, "FFFFF", "056");
VerifyToString(ts1, "FFFFFF", "056007");
VerifyToString(ts1, "FFFFFFF", "0560078");
ts1 = new TimeSpan(1, 2, 3, 4).Add(new TimeSpan(789));
VerifyToString(ts1, "'.'F", ".");
VerifyToString(ts1, "FF", "");
VerifyToString(ts1, "FFF", "");
VerifyToString(ts1, "FFFF", "");
VerifyToString(ts1, "FFFFF", "00007");
VerifyToString(ts1, "FFFFFF", "000078");
VerifyToString(ts1, "FFFFFFF", "0000789");
// Literals
ts1 = new TimeSpan(1, 2, 3, 4, 56).Add(new TimeSpan(78));
VerifyToString(ts1, "d'd'", "1d");
VerifyToString(ts1, "d' days'", "1 days");
VerifyToString(ts1, "d' days, 'h' hours, 'm' minutes, 's'.'FFFF' seconds'", "1 days, 2 hours, 3 minutes, 4.056 seconds");
// Error formats
foreach (String errorFormat in Support.ErrorFormats)
{
ts1 = new TimeSpan(1, 2, 3, 4, 56).Add(new TimeSpan(78));
VerifyToStringException<FormatException>(ts1, errorFormat);
}
// Vary current culture
Utilities.CurrentCulture = CultureInfo.InvariantCulture;
foreach (TimeSpan ts in Support.InterestingTimeSpans)
{
String defaultFormat = Support.CFormat(ts);
VerifyToString(ts, defaultFormat);
VerifyToString(ts, "c", defaultFormat);
VerifyToString(ts, "t", defaultFormat);
VerifyToString(ts, "T", defaultFormat);
VerifyToString(ts, null, defaultFormat);
VerifyToString(ts, "", defaultFormat);
VerifyToString(ts, "g", Support.gFormat(ts, "."));
VerifyToString(ts, "G", Support.GFormat(ts, "."));
}
Utilities.CurrentCulture = new CultureInfo("en-US");
foreach (TimeSpan ts in Support.InterestingTimeSpans)
{
String defaultFormat = Support.CFormat(ts);
VerifyToString(ts, defaultFormat);
VerifyToString(ts, "c", defaultFormat);
VerifyToString(ts, "t", defaultFormat);
VerifyToString(ts, "T", defaultFormat);
VerifyToString(ts, null, defaultFormat);
VerifyToString(ts, "", defaultFormat);
VerifyToString(ts, "g", Support.gFormat(ts, "."));
VerifyToString(ts, "G", Support.GFormat(ts, "."));
}
Utilities.CurrentCulture = new CultureInfo("de-DE");
foreach (TimeSpan ts in Support.InterestingTimeSpans)
{
String defaultFormat = Support.CFormat(ts);
VerifyToString(ts, defaultFormat);
VerifyToString(ts, "c", defaultFormat);
VerifyToString(ts, "t", defaultFormat);
VerifyToString(ts, "T", defaultFormat);
VerifyToString(ts, null, defaultFormat);
VerifyToString(ts, "", defaultFormat);
VerifyToString(ts, "g", Support.gFormat(ts, ","));
VerifyToString(ts, "G", Support.GFormat(ts, ","));
}
}
public static void VerifyToString(TimeSpan timeSpan, String expectedResult)
{
iCountTestcases++;
try
{
String result = timeSpan.ToString();
if (verbose)
Logging.WriteLine("{0} ({1}) ==> {2}", Support.PrintTimeSpan(timeSpan), "default", result);
if (result != expectedResult)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Input = {0}, Format: '{1}', Expected Return: '{2}', Actual Return: '{3}'", Support.PrintTimeSpan(timeSpan), "default", expectedResult, result);
}
}
catch (Exception ex)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Unexpected Exception, Input = {0}, Format = '{1}', Exception: {2}", Support.PrintTimeSpan(timeSpan), "default", ex);
}
}
public static void VerifyToString(TimeSpan timeSpan, String format, String expectedResult)
{
iCountTestcases++;
try
{
String result = timeSpan.ToString(format);
if (verbose)
Logging.WriteLine("{0} ('{1}') ==> {2}", Support.PrintTimeSpan(timeSpan), format, result);
if (result != expectedResult)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Input = {0}, Format: '{1}', Expected Return: '{2}', Actual Return: '{3}'", Support.PrintTimeSpan(timeSpan), format, expectedResult, result);
}
}
catch (Exception ex)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Unexpected Exception, Input = {0}, Format = '{1}', Exception: {2}", Support.PrintTimeSpan(timeSpan), format, ex);
}
}
public static void VerifyToStringException<TException>(TimeSpan timeSpan, String format) where TException : Exception
{
iCountTestcases++;
if (verbose)
Logging.WriteLine("Expecting {2}: {0} ('{1}')", Support.PrintTimeSpan(timeSpan), format, typeof(TException));
try
{
String result = timeSpan.ToString(format);
iCountErrors++;
Logging.WriteLine("FAILURE: Input = {0}, Format: '{1}', Expected Exception: {2}, Actual Return: '{3}'", Support.PrintTimeSpan(timeSpan), format, typeof(TException), result);
}
catch (TException)
{
//Logging.WriteLine("INFO: {0}: {1}", ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Logging.WriteLine("FAILURE: Unexpected Exception, Input = {0}, Format = '{1}', Exception: {2}", Support.PrintTimeSpan(timeSpan), format, ex);
}
}
}
| |
//
// ExportedType.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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 Mono.Cecil {
public class ExportedType : IMetadataTokenProvider {
string @namespace;
string name;
uint attributes;
IMetadataScope scope;
ModuleDefinition module;
int identifier;
ExportedType declaring_type;
internal MetadataToken token;
public string Namespace {
get { return @namespace; }
set { @namespace = value; }
}
public string Name {
get { return name; }
set { name = value; }
}
public TypeAttributes Attributes {
get { return (TypeAttributes) attributes; }
set { attributes = (uint) value; }
}
public IMetadataScope Scope {
get {
if (declaring_type != null)
return declaring_type.Scope;
return scope;
}
}
public ExportedType DeclaringType {
get { return declaring_type; }
set { declaring_type = value; }
}
public MetadataToken MetadataToken {
get { return token; }
set { token = value; }
}
public int Identifier {
get { return identifier; }
set { identifier = value; }
}
#region TypeAttributes
public bool IsNotPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); }
}
public bool IsNestedPublic {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); }
}
public bool IsNestedPrivate {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); }
}
public bool IsNestedFamily {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); }
}
public bool IsNestedAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); }
}
public bool IsNestedFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); }
}
public bool IsNestedFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); }
}
public bool IsAutoLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); }
}
public bool IsSequentialLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); }
}
public bool IsExplicitLayout {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); }
}
public bool IsClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); }
}
public bool IsInterface {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); }
}
public bool IsAbstract {
get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); }
}
public bool IsSealed {
get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); }
}
public bool IsImport {
get { return attributes.GetAttributes ((uint) TypeAttributes.Import); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); }
}
public bool IsSerializable {
get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); }
}
public bool IsAnsiClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); }
}
public bool IsUnicodeClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); }
}
public bool IsAutoClass {
get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); }
set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); }
}
public bool IsBeforeFieldInit {
get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); }
}
public bool HasSecurity {
get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); }
}
#endregion
public bool IsForwarder {
get { return attributes.GetAttributes ((uint) TypeAttributes.Forwarder); }
set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Forwarder, value); }
}
public string FullName {
get {
var fullname = string.IsNullOrEmpty (@namespace)
? name
: @namespace + '.' + name;
if (declaring_type != null)
return declaring_type.FullName + "/" + fullname;
return fullname;
}
}
public ExportedType (string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
{
this.@namespace = @namespace;
this.name = name;
this.scope = scope;
this.module = module;
}
public override string ToString ()
{
return FullName;
}
public TypeDefinition Resolve ()
{
return module.Resolve (CreateReference ());
}
internal TypeReference CreateReference ()
{
return new TypeReference (@namespace, name, module, scope) {
DeclaringType = declaring_type != null ? declaring_type.CreateReference () : null,
};
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcmv = Google.Cloud.Monitoring.V3;
namespace Google.Cloud.Monitoring.V3
{
public partial class CreateServiceRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::OrganizationName ParentAsOrganizationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::FolderName ParentAsFolderName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization))
{
return organization;
}
if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder))
{
return folder;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetServiceRequest
{
/// <summary>
/// <see cref="gcmv::ServiceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcmv::ServiceName ServiceName
{
get => string.IsNullOrEmpty(Name) ? null : gcmv::ServiceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gcmv::ServiceName.TryParse(Name, out gcmv::ServiceName service))
{
return service;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
public partial class ListServicesRequest
{
/// <summary>
/// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::ProjectName ParentAsProjectName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::OrganizationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::OrganizationName ParentAsOrganizationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::OrganizationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagr::FolderName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::FolderName ParentAsFolderName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::FolderName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (gagr::ProjectName.TryParse(Parent, out gagr::ProjectName project))
{
return project;
}
if (gagr::OrganizationName.TryParse(Parent, out gagr::OrganizationName organization))
{
return organization;
}
if (gagr::FolderName.TryParse(Parent, out gagr::FolderName folder))
{
return folder;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteServiceRequest
{
/// <summary>
/// <see cref="gcmv::ServiceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcmv::ServiceName ServiceName
{
get => string.IsNullOrEmpty(Name) ? null : gcmv::ServiceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gcmv::ServiceName.TryParse(Name, out gcmv::ServiceName service))
{
return service;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateServiceLevelObjectiveRequest
{
/// <summary>
/// <see cref="ServiceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public ServiceName ParentAsServiceName
{
get => string.IsNullOrEmpty(Parent) ? null : ServiceName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (ServiceName.TryParse(Parent, out ServiceName service))
{
return service;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetServiceLevelObjectiveRequest
{
/// <summary>
/// <see cref="gcmv::ServiceLevelObjectiveName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcmv::ServiceLevelObjectiveName ServiceLevelObjectiveName
{
get => string.IsNullOrEmpty(Name) ? null : gcmv::ServiceLevelObjectiveName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gcmv::ServiceLevelObjectiveName.TryParse(Name, out gcmv::ServiceLevelObjectiveName serviceLevelObjective))
{
return serviceLevelObjective;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
public partial class ListServiceLevelObjectivesRequest
{
/// <summary>
/// <see cref="ServiceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public ServiceName ParentAsServiceName
{
get => string.IsNullOrEmpty(Parent) ? null : ServiceName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gax::IResourceName ParentAsResourceName
{
get
{
if (string.IsNullOrEmpty(Parent))
{
return null;
}
if (ServiceName.TryParse(Parent, out ServiceName service))
{
return service;
}
return gax::UnparsedResourceName.Parse(Parent);
}
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteServiceLevelObjectiveRequest
{
/// <summary>
/// <see cref="gcmv::ServiceLevelObjectiveName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcmv::ServiceLevelObjectiveName ServiceLevelObjectiveName
{
get => string.IsNullOrEmpty(Name) ? null : gcmv::ServiceLevelObjectiveName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gax::IResourceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gax::IResourceName ResourceName
{
get
{
if (string.IsNullOrEmpty(Name))
{
return null;
}
if (gcmv::ServiceLevelObjectiveName.TryParse(Name, out gcmv::ServiceLevelObjectiveName serviceLevelObjective))
{
return serviceLevelObjective;
}
return gax::UnparsedResourceName.Parse(Name);
}
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using Amazon.Auth.AccessControlPolicy;
using Amazon.Auth.AccessControlPolicy.ActionIdentifiers;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;
using Amazon.Lambda;
using Amazon.Lambda.Model;
using Amazon.Runtime;
using CommonTests.Framework;
using NUnit.Framework;
using System.IO.Compression;
using System.Text;
namespace CommonTests.IntegrationTests
{
[TestFixture]
public class LambdaTests : TestBase<AmazonLambdaClient>
{
static IAmazonIdentityManagementService iamClient = TestBase.CreateClient<AmazonIdentityManagementServiceClient>();
static List<string> createdFunctionNames = new List<string>();
[OneTimeTearDown]
public void Cleanup()
{
BaseClean();
}
[TearDown]
public void TestCleanup()
{
DeleteCreatedFunctions(Client);
}
public static void DeleteCreatedFunctions(IAmazonLambda lambdaClient)
{
var deletedFunctions = new List<string>();
foreach(var function in createdFunctionNames)
{
try
{
lambdaClient.DeleteFunctionAsync(function).Wait();
deletedFunctions.Add(function);
}
catch { }
}
foreach (var df in deletedFunctions)
createdFunctionNames.Remove(df);
}
[Test]
public void ListFunctionsTest()
{
var result = Client.ListFunctionsAsync().Result;
Assert.IsNotNull(result);
Assert.IsNotNull(result.ResponseMetadata);
Assert.IsNotNull(result.ResponseMetadata.RequestId);
}
static readonly string LAMBDA_ASSUME_ROLE_POLICY =
@"
{
""Version"": ""2012-10-17"",
""Statement"": [
{
""Sid"": """",
""Effect"": ""Allow"",
""Principal"": {
""Service"": ""lambda.amazonaws.com""
},
""Action"": ""sts:AssumeRole""
}
]
}
".Trim();
[Test]
public void LambdaFunctionTest()
{
string functionName;
string iamRoleName = null;
bool iamRoleCreated = false;
try
{
string iamRoleArn;
string functionArn;
CreateLambdaFunction(out functionName, out functionArn, out iamRoleName, out iamRoleArn);
// List all the functions and make sure the newly uploaded function is in the collection
var listResponse = Client.ListFunctionsAsync().Result;
var function = listResponse.Functions.FirstOrDefault(x => x.FunctionName == functionName);
Assert.IsNotNull(function);
Assert.AreEqual("helloworld.handler", function.Handler);
Assert.AreEqual(iamRoleArn, function.Role);
// Get the function with a presigned URL to the uploaded code
var getFunctionResponse = Client.GetFunctionAsync(functionName).Result;
Assert.AreEqual("helloworld.handler", getFunctionResponse.Configuration.Handler);
Assert.IsNotNull(getFunctionResponse.Code.Location);
// Get the function's configuration only
var getFunctionConfiguration = Client.GetFunctionConfigurationAsync(functionName).Result;
Assert.AreEqual("helloworld.handler", getFunctionConfiguration.Handler);
// Call the function
var invokeAsyncResponse = Client.InvokeAsyncAsync(new InvokeAsyncRequest
{
FunctionName = functionName,
InvokeArgs = "{}"
}).Result;
Assert.AreEqual(invokeAsyncResponse.Status, 202); // Status Code Accepted
var clientContext = @"{""System"": ""Windows""}";
var clientContextBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(clientContext));
var request = new InvokeRequest
{
FunctionName = functionName,
InvocationType = InvocationType.RequestResponse,
LogType = LogType.None,
ClientContext = clientContext,
Payload = @"{""Key"": ""testing""}"
};
Assert.AreEqual(clientContext, request.ClientContext);
Assert.AreEqual(clientContextBase64, request.ClientContextBase64);
// Call the function sync
var invokeSyncResponse = Client.InvokeAsync(request).Result;
Assert.IsNull(invokeSyncResponse.FunctionError);
Assert.IsNull(invokeSyncResponse.LogResult);
Assert.IsNotNull(invokeSyncResponse.Payload);
Assert.AreNotEqual(0, invokeSyncResponse.Payload.Length);
Assert.AreNotEqual(0, invokeSyncResponse.StatusCode);
// Call the function sync, dry run, no payload
invokeSyncResponse = Client.InvokeAsync(new InvokeRequest
{
FunctionName = functionName,
InvocationType = InvocationType.DryRun,
LogType = LogType.None,
ClientContext = clientContext,
Payload = @"{""Key"": ""testing""}"
}).Result;
Assert.IsNull(invokeSyncResponse.FunctionError);
Assert.IsNull(invokeSyncResponse.LogResult);
Assert.IsNotNull(invokeSyncResponse.Payload);
Assert.AreEqual(0, invokeSyncResponse.Payload.Length);
Assert.AreNotEqual(0, invokeSyncResponse.StatusCode);
// Call the function sync, pass non-JSON payload
invokeSyncResponse = Client.InvokeAsync(new InvokeRequest
{
FunctionName = functionName,
InvocationType = InvocationType.RequestResponse,
LogType = LogType.None,
ClientContext = clientContext,
Payload = @"""Key"": ""testing"""
}).Result;
Assert.IsNotNull(invokeSyncResponse.FunctionError);
Assert.IsNull(invokeSyncResponse.LogResult);
Assert.IsNotNull(invokeSyncResponse.Payload);
Assert.AreNotEqual(0, invokeSyncResponse.Payload.Length);
Assert.AreNotEqual(0, invokeSyncResponse.StatusCode);
}
finally
{
if (iamRoleCreated)
iamClient.DeleteRoleAsync(new DeleteRoleRequest { RoleName = iamRoleName }).Wait();
}
}
public void CreateLambdaFunction(out string functionName, out string functionArn, out string iamRoleName, out string iamRoleArn)
{
functionName = "HelloWorld-" + DateTime.Now.Ticks;
iamRoleName = "Lambda-" + DateTime.Now.Ticks;
CreateLambdaFunction(functionName, iamRoleName, out iamRoleArn, out functionArn);
}
public void CreateLambdaFunction(string functionName, string iamRoleName, out string iamRoleArn, out string functionArn)
{
var iamCreateResponse = iamClient.CreateRoleAsync(new CreateRoleRequest
{
RoleName = iamRoleName,
AssumeRolePolicyDocument = LAMBDA_ASSUME_ROLE_POLICY
}).Result;
iamRoleArn = iamCreateResponse.Role.Arn;
var statement = new Amazon.Auth.AccessControlPolicy.Statement(
Amazon.Auth.AccessControlPolicy.Statement.StatementEffect.Allow);
statement.Actions.Add(S3ActionIdentifiers.PutObject);
statement.Actions.Add(S3ActionIdentifiers.GetObject);
statement.Resources.Add(new Resource("*"));
var policy = new Amazon.Auth.AccessControlPolicy.Policy();
policy.Statements.Add(statement);
iamClient.PutRolePolicyAsync(new PutRolePolicyRequest
{
RoleName = iamRoleName,
PolicyName = "admin",
PolicyDocument = policy.ToJson()
}).Wait();
MemoryStream stream = GetScriptStream();
var uploadRequest = new CreateFunctionRequest
{
FunctionName = functionName,
Code = new FunctionCode
{
ZipFile = stream
},
Handler = "helloworld.handler",
//Mode = Mode.Event,
Runtime = Runtime.Nodejs,
Role = iamCreateResponse.Role.Arn
};
var uploadResponse = UtilityMethods.WaitUntilSuccess(() => Client.CreateFunctionAsync(uploadRequest).Result);
createdFunctionNames.Add(functionName);
Assert.IsTrue(uploadResponse.CodeSize > 0);
Assert.IsNotNull(uploadResponse.FunctionArn);
functionArn = uploadResponse.FunctionArn;
}
private static MemoryStream GetScriptStream()
{
return new MemoryStream(Convert.FromBase64String(HELLO_SCRIPT_BYTES_BASE64));
}
private static string HELLO_SCRIPT_BYTES_BASE64 = "UEsDBBQAAAAIANZsA0emOtZ2nwAAANoAAAANAAAAaGVsbG93b3JsZC5qc1XMQQuCQBCG4bvgfxj2opKs96STBEHdJDovOqkwzoS7mhL999Qw6DYfzPMWwlYINUkVBhcxZcMV4IDsgij1PRwf0jmra8MlYQcHuPdcuEY4XJ9iKIQdji6Cl+/Bsn45NRjqcSYKdt+kPuO0VGFTuhTGkHuiGNQJiQRu0lG5/yPzreK1srF8sg7bKAVIEsivWXbMc3g2roYWrTUV+t77A1BLAQIUABQAAAAIANZsA0emOtZ2nwAAANoAAAANAAAAAAAAAAAAAAAAAAAAAABoZWxsb3dvcmxkLmpzUEsFBgAAAAABAAEAOwAAAMoAAAAAAA==";
// The above base64 string was generated by calling the below function in a 4.5 application with name="helloworld" and script=HELLO_SCRIPT
// private static string HELLO_SCRIPT =
//@"console.log('Loading event');
//exports.handler = function(event, context) {
// console.log(""value = "" + event.Key);
// context.done(null, ""Hello World:"" + event.Key + "", "" + context.System); // SUCCESS with message
//}";
//private static string CreateScriptBytesBase64(string name, string script)
//{
// using (var stream = new MemoryStream())
// {
// using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
// {
// var entry = archive.CreateEntry(name + ".js");
// using (var entryStream = entry.Open())
// using (var writer = new StreamWriter(entryStream))
// {
// writer.Write(script);
// }
// }
// var bytes = stream.ToArray();
// var base64 = Convert.ToBase64String(bytes);
// return base64;
// }
//}
//#endif
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT
namespace NLog
{
using System;
using System.Collections.Generic;
using Internal;
/// <summary>
/// Async version of Mapped Diagnostics Context - a logical context structure that keeps a dictionary
/// of strings and provides methods to output them in layouts. Allows for maintaining state across
/// asynchronous tasks and call contexts.
/// </summary>
/// <remarks>
/// Ideally, these changes should be incorporated as a new version of the MappedDiagnosticsContext class in the original
/// NLog library so that state can be maintained for multiple threads in asynchronous situations.
/// </remarks>
public static class MappedDiagnosticsLogicalContext
{
/// <summary>
/// Simulate ImmutableDictionary behavior (which is not yet part of all .NET frameworks).
/// In future the real ImmutableDictionary could be used here to minimize memory usage and copying time.
/// </summary>
/// <param name="clone">Must be true for any subsequent dictionary modification operation</param>
/// <returns></returns>
private static IDictionary<string, object> GetLogicalThreadDictionary(bool clone = false)
{
var dictionary = GetThreadLocal();
if (dictionary == null)
{
if (!clone)
return EmptyDefaultDictionary;
dictionary = new Dictionary<string, object>();
SetThreadLocal(dictionary);
}
else if (clone)
{
dictionary = new Dictionary<string, object>(dictionary);
SetThreadLocal(dictionary);
}
return dictionary;
}
/// <summary>
/// Gets the current logical context named item, as <see cref="string"/>.
/// </summary>
/// <param name="item">Item name.</param>
/// <returns>The value of <paramref name="item"/>, if defined; otherwise <see cref="String.Empty"/>.</returns>
/// <remarks>If the value isn't a <see cref="string"/> already, this call locks the <see cref="LogFactory"/> for reading the <see cref="Config.LoggingConfiguration.DefaultCultureInfo"/> needed for converting to <see cref="string"/>. </remarks>
public static string Get(string item)
{
return Get(item, null);
}
/// <summary>
/// Gets the current logical context named item, as <see cref="string"/>.
/// </summary>
/// <param name="item">Item name.</param>
/// <param name="formatProvider">The <see cref="IFormatProvider"/> to use when converting a value to a string.</param>
/// <returns>The value of <paramref name="item"/>, if defined; otherwise <see cref="String.Empty"/>.</returns>
/// <remarks>If <paramref name="formatProvider"/> is <c>null</c> and the value isn't a <see cref="string"/> already, this call locks the <see cref="LogFactory"/> for reading the <see cref="Config.LoggingConfiguration.DefaultCultureInfo"/> needed for converting to <see cref="string"/>. </remarks>
public static string Get(string item, IFormatProvider formatProvider)
{
return FormatHelper.ConvertToString(GetObject(item), formatProvider);
}
/// <summary>
/// Gets the current logical context named item, as <see cref="object"/>.
/// </summary>
/// <param name="item">Item name.</param>
/// <returns>The value of <paramref name="item"/>, if defined; otherwise <c>null</c>.</returns>
public static object GetObject(string item)
{
object value;
GetLogicalThreadDictionary().TryGetValue(item, out value);
return value;
}
/// <summary>
/// Sets the current logical context item to the specified value.
/// </summary>
/// <param name="item">Item name.</param>
/// <param name="value">Item value.</param>
public static void Set(string item, string value)
{
GetLogicalThreadDictionary(true)[item] = value;
}
/// <summary>
/// Sets the current logical context item to the specified value.
/// </summary>
/// <param name="item">Item name.</param>
/// <param name="value">Item value.</param>
public static void Set(string item, object value)
{
GetLogicalThreadDictionary(true)[item] = value;
}
/// <summary>
/// Returns all item names
/// </summary>
/// <returns>A collection of the names of all items in current logical context.</returns>
public static ICollection<string> GetNames()
{
return GetLogicalThreadDictionary().Keys;
}
/// <summary>
/// Checks whether the specified <paramref name="item"/> exists in current logical context.
/// </summary>
/// <param name="item">Item name.</param>
/// <returns>A boolean indicating whether the specified <paramref name="item"/> exists in current logical context.</returns>
public static bool Contains(string item)
{
return GetLogicalThreadDictionary().ContainsKey(item);
}
/// <summary>
/// Removes the specified <paramref name="item"/> from current logical context.
/// </summary>
/// <param name="item">Item name.</param>
public static void Remove(string item)
{
GetLogicalThreadDictionary(true).Remove(item);
}
/// <summary>
/// Clears the content of current logical context.
/// </summary>
public static void Clear()
{
Clear(false);
}
/// <summary>
/// Clears the content of current logical context.
/// </summary>
/// <param name="free">Free the full slot.</param>
public static void Clear(bool free)
{
if (free)
{
SetThreadLocal(null);
}
else
{
GetLogicalThreadDictionary(true).Clear();
}
}
private static void SetThreadLocal(IDictionary<string, object> newValue)
{
#if NET4_6 || NETSTANDARD
AsyncLocalDictionary.Value = newValue;
#else
if (newValue == null)
System.Runtime.Remoting.Messaging.CallContext.FreeNamedDataSlot(LogicalThreadDictionaryKey);
else
System.Runtime.Remoting.Messaging.CallContext.LogicalSetData(LogicalThreadDictionaryKey, newValue);
#endif
}
private static IDictionary<string, object> GetThreadLocal()
{
#if NET4_6 || NETSTANDARD
return AsyncLocalDictionary.Value;
#else
return System.Runtime.Remoting.Messaging.CallContext.LogicalGetData(LogicalThreadDictionaryKey) as Dictionary<string, object>;
#endif
}
#if NET4_6 || NETSTANDARD
private static readonly System.Threading.AsyncLocal<IDictionary<string, object>> AsyncLocalDictionary = new System.Threading.AsyncLocal<IDictionary<string, object>>();
#else
private const string LogicalThreadDictionaryKey = "NLog.AsyncableMappedDiagnosticsContext";
#endif
private static readonly IDictionary<string, object> EmptyDefaultDictionary = new SortHelpers.ReadOnlySingleBucketDictionary<string, object>();
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
** Purpose: An array implementation of a generic stack.
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace System.Collections.Generic
{
// A simple stack of objects. Internally it is implemented as an array,
// so Push can be O(n). Pop is O(1).
[DebuggerTypeProxy(typeof(StackDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class Stack<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array; // Storage for stack elements. Do not rename (binary serialization)
private int _size; // Number of items in the stack. Do not rename (binary serialization)
private int _version; // Used to keep enumerator in sync w/ collection. Do not rename (binary serialization)
[NonSerialized]
private object _syncRoot;
private const int DefaultCapacity = 4;
public Stack()
{
_array = Array.Empty<T>();
}
// Create a stack with a specific initial capacity. The initial capacity
// must be a non-negative number.
public Stack(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
_array = new T[capacity];
}
// Fills a Stack with the contents of a particular collection. The items are
// pushed onto the stack in the same order they are read by the enumerator.
public Stack(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
_array = EnumerableHelpers.ToArray(collection, out _size);
}
public int Count
{
get { return _size; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the Stack.
public void Clear()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
}
_size = 0;
_version++;
}
public bool Contains(T item)
{
// Compare items using the default equality comparer
// PERF: Internally Array.LastIndexOf calls
// EqualityComparer<T>.Default.LastIndexOf, which
// is specialized for different types. This
// boosts performance since instead of making a
// virtual method call each iteration of the loop,
// via EqualityComparer<T>.Default.Equals, we
// only make one virtual call to EqualityComparer.LastIndexOf.
return _size != 0 && Array.LastIndexOf(_array, item, _size - 1) != -1;
}
// Copies the stack into an array.
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Debug.Assert(array != _array);
int srcIndex = 0;
int dstIndex = arrayIndex + _size;
while(srcIndex < _size)
{
array[--dstIndex] = _array[srcIndex++];
}
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
try
{
Array.Copy(_array, 0, array, arrayIndex, _size);
Array.Reverse(array, arrayIndex, _size);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Returns an IEnumerator for this Stack.
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
public void TrimExcess()
{
int threshold = (int)(((double)_array.Length) * 0.9);
if (_size < threshold)
{
Array.Resize(ref _array, _size);
_version++;
}
}
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
public T Peek()
{
int size = _size - 1;
T[] array = _array;
if ((uint)size >= (uint)array.Length)
{
ThrowForEmptyStack();
}
return array[size];
}
public bool TryPeek(out T result)
{
int size = _size - 1;
T[] array = _array;
if ((uint)size >= (uint)array.Length)
{
result = default;
return false;
}
result = array[size];
return true;
}
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
public T Pop()
{
int size = _size - 1;
T[] array = _array;
// if (_size == 0) is equivalent to if (size == -1), and this case
// is covered with (uint)size, thus allowing bounds check elimination
// https://github.com/dotnet/coreclr/pull/9773
if ((uint)size >= (uint)array.Length)
{
ThrowForEmptyStack();
}
_version++;
_size = size;
T item = array[size];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
array[size] = default; // Free memory quicker.
}
return item;
}
public bool TryPop(out T result)
{
int size = _size - 1;
T[] array = _array;
if ((uint)size >= (uint)array.Length)
{
result = default;
return false;
}
_version++;
_size = size;
result = array[size];
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
array[size] = default; // Free memory quicker.
}
return true;
}
// Pushes an item to the top of the stack.
public void Push(T item)
{
int size = _size;
T[] array = _array;
if ((uint)size < (uint)array.Length)
{
array[size] = item;
_version++;
_size = size + 1;
}
else
{
PushWithResize(item);
}
}
// Non-inline from Stack.Push to improve its code quality as uncommon path
[MethodImpl(MethodImplOptions.NoInlining)]
private void PushWithResize(T item)
{
Array.Resize(ref _array, (_array.Length == 0) ? DefaultCapacity : 2 * _array.Length);
_array[_size] = item;
_version++;
_size++;
}
// Copies the Stack to an array, in the same order Pop would return the items.
public T[] ToArray()
{
if (_size == 0)
return Array.Empty<T>();
T[] objArray = new T[_size];
int i = 0;
while (i < _size)
{
objArray[i] = _array[_size - i - 1];
i++;
}
return objArray;
}
private void ThrowForEmptyStack()
{
Debug.Assert(_size == 0);
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator
{
private readonly Stack<T> _stack;
private readonly int _version;
private int _index;
private T _currentElement;
internal Enumerator(Stack<T> stack)
{
_stack = stack;
_version = stack._version;
_index = -2;
_currentElement = default(T);
}
public void Dispose()
{
_index = -1;
}
public bool MoveNext()
{
bool retval;
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
{ // First call to enumerator.
_index = _stack._size - 1;
retval = (_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
return retval;
}
if (_index == -1)
{ // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
else
_currentElement = default(T);
return retval;
}
public T Current
{
get
{
if (_index < 0)
ThrowEnumerationNotStartedOrEnded();
return _currentElement;
}
}
private void ThrowEnumerationNotStartedOrEnded()
{
Debug.Assert(_index == -1 || _index == -2);
throw new InvalidOperationException(_index == -2 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded);
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -2;
_currentElement = default(T);
}
}
}
}
| |
//
// Copyright (c) 2004-2020 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.Config
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
// ReSharper disable once RedundantUsingDirective
using NLog.Internal;
/// <summary>
/// Provides context for install/uninstall operations.
/// </summary>
public sealed class InstallationContext : IDisposable
{
#if !SILVERLIGHT && !NETSTANDARD1_3
/// <summary>
/// Mapping between log levels and console output colors.
/// </summary>
private static readonly Dictionary<LogLevel, ConsoleColor> LogLevel2ConsoleColor = new Dictionary<LogLevel, ConsoleColor>()
{
{ LogLevel.Trace, ConsoleColor.DarkGray },
{ LogLevel.Debug, ConsoleColor.Gray },
{ LogLevel.Info, ConsoleColor.White },
{ LogLevel.Warn, ConsoleColor.Yellow },
{ LogLevel.Error, ConsoleColor.Red },
{ LogLevel.Fatal, ConsoleColor.DarkRed },
};
#endif
/// <summary>
/// Initializes a new instance of the <see cref="InstallationContext"/> class.
/// </summary>
public InstallationContext()
: this(TextWriter.Null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="InstallationContext"/> class.
/// </summary>
/// <param name="logOutput">The log output.</param>
public InstallationContext(TextWriter logOutput)
{
LogOutput = logOutput;
Parameters = new Dictionary<string, string>();
LogLevel = LogLevel.Info;
ThrowExceptions = false;
}
/// <summary>
/// Gets or sets the installation log level.
/// </summary>
public LogLevel LogLevel { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to ignore failures during installation.
/// </summary>
public bool IgnoreFailures { get; set; }
/// <summary>
/// Whether installation exceptions should be rethrown. If IgnoreFailures is set to true,
/// this property has no effect (there are no exceptions to rethrow).
/// </summary>
public bool ThrowExceptions { get; set; }
/// <summary>
/// Gets the installation parameters.
/// </summary>
public IDictionary<string, string> Parameters { get; private set; }
/// <summary>
/// Gets or sets the log output.
/// </summary>
public TextWriter LogOutput { get; set; }
/// <summary>
/// Logs the specified trace message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Trace([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Trace, message, arguments);
}
/// <summary>
/// Logs the specified debug message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Debug([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Debug, message, arguments);
}
/// <summary>
/// Logs the specified informational message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Info([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Info, message, arguments);
}
/// <summary>
/// Logs the specified warning message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Warning([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Warn, message, arguments);
}
/// <summary>
/// Logs the specified error message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="arguments">The arguments.</param>
public void Error([Localizable(false)] string message, params object[] arguments)
{
Log(LogLevel.Error, message, arguments);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (LogOutput != null)
{
LogOutput.Close();
LogOutput = null;
}
}
/// <summary>
/// Creates the log event which can be used to render layouts during installation/uninstallations.
/// </summary>
/// <returns>Log event info object.</returns>
public LogEventInfo CreateLogEvent()
{
var eventInfo = LogEventInfo.CreateNullEvent();
// set properties on the event
foreach (var kvp in Parameters)
{
eventInfo.Properties.Add(kvp.Key, kvp.Value);
}
return eventInfo;
}
private void Log(LogLevel logLevel, [Localizable(false)] string message, object[] arguments)
{
if (logLevel >= LogLevel)
{
if (arguments != null && arguments.Length > 0)
{
message = string.Format(CultureInfo.InvariantCulture, message, arguments);
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = LogLevel2ConsoleColor[logLevel];
try
{
LogOutput.WriteLine(message);
}
finally
{
Console.ForegroundColor = oldColor;
}
#else
this.LogOutput.WriteLine(message);
#endif
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.