context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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 gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="ConversionValueRuleSetServiceClient"/> instances.</summary> public sealed partial class ConversionValueRuleSetServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ConversionValueRuleSetServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ConversionValueRuleSetServiceSettings"/>.</returns> public static ConversionValueRuleSetServiceSettings GetDefault() => new ConversionValueRuleSetServiceSettings(); /// <summary> /// Constructs a new <see cref="ConversionValueRuleSetServiceSettings"/> object with default settings. /// </summary> public ConversionValueRuleSetServiceSettings() { } private ConversionValueRuleSetServiceSettings(ConversionValueRuleSetServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetConversionValueRuleSetSettings = existing.GetConversionValueRuleSetSettings; MutateConversionValueRuleSetsSettings = existing.MutateConversionValueRuleSetsSettings; OnCopy(existing); } partial void OnCopy(ConversionValueRuleSetServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ConversionValueRuleSetServiceClient.GetConversionValueRuleSet</c> and /// <c>ConversionValueRuleSetServiceClient.GetConversionValueRuleSetAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetConversionValueRuleSetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ConversionValueRuleSetServiceClient.MutateConversionValueRuleSets</c> and /// <c>ConversionValueRuleSetServiceClient.MutateConversionValueRuleSetsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateConversionValueRuleSetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ConversionValueRuleSetServiceSettings"/> object.</returns> public ConversionValueRuleSetServiceSettings Clone() => new ConversionValueRuleSetServiceSettings(this); } /// <summary> /// Builder class for <see cref="ConversionValueRuleSetServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class ConversionValueRuleSetServiceClientBuilder : gaxgrpc::ClientBuilderBase<ConversionValueRuleSetServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ConversionValueRuleSetServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ConversionValueRuleSetServiceClientBuilder() { UseJwtAccessWithScopes = ConversionValueRuleSetServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ConversionValueRuleSetServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ConversionValueRuleSetServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ConversionValueRuleSetServiceClient Build() { ConversionValueRuleSetServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ConversionValueRuleSetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ConversionValueRuleSetServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ConversionValueRuleSetServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ConversionValueRuleSetServiceClient.Create(callInvoker, Settings); } private async stt::Task<ConversionValueRuleSetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ConversionValueRuleSetServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ConversionValueRuleSetServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ConversionValueRuleSetServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ConversionValueRuleSetServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ConversionValueRuleSetService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage conversion value rule sets. /// </remarks> public abstract partial class ConversionValueRuleSetServiceClient { /// <summary> /// The default endpoint for the ConversionValueRuleSetService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ConversionValueRuleSetService scopes.</summary> /// <remarks> /// The default ConversionValueRuleSetService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ConversionValueRuleSetServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ConversionValueRuleSetServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ConversionValueRuleSetServiceClient"/>.</returns> public static stt::Task<ConversionValueRuleSetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ConversionValueRuleSetServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ConversionValueRuleSetServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="ConversionValueRuleSetServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ConversionValueRuleSetServiceClient"/>.</returns> public static ConversionValueRuleSetServiceClient Create() => new ConversionValueRuleSetServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ConversionValueRuleSetServiceClient"/> 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="ConversionValueRuleSetServiceSettings"/>.</param> /// <returns>The created <see cref="ConversionValueRuleSetServiceClient"/>.</returns> internal static ConversionValueRuleSetServiceClient Create(grpccore::CallInvoker callInvoker, ConversionValueRuleSetServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ConversionValueRuleSetService.ConversionValueRuleSetServiceClient grpcClient = new ConversionValueRuleSetService.ConversionValueRuleSetServiceClient(callInvoker); return new ConversionValueRuleSetServiceClientImpl(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 ConversionValueRuleSetService client</summary> public virtual ConversionValueRuleSetService.ConversionValueRuleSetServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested conversion value rule set. /// </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 gagvr::ConversionValueRuleSet GetConversionValueRuleSet(GetConversionValueRuleSetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested conversion value rule set. /// </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<gagvr::ConversionValueRuleSet> GetConversionValueRuleSetAsync(GetConversionValueRuleSetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested conversion value rule set. /// </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<gagvr::ConversionValueRuleSet> GetConversionValueRuleSetAsync(GetConversionValueRuleSetRequest request, st::CancellationToken cancellationToken) => GetConversionValueRuleSetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested conversion value rule set. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule set to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ConversionValueRuleSet GetConversionValueRuleSet(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionValueRuleSet(new GetConversionValueRuleSetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion value rule set. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule set to fetch. /// </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<gagvr::ConversionValueRuleSet> GetConversionValueRuleSetAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionValueRuleSetAsync(new GetConversionValueRuleSetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion value rule set. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule set to fetch. /// </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<gagvr::ConversionValueRuleSet> GetConversionValueRuleSetAsync(string resourceName, st::CancellationToken cancellationToken) => GetConversionValueRuleSetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested conversion value rule set. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule set to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ConversionValueRuleSet GetConversionValueRuleSet(gagvr::ConversionValueRuleSetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionValueRuleSet(new GetConversionValueRuleSetRequest { ResourceNameAsConversionValueRuleSetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion value rule set. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule set to fetch. /// </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<gagvr::ConversionValueRuleSet> GetConversionValueRuleSetAsync(gagvr::ConversionValueRuleSetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetConversionValueRuleSetAsync(new GetConversionValueRuleSetRequest { ResourceNameAsConversionValueRuleSetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested conversion value rule set. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the conversion value rule set to fetch. /// </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<gagvr::ConversionValueRuleSet> GetConversionValueRuleSetAsync(gagvr::ConversionValueRuleSetName resourceName, st::CancellationToken cancellationToken) => GetConversionValueRuleSetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </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 MutateConversionValueRuleSetsResponse MutateConversionValueRuleSets(MutateConversionValueRuleSetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </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<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(MutateConversionValueRuleSetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </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<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(MutateConversionValueRuleSetsRequest request, st::CancellationToken cancellationToken) => MutateConversionValueRuleSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion value rule sets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion value rule sets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateConversionValueRuleSetsResponse MutateConversionValueRuleSets(string customerId, scg::IEnumerable<ConversionValueRuleSetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionValueRuleSets(new MutateConversionValueRuleSetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion value rule sets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion value rule sets. /// </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<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(string customerId, scg::IEnumerable<ConversionValueRuleSetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateConversionValueRuleSetsAsync(new MutateConversionValueRuleSetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose conversion value rule sets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual conversion value rule sets. /// </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<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(string customerId, scg::IEnumerable<ConversionValueRuleSetOperation> operations, st::CancellationToken cancellationToken) => MutateConversionValueRuleSetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ConversionValueRuleSetService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage conversion value rule sets. /// </remarks> public sealed partial class ConversionValueRuleSetServiceClientImpl : ConversionValueRuleSetServiceClient { private readonly gaxgrpc::ApiCall<GetConversionValueRuleSetRequest, gagvr::ConversionValueRuleSet> _callGetConversionValueRuleSet; private readonly gaxgrpc::ApiCall<MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse> _callMutateConversionValueRuleSets; /// <summary> /// Constructs a client wrapper for the ConversionValueRuleSetService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ConversionValueRuleSetServiceSettings"/> used within this client. /// </param> public ConversionValueRuleSetServiceClientImpl(ConversionValueRuleSetService.ConversionValueRuleSetServiceClient grpcClient, ConversionValueRuleSetServiceSettings settings) { GrpcClient = grpcClient; ConversionValueRuleSetServiceSettings effectiveSettings = settings ?? ConversionValueRuleSetServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetConversionValueRuleSet = clientHelper.BuildApiCall<GetConversionValueRuleSetRequest, gagvr::ConversionValueRuleSet>(grpcClient.GetConversionValueRuleSetAsync, grpcClient.GetConversionValueRuleSet, effectiveSettings.GetConversionValueRuleSetSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetConversionValueRuleSet); Modify_GetConversionValueRuleSetApiCall(ref _callGetConversionValueRuleSet); _callMutateConversionValueRuleSets = clientHelper.BuildApiCall<MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse>(grpcClient.MutateConversionValueRuleSetsAsync, grpcClient.MutateConversionValueRuleSets, effectiveSettings.MutateConversionValueRuleSetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateConversionValueRuleSets); Modify_MutateConversionValueRuleSetsApiCall(ref _callMutateConversionValueRuleSets); 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_GetConversionValueRuleSetApiCall(ref gaxgrpc::ApiCall<GetConversionValueRuleSetRequest, gagvr::ConversionValueRuleSet> call); partial void Modify_MutateConversionValueRuleSetsApiCall(ref gaxgrpc::ApiCall<MutateConversionValueRuleSetsRequest, MutateConversionValueRuleSetsResponse> call); partial void OnConstruction(ConversionValueRuleSetService.ConversionValueRuleSetServiceClient grpcClient, ConversionValueRuleSetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ConversionValueRuleSetService client</summary> public override ConversionValueRuleSetService.ConversionValueRuleSetServiceClient GrpcClient { get; } partial void Modify_GetConversionValueRuleSetRequest(ref GetConversionValueRuleSetRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateConversionValueRuleSetsRequest(ref MutateConversionValueRuleSetsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested conversion value rule set. /// </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 gagvr::ConversionValueRuleSet GetConversionValueRuleSet(GetConversionValueRuleSetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetConversionValueRuleSetRequest(ref request, ref callSettings); return _callGetConversionValueRuleSet.Sync(request, callSettings); } /// <summary> /// Returns the requested conversion value rule set. /// </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<gagvr::ConversionValueRuleSet> GetConversionValueRuleSetAsync(GetConversionValueRuleSetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetConversionValueRuleSetRequest(ref request, ref callSettings); return _callGetConversionValueRuleSet.Async(request, callSettings); } /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </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 MutateConversionValueRuleSetsResponse MutateConversionValueRuleSets(MutateConversionValueRuleSetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionValueRuleSetsRequest(ref request, ref callSettings); return _callMutateConversionValueRuleSets.Sync(request, callSettings); } /// <summary> /// Creates, updates or removes conversion value rule sets. Operation statuses /// are returned. /// </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<MutateConversionValueRuleSetsResponse> MutateConversionValueRuleSetsAsync(MutateConversionValueRuleSetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateConversionValueRuleSetsRequest(ref request, ref callSettings); return _callMutateConversionValueRuleSets.Async(request, callSettings); } } }
using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Documents; using Lucene.Net.Support; using Lucene.Net.Support.Threading; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using Document = Documents.Document; using Field = Field; using IBits = Lucene.Net.Util.IBits; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using PayloadAttribute = Lucene.Net.Analysis.TokenAttributes.PayloadAttribute; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; [TestFixture] public class TestPayloads : LuceneTestCase { // Simple tests to test the payloads [Test] public virtual void TestPayload() { BytesRef payload = new BytesRef("this is a test!"); Assert.AreEqual(payload.Length, "this is a test!".Length, "Wrong payload length."); BytesRef clone = (BytesRef)payload.Clone(); Assert.AreEqual(payload.Length, clone.Length); for (int i = 0; i < payload.Length; i++) { Assert.AreEqual(payload.Bytes[i + payload.Offset], clone.Bytes[i + clone.Offset]); } } // Tests whether the DocumentWriter and SegmentMerger correctly enable the // payload bit in the FieldInfo [Test] public virtual void TestPayloadFieldBit() { Directory ram = NewDirectory(); PayloadAnalyzer analyzer = new PayloadAnalyzer(); IndexWriter writer = new IndexWriter(ram, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer)); Document d = new Document(); // this field won't have any payloads d.Add(NewTextField("f1", "this field has no payloads", Field.Store.NO)); // this field will have payloads in all docs, however not for all term positions, // so this field is used to check if the DocumentWriter correctly enables the payloads bit // even if only some term positions have payloads d.Add(NewTextField("f2", "this field has payloads in all docs", Field.Store.NO)); d.Add(NewTextField("f2", "this field has payloads in all docs NO PAYLOAD", Field.Store.NO)); // this field is used to verify if the SegmentMerger enables payloads for a field if it has payloads // enabled in only some documents d.Add(NewTextField("f3", "this field has payloads in some docs", Field.Store.NO)); // only add payload data for field f2 #pragma warning disable 612, 618 analyzer.SetPayloadData("f2", "somedata".GetBytes(IOUtils.CHARSET_UTF_8), 0, 1); #pragma warning restore 612, 618 writer.AddDocument(d); // flush writer.Dispose(); SegmentReader reader = GetOnlySegmentReader(DirectoryReader.Open(ram)); FieldInfos fi = reader.FieldInfos; Assert.IsFalse(fi.FieldInfo("f1").HasPayloads, "Payload field bit should not be set."); Assert.IsTrue(fi.FieldInfo("f2").HasPayloads, "Payload field bit should be set."); Assert.IsFalse(fi.FieldInfo("f3").HasPayloads, "Payload field bit should not be set."); reader.Dispose(); // now we add another document which has payloads for field f3 and verify if the SegmentMerger // enabled payloads for that field analyzer = new PayloadAnalyzer(); // Clear payload state for each field writer = new IndexWriter(ram, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetOpenMode(OpenMode.CREATE)); d = new Document(); d.Add(NewTextField("f1", "this field has no payloads", Field.Store.NO)); d.Add(NewTextField("f2", "this field has payloads in all docs", Field.Store.NO)); d.Add(NewTextField("f2", "this field has payloads in all docs", Field.Store.NO)); d.Add(NewTextField("f3", "this field has payloads in some docs", Field.Store.NO)); // add payload data for field f2 and f3 #pragma warning disable 612, 618 analyzer.SetPayloadData("f2", "somedata".GetBytes(IOUtils.CHARSET_UTF_8), 0, 1); analyzer.SetPayloadData("f3", "somedata".GetBytes(IOUtils.CHARSET_UTF_8), 0, 3); #pragma warning restore 612, 618 writer.AddDocument(d); // force merge writer.ForceMerge(1); // flush writer.Dispose(); reader = GetOnlySegmentReader(DirectoryReader.Open(ram)); fi = reader.FieldInfos; Assert.IsFalse(fi.FieldInfo("f1").HasPayloads, "Payload field bit should not be set."); Assert.IsTrue(fi.FieldInfo("f2").HasPayloads, "Payload field bit should be set."); Assert.IsTrue(fi.FieldInfo("f3").HasPayloads, "Payload field bit should be set."); reader.Dispose(); ram.Dispose(); } // Tests if payloads are correctly stored and loaded using both RamDirectory and FSDirectory [Test] public virtual void TestPayloadsEncoding() { Directory dir = NewDirectory(); PerformTest(dir); dir.Dispose(); } // builds an index with payloads in the given Directory and performs // different tests to verify the payload encoding private void PerformTest(Directory dir) { PayloadAnalyzer analyzer = new PayloadAnalyzer(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetOpenMode(OpenMode.CREATE).SetMergePolicy(NewLogMergePolicy())); // should be in sync with value in TermInfosWriter const int skipInterval = 16; const int numTerms = 5; const string fieldName = "f1"; int numDocs = skipInterval + 1; // create content for the test documents with just a few terms Term[] terms = GenerateTerms(fieldName, numTerms); StringBuilder sb = new StringBuilder(); for (int i = 0; i < terms.Length; i++) { sb.Append(terms[i].Text()); sb.Append(" "); } string content = sb.ToString(); int payloadDataLength = numTerms * numDocs * 2 + numTerms * numDocs * (numDocs - 1) / 2; var payloadData = GenerateRandomData(payloadDataLength); Document d = new Document(); d.Add(NewTextField(fieldName, content, Field.Store.NO)); // add the same document multiple times to have the same payload lengths for all // occurrences within two consecutive skip intervals int offset = 0; for (int i = 0; i < 2 * numDocs; i++) { analyzer = new PayloadAnalyzer(fieldName, payloadData, offset, 1); offset += numTerms; writer.AddDocument(d, analyzer); } // make sure we create more than one segment to test merging writer.Commit(); // now we make sure to have different payload lengths next at the next skip point for (int i = 0; i < numDocs; i++) { analyzer = new PayloadAnalyzer(fieldName, payloadData, offset, i); offset += i * numTerms; writer.AddDocument(d, analyzer); } writer.ForceMerge(1); // flush writer.Dispose(); /* * Verify the index * first we test if all payloads are stored correctly */ IndexReader reader = DirectoryReader.Open(dir); var verifyPayloadData = new byte[payloadDataLength]; offset = 0; var tps = new DocsAndPositionsEnum[numTerms]; for (int i = 0; i < numTerms; i++) { tps[i] = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), terms[i].Field, new BytesRef(terms[i].Text())); } while (tps[0].NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { for (int i = 1; i < numTerms; i++) { tps[i].NextDoc(); } int freq = tps[0].Freq; for (int i = 0; i < freq; i++) { for (int j = 0; j < numTerms; j++) { tps[j].NextPosition(); BytesRef br = tps[j].GetPayload(); if (br != null) { Array.Copy(br.Bytes, br.Offset, verifyPayloadData, offset, br.Length); offset += br.Length; } } } } AssertByteArrayEquals(payloadData, verifyPayloadData); /* * test lazy skipping */ DocsAndPositionsEnum tp = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), terms[0].Field, new BytesRef(terms[0].Text())); tp.NextDoc(); tp.NextPosition(); // NOTE: prior rev of this test was failing to first // call next here: tp.NextDoc(); // now we don't read this payload tp.NextPosition(); BytesRef payload = tp.GetPayload(); Assert.AreEqual(1, payload.Length, "Wrong payload length."); Assert.AreEqual(payload.Bytes[payload.Offset], payloadData[numTerms]); tp.NextDoc(); tp.NextPosition(); // we don't read this payload and skip to a different document tp.Advance(5); tp.NextPosition(); payload = tp.GetPayload(); Assert.AreEqual(1, payload.Length, "Wrong payload length."); Assert.AreEqual(payload.Bytes[payload.Offset], payloadData[5 * numTerms]); /* * Test different lengths at skip points */ tp = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), terms[1].Field, new BytesRef(terms[1].Text())); tp.NextDoc(); tp.NextPosition(); Assert.AreEqual(1, tp.GetPayload().Length, "Wrong payload length."); tp.Advance(skipInterval - 1); tp.NextPosition(); Assert.AreEqual(1, tp.GetPayload().Length, "Wrong payload length."); tp.Advance(2 * skipInterval - 1); tp.NextPosition(); Assert.AreEqual(1, tp.GetPayload().Length, "Wrong payload length."); tp.Advance(3 * skipInterval - 1); tp.NextPosition(); Assert.AreEqual(3 * skipInterval - 2 * numDocs - 1, tp.GetPayload().Length, "Wrong payload length."); reader.Dispose(); // test long payload analyzer = new PayloadAnalyzer(); writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetOpenMode(OpenMode.CREATE)); string singleTerm = "lucene"; d = new Document(); d.Add(NewTextField(fieldName, singleTerm, Field.Store.NO)); // add a payload whose length is greater than the buffer size of BufferedIndexOutput payloadData = GenerateRandomData(2000); analyzer.SetPayloadData(fieldName, payloadData, 100, 1500); writer.AddDocument(d); writer.ForceMerge(1); // flush writer.Dispose(); reader = DirectoryReader.Open(dir); tp = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), fieldName, new BytesRef(singleTerm)); tp.NextDoc(); tp.NextPosition(); BytesRef bref = tp.GetPayload(); verifyPayloadData = new byte[bref.Length]; var portion = new byte[1500]; Array.Copy(payloadData, 100, portion, 0, 1500); AssertByteArrayEquals(portion, bref.Bytes, bref.Offset, bref.Length); reader.Dispose(); } #pragma warning disable 612, 618 internal static readonly Encoding Utf8 = IOUtils.CHARSET_UTF_8; #pragma warning restore 612, 618 private void GenerateRandomData(byte[] data) { // this test needs the random data to be valid unicode string s = TestUtil.RandomFixedByteLengthUnicodeString(Random(), data.Length); var b = s.GetBytes(Utf8); Debug.Assert(b.Length == data.Length); System.Buffer.BlockCopy(b, 0, data, 0, b.Length); } private byte[] GenerateRandomData(int n) { var data = new byte[n]; GenerateRandomData(data); return data; } private Term[] GenerateTerms(string fieldName, int n) { int maxDigits = (int)(Math.Log(n) / Math.Log(10)); Term[] terms = new Term[n]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.Length = 0; sb.Append("t"); int zeros = maxDigits - (int)(Math.Log(i) / Math.Log(10)); for (int j = 0; j < zeros; j++) { sb.Append("0"); } sb.Append(i); terms[i] = new Term(fieldName, sb.ToString()); } return terms; } internal virtual void AssertByteArrayEquals(byte[] b1, byte[] b2) { if (b1.Length != b2.Length) { Assert.Fail("Byte arrays have different lengths: " + b1.Length + ", " + b2.Length); } for (int i = 0; i < b1.Length; i++) { if (b1[i] != b2[i]) { Assert.Fail("Byte arrays different at index " + i + ": " + b1[i] + ", " + b2[i]); } } } internal virtual void AssertByteArrayEquals(byte[] b1, byte[] b2, int b2offset, int b2length) { if (b1.Length != b2length) { Assert.Fail("Byte arrays have different lengths: " + b1.Length + ", " + b2length); } for (int i = 0; i < b1.Length; i++) { if (b1[i] != b2[b2offset + i]) { Assert.Fail("Byte arrays different at index " + i + ": " + b1[i] + ", " + b2[b2offset + i]); } } } /// <summary> /// this Analyzer uses an WhitespaceTokenizer and PayloadFilter. /// </summary> private class PayloadAnalyzer : Analyzer { internal readonly IDictionary<string, PayloadData> FieldToData = new Dictionary<string, PayloadData>(); public PayloadAnalyzer() : base(PER_FIELD_REUSE_STRATEGY) { } public PayloadAnalyzer(string field, byte[] data, int offset, int length) : base(PER_FIELD_REUSE_STRATEGY) { SetPayloadData(field, data, offset, length); } internal virtual void SetPayloadData(string field, byte[] data, int offset, int length) { FieldToData[field] = new PayloadData(data, offset, length); } protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { PayloadData payload; FieldToData.TryGetValue(fieldName, out payload); Tokenizer ts = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); TokenStream tokenStream = (payload != null) ? (TokenStream)new PayloadFilter(ts, payload.Data, payload.Offset, payload.Length) : ts; return new TokenStreamComponents(ts, tokenStream); } internal class PayloadData { internal byte[] Data; internal int Offset; internal int Length; internal PayloadData(byte[] data, int offset, int length) { this.Data = data; this.Offset = offset; this.Length = length; } } } /// <summary> /// this Filter adds payloads to the tokens. /// </summary> private class PayloadFilter : TokenFilter { internal byte[] Data; internal int Length; internal int Offset; internal int StartOffset; internal IPayloadAttribute PayloadAtt; internal ICharTermAttribute TermAttribute; public PayloadFilter(TokenStream @in, byte[] data, int offset, int length) : base(@in) { this.Data = data; this.Length = length; this.Offset = offset; this.StartOffset = offset; PayloadAtt = AddAttribute<IPayloadAttribute>(); TermAttribute = AddAttribute<ICharTermAttribute>(); } public sealed override bool IncrementToken() { bool hasNext = m_input.IncrementToken(); if (!hasNext) { return false; } // Some values of the same field are to have payloads and others not if (Offset + Length <= Data.Length && !TermAttribute.ToString().EndsWith("NO PAYLOAD", StringComparison.Ordinal)) { BytesRef p = new BytesRef(Data, Offset, Length); PayloadAtt.Payload = p; Offset += Length; } else { PayloadAtt.Payload = null; } return true; } public override void Reset() { base.Reset(); this.Offset = StartOffset; } } [Test] public virtual void TestThreadSafety() { const int numThreads = 5; int numDocs = AtLeast(50); ByteArrayPool pool = new ByteArrayPool(numThreads, 5); Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); const string field = "test"; ThreadClass[] ingesters = new ThreadClass[numThreads]; for (int i = 0; i < numThreads; i++) { ingesters[i] = new ThreadAnonymousInnerClassHelper(this, numDocs, pool, writer, field); ingesters[i].Start(); } for (int i = 0; i < numThreads; i++) { ingesters[i].Join(); } writer.Dispose(); IndexReader reader = DirectoryReader.Open(dir); TermsEnum terms = MultiFields.GetFields(reader).GetTerms(field).GetIterator(null); IBits liveDocs = MultiFields.GetLiveDocs(reader); DocsAndPositionsEnum tp = null; while (terms.Next() != null) { string termText = terms.Term.Utf8ToString(); tp = terms.DocsAndPositions(liveDocs, tp); while (tp.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { int freq = tp.Freq; for (int i = 0; i < freq; i++) { tp.NextPosition(); BytesRef payload = tp.GetPayload(); Assert.AreEqual(termText, payload.Utf8ToString()); } } } reader.Dispose(); dir.Dispose(); Assert.AreEqual(pool.Count, numThreads); } private class ThreadAnonymousInnerClassHelper : ThreadClass { private readonly TestPayloads OuterInstance; private int NumDocs; private Lucene.Net.Index.TestPayloads.ByteArrayPool Pool; private IndexWriter Writer; private string Field; public ThreadAnonymousInnerClassHelper(TestPayloads outerInstance, int numDocs, Lucene.Net.Index.TestPayloads.ByteArrayPool pool, IndexWriter writer, string field) { this.OuterInstance = outerInstance; this.NumDocs = numDocs; this.Pool = pool; this.Writer = writer; this.Field = field; } public override void Run() { try { for (int j = 0; j < NumDocs; j++) { Document d = new Document(); d.Add(new TextField(Field, new PoolingPayloadTokenStream(OuterInstance, Pool))); Writer.AddDocument(d); } } catch (Exception e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); Assert.Fail(e.ToString()); } } } private class PoolingPayloadTokenStream : TokenStream { private readonly TestPayloads OuterInstance; private byte[] Payload; internal bool First; internal ByteArrayPool Pool; internal string Term; internal ICharTermAttribute TermAtt; internal IPayloadAttribute PayloadAtt; internal PoolingPayloadTokenStream(TestPayloads outerInstance, ByteArrayPool pool) { this.OuterInstance = outerInstance; this.Pool = pool; Payload = pool.Get(); OuterInstance.GenerateRandomData(Payload); Term = Encoding.UTF8.GetString(Payload); First = true; PayloadAtt = AddAttribute<IPayloadAttribute>(); TermAtt = AddAttribute<ICharTermAttribute>(); } public sealed override bool IncrementToken() { if (!First) { return false; } First = false; ClearAttributes(); TermAtt.Append(Term); PayloadAtt.Payload = new BytesRef(Payload); return true; } protected override void Dispose(bool disposing) { if (disposing) { Pool.Release(Payload); } } } private class ByteArrayPool { internal readonly IList<byte[]> Pool; internal ByteArrayPool(int capacity, int size) { Pool = new List<byte[]>(); for (int i = 0; i < capacity; i++) { Pool.Add(new byte[size]); } } internal virtual byte[] Get() { lock (this) // TODO use BlockingCollection / BCL datastructures instead { var retArray = Pool[0]; Pool.RemoveAt(0); return retArray; } } internal virtual void Release(byte[] b) { lock (this) { Pool.Add(b); } } internal virtual int Count { get { lock (this) { return Pool.Count; } } } } [Test] public virtual void TestAcrossFields() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, true), Similarity, TimeZone); Document doc = new Document(); doc.Add(new TextField("hasMaybepayload", "here we go", Field.Store.YES)); writer.AddDocument(doc); writer.Dispose(); writer = new RandomIndexWriter(Random(), dir, new MockAnalyzer(Random(), MockTokenizer.WHITESPACE, true), Similarity, TimeZone); doc = new Document(); doc.Add(new TextField("hasMaybepayload2", "here we go", Field.Store.YES)); writer.AddDocument(doc); writer.AddDocument(doc); writer.ForceMerge(1); writer.Dispose(); dir.Dispose(); } /// <summary> /// some docs have payload att, some not </summary> [Test] public virtual void TestMixupDocs() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, null); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, iwc); Document doc = new Document(); Field field = new TextField("field", "", Field.Store.NO); TokenStream ts = new MockTokenizer(new StringReader("here we go"), MockTokenizer.WHITESPACE, true); Assert.IsFalse(ts.HasAttribute<PayloadAttribute>()); field.SetTokenStream(ts); doc.Add(field); writer.AddDocument(doc); Token withPayload = new Token("withPayload", 0, 11); withPayload.Payload = new BytesRef("test"); ts = new CannedTokenStream(withPayload); Assert.IsTrue(ts.HasAttribute<IPayloadAttribute>()); field.SetTokenStream(ts); writer.AddDocument(doc); ts = new MockTokenizer(new StringReader("another"), MockTokenizer.WHITESPACE, true); Assert.IsFalse(ts.HasAttribute<PayloadAttribute>()); field.SetTokenStream(ts); writer.AddDocument(doc); DirectoryReader reader = writer.Reader; AtomicReader sr = SlowCompositeReaderWrapper.Wrap(reader); DocsAndPositionsEnum de = sr.GetTermPositionsEnum(new Term("field", "withPayload")); de.NextDoc(); de.NextPosition(); Assert.AreEqual(new BytesRef("test"), de.GetPayload()); writer.Dispose(); reader.Dispose(); dir.Dispose(); } /// <summary> /// some field instances have payload att, some not </summary> [Test] public virtual void TestMixupMultiValued() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, Similarity, TimeZone); Document doc = new Document(); Field field = new TextField("field", "", Field.Store.NO); TokenStream ts = new MockTokenizer(new StringReader("here we go"), MockTokenizer.WHITESPACE, true); Assert.IsFalse(ts.HasAttribute<PayloadAttribute>()); field.SetTokenStream(ts); doc.Add(field); Field field2 = new TextField("field", "", Field.Store.NO); Token withPayload = new Token("withPayload", 0, 11); withPayload.Payload = new BytesRef("test"); ts = new CannedTokenStream(withPayload); Assert.IsTrue(ts.HasAttribute<IPayloadAttribute>()); field2.SetTokenStream(ts); doc.Add(field2); Field field3 = new TextField("field", "", Field.Store.NO); ts = new MockTokenizer(new StringReader("nopayload"), MockTokenizer.WHITESPACE, true); Assert.IsFalse(ts.HasAttribute<PayloadAttribute>()); field3.SetTokenStream(ts); doc.Add(field3); writer.AddDocument(doc); DirectoryReader reader = writer.Reader; SegmentReader sr = GetOnlySegmentReader(reader); DocsAndPositionsEnum de = sr.GetTermPositionsEnum(new Term("field", "withPayload")); de.NextDoc(); de.NextPosition(); Assert.AreEqual(new BytesRef("test"), de.GetPayload()); writer.Dispose(); reader.Dispose(); dir.Dispose(); } } }
/* ==================================================================== */ using System; using Oranikle.Report.Engine; using System.IO; using System.Collections; using System.Text; namespace Oranikle.Report.Engine { ///<summary> ///The primary class to "run" a report to XML ///</summary> public class RenderXml: IPresent { Report r; // report TextWriter tw; // where the output is going Stack stkReportItem; // stack of nested report items Stack stkContainers; // stack to hold container elements string rowstart=null; public RenderXml(Report rep, IStreamGen sg) { r = rep; tw = sg.GetTextWriter(); stkReportItem = new Stack(); stkContainers = new Stack(); } public Report Report() { return r; } public bool IsPagingNeeded() { return false; } public void Start() { tw.WriteLine("<?xml version='1.0' encoding='UTF-8'?>"); PushContainer(r.ReportDefinition.DataElementName); return; } public void End() { ContainerIO cio = (ContainerIO) stkContainers.Pop(); // this pop should empty the stack cio.WriteAttribute(">"); tw.WriteLine(cio.attribute_sb); tw.WriteLine(cio.subelement_sb); tw.WriteLine("</" + r.ReportDefinition.DataElementName + ">"); return; } // Body: main container for the report public void BodyStart(Body b) { } public void BodyEnd(Body b) { } public void PageHeaderStart(PageHeader ph) { } public void PageHeaderEnd(PageHeader ph) { } public void PageFooterStart(PageFooter pf) { } public void PageFooterEnd(PageFooter pf) { } public void Textbox(Textbox tb, string t, Row row) { if (tb.DataElementOutput != DataElementOutputEnum.Output || tb.DataElementName == null) return; if (rowstart != null) // In case no items in row are visible { // we delay until we get one. // WriteElement(rowstart); rowstart = null; } t = XmlUtil.XmlAnsi(t); if (tb.DataElementStyle == DataElementStyleEnum.AttributeNormal) { // write out as attribute WriteAttribute(" {0}='{1}'", tb.DataElementName, XmlUtil.EscapeXmlAttribute(t)); } else { // write out as element WriteElement("<{0}>{1}</{0}>", tb.DataElementName, t); } } public void DataRegionNoRows(DataRegion t, string noRowMsg) { } // Lists public bool ListStart(List l, Row r) { if (l.DataElementOutput == DataElementOutputEnum.NoOutput) return false; if (l.DataElementOutput == DataElementOutputEnum.ContentsOnly) return true; WriteElementLine("<{0}>", l.DataElementName); return true; //want to continue } public void ListEnd(List l, Row r) { if (l.DataElementOutput == DataElementOutputEnum.NoOutput || l.DataElementOutput == DataElementOutputEnum.ContentsOnly) return; WriteElementLine("</{0}>", l.DataElementName); return; } public void ListEntryBegin(List l, Row r) { string d; if (l.Grouping == null) { if (l.DataElementOutput != DataElementOutputEnum.Output) return; d = string.Format("<{0}", l.DataInstanceName); } else { Grouping g = l.Grouping; if (g.DataElementOutput != DataElementOutputEnum.Output) return; d = string.Format("<{0}", l.DataInstanceName); } PushContainer(l.DataInstanceName); return; } public void ListEntryEnd(List l, Row r) { if (l.DataElementOutput != DataElementOutputEnum.Output) return; PopContainer(l.DataInstanceName); } // Tables // Report item table public bool TableStart(Table t, Row row) { if (t.DataElementOutput == DataElementOutputEnum.NoOutput) return false; PushContainer(t.DataElementName); stkReportItem.Push(t); string cName = TableGetCollectionName(t); if (cName != null) WriteAttributeLine("><{0}", cName); return true; } public void TableEnd(Table t, Row row) { if (t.DataElementOutput == DataElementOutputEnum.NoOutput) return; string cName = TableGetCollectionName(t); PopContainer(cName); WriteElementLine("</{0}>", t.DataElementName); stkReportItem.Pop(); return; } string TableGetCollectionName(Table t) { string cName; if (t.TableGroups == null) { if (t.Details != null && t.Details.Grouping != null) cName = t.Details.Grouping.DataCollectionName; else cName = t.DetailDataCollectionName; } else cName = null; return cName; } public void TableBodyStart(Table t, Row row) { } public void TableBodyEnd(Table t, Row row) { } public void TableFooterStart(Footer f, Row row) { } public void TableFooterEnd(Footer f, Row row) { } public void TableHeaderStart(Header h, Row row) { } public void TableHeaderEnd(Header h, Row row) { } public void TableRowStart(TableRow tr, Row row) { string n = TableGetRowElementName(tr); if (n == null) return; PushContainer(n); } public void TableRowEnd(TableRow tr, Row row) { string n = TableGetRowElementName(tr); if (n == null) return; this.PopContainer(n); } string TableGetRowElementName(TableRow tr) { for (ReportLink rl = tr.Parent; !(rl is Table); rl = rl.Parent) { if (rl is Header || rl is Footer) return null; if (rl is TableGroup) { TableGroup tg = rl as TableGroup; Grouping g = tg.Grouping; return g.DataElementName; } if (rl is Details) { Table t = (Table) stkReportItem.Peek(); return t.DetailDataElementOutput == DataElementOutputEnum.NoOutput? null: t.DetailDataElementName; } } return null; } public void TableCellStart(TableCell t, Row row) { return; } public void TableCellEnd(TableCell t, Row row) { return; } public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first { if (m.DataElementOutput != DataElementOutputEnum.Output) return false; tw.WriteLine("<" + (m.DataElementName == null? "Matrix": m.DataElementName) + ">"); return true; } public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart { } public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan) { } public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r) { } public void MatrixRowStart(Matrix m, int row, Row r) { } public void MatrixRowEnd(Matrix m, int row, Row r) { } public void MatrixEnd(Matrix m, Row r) // called last { tw.WriteLine("</" + (m.DataElementName == null? "Matrix": m.DataElementName) + ">"); } public void Chart(Chart c, Row r, ChartBase cb) { } public void Image(Image i, Row r, string mimeType, Stream io) { } public void Line(Line l, Row r) { } public bool RectangleStart(Oranikle.Report.Engine.Rectangle rect, Row r) { bool rc=true; switch (rect.DataElementOutput) { case DataElementOutputEnum.NoOutput: rc = false; break; case DataElementOutputEnum.Output: if (rowstart != null) // In case no items in row are visible { // we delay until we get one. tw.Write(rowstart); rowstart = null; } PushContainer(rect.DataElementName); break; case DataElementOutputEnum.Auto: case DataElementOutputEnum.ContentsOnly: default: break; } return rc; } public void RectangleEnd(Oranikle.Report.Engine.Rectangle rect, Row r) { if (rect.DataElementOutput != DataElementOutputEnum.Output) return; PopContainer(rect.DataElementName); } public void Subreport(Subreport s, Row r) { if (s.DataElementOutput != DataElementOutputEnum.Output) return; PushContainer(s.DataElementName); s.ReportDefn.Run(this); PopContainer(s.DataElementName); return; } public void GroupingStart(Grouping g) // called at start of grouping { if (g.DataElementOutput != DataElementOutputEnum.Output) return; PushContainer(g.DataCollectionName); } public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance { if (g.DataElementOutput != DataElementOutputEnum.Output) return; PushContainer(g.DataElementName); } public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance { if (g.DataElementOutput != DataElementOutputEnum.Output) return; PopContainer(g.DataElementName); } public void GroupingEnd(Grouping g) // called at end of grouping { if (g.DataElementOutput != DataElementOutputEnum.Output) return; PopContainer(g.DataCollectionName); } public void RunPages(Pages pgs) // we don't have paging turned on for xml { return; } void PopContainer(string name) { ContainerIO cio = (ContainerIO) this.stkContainers.Pop(); if (cio.bEmpty) return; cio.WriteAttribute(">"); WriteElementLine(cio.attribute_sb.ToString()); WriteElementLine(cio.subelement_sb.ToString()); if (name != null) WriteElementLine("</{0}>", name); } void PushContainer(string name) { ContainerIO cio = new ContainerIO("<" + name); stkContainers.Push(cio); } void WriteElement(string format) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteElement(format); } void WriteElement(string format, params object[] arg) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteElement(format, arg); } void WriteElementLine(string format) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteElementLine(format); } void WriteElementLine(string format, params object[] arg) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteElementLine(format, arg); } void WriteAttribute(string format) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteAttribute(format); } void WriteAttribute(string format, params object[] arg) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteAttribute(format, arg); } void WriteAttributeLine(string format) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteAttributeLine(format); } void WriteAttributeLine(string format, params object[] arg) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteAttributeLine(format, arg); } class ContainerIO { public StringBuilder attribute_sb; public StringWriter attribute_sw; public StringBuilder subelement_sb; public StringWriter subelement_sw; public bool bEmpty=true; public ContainerIO(string begin) { subelement_sb = new StringBuilder(); subelement_sw = new StringWriter(subelement_sb); attribute_sb = new StringBuilder(begin); attribute_sw = new StringWriter(attribute_sb); } public void WriteElement(string format) { bEmpty = false; subelement_sw.Write(format); } public void WriteElement(string format, params object[] arg) { bEmpty = false; subelement_sw.Write(format, arg); } public void WriteElementLine(string format) { bEmpty = false; subelement_sw.WriteLine(format); } public void WriteElementLine(string format, params object[] arg) { bEmpty = false; subelement_sw.WriteLine(format, arg); } public void WriteAttribute(string format) { bEmpty = false; attribute_sw.Write(format); } public void WriteAttribute(string format, params object[] arg) { bEmpty = false; attribute_sw.Write(format, arg); } public void WriteAttributeLine(string format) { bEmpty = false; attribute_sw.WriteLine(format); } public void WriteAttributeLine(string format, params object[] arg) { bEmpty = false; attribute_sw.WriteLine(format, arg); } } } }
#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; using System.Abstract; using System.Linq; using System.Reflection; using Contoso.Abstract.NServiceBus; using NServiceBus; using NServiceBus.Unicast.Transport; namespace Contoso.Abstract { /// <summary> /// INServiceBus /// </summary> public interface INServiceBus : IPublishingServiceBus { //int SendWithReturn(int executeTimeout, IServiceBusEndpoint endpoint, params object[] messages); /// <summary> /// Returns the specified value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> void Return<T>(T value); /// <summary> /// Gets the bus. /// </summary> IBus Bus { get; } } /// <summary> /// NServiceBusAbstractor /// </summary> public class NServiceBusAbstractor : INServiceBus, ServiceBusManager.ISetupRegistration { private IServiceLocator _serviceLocator; static NServiceBusAbstractor() { ServiceBusManager.EnsureRegistration(); } /// <summary> /// Initializes a new instance of the <see cref="NServiceBusAbstractor"/> class. /// </summary> /// <param name="assemblies">The assemblies.</param> public NServiceBusAbstractor(params Assembly[] assemblies) : this(ServiceLocatorManager.Current, DefaultBusCreator(null, assemblies)) { } /// <summary> /// Initializes a new instance of the <see cref="NServiceBusAbstractor"/> class. /// </summary> /// <param name="serviceLocator">The service locator.</param> /// <param name="assemblies">The assemblies.</param> public NServiceBusAbstractor(IServiceLocator serviceLocator, params Assembly[] assemblies) : this(serviceLocator, DefaultBusCreator(serviceLocator, assemblies)) { } /// <summary> /// Initializes a new instance of the <see cref="NServiceBusAbstractor"/> class. /// </summary> /// <param name="serviceLocator">The service locator.</param> /// <param name="startableBus">The startable bus.</param> public NServiceBusAbstractor(IServiceLocator serviceLocator, IStartableBus startableBus) { if (serviceLocator == null) throw new ArgumentNullException("serviceLocator"); if (startableBus == null) throw new ArgumentNullException("startableBus", "The specified NServiceBus bus cannot be null."); _serviceLocator = serviceLocator; Bus = startableBus.Start(); } /// <summary> /// Initializes a new instance of the <see cref="NServiceBusAbstractor"/> class. /// </summary> /// <param name="serviceLocator">The service locator.</param> /// <param name="bus">The bus.</param> public NServiceBusAbstractor(IServiceLocator serviceLocator, IBus bus) { if (serviceLocator == null) throw new ArgumentNullException("serviceLocator"); if (bus == null) throw new ArgumentNullException("bus", "The specified NServiceBus bus cannot be null."); _serviceLocator = serviceLocator; Bus = bus; } Action<IServiceLocator, string> ServiceBusManager.ISetupRegistration.DefaultServiceRegistrar { get { return (locator, name) => ServiceBusManager.RegisterInstance<INServiceBus>(this, locator, name); } } /// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType">An object that specifies the type of service object to get.</param> /// <returns> /// A service object of type <paramref name="serviceType"/>.-or- null if there is no service object of type <paramref name="serviceType"/>. /// </returns> public object GetService(Type serviceType) { throw new NotImplementedException(); } /// <summary> /// Creates the message. /// </summary> /// <typeparam name="TMessage">The type of the message.</typeparam> /// <param name="messageBuilder">The message builder.</param> /// <returns></returns> public TMessage CreateMessage<TMessage>(Action<TMessage> messageBuilder) where TMessage : class { var message = (TMessage)Bus.CreateInstance(typeof(TMessage)); if (messageBuilder != null) messageBuilder(message); return message; } /// <summary> /// Sends the specified endpoint. /// </summary> /// <param name="endpoint">The endpoint.</param> /// <param name="messages">The messages.</param> /// <returns></returns> public virtual IServiceBusCallback Send(IServiceBusEndpoint endpoint, params object[] messages) { if (messages == null || messages.Length == 0 || messages[0] == null) throw new ArgumentNullException("messages", "Please include at least one message."); try { if (endpoint == null) Bus.Send(NServiceBusTransport.Cast(messages)); else if (endpoint != ServiceBus.SelfEndpoint) Bus.Send(NServiceBusTransport.Cast(endpoint), NServiceBusTransport.Cast(messages)); else Bus.SendLocal(NServiceBusTransport.Cast(messages)); } catch (Exception ex) { throw new ServiceBusMessageException(messages[0].GetType(), ex); } return null; } /// <summary> /// Replies the specified messages. /// </summary> /// <param name="messages">The messages.</param> public virtual void Reply(params object[] messages) { if (messages == null || messages.Length == 0 || messages[0] == null) throw new ArgumentNullException("messages", "Please include at least one message."); try { Bus.Reply(NServiceBusTransport.Cast(messages)); } catch (Exception ex) { throw new ServiceBusMessageException(messages[0].GetType(), ex); } } #region Publishing ServiceBus /// <summary> /// Publishes the specified messages. /// </summary> /// <param name="messages">The messages.</param> public virtual void Publish(params object[] messages) { if (messages == null || messages.Length == 0 || messages[0] == null) throw new ArgumentNullException("messages"); try { Bus.Publish(NServiceBusTransport.Cast(messages)); } catch (Exception ex) { throw new ServiceBusMessageException(messages[0].GetType(), ex); } } /// <summary> /// Subscribes the specified message type. /// </summary> /// <param name="messageType">Type of the message.</param> /// <param name="predicate">The predicate.</param> public virtual void Subscribe(Type messageType, Predicate<object> predicate) { if (messageType == null) throw new ArgumentNullException("messageType"); try { if (predicate == null) Bus.Subscribe(messageType); else Bus.Subscribe(messageType, #if !CLR4 NServiceBusTransport.Cast(predicate) #else predicate #endif ); } catch (Exception ex) { throw new ServiceBusMessageException(messageType, ex); } } /// <summary> /// Unsubscribes the specified message type. /// </summary> /// <param name="messageType">Type of the message.</param> public virtual void Unsubscribe(Type messageType) { if (messageType == null) throw new ArgumentNullException("messageType"); try { Bus.Unsubscribe(messageType); } catch (Exception ex) { throw new ServiceBusMessageException(messageType, ex); } } #endregion #region Domain-specific /// <summary> /// Gets the bus. /// </summary> public IBus Bus { get; set; } /// <summary> /// Sends the with return. /// </summary> /// <param name="executeTimeout">The execute timeout.</param> /// <param name="endpoint">The endpoint.</param> /// <param name="messages">The messages.</param> /// <returns></returns> public virtual int SendWithReturn(int executeTimeout, IServiceBusEndpoint endpoint, params object[] messages) { if (messages == null || messages.Length == 0 || messages[0] == null) throw new ArgumentNullException("messages", "Please include at least one message."); IAsyncResult asyncResult; try { if (endpoint == null) asyncResult = Bus.Send(NServiceBusTransport.Cast(messages)).Register(state => { }, null); if (endpoint != ServiceBus.SelfEndpoint) asyncResult = Bus.Send(NServiceBusTransport.Cast(endpoint), NServiceBusTransport.Cast(messages)).Register(state => { }, null); else throw new NotSupportedException(); } catch (Exception ex) { throw new ServiceBusMessageException(messages[0].GetType(), ex); } if (!asyncResult.AsyncWaitHandle.WaitOne(executeTimeout)) throw new TimeoutException(); return ((CompletionResult)asyncResult.AsyncState).ErrorCode; } /// <summary> /// Returns the specified value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> public virtual void Return<T>(T value) { if (typeof(T) != typeof(int)) throw new NotSupportedException(); try { Bus.Return(Convert.ToInt32(value)); } catch (Exception ex) { throw new ServiceBusMessageException(null, ex); } } #endregion /// <summary> /// Defaults the bus creator. /// </summary> /// <param name="serviceLocator">The service locator.</param> /// <param name="assemblies">The assemblies.</param> /// <returns></returns> public static IStartableBus DefaultBusCreator(IServiceLocator serviceLocator, params Assembly[] assemblies) { if (serviceLocator == null) serviceLocator = ServiceLocatorManager.Current; //return Configure.Instance.Builder.Build<IBus>() as IStartableBus; return Configure.With(new[] { typeof(CompletionMessage).Assembly }.Union(assemblies)) .AbstractServiceBuilder() //.DefaultBuilder() .XmlSerializer() .MsmqTransport() .UnicastBus() .CreateBus(); } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * 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.IO; using System.Security.Cryptography; using System.Text; using MindTouch.Deki.Data; using MindTouch.Dream; using MindTouch.IO; using MindTouch.Tasking; using MindTouch.Xml; namespace MindTouch.Deki.Storage { public class S3Storage : IStorageProvider { //--- Constants --- private const string AWS_DATE = "X-Amz-Date"; private const int CACHE_TTL = 60 * 60; private const double DEFAUTL_S3_TIMEOUT = 30; //--- Class Methods --- private static void SafeFileDelete(string filename) { if(File.Exists(filename)) { try { File.Delete(filename); } catch { } } } //--- Fields --- private string _public_key; private string _private_key; private string _bucket; private Plug _s3; private string _prefix; private Dictionary<string, Tuplet<string, TaskTimer, DateTime?>> _cache = new Dictionary<string, Tuplet<string, TaskTimer, DateTime?>>(); private bool _allowRedirects; private TimeSpan _redirectTimeout; //--- Constructors --- public S3Storage(XDoc configuration) { _public_key = configuration["publickey"].AsText; _private_key = configuration["privatekey"].AsText; _bucket = configuration["bucket"].AsText; _prefix = configuration["prefix"].AsText; if(string.IsNullOrEmpty(_public_key)) { throw new ArgumentException("Invalid Amazon S3 publickey"); } if(string.IsNullOrEmpty(_private_key)) { throw new ArgumentException("Invalid Amazon S3 privatekey"); } if(string.IsNullOrEmpty(_bucket)) { throw new ArgumentException("Invalid Amazon S3 bucket"); } if(string.IsNullOrEmpty(_prefix)) { throw new ArgumentException("Invalid Amazon S3 prefix"); } _allowRedirects = configuration["allowredirects"].AsBool ?? false; _redirectTimeout = TimeSpan.FromSeconds(configuration["redirecttimeout"].AsInt ?? 60); // initialize S3 plug _s3 = Plug.New("http://s3.amazonaws.com", TimeSpan.FromSeconds(configuration["timeout"].AsDouble ?? DEFAUTL_S3_TIMEOUT)).WithPreHandler(S3AuthenticationHeader).At(_bucket); } //--- Methods --- public StreamInfo GetFile(AttachmentBE attachment, SizeType size, bool allowFileLink) { MimeType mime; switch(size) { case SizeType.THUMB: case SizeType.WEBVIEW: mime = Deki.Logic.AttachmentPreviewBL.ResolvePreviewMime(attachment.MimeType); break; default: mime = attachment.MimeType; break; } return GetFileInternal(BuildS3Filename(attachment, size), mime, allowFileLink); } public void PutFile(AttachmentBE attachment, SizeType size, StreamInfo file) { PutFileInternal(BuildS3Filename(attachment, size), attachment.Name, file); } public void MoveFile(AttachmentBE attachment, PageBE targetPage) { //Nothing to do here. } public void DeleteFile(AttachmentBE attachment, SizeType size) { DeleteFileInternal(BuildS3Filename(attachment, size)); } public void PutSiteFile(string label, StreamInfo file) { PutFileInternal(BuildS3SiteFilename(label), string.Empty, file); } public DateTime GetSiteFileTimestamp(string label) { return GetFileTimeStampInternal(BuildS3SiteFilename(label)); } public StreamInfo GetSiteFile(string label, bool allowFileLink) { return GetFileInternal(BuildS3SiteFilename(label), MimeType.FromFileExtension(label), allowFileLink); } public void DeleteSiteFile(string label) { DeleteFileInternal(BuildS3SiteFilename(label)); } public void Shutdown() { // copy list of cached files List<Tuplet<string, TaskTimer, DateTime?>> entries = new List<Tuplet<string, TaskTimer, DateTime?>>(_cache.Count); lock(_cache) { entries.AddRange(_cache.Values); _cache.Clear(); } // delete all cached files foreach(Tuplet<string, TaskTimer, DateTime?> entry in entries) { entry.Item2.Cancel(); SafeFileDelete(entry.Item1); } } private StreamInfo GetFileInternal(string filename, MimeType type, bool allowFileLink) { if(allowFileLink && _allowRedirects) { return new StreamInfo(BuildS3Uri(Verb.GET, _s3.AtPath(filename), _redirectTimeout)); } // check if file is cached Tuplet<string, TaskTimer, DateTime?> entry = GetCachedEntry(filename); if(entry != null) { Stream filestream = File.Open(entry.Item1, FileMode.Open, FileAccess.Read, FileShare.Read); return new StreamInfo(filestream, filestream.Length, type, entry.Item3); } // get file from S3 Result<DreamMessage> result = new Result<DreamMessage>(); _s3.AtPath(filename).InvokeEx(Verb.GET, DreamMessage.Ok(), result); DreamMessage response = result.Wait(); try { if(response.IsSuccessful) { return new StreamInfo(response.AsStream(), response.ContentLength, response.ContentType, GetLastModifiedTimestampFromResponse(response)); } else if(response.Status == DreamStatus.NotFound) { response.Close(); return null; } else { throw new DreamInternalErrorException(string.Format("S3 unable to fetch file (status {0}, message {1})", response.Status, response.AsText())); } } catch { if(response != null) { response.Close(); } throw; } } private void PutFileInternal(string s3Filename, string filename, StreamInfo file) { string tmpfile; using(file) { tmpfile = Path.GetTempFileName(); // create tmp file try { // copy stream to tmp file using(Stream stream = File.Create(tmpfile)) { file.Stream.CopyTo(stream, file.Length, new Result<long>(TimeSpan.MaxValue)).Wait(); } // create cached entry TaskTimer timer = TaskTimer.New(TimeSpan.FromSeconds(CACHE_TTL), OnTimer, s3Filename, TaskEnv.None); lock(_cache) { // cach everything we know about the file _cache[s3Filename] = new Tuplet<string, TaskTimer, DateTime?>(tmpfile, timer, file.Modified); } } catch(Exception e) { try { // delete tmp file if it exists SafeFileDelete(tmpfile); lock(_cache) { _cache.Remove(s3Filename); } } catch { } throw new DreamInternalErrorException(string.Format("Unable to cache file attachment to '{0}' ({1})", s3Filename, e.Message)); } } // forward cached file to S3 Stream filestream = File.Open(tmpfile, FileMode.Open, FileAccess.Read, FileShare.Read); file = new StreamInfo(filestream, file.Length, file.Type); DreamMessage s3Msg = DreamMessage.Ok(file.Type, file.Length, file.Stream); s3Msg.Headers.ContentDisposition = new ContentDisposition(true, DateTime.UtcNow, null, null, filename, file.Length); // Note (arnec): The timeout is just a workaround Plug not having some kind of heartbeat on progress. Ideally 30 seconds of inactivity // should be perfectly fine, as long as we track uploads that are proceeding as active _s3.AtPath(s3Filename).WithTimeout(TimeSpan.FromMinutes(30)).Put(s3Msg); } private void DeleteFileInternal(string filename) { RemoveCachedEntry(filename, false); _s3.AtPath(filename).DeleteAsync().Wait(); } private DateTime GetFileTimeStampInternal(string filename) { // check cache Tuplet<string, TaskTimer, DateTime?> entry = GetCachedEntry(filename); if(entry != null) { return entry.Item3 ?? DateTime.MinValue; } // get file information from S3 DreamMessage response = _s3.AtPath(filename).InvokeAsync("HEAD", DreamMessage.Ok()).Wait(); return GetLastModifiedTimestampFromResponse(response); } private DateTime GetLastModifiedTimestampFromResponse(DreamMessage response) { if(response.IsSuccessful) { return response.Headers.LastModified ?? DateTime.MinValue; } return DateTime.MinValue; } private string BuildS3Filename(AttachmentBE attachment, SizeType size) { string id; //Legacy pre-Lyons S3 paths are based on fileid. If the fileid is present in the resource then use it otherwise base on resourceid. if(attachment.FileId == null) { id = string.Format("r{0}", attachment.ResourceId); } else { id = attachment.FileId.ToString(); } switch(size) { case SizeType.THUMB: case SizeType.WEBVIEW: return string.Format("{0}/{1}/{2}/{3}", _prefix, id, attachment.Content.Revision - 1, size.ToString().ToLowerInvariant()); default: return string.Format("{0}/{1}/{2}", _prefix, id, attachment.Content.Revision - 1); } } private string BuildS3SiteFilename(string label) { return string.Format("{0}/{1}/{2}", _prefix, "SITE", label); } private DreamMessage S3AuthenticationHeader(string verb, XUri uri, XUri normalizedUri, DreamMessage message) { // add amazon date header string date = DateTime.UtcNow.ToString("r"); message.Headers[AWS_DATE] = date; // add authorization header string result = string.Format("{0}\n{1}\n{2}\n\n{3}:{4}\n{5}", verb, message.Headers[DreamHeaders.CONTENT_MD5], message.ContentType, AWS_DATE.ToLowerInvariant(), date, normalizedUri.Path); HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(_private_key)); string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(result))); message.Headers.Authorization = string.Format("AWS {0}:{1}", _public_key, signature); message.Headers.ContentType = message.ContentType; return message; } private XUri BuildS3Uri(string verb, XUri uri, TimeSpan expireTime) { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); string expireTimeSeconds = expireTimeSeconds = ((long)(new TimeSpan(DateTime.UtcNow.Add(expireTime).Subtract(epoch).Ticks).TotalSeconds)).ToString(); string result = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", verb, string.Empty, string.Empty, expireTimeSeconds, uri.Path); HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(_private_key)); string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(result))); XUri ret = uri.With("AWSAccessKeyId", _public_key).With("Signature", signature).With("Expires", expireTimeSeconds); return ret; } private void OnTimer(TaskTimer timer) { RemoveCachedEntry((string)timer.State, true); } private Tuplet<string, TaskTimer, DateTime?> GetCachedEntry(string filename) { Tuplet<string, TaskTimer, DateTime?> result; lock(_cache) { if(_cache.TryGetValue(filename, out result)) { if(File.Exists(result.Item1)) { result.Item2.Change(TimeSpan.FromSeconds(CACHE_TTL), TaskEnv.Current); } else { result.Item2.Cancel(); _cache.Remove(filename); return null; } } } return result; } private void RemoveCachedEntry(string filename, bool timeout) { Tuplet<string, TaskTimer, DateTime?> entry; lock(_cache) { if(_cache.TryGetValue(filename, out entry)) { // avoid race condition if(timeout) { if(entry.Item2.When != DateTime.MaxValue) { return; } } else { entry.Item2.Cancel(); } _cache.Remove(filename); } } if(entry != null) { SafeFileDelete(entry.Item1); } } } }
using System.ComponentModel; namespace Aspose.Slides.Web.API.Clients.Enums { /// <summary> /// Represents a type of chart. /// </summary> public enum ChartTypes { /// <summary> /// Represents Clustered Column Chart. /// </summary> [Description("Clustered column")] ClusteredColumn = 0, /// <summary> /// Represents Stacked Column Chart. /// </summary> [Description("Stacked column")] StackedColumn = 1, /// <summary> /// Represents 100% Stacked Column Chart. /// </summary> [Description("Percents stacked column")] PercentsStackedColumn = 2, /// <summary> /// Represents 3D Colustered Column Chart. /// </summary> [Description("Clustered 3D column")] ClusteredColumn3D = 3, /// <summary> /// Represents 3D Stacked Column Chart. /// </summary> [Description("Stacked 3D column")] StackedColumn3D = 4, /// <summary> /// Represents 3D 100% Stacked Column Chart. /// </summary> [Description("Percents stacked 3D column")] PercentsStackedColumn3D = 5, /// <summary> /// Represents 3D Column Chart. /// </summary> [Description("Column 3D")] Column3D = 6, /// <summary> /// Represents Cylinder Chart. /// </summary> [Description("Clustered cylinder")] ClusteredCylinder = 7, /// <summary> /// Represents Stacked Cylinder Chart. /// </summary> [Description("Stacked cylinder")] StackedCylinder = 8, /// <summary> /// Represents 100% Stacked Cylinder Chart. /// </summary> [Description("Percents stacked cylinder")] PercentsStackedCylinder = 9, /// <summary> /// Represents 3D Cylindrical Column Chart. /// </summary> [Description("Cylinder 3D")] Cylinder3D = 10, /// <summary> /// Represents Cone Chart. /// </summary> [Description("Clustered cone")] ClusteredCone = 11, /// <summary> /// Represents Stacked Cone Chart. /// </summary> [Description("Stacked cone")] StackedCone = 12, /// <summary> /// Represents 100% Stacked Cone Chart. /// </summary> [Description("Percents stacked cone")] PercentsStackedCone = 13, /// <summary> /// Represents 3D Conical Column Chart. /// </summary> [Description("Cone 3D")] Cone3D = 14, /// <summary> /// Represents Pyramid Chart. /// </summary> [Description("Clustered pyramid")] ClusteredPyramid = 15, /// <summary> /// /// </summary> [Description("Stacked pyramid")] StackedPyramid = 16, /// <summary> /// Represents 100% Stacked Pyramid Chart. /// </summary> [Description("Percents stacked pyramid")] PercentsStackedPyramid = 17, /// <summary> /// Represents 3D Pyramid Column Chart. /// </summary> [Description("Pyramid 3D")] Pyramid3D = 18, /// <summary> /// Represents Line Chart. /// </summary> [Description("Line")] Line = 19, /// <summary> /// Represents Stacked Line Chart. /// </summary> [Description("Stacked Line")] StackedLine = 20, /// <summary> /// Represents 100% Stacked Line Chart. /// </summary> [Description("Percents stacked line")] PercentsStackedLine = 21, /// <summary> /// Represents Line Chart with data markers. /// </summary> [Description("Line with markers")] LineWithMarkers = 22, /// <summary> /// Represents Stacked Line Chart with data markers. /// </summary> [Description("Stacked line with markers")] StackedLineWithMarkers = 23, /// <summary> /// Represents 100% Stacked Line Chart with data markers. /// </summary> [Description("Percents stacked line with markers")] PercentsStackedLineWithMarkers = 24, /// <summary> /// Represents 3D Line Chart. /// </summary> [Description("Line 3D")] Line3D = 25, /// <summary> /// Represents Pie Chart. /// </summary> [Description("Pie")] Pie = 26, // TODO https://issue.lutsk.dynabic.com/issues/SLIDESAPP-561 /// <summary> /// Represents 3D Pie Chart. /// </summary> //[Description("Pie 3D")] //Pie3D = 27, /// <summary> /// Represents Pie of Pie Chart. /// </summary> [Description("Pie of pie")] PieOfPie = 28, /// <summary> /// Represents Exploded Pie Chart. /// </summary> [Description("Exploded pie")] ExplodedPie = 29, /// <summary> /// Represents 3D Exploded Pie Chart. /// </summary> [Description("Exploded pie 3D")] ExplodedPie3D = 30, /// <summary> /// Represents Bar of Pie Chart. /// </summary> [Description("Bar of pie")] BarOfPie = 31, /// <summary> /// Represents 100% Stacked Bar Chart. /// </summary> [Description("Percents stacked bar")] PercentsStackedBar = 32, /// <summary> /// Represents 3D Colustered Bar Chart. /// </summary> [Description("Clustered bar 3D")] ClusteredBar3D = 33, /// <summary> /// Represents Clustered Bar Chart. /// </summary> [Description("Clustered bar")] ClusteredBar = 34, /// <summary> /// Represents Stacked Bar Chart. /// </summary> [Description("Stacked bar")] StackedBar = 35, /// <summary> /// Represents 3D Stacked Bar Chart. /// </summary> [Description("Stacked bar 3D")] StackedBar3D = 36, /// <summary> /// Represents 3D 100% Stacked Bar Chart. /// </summary> [Description("Percents stacked bar 3D")] PercentsStackedBar3D = 37, /// <summary> /// Represents Cylindrical Bar Chart. /// </summary> [Description("Clustered horizontal cylinder")] ClusteredHorizontalCylinder = 38, /// <summary> /// Represents Stacked Cylindrical Bar Chart. /// </summary> [Description("Stacked horizontal cylinder")] StackedHorizontalCylinder = 39, /// <summary> /// Represents 100% Stacked Cylindrical Bar Chart. /// </summary> [Description("Percents stacked horizontal cylinder")] PercentsStackedHorizontalCylinder = 40, /// <summary> /// Represents Conical Bar Chart. /// </summary> [Description("Clustered horizontal cone")] ClusteredHorizontalCone = 41, /// <summary> /// Represents Stacked Conical Bar Chart. /// </summary> [Description("Stacked horizontal cone")] StackedHorizontalCone = 42, /// <summary> /// Represents 100% Stacked Conical Bar Chart. /// </summary> [Description("Percents stacked horizontal cone")] PercentsStackedHorizontalCone = 43, /// <summary> /// Represents Pyramid Bar Chart. /// </summary> [Description("Clustered horizontal pyramid")] ClusteredHorizontalPyramid = 44, /// <summary> /// Represents Stacked Pyramid Bar Chart. /// </summary> [Description("Stacked horizontal pyramid")] StackedHorizontalPyramid = 45, /// <summary> /// Represents 100% Stacked Pyramid Bar Chart. /// </summary> [Description("Percents stacked horizontal pyramid")] PercentsStackedHorizontalPyramid = 46, /// <summary> /// Represents Area Chart. /// </summary> [Description("Area")] Area = 47, /// <summary> /// Represents Stacked Area Chart. /// </summary> [Description("Stacked area")] StackedArea = 48, /// <summary> /// Represents 100% Stacked Area Chart. /// </summary> [Description("Percents stacked area")] PercentsStackedArea = 49, /// <summary> /// Represents 3D Area Chart. /// </summary> [Description("Area 3D")] Area3D = 50, /// <summary> /// Represents 3D Stacked Area Chart. /// </summary> [Description("Stacked area 3D")] StackedArea3D = 51, /// <summary> /// Represents 3D 100% Stacked Area Chart. /// </summary> [Description("Percents stacked area 3D")] PercentsStackedArea3D = 52, /// <summary> /// Represents Scatter Chart. /// </summary> [Description("Scatter with markers")] ScatterWithMarkers = 53, /// <summary> /// Represents Scatter Chart connected by curves, with data markers. /// </summary> [Description("Scatter with smooth lines and markers")] ScatterWithSmoothLinesAndMarkers = 54, /// <summary> /// Represents Scatter Chart connected by curves, without data markers. /// </summary> [Description("Scatter with smooth lines")] ScatterWithSmoothLines = 55, /// <summary> /// Represents Scatter Chart connected by lines, with data markers. /// </summary> [Description("Scatter with straight lines and markers")] ScatterWithStraightLinesAndMarkers = 56, /// <summary> /// Represents Scatter Chart connected by lines, without data markers. /// </summary> [Description("Scatter with straight lines")] ScatterWithStraightLines = 57, /// <summary> /// Represents High-Low-Close Stock Chart. /// </summary> [Description("High low close")] HighLowClose = 58, /// <summary> /// Represents Open-High-Low-Close Stock Chart. /// </summary> [Description("Open high low close")] OpenHighLowClose = 59, /// <summary> /// Represents Volume-High-Low-Close Stock Chart. /// </summary> [Description("Volume high low close")] VolumeHighLowClose = 60, /// <summary> /// Represents Volume-Open-High-Low-Close Stock Chart. /// </summary> [Description("Volume open high low close")] VolumeOpenHighLowClose = 61, /// <summary> /// Represents 3D Surface Chart. /// </summary> [Description("Surface 3D")] Surface3D = 62, /// <summary> /// Represents Wireframe 3D Surface Chart. /// </summary> [Description("Wireframe Surface 3D")] WireframeSurface3D = 63, /// <summary> /// Represents Contour Chart. /// </summary> [Description("Contour")] Contour = 64, /// <summary> /// Represents Wireframe Contour Chart. /// </summary> [Description("Wireframe Contour")] WireframeContour = 65, /// <summary> /// Represents Doughnut Chart. /// </summary> [Description("Doughnut")] Doughnut = 66, /// <summary> /// Represents Exploded Doughnut Chart. /// </summary> [Description("Exploded doughnut")] ExplodedDoughnut = 67, /// <summary> /// Represents Bubble Chart. /// </summary> [Description("Bubble")] Bubble = 68, /// <summary> /// Represents 3D Bubble Chart. /// </summary> [Description("Bubble with 3D")] BubbleWith3D = 69, /// <summary> /// Represents Radar Chart. /// </summary> [Description("Radar")] Radar = 70, /// <summary> /// Represents Radar Chart with data markers. /// </summary> [Description("Radar with markers")] RadarWithMarkers = 71, /// <summary> /// Represents Filled Radar Chart. /// </summary> [Description("Filled radar")] FilledRadar = 72, /// <summary> /// Represents Treemap chart. /// </summary> [Description("Treemap")] Treemap = 74, /// <summary> /// Represents Sunburst chart. /// </summary> [Description("Sunburst")] Sunburst = 75, /// <summary> /// Represents Histogram chart. /// </summary> [Description("Histogram")] Histogram = 76, /// <summary> /// Represents Pareto line series type (Histogram Pareto chart). /// </summary> [Description("Pareto line")] ParetoLine = 77, /// <summary> /// Represents BoxAndWhisker chart. /// </summary> [Description("Box and whisker")] BoxAndWhisker = 78, /// <summary> /// Represents Waterfall chart. /// </summary> [Description("Waterfall")] Waterfall = 79, /// <summary> /// Represents Funnel chart. /// </summary> [Description("Funnel")] Funnel = 80, // TODO: https://issue.lutsk.dynabic.com/issues/SLIDESAPP-555 /// <summary> /// Represents Map chart. /// </summary> //[Description("Map")] //Map = 81 } }
namespace XenAdmin.Wizards.NewNetworkWizard_Pages { partial class NetWDetails { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NetWDetails)); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.labelExternal = new System.Windows.Forms.Label(); this.labelInternal = new System.Windows.Forms.Label(); this.labelNIC = new System.Windows.Forms.Label(); this.comboBoxNICList = new System.Windows.Forms.ComboBox(); this.labelVLAN = new System.Windows.Forms.Label(); this.numericUpDownVLAN = new System.Windows.Forms.NumericUpDown(); this.infoVlanPanel = new System.Windows.Forms.TableLayoutPanel(); this.pictureBoxVlan = new System.Windows.Forms.PictureBox(); this.labelVlanMessage = new System.Windows.Forms.Label(); this.labelMTU = new System.Windows.Forms.Label(); this.numericUpDownMTU = new System.Windows.Forms.NumericUpDown(); this.infoMtuPanel = new System.Windows.Forms.TableLayoutPanel(); this.pictureBoxMtu = new System.Windows.Forms.PictureBox(); this.labelMtuMessage = new System.Windows.Forms.Label(); this.checkBoxSriov = new System.Windows.Forms.CheckBox(); this.checkBoxAutomatic = new System.Windows.Forms.CheckBox(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownVLAN)).BeginInit(); this.infoVlanPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxVlan)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownMTU)).BeginInit(); this.infoMtuPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxMtu)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.labelExternal, 0, 0); this.tableLayoutPanel1.Controls.Add(this.labelInternal, 0, 1); this.tableLayoutPanel1.Controls.Add(this.labelNIC, 0, 2); this.tableLayoutPanel1.Controls.Add(this.comboBoxNICList, 1, 2); this.tableLayoutPanel1.Controls.Add(this.labelVLAN, 0, 3); this.tableLayoutPanel1.Controls.Add(this.numericUpDownVLAN, 1, 3); this.tableLayoutPanel1.Controls.Add(this.infoVlanPanel, 2, 3); this.tableLayoutPanel1.Controls.Add(this.labelMTU, 0, 4); this.tableLayoutPanel1.Controls.Add(this.numericUpDownMTU, 1, 4); this.tableLayoutPanel1.Controls.Add(this.infoMtuPanel, 2, 4); this.tableLayoutPanel1.Controls.Add(this.checkBoxSriov, 0, 5); this.tableLayoutPanel1.Controls.Add(this.checkBoxAutomatic, 0, 6); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // labelExternal // resources.ApplyResources(this.labelExternal, "labelExternal"); this.tableLayoutPanel1.SetColumnSpan(this.labelExternal, 4); this.labelExternal.Name = "labelExternal"; // // labelInternal // resources.ApplyResources(this.labelInternal, "labelInternal"); this.tableLayoutPanel1.SetColumnSpan(this.labelInternal, 4); this.labelInternal.Name = "labelInternal"; // // labelNIC // resources.ApplyResources(this.labelNIC, "labelNIC"); this.labelNIC.Name = "labelNIC"; // // comboBoxNICList // this.tableLayoutPanel1.SetColumnSpan(this.comboBoxNICList, 2); this.comboBoxNICList.DisplayMember = "Server"; this.comboBoxNICList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxNICList.FormattingEnabled = true; resources.ApplyResources(this.comboBoxNICList, "comboBoxNICList"); this.comboBoxNICList.Name = "comboBoxNICList"; this.comboBoxNICList.Sorted = true; this.comboBoxNICList.SelectedIndexChanged += new System.EventHandler(this.cmbHostNicList_SelectedIndexChanged); // // labelVLAN // resources.ApplyResources(this.labelVLAN, "labelVLAN"); this.labelVLAN.Name = "labelVLAN"; // // numericUpDownVLAN // resources.ApplyResources(this.numericUpDownVLAN, "numericUpDownVLAN"); this.numericUpDownVLAN.Name = "numericUpDownVLAN"; this.numericUpDownVLAN.ValueChanged += new System.EventHandler(this.numericUpDownVLAN_ValueChanged); this.numericUpDownVLAN.Leave += new System.EventHandler(this.numericUpDownVLAN_Leave); // // infoVlanPanel // resources.ApplyResources(this.infoVlanPanel, "infoVlanPanel"); this.tableLayoutPanel1.SetColumnSpan(this.infoVlanPanel, 2); this.infoVlanPanel.Controls.Add(this.pictureBoxVlan, 0, 0); this.infoVlanPanel.Controls.Add(this.labelVlanMessage, 1, 0); this.infoVlanPanel.Name = "infoVlanPanel"; // // pictureBoxVlan // resources.ApplyResources(this.pictureBoxVlan, "pictureBoxVlan"); this.pictureBoxVlan.Name = "pictureBoxVlan"; this.pictureBoxVlan.TabStop = false; // // labelVlanMessage // resources.ApplyResources(this.labelVlanMessage, "labelVlanMessage"); this.labelVlanMessage.Name = "labelVlanMessage"; // // labelMTU // resources.ApplyResources(this.labelMTU, "labelMTU"); this.labelMTU.Name = "labelMTU"; // // numericUpDownMTU // resources.ApplyResources(this.numericUpDownMTU, "numericUpDownMTU"); this.numericUpDownMTU.Name = "numericUpDownMTU"; this.numericUpDownMTU.ValueChanged += new System.EventHandler(this.numericUpDownMTU_ValueChanged); this.numericUpDownMTU.Leave += new System.EventHandler(this.numericUpDownMTU_Leave); // // infoMtuPanel // resources.ApplyResources(this.infoMtuPanel, "infoMtuPanel"); this.tableLayoutPanel1.SetColumnSpan(this.infoMtuPanel, 2); this.infoMtuPanel.Controls.Add(this.pictureBoxMtu, 0, 0); this.infoMtuPanel.Controls.Add(this.labelMtuMessage, 1, 0); this.infoMtuPanel.Name = "infoMtuPanel"; // // pictureBoxMtu // resources.ApplyResources(this.pictureBoxMtu, "pictureBoxMtu"); this.pictureBoxMtu.Name = "pictureBoxMtu"; this.pictureBoxMtu.TabStop = false; // // labelMtuMessage // resources.ApplyResources(this.labelMtuMessage, "labelMtuMessage"); this.labelMtuMessage.Name = "labelMtuMessage"; // // checkBoxSriov // resources.ApplyResources(this.checkBoxSriov, "checkBoxSriov"); this.tableLayoutPanel1.SetColumnSpan(this.checkBoxSriov, 4); this.checkBoxSriov.Name = "checkBoxSriov"; this.checkBoxSriov.UseVisualStyleBackColor = true; this.checkBoxSriov.CheckedChanged += new System.EventHandler(this.checkBoxSriov_CheckedChanged); // // checkBoxAutomatic // resources.ApplyResources(this.checkBoxAutomatic, "checkBoxAutomatic"); this.tableLayoutPanel1.SetColumnSpan(this.checkBoxAutomatic, 4); this.checkBoxAutomatic.Name = "checkBoxAutomatic"; this.checkBoxAutomatic.UseVisualStyleBackColor = true; // // NetWDetails // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.SystemColors.Control; this.Controls.Add(this.tableLayoutPanel1); this.Name = "NetWDetails"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownVLAN)).EndInit(); this.infoVlanPanel.ResumeLayout(false); this.infoVlanPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxVlan)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownMTU)).EndInit(); this.infoMtuPanel.ResumeLayout(false); this.infoMtuPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxMtu)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label labelNIC; private System.Windows.Forms.ComboBox comboBoxNICList; private System.Windows.Forms.Label labelVLAN; private System.Windows.Forms.Label labelInternal; private System.Windows.Forms.CheckBox checkBoxAutomatic; private System.Windows.Forms.Label labelMTU; private System.Windows.Forms.Label labelMtuMessage; private System.Windows.Forms.PictureBox pictureBoxMtu; private System.Windows.Forms.CheckBox checkBoxSriov; private System.Windows.Forms.Label labelExternal; private System.Windows.Forms.TableLayoutPanel infoMtuPanel; private System.Windows.Forms.TableLayoutPanel infoVlanPanel; private System.Windows.Forms.PictureBox pictureBoxVlan; private System.Windows.Forms.Label labelVlanMessage; private System.Windows.Forms.NumericUpDown numericUpDownVLAN; private System.Windows.Forms.NumericUpDown numericUpDownMTU; } }
// 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.AcceptanceTestsModelFlattening { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Resource Flattening for AutoRest /// </summary> public partial interface IAutoRestResourceFlatteningTestService : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Put External Resource as an Array /// </summary> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutArrayWithHttpMessagesAsync(IList<Resource> resourceArray = default(IList<Resource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get External Resource as an Array /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// No need to have a route in Express server for this operation. Used /// to verify the type flattened is not removed if it's referenced in /// an array /// </summary> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutWrappedArrayWithHttpMessagesAsync(IList<WrappedProduct> resourceArray = default(IList<WrappedProduct>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// No need to have a route in Express server for this operation. Used /// to verify the type flattened is not removed if it's referenced in /// an array /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<ProductWrapper>>> GetWrappedArrayWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put External Resource as a Dictionary /// </summary> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDictionaryWithHttpMessagesAsync(IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get External Resource as a Dictionary /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put External Resource as a ResourceCollection /// </summary> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get External Resource as a ResourceCollection /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='simpleBodyProduct'> /// Simple body product to put /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<SimpleProduct>> PutSimpleProductWithHttpMessagesAsync(SimpleProduct simpleBodyProduct = default(SimpleProduct), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put Flattened Simple Product with client flattening true on the /// parameter /// </summary> /// <param name='productId'> /// Unique identifier representing a specific product for a given /// latitude &amp; longitude. For example, uberX in San Francisco will /// have a different product_id than uberX in Los Angeles. /// </param> /// <param name='maxProductDisplayName'> /// Display name of product. /// </param> /// <param name='description'> /// Description of product. /// </param> /// <param name='genericValue'> /// Generic URL value. /// </param> /// <param name='odatavalue'> /// URL value. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<SimpleProduct>> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='flattenParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<SimpleProduct>> PutSimpleProductWithGroupingWithHttpMessagesAsync(FlattenParameterGroup flattenParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.10.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Enterprise License Manager API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/google-apps/licensing/'>Enterprise License Manager API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20150901 (243) * <tr><th>API Docs * <td><a href='https://developers.google.com/google-apps/licensing/'> * https://developers.google.com/google-apps/licensing/</a> * <tr><th>Discovery Name<td>licensing * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Enterprise License Manager API can be found at * <a href='https://developers.google.com/google-apps/licensing/'>https://developers.google.com/google-apps/licensing/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Licensing.v1 { /// <summary>The Licensing Service.</summary> public class LicensingService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public LicensingService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public LicensingService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { licenseAssignments = new LicenseAssignmentsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "licensing"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/apps/licensing/v1/product/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "apps/licensing/v1/product/"; } } /// <summary>Available OAuth 2.0 scopes for use with the Enterprise License Manager API.</summary> public class Scope { /// <summary>View and manage Google Apps licenses for your domain</summary> public static string AppsLicensing = "https://www.googleapis.com/auth/apps.licensing"; } private readonly LicenseAssignmentsResource licenseAssignments; /// <summary>Gets the LicenseAssignments resource.</summary> public virtual LicenseAssignmentsResource LicenseAssignments { get { return licenseAssignments; } } } ///<summary>A base abstract class for Licensing requests.</summary> public abstract class LicensingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new LicensingBaseServiceRequest instance.</summary> protected LicensingBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Licensing parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "licenseAssignments" collection of methods.</summary> public class LicenseAssignmentsResource { private const string Resource = "licenseAssignments"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public LicenseAssignmentsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Revoke License.</summary> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku</param> /// <param /// name="userId">email id or unique Id of the user</param> public virtual DeleteRequest Delete(string productId, string skuId, string userId) { return new DeleteRequest(service, productId, skuId, userId); } /// <summary>Revoke License.</summary> public class DeleteRequest : LicensingBaseServiceRequest<string> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string productId, string skuId, string userId) : base(service) { ProductId = productId; SkuId = skuId; UserId = userId; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>email id or unique Id of the user</summary> [Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)] public virtual string UserId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user/{userId}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userId", new Google.Apis.Discovery.Parameter { Name = "userId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Get license assignment of a particular product and sku for a user</summary> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku</param> /// <param /// name="userId">email id or unique Id of the user</param> public virtual GetRequest Get(string productId, string skuId, string userId) { return new GetRequest(service, productId, skuId, userId); } /// <summary>Get license assignment of a particular product and sku for a user</summary> public class GetRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string productId, string skuId, string userId) : base(service) { ProductId = productId; SkuId = skuId; UserId = userId; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>email id or unique Id of the user</summary> [Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)] public virtual string UserId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user/{userId}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userId", new Google.Apis.Discovery.Parameter { Name = "userId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Assign License.</summary> /// <param name="body">The body of the request.</param> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku</param> public virtual InsertRequest Insert(Google.Apis.Licensing.v1.Data.LicenseAssignmentInsert body, string productId, string skuId) { return new InsertRequest(service, body, productId, skuId); } /// <summary>Assign License.</summary> public class InsertRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment> { /// <summary>Constructs a new Insert request.</summary> public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Licensing.v1.Data.LicenseAssignmentInsert body, string productId, string skuId) : base(service) { ProductId = productId; SkuId = skuId; Body = body; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Licensing.v1.Data.LicenseAssignmentInsert Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "insert"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user"; } } /// <summary>Initializes Insert parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>List license assignments for given product of the customer.</summary> /// <param name="productId">Name for product</param> /// <param name="customerId">CustomerId represents the customer /// for whom licenseassignments are queried</param> public virtual ListForProductRequest ListForProduct(string productId, string customerId) { return new ListForProductRequest(service, productId, customerId); } /// <summary>List license assignments for given product of the customer.</summary> public class ListForProductRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignmentList> { /// <summary>Constructs a new ListForProduct request.</summary> public ListForProductRequest(Google.Apis.Services.IClientService service, string productId, string customerId) : base(service) { ProductId = productId; CustomerId = customerId; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>CustomerId represents the customer for whom licenseassignments are queried</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)] public virtual string CustomerId { get; private set; } /// <summary>Maximum number of campaigns to return at one time. Must be positive. Optional. Default value is /// 100.</summary> /// [default: 100] /// [minimum: 1] /// [maximum: 1000] [Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<long> MaxResults { get; set; } /// <summary>Token to fetch the next page.Optional. By default server will return first page</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "listForProduct"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/users"; } } /// <summary>Initializes ListForProduct parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "maxResults", new Google.Apis.Discovery.Parameter { Name = "maxResults", IsRequired = false, ParameterType = "query", DefaultValue = "100", Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>List license assignments for given product and sku of the customer.</summary> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku</param> /// <param /// name="customerId">CustomerId represents the customer for whom licenseassignments are queried</param> public virtual ListForProductAndSkuRequest ListForProductAndSku(string productId, string skuId, string customerId) { return new ListForProductAndSkuRequest(service, productId, skuId, customerId); } /// <summary>List license assignments for given product and sku of the customer.</summary> public class ListForProductAndSkuRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignmentList> { /// <summary>Constructs a new ListForProductAndSku request.</summary> public ListForProductAndSkuRequest(Google.Apis.Services.IClientService service, string productId, string skuId, string customerId) : base(service) { ProductId = productId; SkuId = skuId; CustomerId = customerId; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>CustomerId represents the customer for whom licenseassignments are queried</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)] public virtual string CustomerId { get; private set; } /// <summary>Maximum number of campaigns to return at one time. Must be positive. Optional. Default value is /// 100.</summary> /// [default: 100] /// [minimum: 1] /// [maximum: 1000] [Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<long> MaxResults { get; set; } /// <summary>Token to fetch the next page.Optional. By default server will return first page</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "listForProductAndSku"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/users"; } } /// <summary>Initializes ListForProductAndSku parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "maxResults", new Google.Apis.Discovery.Parameter { Name = "maxResults", IsRequired = false, ParameterType = "query", DefaultValue = "100", Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Assign License. This method supports patch semantics.</summary> /// <param name="body">The body of the request.</param> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku for which license would be /// revoked</param> /// <param name="userId">email id or unique Id of the user</param> public virtual PatchRequest Patch(Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId) { return new PatchRequest(service, body, productId, skuId, userId); } /// <summary>Assign License. This method supports patch semantics.</summary> public class PatchRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId) : base(service) { ProductId = productId; SkuId = skuId; UserId = userId; Body = body; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku for which license would be revoked</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>email id or unique Id of the user</summary> [Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)] public virtual string UserId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Licensing.v1.Data.LicenseAssignment Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "patch"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PATCH"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user/{userId}"; } } /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userId", new Google.Apis.Discovery.Parameter { Name = "userId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Assign License.</summary> /// <param name="body">The body of the request.</param> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku for which license would be /// revoked</param> /// <param name="userId">email id or unique Id of the user</param> public virtual UpdateRequest Update(Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId) { return new UpdateRequest(service, body, productId, skuId, userId); } /// <summary>Assign License.</summary> public class UpdateRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId) : base(service) { ProductId = productId; SkuId = skuId; UserId = userId; Body = body; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku for which license would be revoked</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>email id or unique Id of the user</summary> [Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)] public virtual string UserId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Licensing.v1.Data.LicenseAssignment Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "update"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PUT"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user/{userId}"; } } /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userId", new Google.Apis.Discovery.Parameter { Name = "userId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Licensing.v1.Data { /// <summary>Template for LiscenseAssignment Resource</summary> public class LicenseAssignment : Google.Apis.Requests.IDirectResponseSchema { /// <summary>ETag of the resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("etags")] public virtual string Etags { get; set; } /// <summary>Identifies the resource as a LicenseAssignment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Name of the product.</summary> [Newtonsoft.Json.JsonPropertyAttribute("productId")] public virtual string ProductId { get; set; } /// <summary>Link to this page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>Name of the sku of the product.</summary> [Newtonsoft.Json.JsonPropertyAttribute("skuId")] public virtual string SkuId { get; set; } /// <summary>Email id of the user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("userId")] public virtual string UserId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Template for LicenseAssignment Insert request</summary> public class LicenseAssignmentInsert : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Email id of the user</summary> [Newtonsoft.Json.JsonPropertyAttribute("userId")] public virtual string UserId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>LicesnseAssignment List for a given product/sku for a customer.</summary> public class LicenseAssignmentList : Google.Apis.Requests.IDirectResponseSchema { /// <summary>ETag of the resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("etag")] public virtual string ETag { get; set; } /// <summary>The LicenseAssignments in this page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<LicenseAssignment> Items { get; set; } /// <summary>Identifies the resource as a collection of LicenseAssignments.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The continuation token, used to page through large result sets. Provide this value in a subsequent /// request to return the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } } }
using System.Collections.Generic; using Codility.Katas.Lessons; using NUnit.Framework; namespace Codility.Katas.Tests { [TestFixture] public class TestLessons { #region Iterations [TestCase(1041, 5)] [TestCase(9, 2)] [TestCase(529, 4)] [TestCase(20, 1)] [TestCase(15, 0)] [TestCase(328, 2)] [TestCase(1162, 3)] [TestCase(1610612737, 28)] public void TestBinaryGapWithSuccess(int n, int expectedResult) { var result = Iterations.solutionBinaryGap2(n); Assert.IsTrue(result == expectedResult); } #endregion #region Arrays [TestCase(new int[] { 3, 8, 9, 7, 6 }, 1, new int[] { 6, 3, 8, 9, 7 })] [TestCase(new int[] { 3, 8, 9, 7, 6 }, 3, new int[] { 9, 7, 6, 3, 8 })] [TestCase(new int[] { 3, 8, 9, 7, 6 }, 1, new int[] { 6, 3, 8, 9, 7 })] [TestCase(new int[] { }, 4, new int[] { })] public void TestCyclicRotationWithSuccess(int[] array, int k, int[] expectedResult) { var result = Arrays.solutionCyclicRotation(array, k); Assert.AreEqual(result, expectedResult); } [TestCase(new int[] { 9, 3, 9, 3, 9, 7, 9 }, 7)] public void TestOddOccurrencesInArrayWithSuccess1(int[] array, int expectedResult) { var result = Arrays.solutionOddOccurrencesInArray(array); Assert.IsTrue(result == expectedResult); } #endregion #region Time Complexity [Test] public void TestTapeEquilibriumWithSuccess() { var array = new int[] { 3, 1, 2, 4, 3 }; var expectedResult = 1; var result = TimeComplexity.solutionTapeEquilibrium(array); Assert.IsTrue(result == expectedResult); } [Test] public void TestFrogJumpWithSuccess() { var X = 10; var Y = 85; var D = 30; var expectedResult = 3; var result = TimeComplexity.solutionFrogJump(X, Y, D); Assert.IsTrue(result == expectedResult); } [Test] public void TestPermMissingElem() { var array = new int[] { 2, 3, 1, 5 }; var expectedResult = 4; var result = TimeComplexity.solutionPermMissingElem(array); Assert.IsTrue(result == expectedResult); } #endregion #region Counting Elements [TestCase(1, new int[] { 1 }, 0)] [TestCase(5, new int[] { 1, 3, 1, 4, 2, 3, 5, 4 }, 6)] [TestCase(2, new int[] { 2, 2, 2, 2, 2 }, -1)] public void TestFrogRiverOneWithSuccess(int x, int[] array, int expectedResult) { var result = CountingElements.solutionFrogRiverOne(x, array); Assert.IsTrue(result == expectedResult); } [TestCase(new int[] { 4, 1, 3, 2 }, 1)] //[TestCase(new int[] { 4, 1, 3, 2 }, 1)] public void TestPermCheckWithSuccess(int[] array, int expectedResult) { var result = CountingElements.solutionPermCheck(array); Assert.IsTrue(result == expectedResult); } [TestCase(new int[] { 4, 1, 2, 3 }, 1)] [TestCase(new int[] { 4, 1, 3 }, 0)] [TestCase(new int[] { 9, 5, 7, 3, 2, 7, 3, 1, 10, 8 }, 0)] [TestCase(new int[] { 1, 1 }, 0)] public void TestPermCheck(int[] array, int expectedResult) { var result = CountingElements.solutionPermCheck(array); Assert.IsTrue(result == expectedResult); } [TestCase(new int[] { 2 }, 1)] [TestCase(new int[] { 1, 3, 6, 4, 1, 2 }, 5)] [TestCase(new int[] { 1, 2, 3 }, 4)] [TestCase(new int[] { 1, 2, 3, 2, 1, 2 }, 4)] [TestCase(new int[] { -1, -3 }, 1)] public void TestMissingIntegerWithSuccess(int[] array, int expectedResult) { var result = CountingElements.solutionMissingInteger(array); Assert.IsTrue(result == expectedResult); } [TestCase(5, new int[] { 3, 4, 4, 6, 1, 4, 4 }, new int[] { 3, 2, 2, 4, 2 })] [TestCase(1, new int[] { 1 }, new int[] { 1 })] [TestCase(4, new int[] { 1, 2, 3, 4, 5 }, new int[] { 1, 1, 1, 1 })] [TestCase(4, new int[] { 5, 4, 3, 2, 1 }, new int[] { 1, 1, 1, 1 })] [TestCase(4, new int[] { 5, 4, 3, 2, 1, 5 }, new int[] { 1, 1, 1, 1 })] [TestCase(4, new int[] { 1, 5, 4, 3, 2, 1, 5 }, new int[] { 2, 2, 2, 2 })] [TestCase(4, new int[] { 1, 5, 4, 3, 2, 1, 1, 1, 5 }, new int[] { 4, 4, 4, 4 })] [TestCase(4, new int[] { 1, 5, 4, 3, 2, 1, 1, 1 }, new int[] { 4, 2, 2, 2 })] public void TestMaxCountersWithSuccess(int n, int[] array, int[] expectedResult) { var result = CountingElements.solutionMaxCounters(n, array); Assert.IsTrue(result.Length == expectedResult.Length); for (int i = 0; i < expectedResult.Length; i++) { Assert.IsTrue(result[i] == expectedResult[i]); } } #endregion #region Prefix Sums [TestCase(6, 11, 2, 3)] [TestCase(0, 0, 11, 1)] // A = B = 0, K = 11 => 1 [TestCase(0, 1, 11, 1)] // A = 0, B = 1, K = 11 => 1 [TestCase(1, 1, 11, 0)] // A = B = 1, K = 11 => 0 [TestCase(10, 10, 5, 1)] [TestCase(11, 345, 17, 20)] //A = 11, B = 345, K = 17 => 20 [TestCase(10, 10, 5, 1)] //A = 10, B = 10, K in {5,7,20} => 1 [TestCase(10, 10, 7, 0)] //A = 10, B = 10, K in {5,7,20} => 0 [TestCase(10, 10, 20, 0)] //A = 10, B = 10, K in {5,7,20} => 0 [TestCase(101, 123000000, 10000, 12300)] //A = 101, B = 123M+, K = 10K => 12300 [TestCase(0, 2000000000, 1, 2000000001)] //A = 0, B = MAXINT, K = 1 => 2000000001 [TestCase(0, 2000000000, 2000000000, 2)] //A = 0, B = MAXINT, K = MAXINT => 2 public void TestCountDivWithSuccess(int a, int b, int k, int expectedResult) { var result = PerfixSums.solutionCountDiv(a, b, k); Assert.IsTrue(result == expectedResult); } [TestCase(new int[] { 0, 1, 0, 1, 1 }, 5)] // A = B = 0, K = 11 => 1 [TestCase(new int[] { 0, 1, 0, 1, 1, 0, 1 }, 8)] [TestCase(new int[] { 0 }, 0)] [TestCase(new int[] { 1, 0 }, 0)] [TestCase(new int[] { 0, 1 }, 1)] public void TestPassingCarsWithSuccess(int[] a, int expectedResult) { var result = PerfixSums.solutionPassingCars(a); Assert.IsTrue(result == expectedResult); } [TestCase("CAGCCTA", new int[] { 2, 5, 0 }, new int[] { 4, 5, 6 }, new int[] { 2, 4, 1 })] // A = B = 0, K = 11 => 1 [TestCase("A", new int[] { 0 }, new int[] { 0 }, new int[] { 1 })] // A = B = 0, K = 11 => 1 public void TestGenomicRangeQueryWithSuccess(string s, int[] p, int[] q, int[] expectedResult) { var result = PerfixSums.solutionGenomicRangeQuery(s, p, q); Assert.IsTrue(result.Length == expectedResult.Length); for (int i = 0; i < result.Length; i++) { Assert.IsTrue(result[i] == expectedResult[i]); } } [TestCase(new int[] { 4, 2, 2, 5, 1, 5, 8 }, 1)] [TestCase(new int[] { -3, -5, -8, -4, -10 }, 2)] public void TestMinAvgTwoSlicesWithSuccess(int[] a, int expectedResult) { var result = PerfixSums.solutionMinAvgTwoSlice(a); Assert.IsTrue(result == expectedResult); } #endregion #region Sorting [TestCase(new int[] { }, 0)] [TestCase(new int[] { 2, 1, 1, 2, 3, 1 }, 3)] [TestCase(new int[] { -2, 1, -1, 2, 3, 1 }, 5)] public void TestSortingDistinctWithSuccess(int[] a, int expectedResult) { var result = Sorting.Distinct(a); Assert.IsTrue(result == expectedResult); } [TestCase(new int[] { -50, -20, 1, 2, 3 }, 3000)] [TestCase(new int[] { -1, 1, 1 }, -1)] [TestCase(new int[] { 0, 0, 0 }, 0)] [TestCase(new int[] { -3, 1, 2, -2, 5, 6 }, 60)] public void TestSortingMaxProductOfThreeWithSuccess(int[] a, int expectedResult) { var result = Sorting.MaxProductOfThree(a); Assert.IsTrue(result == expectedResult); } [TestCase(new int[] { 10, 2, 5, 1, 8, 20 }, 1)] [TestCase(new int[] { 10, 50, 5 }, 0)] [TestCase(new int[] { 10, 50, 5, 1 }, 0)] [TestCase(new int[] { 1, 1, 1 }, 1)] [TestCase(new int[] { int.MaxValue-2, int.MaxValue-1, int.MaxValue }, 1)] public void TestSortingTriangleWithSuccess(int[] a, int expectedResult) { var result = Sorting.Triangle(a); Assert.IsTrue(result == expectedResult); } [TestCase(new int[] { 1, 5, 2, 1, 4, 0 }, 11)] [TestCase(new int[] { 1, int.MaxValue, 2, 1, 4, 0 }, 11)] public void TestSortingNumberOfDiscIntersectionsWithSuccess(int[] a, int expectedResult) { var result = Sorting.NumberOfDiscIntersections(a); Assert.IsTrue(result == expectedResult); } #endregion #region Stacks and Queues [TestCase("abcd", 'd')] [TestCase("", '\0')] public void TestStacksPopWithSuccess(string s, char expectedResult) { var result = StacksQueues.StackPop(ref s); Assert.IsTrue(result == expectedResult); } [TestCase("abcd", 'e', "abcde", 4)] [TestCase("", 'a', "a", 0)] public void TestStacksPushWithSuccess(string s, char c, string expectedResult, int expectedIndex) { var result = StacksQueues.StackPush(ref s, c); Assert.IsTrue(expectedIndex.Equals(result)); Assert.IsTrue(expectedResult.Equals(s)); } [TestCase("abcd", 'a')] [TestCase("", '\0')] public void TestQueuesPopWithSuccess(string s, char expectedResult) { var result = StacksQueues.QueuePop(ref s); Assert.IsTrue(result == expectedResult); } [TestCase("bcd", 'a', "abcd", 0)] [TestCase("", 'a', "a", 0)] public void TestQueuesPushWithSuccess(string s, char c, string expectedResult, int expectedIndex) { var result = StacksQueues.QueuePush(ref s, c); Assert.IsTrue(expectedIndex.Equals(result)); Assert.IsTrue(expectedResult.Equals(s)); } [TestCase("(()())()", 1)] [TestCase("{{({}[]{})}}[]{}", 1)] [TestCase("({{({}[]{})}}[]{})", 1)] [TestCase("()()()", 1)] [TestCase("", 1)] [TestCase("{[()()]}", 1)] [TestCase("([)()]", 0)] [TestCase("([)()", 0)] public void TestStacksQueuesBracketsWithSuccess(string s, int expectedResult) { var result = StacksQueues.Brackets(s); Assert.IsTrue(result == expectedResult); } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V10.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>AccountBudget</c> resource.</summary> public sealed partial class AccountBudgetName : gax::IResourceName, sys::IEquatable<AccountBudgetName> { /// <summary>The possible contents of <see cref="AccountBudgetName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>. /// </summary> CustomerAccountBudget = 1, } private static gax::PathTemplate s_customerAccountBudget = new gax::PathTemplate("customers/{customer_id}/accountBudgets/{account_budget_id}"); /// <summary>Creates a <see cref="AccountBudgetName"/> 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="AccountBudgetName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AccountBudgetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AccountBudgetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AccountBudgetName"/> with the pattern /// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="accountBudgetId">The <c>AccountBudget</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AccountBudgetName"/> constructed from the provided ids.</returns> public static AccountBudgetName FromCustomerAccountBudget(string customerId, string accountBudgetId) => new AccountBudgetName(ResourceNameType.CustomerAccountBudget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), accountBudgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountBudgetId, nameof(accountBudgetId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AccountBudgetName"/> with pattern /// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="accountBudgetId">The <c>AccountBudget</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AccountBudgetName"/> with pattern /// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>. /// </returns> public static string Format(string customerId, string accountBudgetId) => FormatCustomerAccountBudget(customerId, accountBudgetId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AccountBudgetName"/> with pattern /// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="accountBudgetId">The <c>AccountBudget</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AccountBudgetName"/> with pattern /// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c>. /// </returns> public static string FormatCustomerAccountBudget(string customerId, string accountBudgetId) => s_customerAccountBudget.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(accountBudgetId, nameof(accountBudgetId))); /// <summary> /// Parses the given resource name string into a new <see cref="AccountBudgetName"/> 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}/accountBudgets/{account_budget_id}</c></description></item> /// </list> /// </remarks> /// <param name="accountBudgetName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AccountBudgetName"/> if successful.</returns> public static AccountBudgetName Parse(string accountBudgetName) => Parse(accountBudgetName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AccountBudgetName"/> 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}/accountBudgets/{account_budget_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="accountBudgetName">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="AccountBudgetName"/> if successful.</returns> public static AccountBudgetName Parse(string accountBudgetName, bool allowUnparsed) => TryParse(accountBudgetName, allowUnparsed, out AccountBudgetName 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="AccountBudgetName"/> 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}/accountBudgets/{account_budget_id}</c></description></item> /// </list> /// </remarks> /// <param name="accountBudgetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AccountBudgetName"/>, 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 accountBudgetName, out AccountBudgetName result) => TryParse(accountBudgetName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AccountBudgetName"/> 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}/accountBudgets/{account_budget_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="accountBudgetName">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="AccountBudgetName"/>, 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 accountBudgetName, bool allowUnparsed, out AccountBudgetName result) { gax::GaxPreconditions.CheckNotNull(accountBudgetName, nameof(accountBudgetName)); gax::TemplatedResourceName resourceName; if (s_customerAccountBudget.TryParseName(accountBudgetName, out resourceName)) { result = FromCustomerAccountBudget(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(accountBudgetName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private AccountBudgetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string accountBudgetId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AccountBudgetId = accountBudgetId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="AccountBudgetName"/> class from the component parts of pattern /// <c>customers/{customer_id}/accountBudgets/{account_budget_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="accountBudgetId">The <c>AccountBudget</c> ID. Must not be <c>null</c> or empty.</param> public AccountBudgetName(string customerId, string accountBudgetId) : this(ResourceNameType.CustomerAccountBudget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), accountBudgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(accountBudgetId, nameof(accountBudgetId))) { } /// <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>AccountBudget</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string AccountBudgetId { 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>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.CustomerAccountBudget: return s_customerAccountBudget.Expand(CustomerId, AccountBudgetId); 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 AccountBudgetName); /// <inheritdoc/> public bool Equals(AccountBudgetName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AccountBudgetName a, AccountBudgetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AccountBudgetName a, AccountBudgetName b) => !(a == b); } public partial class AccountBudget { /// <summary> /// <see cref="gagvr::AccountBudgetName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal AccountBudgetName ResourceNameAsAccountBudgetName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::AccountBudgetName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="BillingSetupName"/>-typed view over the <see cref="BillingSetup"/> resource name property. /// </summary> internal BillingSetupName BillingSetupAsBillingSetupName { get => string.IsNullOrEmpty(BillingSetup) ? null : BillingSetupName.Parse(BillingSetup, allowUnparsed: true); set => BillingSetup = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::AccountBudgetName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> internal AccountBudgetName AccountBudgetName { get => string.IsNullOrEmpty(Name) ? null : gagvr::AccountBudgetName.Parse(Name, allowUnparsed: true); set => Name = 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 Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { public partial class Process : IDisposable { private static readonly UTF8Encoding s_utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private static volatile bool s_sigchildHandlerRegistered = false; private static readonly object s_sigchildGate = new object(); private static readonly Interop.Sys.SigChldCallback s_sigChildHandler = OnSigChild; private static readonly ReaderWriterLockSlim s_processStartLock = new ReaderWriterLockSlim(); /// <summary> /// Puts a Process component in state to interact with operating system processes that run in a /// special mode by enabling the native property SeDebugPrivilege on the current thread. /// </summary> public static void EnterDebugMode() { // Nop. } /// <summary> /// Takes a Process component out of the state that lets it interact with operating system processes /// that run in a special mode. /// </summary> public static void LeaveDebugMode() { // Nop. } [CLSCompliant(false)] public static Process Start(string fileName, string userName, SecureString password, string domain) { throw new PlatformNotSupportedException(SR.ProcessStartWithPasswordAndDomainNotSupported); } [CLSCompliant(false)] public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain) { throw new PlatformNotSupportedException(SR.ProcessStartWithPasswordAndDomainNotSupported); } /// <summary>Stops the associated process immediately.</summary> public void Kill() { EnsureState(State.HaveNonExitedId); if (Interop.Sys.Kill(_processId, Interop.Sys.Signals.SIGKILL) != 0) { throw new Win32Exception(); // same exception as on Windows } } /// <summary>Discards any information about the associated process.</summary> private void RefreshCore() { // Nop. No additional state to reset. } /// <summary>Additional logic invoked when the Process is closed.</summary> private void CloseCore() { if (_waitStateHolder != null) { _waitStateHolder.Dispose(); _waitStateHolder = null; } } /// <summary>Additional configuration when a process ID is set.</summary> partial void ConfigureAfterProcessIdSet() { // Make sure that we configure the wait state holder for this process object, which we can only do once we have a process ID. Debug.Assert(_haveProcessId, $"{nameof(ConfigureAfterProcessIdSet)} should only be called once a process ID is set"); // Initialize WaitStateHolder for non-child processes GetWaitState(); } /// <devdoc> /// Make sure we are watching for a process exit. /// </devdoc> /// <internalonly/> private void EnsureWatchingForExit() { if (!_watchingForExit) { lock (this) { if (!_watchingForExit) { Debug.Assert(_haveProcessHandle, "Process.EnsureWatchingForExit called with no process handle"); Debug.Assert(Associated, "Process.EnsureWatchingForExit called with no associated process"); _watchingForExit = true; try { _waitHandle = new ProcessWaitHandle(GetWaitState()); _registeredWaitHandle = ThreadPool.RegisterWaitForSingleObject(_waitHandle, new WaitOrTimerCallback(CompletionCallback), _waitHandle, -1, true); } catch { _waitHandle?.Dispose(); _waitHandle = null; _watchingForExit = false; throw; } } } } } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. /// </summary> private bool WaitForExitCore(int milliseconds) { bool exited = GetWaitState().WaitForExit(milliseconds); Debug.Assert(exited || milliseconds != Timeout.Infinite); if (exited && milliseconds == Timeout.Infinite) // if we have a hard timeout, we cannot wait for the streams { if (_output != null) { _output.WaitUtilEOF(); } if (_error != null) { _error.WaitUtilEOF(); } } return exited; } /// <summary>Gets the main module for the associated process.</summary> public ProcessModule MainModule { get { ProcessModuleCollection pmc = Modules; return pmc.Count > 0 ? pmc[0] : null; } } /// <summary>Checks whether the process has exited and updates state accordingly.</summary> private void UpdateHasExited() { int? exitCode; _exited = GetWaitState().GetExited(out exitCode, refresh: true); if (_exited && exitCode != null) { _exitCode = exitCode.Value; } } /// <summary>Gets the time that the associated process exited.</summary> private DateTime ExitTimeCore { get { return GetWaitState().ExitTime; } } /// <summary> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </summary> private bool PriorityBoostEnabledCore { get { return false; } //Nop set { } // Nop } /// <summary> /// Gets or sets the overall priority category for the associated process. /// </summary> private ProcessPriorityClass PriorityClassCore { // This mapping is relatively arbitrary. 0 is normal based on the man page, // and the other values above and below are simply distributed evenly. get { EnsureState(State.HaveNonExitedId); int pri = 0; int errno = Interop.Sys.GetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, out pri); if (errno != 0) // Interop.Sys.GetPriority returns GetLastWin32Error() { throw new Win32Exception(errno); // match Windows exception } Debug.Assert(pri >= -20 && pri <= 20); return pri < -15 ? ProcessPriorityClass.RealTime : pri < -10 ? ProcessPriorityClass.High : pri < -5 ? ProcessPriorityClass.AboveNormal : pri == 0 ? ProcessPriorityClass.Normal : pri <= 10 ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Idle; } set { EnsureState(State.HaveNonExitedId); int pri = 0; // Normal switch (value) { case ProcessPriorityClass.RealTime: pri = -19; break; case ProcessPriorityClass.High: pri = -11; break; case ProcessPriorityClass.AboveNormal: pri = -6; break; case ProcessPriorityClass.BelowNormal: pri = 10; break; case ProcessPriorityClass.Idle: pri = 19; break; default: Debug.Assert(value == ProcessPriorityClass.Normal, "Input should have been validated by caller"); break; } int result = Interop.Sys.SetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, pri); if (result == -1) { throw new Win32Exception(); // match Windows exception } } } /// <summary>Gets the ID of the current process.</summary> private static int GetCurrentProcessId() { return Interop.Sys.GetPid(); } partial void ThrowIfExited(bool refresh) { // Don't allocate a ProcessWaitState.Holder unless we're refreshing. if (_waitStateHolder == null && !refresh) { return; } if (GetWaitState().GetExited(out _, refresh)) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString())); } } /// <summary> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle GetProcessHandle() { if (_haveProcessHandle) { ThrowIfExited(refresh: true); return _processHandle; } EnsureState(State.HaveNonExitedId | State.IsLocal); return new SafeProcessHandle(_processId); } /// <summary> /// Starts the process using the supplied start info. /// With UseShellExecute option, we'll try the shell tools to launch it(e.g. "open fileName") /// </summary> /// <param name="startInfo">The start info with which to start the process.</param> private bool StartCore(ProcessStartInfo startInfo) { EnsureSigChildHandler(); string filename; string[] argv; if (startInfo.UseShellExecute) { if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.CantRedirectStreams); } } int childPid, stdinFd, stdoutFd, stderrFd; string[] envp = CreateEnvp(startInfo); string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null; if (startInfo.UseShellExecute) { // use default program to open file/url filename = GetPathToOpenFile(); argv = ParseArgv(startInfo, filename); } else { filename = ResolvePath(startInfo.FileName); argv = ParseArgv(startInfo); if (Directory.Exists(filename)) { throw new Win32Exception(SR.DirectoryNotValidAsInput); } } if (string.IsNullOrEmpty(filename)) { throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno); } bool setCredentials = !string.IsNullOrEmpty(startInfo.UserName); uint userId = 0; uint groupId = 0; if (setCredentials) { (userId, groupId) = GetUserAndGroupIds(startInfo); } // Lock to avoid races with OnSigChild // By using a ReaderWriterLock we allow multiple processes to start concurrently. s_processStartLock.EnterReadLock(); try { // Invoke the shim fork/execve routine. It will create pipes for all requested // redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr // descriptors, and execve to execute the requested process. The shim implementation // is used to fork/execve as executing managed code in a forked process is not safe (only // the calling thread will transfer, thread IDs aren't stable across the fork, etc.) Interop.Sys.ForkAndExecProcess( filename, argv, envp, cwd, startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError, setCredentials, userId, groupId, out childPid, out stdinFd, out stdoutFd, out stderrFd); // Ensure we'll reap this process. // note: SetProcessId will set this if we don't set it first. _waitStateHolder = new ProcessWaitState.Holder(childPid, isNewChild: true); // Store the child's information into this Process object. Debug.Assert(childPid >= 0); SetProcessId(childPid); SetProcessHandle(new SafeProcessHandle(childPid)); } finally { s_processStartLock.ExitReadLock(); } // Configure the parent's ends of the redirection streams. // We use UTF8 encoding without BOM by-default(instead of Console encoding as on Windows) // as there is no good way to get this information from the native layer // and we do not want to take dependency on Console contract. if (startInfo.RedirectStandardInput) { Debug.Assert(stdinFd >= 0); _standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write), startInfo.StandardInputEncoding ?? s_utf8NoBom, StreamBufferSize) { AutoFlush = true }; } if (startInfo.RedirectStandardOutput) { Debug.Assert(stdoutFd >= 0); _standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read), startInfo.StandardOutputEncoding ?? s_utf8NoBom, true, StreamBufferSize); } if (startInfo.RedirectStandardError) { Debug.Assert(stderrFd >= 0); _standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read), startInfo.StandardErrorEncoding ?? s_utf8NoBom, true, StreamBufferSize); } return true; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary>Finalizable holder for the underlying shared wait state object.</summary> private ProcessWaitState.Holder _waitStateHolder; /// <summary>Size to use for redirect streams and stream readers/writers.</summary> private const int StreamBufferSize = 4096; /// <summary>Converts the filename and arguments information from a ProcessStartInfo into an argv array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <param name="alternativePath">alternative resolved path to use as first argument</param> /// <returns>The argv array.</returns> private static string[] ParseArgv(ProcessStartInfo psi, string alternativePath = null) { string argv0 = psi.FileName; // when no alternative path exists, pass filename (instead of resolved path) as argv[0], to match what caller supplied if (string.IsNullOrEmpty(psi.Arguments) && string.IsNullOrEmpty(alternativePath) && psi.ArgumentList.Count == 0) { return new string[] { argv0 }; } var argvList = new List<string>(); if (!string.IsNullOrEmpty(alternativePath)) { argvList.Add(alternativePath); if (alternativePath.Contains("kfmclient")) { argvList.Add("openURL"); // kfmclient needs OpenURL } } argvList.Add(argv0); if (!string.IsNullOrEmpty(psi.Arguments)) { ParseArgumentsIntoList(psi.Arguments, argvList); } else { argvList.AddRange(psi.ArgumentList); } return argvList.ToArray(); } /// <summary>Converts the environment variables information from a ProcessStartInfo into an envp array.</summary> /// <param name="psi">The ProcessStartInfo.</param> /// <returns>The envp array.</returns> private static string[] CreateEnvp(ProcessStartInfo psi) { var envp = new string[psi.Environment.Count]; int index = 0; foreach (var pair in psi.Environment) { envp[index++] = pair.Key + "=" + pair.Value; } return envp; } /// <summary>Resolves a path to the filename passed to ProcessStartInfo. </summary> /// <param name="filename">The filename.</param> /// <returns>The resolved path. It can return null in case of URLs.</returns> private static string ResolvePath(string filename) { // Follow the same resolution that Windows uses with CreateProcess: // 1. First try the exact path provided // 2. Then try the file relative to the executable directory // 3. Then try the file relative to the current directory // 4. then try the file in each of the directories specified in PATH // Windows does additional Windows-specific steps between 3 and 4, // and we ignore those here. // If the filename is a complete path, use it, regardless of whether it exists. if (Path.IsPathRooted(filename)) { // In this case, it doesn't matter whether the file exists or not; // it's what the caller asked for, so it's what they'll get return filename; } // Then check the executable's directory string path = GetExePath(); if (path != null) { try { path = Path.Combine(Path.GetDirectoryName(path), filename); if (File.Exists(path)) { return path; } } catch (ArgumentException) { } // ignore any errors in data that may come from the exe path } // Then check the current directory path = Path.Combine(Directory.GetCurrentDirectory(), filename); if (File.Exists(path)) { return path; } // Then check each directory listed in the PATH environment variables return FindProgramInPath(filename); } /// <summary> /// Gets the path to the program /// </summary> /// <param name="program"></param> /// <returns></returns> private static string FindProgramInPath(string program) { string path; string pathEnvVar = Environment.GetEnvironmentVariable("PATH"); if (pathEnvVar != null) { var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true); while (pathParser.MoveNext()) { string subPath = pathParser.ExtractCurrent(); path = Path.Combine(subPath, program); if (File.Exists(path)) { return path; } } } return null; } /// <summary>Convert a number of "jiffies", or ticks, to a TimeSpan.</summary> /// <param name="ticks">The number of ticks.</param> /// <returns>The equivalent TimeSpan.</returns> internal static TimeSpan TicksToTimeSpan(double ticks) { // Look up the number of ticks per second in the system's configuration, // then use that to convert to a TimeSpan long ticksPerSecond = Interop.Sys.SysConf(Interop.Sys.SysConfName._SC_CLK_TCK); if (ticksPerSecond <= 0) { throw new Win32Exception(); } return TimeSpan.FromSeconds(ticks / (double)ticksPerSecond); } /// <summary>Opens a stream around the specified file descriptor and with the specified access.</summary> /// <param name="fd">The file descriptor.</param> /// <param name="access">The access mode.</param> /// <returns>The opened stream.</returns> private static FileStream OpenStream(int fd, FileAccess access) { Debug.Assert(fd >= 0); return new FileStream( new SafeFileHandle((IntPtr)fd, ownsHandle: true), access, StreamBufferSize, isAsync: false); } /// <summary>Parses a command-line argument string into a list of arguments.</summary> /// <param name="arguments">The argument string.</param> /// <param name="results">The list into which the component arguments should be stored.</param> /// <remarks> /// This follows the rules outlined in "Parsing C++ Command-Line Arguments" at /// https://msdn.microsoft.com/en-us/library/17w5ykft.aspx. /// </remarks> private static void ParseArgumentsIntoList(string arguments, List<string> results) { // Iterate through all of the characters in the argument string. for (int i = 0; i < arguments.Length; i++) { while (i < arguments.Length && (arguments[i] == ' ' || arguments[i] == '\t')) i++; if (i == arguments.Length) break; results.Add(GetNextArgument(arguments, ref i)); } } private static string GetNextArgument(string arguments, ref int i) { var currentArgument = StringBuilderCache.Acquire(); bool inQuotes = false; while (i < arguments.Length) { // From the current position, iterate through contiguous backslashes. int backslashCount = 0; while (i < arguments.Length && arguments[i] == '\\') { i++; backslashCount++; } if (backslashCount > 0) { if (i >= arguments.Length || arguments[i] != '"') { // Backslashes not followed by a double quote: // they should all be treated as literal backslashes. currentArgument.Append('\\', backslashCount); } else { // Backslashes followed by a double quote: // - Output a literal slash for each complete pair of slashes // - If one remains, use it to make the subsequent quote a literal. currentArgument.Append('\\', backslashCount / 2); if (backslashCount % 2 != 0) { currentArgument.Append('"'); i++; } } continue; } char c = arguments[i]; // If this is a double quote, track whether we're inside of quotes or not. // Anything within quotes will be treated as a single argument, even if // it contains spaces. if (c == '"') { if (inQuotes && i < arguments.Length - 1 && arguments[i + 1] == '"') { // Two consecutive double quotes inside an inQuotes region should result in a literal double quote // (the parser is left in the inQuotes region). // This behavior is not part of the spec of code:ParseArgumentsIntoList, but is compatible with CRT // and .NET Framework. currentArgument.Append('"'); i++; } else { inQuotes = !inQuotes; } i++; continue; } // If this is a space/tab and we're not in quotes, we're done with the current // argument, it should be added to the results and then reset for the next one. if ((c == ' ' || c == '\t') && !inQuotes) { break; } // Nothing special; add the character to the current argument. currentArgument.Append(c); i++; } return StringBuilderCache.GetStringAndRelease(currentArgument); } /// <summary>Gets the wait state for this Process object.</summary> private ProcessWaitState GetWaitState() { if (_waitStateHolder == null) { EnsureState(State.HaveId); _waitStateHolder = new ProcessWaitState.Holder(_processId); } return _waitStateHolder._state; } private static (uint userId, uint groupId) GetUserAndGroupIds(ProcessStartInfo startInfo) { Debug.Assert(!string.IsNullOrEmpty(startInfo.UserName)); (uint? userId, uint? groupId) = GetUserAndGroupIds(startInfo.UserName); Debug.Assert(userId.HasValue == groupId.HasValue, "userId and groupId both need to have values, or both need to be null."); if (!userId.HasValue) { throw new Win32Exception(SR.Format(SR.UserDoesNotExist, startInfo.UserName)); } return (userId.Value, groupId.Value); } private unsafe static (uint? userId, uint? groupId) GetUserAndGroupIds(string userName) { Interop.Sys.Passwd? passwd; // First try with a buffer that should suffice for 99% of cases. // Note: on CentOS/RedHat 7.1 systems, getpwnam_r returns 'user not found' if the buffer is too small // see https://bugs.centos.org/view.php?id=7324 const int BufLen = Interop.Sys.Passwd.InitialBufferSize; byte* stackBuf = stackalloc byte[BufLen]; if (TryGetPasswd(userName, stackBuf, BufLen, out passwd)) { if (passwd == null) { return (null, null); } return (passwd.Value.UserId, passwd.Value.GroupId); } // Fallback to heap allocations if necessary, growing the buffer until // we succeed. TryGetPasswd will throw if there's an unexpected error. int lastBufLen = BufLen; while (true) { lastBufLen *= 2; byte[] heapBuf = new byte[lastBufLen]; fixed (byte* buf = &heapBuf[0]) { if (TryGetPasswd(userName, buf, heapBuf.Length, out passwd)) { if (passwd == null) { return (null, null); } return (passwd.Value.UserId, passwd.Value.GroupId); } } } } private static unsafe bool TryGetPasswd(string name, byte* buf, int bufLen, out Interop.Sys.Passwd? passwd) { // Call getpwnam_r to get the passwd struct Interop.Sys.Passwd tempPasswd; int error = Interop.Sys.GetPwNamR(name, out tempPasswd, buf, bufLen); // If the call succeeds, give back the passwd retrieved if (error == 0) { passwd = tempPasswd; return true; } // If the current user's entry could not be found, give back null, // but still return true as false indicates the buffer was too small. if (error == -1) { passwd = null; return true; } var errorInfo = new Interop.ErrorInfo(error); // If the call failed because the buffer was too small, return false to // indicate the caller should try again with a larger buffer. if (errorInfo.Error == Interop.Error.ERANGE) { passwd = null; return false; } // Otherwise, fail. throw new Win32Exception(errorInfo.RawErrno, errorInfo.GetErrorMessage()); } public IntPtr MainWindowHandle => IntPtr.Zero; private bool CloseMainWindowCore() => false; public string MainWindowTitle => string.Empty; public bool Responding => true; private bool WaitForInputIdleCore(int milliseconds) => throw new InvalidOperationException(SR.InputIdleUnkownError); private static void EnsureSigChildHandler() { if (s_sigchildHandlerRegistered) { return; } lock (s_sigchildGate) { if (!s_sigchildHandlerRegistered) { // Ensure signal handling is setup and register our callback. if (!Interop.Sys.RegisterForSigChld(s_sigChildHandler)) { throw new Win32Exception(); } s_sigchildHandlerRegistered = true; } } } private static void OnSigChild(bool reapAll) { // Lock to avoid races with Process.Start s_processStartLock.EnterWriteLock(); try { ProcessWaitState.CheckChildren(reapAll); } finally { s_processStartLock.ExitWriteLock(); } } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlTypes; public partial class Backoffice_RawatInap_RIAddRJ : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["RegistrasiRI"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>"; btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>"; if (Request.QueryString["RawatJalanId"] != null && Request.QueryString["RawatJalanId"].ToString() != "") { divSearch.Visible = false; divDataPasien.Visible = true; txtRawatJalanId.Text = Request.QueryString["RawatJalanId"].ToString(); UpdateDataPasien(Int64.Parse(txtRawatJalanId.Text)); } else { divSearch.Visible = true; divDataPasien.Visible = true; } txtTanggalMasuk.Text = DateTime.Now.ToString("dd/MM/yyyy"); txtJamMasuk.Text = DateTime.Now.ToString("HH:mm"); GetNomorRegistrasi(); GetListKelas(); } } #region "Function List" public void GetListKelas() { string KelasId = ""; if (Request.QueryString["KelasId"] != null) KelasId = Request.QueryString["KelasId"].ToString(); SIMRS.DataAccess.RS_Kelas myObj = new SIMRS.DataAccess.RS_Kelas(); DataTable dt = myObj.GetListAvaliable(); cmbKelas.Items.Clear(); int i = 0; cmbKelas.Items.Add(""); cmbKelas.Items[i].Text = ""; cmbKelas.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbKelas.Items.Add(""); cmbKelas.Items[i].Text = dr["KelasNama"].ToString(); cmbKelas.Items[i].Value = dr["KelasId"].ToString(); if (dr["KelasId"].ToString() == KelasId) { cmbKelas.SelectedIndex = i; } i++; } GetListRuang(); } public void GetListRuang() { string RuangId = ""; if (Request.QueryString["RuangId"] != null) RuangId = Request.QueryString["RuangId"].ToString(); int KelasId = 0; if (cmbKelas.SelectedIndex > 0) KelasId = int.Parse(cmbKelas.SelectedItem.Value); SIMRS.DataAccess.RS_Ruang myObj = new SIMRS.DataAccess.RS_Ruang(); DataTable dt = myObj.GetListAvaliableByKelasId(KelasId); cmbRuang.Items.Clear(); int i = 0; cmbRuang.Items.Add(""); cmbRuang.Items[i].Text = ""; cmbRuang.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbRuang.Items.Add(""); cmbRuang.Items[i].Text = dr["RuangNama"].ToString(); cmbRuang.Items[i].Value = dr["RuangId"].ToString(); if (dr["RuangId"].ToString() == RuangId) { cmbRuang.SelectedIndex = i; } i++; } GetListNomorRuang(); } public void GetListNomorRuang() { string RuangRawatId = ""; if (Request.QueryString["RuangRawatId"] != null) RuangRawatId = Request.QueryString["RuangRawatId"].ToString(); SIMRS.DataAccess.RS_RuangRawat myObj = new SIMRS.DataAccess.RS_RuangRawat(); if (cmbKelas.SelectedIndex > 0) myObj.KelasId = int.Parse(cmbKelas.SelectedItem.Value); if (cmbRuang.SelectedIndex > 0) myObj.RuangId = int.Parse(cmbRuang.SelectedItem.Value); DataTable dt = myObj.GetListAvaliableNomorRuang(); cmbNomorRuang.Items.Clear(); int i = 0; cmbNomorRuang.Items.Add(""); cmbNomorRuang.Items[i].Text = ""; cmbNomorRuang.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbNomorRuang.Items.Add(""); cmbNomorRuang.Items[i].Text = dr["NomorRuang"].ToString(); cmbNomorRuang.Items[i].Value = dr["RuangRawatId"].ToString(); if (dr["RuangRawatId"].ToString() == RuangRawatId) { cmbNomorRuang.SelectedIndex = i; } i++; } GetListNomorTempat(); } public void GetListNomorTempat() { string TempatTidurId = ""; if (Request.QueryString["TempatTidurId"] != null) TempatTidurId = Request.QueryString["TempatTidurId"].ToString(); SIMRS.DataAccess.RS_TempatTidur myObj = new SIMRS.DataAccess.RS_TempatTidur(); if(cmbNomorRuang.SelectedIndex > 0) myObj.RuangRawatId = int.Parse(cmbNomorRuang.SelectedItem.Value); DataTable dt = myObj.GetListAvaliableByRawatId(); cmbNomorTempat.Items.Clear(); int i = 0; cmbNomorTempat.Items.Add(""); cmbNomorTempat.Items[i].Text = ""; cmbNomorTempat.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbNomorTempat.Items.Add(""); cmbNomorTempat.Items[i].Text = dr["NomorTempat"].ToString(); cmbNomorTempat.Items[i].Value = dr["TempatTidurId"].ToString(); if (dr["TempatTidurId"].ToString() == TempatTidurId) { cmbNomorTempat.SelectedIndex = i; } i++; } } public void GetNomorRegistrasi() { if (txtTanggalMasuk.Text.IndexOf("_") == -1) { SIMRS.DataAccess.RS_RawatInap myObj = new SIMRS.DataAccess.RS_RawatInap(); myObj.TanggalMasuk = DateTime.Parse(txtTanggalMasuk.Text); txtNoRegistrasi.Text = myObj.GetNomorRegistrasi(); } } public void GetListDokter(string DokterId) { SIMRS.DataAccess.RS_Dokter myObj = new SIMRS.DataAccess.RS_Dokter(); DataTable dt = myObj.GetList(); cmbDokter.Items.Clear(); int i = 0; cmbDokter.Items.Add(""); cmbDokter.Items[i].Text = ""; cmbDokter.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbDokter.Items.Add(""); cmbDokter.Items[i].Text = dr["Nama"].ToString() + " [" + dr["SpesialisNama"].ToString() + "]"; cmbDokter.Items[i].Value = dr["DokterId"].ToString(); if (dr["DokterId"].ToString() == DokterId) cmbDokter.SelectedIndex = i; i++; } } #endregion public void OnSave(Object sender, EventArgs e) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (!Page.IsValid) { return; } int PenjaminId = 0; if (lblPenjaminId.Text != "0") { //Input Data Penjamin SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin(); myPenj.PenjaminId = int.Parse(lblPenjaminId.Text); myPenj.SelectOne(); myPenj.PenjaminId = 0; myPenj.CreatedBy = UserId; myPenj.CreatedDate = DateTime.Now; myPenj.ModifiedBy = SqlInt32.Null; myPenj.ModifiedDate = SqlDateTime.Null; myPenj.Insert(); PenjaminId = (int)myPenj.PenjaminId; } //Input Data Registrasi SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.RegistrasiId = 0; myReg.PasienId = Int64.Parse(txtPasienId.Text); GetNomorRegistrasi(); myReg.NoRegistrasi = txtNoRegistrasi.Text; myReg.JenisRegistrasiId = 2;//Rawat Inap DateTime TanggalMasuk = DateTime.Parse(txtTanggalMasuk.Text); TanggalMasuk = TanggalMasuk.AddHours(double.Parse(txtJamMasuk.Text.Substring(0, 2))); TanggalMasuk = TanggalMasuk.AddMinutes(double.Parse(txtJamMasuk.Text.Substring(3, 2))); myReg.TanggalRegistrasi = TanggalMasuk; myReg.JenisPenjaminId = int.Parse(lblJenisPenjaminId.Text); if (PenjaminId != 0) myReg.PenjaminId = PenjaminId; myReg.CreatedBy = UserId; myReg.CreatedDate = DateTime.Now; myReg.Insert(); //Input Data Rawat Inap SIMRS.DataAccess.RS_RawatInap myRI = new SIMRS.DataAccess.RS_RawatInap(); myRI.RawatInapId = 0; myRI.RegistrasiId = myReg.RegistrasiId; myRI.TanggalMasuk = myReg.TanggalRegistrasi; myRI.AsalPasien = 1; //Dari Rawat Jalan myRI.DariPoliklinikId = int.Parse(lblDariPoliklinikId.Text); if (lblDariDokterId.Text != "") myRI.DariDokterId = int.Parse(lblDariDokterId.Text); if(cmbDokter.SelectedIndex > 0) myRI.DokterId = int.Parse(cmbDokter.SelectedItem.Value); myRI.DiagnosaMasuk = txtDiagnosaMasuk.Text; //if (txtDeposit.Text != "") // myRI.Deposit = decimal.Parse(txtDeposit.Text); myRI.Status = 0;//Baru daftar myRI.CreatedBy = UserId; myRI.CreatedDate = DateTime.Now; myRI.Insert(); //Input Data Tempat Inap SIMRS.DataAccess.RS_TempatInap myTempat = new SIMRS.DataAccess.RS_TempatInap(); myTempat.TempatInapId = 0; myTempat.RawatInapId = myRI.RawatInapId; myTempat.RuangRawatId = int.Parse(cmbNomorRuang.SelectedItem.Value); if (cmbNomorTempat.SelectedIndex > 0) myTempat.TempatTidurId = int.Parse(cmbNomorTempat.SelectedItem.Value); myTempat.TanggalMasuk = myReg.TanggalRegistrasi; myTempat.CreatedBy = UserId; myTempat.CreatedDate = DateTime.Now; myTempat.Insert(); string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect(Request.ApplicationPath+"/Backoffice/Registrasi/RIList.aspx?CurrentPage=" + CurrentPage); } public void OnCancel(Object sender, EventArgs e) { string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect(Request.ApplicationPath + "/Backoffice/Registrasi/RIList.aspx?CurrentPage=" + CurrentPage); } protected void btnSearch_Click(object sender, EventArgs e) { GetListPasien(); EmptyDataPasien(); } public DataView GetResultSearch() { DataSet ds = new DataSet(); DataTable myData = new DataTable(); SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.JenisPoliklinikId = 1;//RawatJalan if (txtTanggalRegistrasi.Text != "") myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); if (txtNoRMSearch.Text != "") myObj.NoRM = txtNoRMSearch.Text; if (txtNamaSearch.Text != "") myObj.Nama = txtNamaSearch.Text; if (txtNRPSearch.Text != "") myObj.NRP = txtNRPSearch.Text; myData = myObj.SelectAllFilterForRawatInap(); DataView dv = myData.DefaultView; return dv; } public void GetListPasien() { GridViewPasien.SelectedIndex = -1; // Re-binds the grid GridViewPasien.DataSource = GetResultSearch(); GridViewPasien.DataBind(); } protected void GridViewPasien_SelectedIndexChanged(object sender, EventArgs e) { Int64 RawatJalanId = (Int64)GridViewPasien.SelectedValue; UpdateDataPasien(RawatJalanId); } public void UpdateDataPasien(Int64 RawatJalanId) { if (RawatJalanId == 0) { EmptyDataPasien(); } else { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.RawatJalanId = RawatJalanId; DataTable dt = myObj.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtRawatJalanId.Text = RawatJalanId.ToString(); txtPasienId.Text = row["PasienId"].ToString(); lblNoRMHeader.Text = row["NoRM"].ToString(); lblNoRM.Text = row["NoRM"].ToString(); lblNamaPasienHeader.Text = row["Nama"].ToString(); lblNamaPasien.Text = row["Nama"].ToString(); lblStatus.Text = row["StatusNama"].ToString(); lblPangkat.Text = row["PangkatNama"].ToString(); lblNoAskes.Text = row["NoAskes"].ToString(); lblNoKTP.Text = row["NoKTP"].ToString(); lblGolDarah.Text = row["GolDarah"].ToString(); lblNRP.Text = row["NRP"].ToString(); lblKesatuan.Text = row["Kesatuan"].ToString(); lblTempatLahir.Text = row["TempatLahir"].ToString() == "" ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : row["TempatLahir"].ToString(); lblTanggalLahir.Text = row["TanggalLahir"].ToString() != "" ? ((DateTime)row["TanggalLahir"]).ToString("dd MMMM yyyy") : ""; lblAlamat.Text = row["Alamat"].ToString(); lblTelepon.Text = row["Telepon"].ToString(); lblJenisKelamin.Text = row["JenisKelamin"].ToString(); lblStatusPerkawinan.Text = row["StatusPerkawinanNama"].ToString(); lblAgama.Text = row["AgamaNama"].ToString(); lblPendidikan.Text = row["PendidikanNama"].ToString(); lblPekerjaan.Text = row["Pekerjaan"].ToString(); lblAlamatKantor.Text = row["AlamatKantor"].ToString(); lblTeleponKantor.Text = row["TeleponKantor"].ToString(); lblKeterangan.Text = row["Keterangan"].ToString(); //Data Registrasi lblNoRegistrasi.Text = row["NoRegistrasi"].ToString(); lblNoRegistrasiHeader.Text = lblNoRegistrasi.Text; lblTanggalBerobat.Text = row["TanggalBerobat"].ToString() != "" ? ((DateTime)row["TanggalBerobat"]).ToString("dd MMMM yyyy") : ""; lblPoliklinik.Text = row["PoliklinikNama"].ToString(); lblDokter.Text = row["DokterNama"].ToString(); lblNoTunggu.Text = row["NomorTunggu"].ToString(); lblJenisPenjaminNama.Text = row["JenisPenjaminNama"].ToString(); lblJenisPenjaminId.Text = row["JenisPenjaminId"].ToString(); lblPenjaminId.Text = row["PenjaminId"].ToString() != "" ? row["PenjaminId"].ToString() : "0"; if (lblJenisPenjaminId.Text == "2") { tblPenjaminKeluargaView.Visible = true; tblPenjaminPerusahaanView.Visible = false; //Data Keluarga Penjamin lblNamaPenjamin.Text = row["NamaPenjamin"].ToString(); lblHubunganNama.Text = row["HubunganNama"].ToString(); lblStatusPenjaminNama.Text = row["StatusNamaPenjamin"].ToString(); lblPangkatPenjaminNama.Text = row["PangkatNamaPenjamin"].ToString(); lblNoKTPPenjamin.Text = row["NoKTPPenjamin"].ToString(); lblGolDarahPenjamin.Text = row["GolDarahPenjamin"].ToString(); lblNRPPenjamin.Text = row["NRPPenjamin"].ToString(); lblKesatuanPenjamin.Text = row["KesatuanPenjamin"].ToString(); lblAlamatPenjamin.Text = row["AlamatPenjamin"].ToString(); lblTeleponPenjamin.Text = row["TeleponPenjamin"].ToString(); lblKeteranganPenjamin.Text = row["KeteranganPenjamin"].ToString(); } else if (lblJenisPenjaminId.Text == "3" || lblJenisPenjaminId.Text == "4") { tblPenjaminKeluargaView.Visible = false; tblPenjaminPerusahaanView.Visible = true; lblNamaPerusahan.Text = row["NamaPenjamin"].ToString(); lblNamaKontak.Text = row["NamaKontakPenjamin"].ToString(); lblAlamatPerusahaan.Text = row["AlamatPenjamin"].ToString(); lblTeleponPerusahaan.Text = row["TeleponPenjamin"].ToString(); lblFaxPerusahaan.Text = row["FaxPenjamin"].ToString(); lblKeteranganPerusahaan.Text = row["KeteranganPenjamin"].ToString(); } else { tblPenjaminKeluargaView.Visible = false; tblPenjaminPerusahaanView.Visible = false; } //Data Registrasi Rawat Jalan txtTanggalMasuk.Text = DateTime.Now.ToString("dd/MM/yyyy"); txtJamMasuk.Text = DateTime.Now.ToString("HH:mm"); GetNomorRegistrasi(); lblDariPoliklinik.Text = row["PoliklinikNama"].ToString(); lblDariPoliklinikId.Text = row["PoliklinikId"].ToString(); lblDariDokter.Text = row["DokterNama"].ToString(); lblDariDokterId.Text = row["DokterId"].ToString(); GetListDokter(lblDariDokterId.Text); } else { EmptyDataPasien(); } } } public void EmptyDataPasien() { txtRawatJalanId.Text = ""; txtPasienId.Text = ""; lblNoRMHeader.Text = ""; lblNoRM.Text = ""; lblNamaPasienHeader.Text = ""; lblNamaPasien.Text = ""; lblStatus.Text = ""; lblPangkat.Text = ""; lblNoAskes.Text = ""; lblNoKTP.Text = ""; lblGolDarah.Text = ""; lblNRP.Text = ""; lblKesatuan.Text = ""; lblTempatLahir.Text = ""; lblTanggalLahir.Text = ""; lblAlamat.Text = ""; lblTelepon.Text = ""; lblJenisKelamin.Text = ""; lblStatusPerkawinan.Text = ""; lblAgama.Text = ""; lblPendidikan.Text = ""; lblPekerjaan.Text = ""; lblAlamatKantor.Text = ""; lblTeleponKantor.Text = ""; lblKeterangan.Text = ""; //Data Registrasi lblNoRegistrasi.Text = ""; lblNoRegistrasiHeader.Text = ""; lblTanggalBerobat.Text = ""; lblPoliklinik.Text = ""; lblDokter.Text = ""; lblNoTunggu.Text = ""; lblJenisPenjaminNama.Text = ""; //Data Keluarga Penjamin lblPenjaminId.Text = ""; lblJenisPenjaminId.Text = ""; lblNamaPenjamin.Text = ""; lblHubunganNama.Text = ""; lblStatusPenjaminNama.Text = ""; lblPangkatPenjaminNama.Text = ""; lblNoKTPPenjamin.Text = ""; lblGolDarahPenjamin.Text = ""; lblNRPPenjamin.Text = ""; lblKesatuanPenjamin.Text = ""; lblAlamatPenjamin.Text = ""; lblTeleponPenjamin.Text = ""; lblKeteranganPenjamin.Text = ""; //Data Perusahaan Penjamin lblNamaPerusahan.Text = ""; lblNamaKontak.Text = ""; lblAlamatPerusahaan.Text = ""; lblTeleponPerusahaan.Text = ""; lblFaxPerusahaan.Text = ""; lblKeteranganPerusahaan.Text = ""; // Data Registrasi Rawat Jalan txtNoRegistrasi.Text = ""; txtTanggalMasuk.Text = ""; txtJamMasuk.Text = ""; lblDariPoliklinik.Text = ""; lblDariPoliklinikId.Text = ""; lblDariDokter.Text = ""; lblDariDokterId.Text = ""; GetListDokter(""); tblPenjaminKeluargaView.Visible = false; tblPenjaminPerusahaanView.Visible = false; } protected void GridViewPasien_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridViewPasien.SelectedIndex = -1; GridViewPasien.PageIndex = e.NewPageIndex; GridViewPasien.DataSource = GetResultSearch(); GridViewPasien.DataBind(); UpdateDataPasien(0); } protected void txtNamaSearch_TextChanged(object sender, EventArgs e) { GetListPasien(); EmptyDataPasien(); } protected void txtNRPSearch_TextChanged(object sender, EventArgs e) { GetListPasien(); EmptyDataPasien(); } protected void txtNoRMSearch_TextChanged(object sender, EventArgs e) { GetListPasien(); EmptyDataPasien(); } //protected void txtDeposit_TextChanged(object sender, EventArgs e) //{ // if (REVDeposit.IsValid && txtDeposit.Text != "") // { // if (txtDeposit.Text != "0") // txtDeposit.Text = (decimal.Parse(txtDeposit.Text)).ToString("#,###.###.###.###"); // } //} protected void txtTanggalMasuk_TextChanged(object sender, EventArgs e) { GetNomorRegistrasi(); } protected void cmbKelas_SelectedIndexChanged(object sender, EventArgs e) { GetListRuang(); } protected void cmbRuang_SelectedIndexChanged(object sender, EventArgs e) { GetListNomorRuang(); } protected void cmbNomorRuang_SelectedIndexChanged(object sender, EventArgs e) { GetListNomorTempat(); } }
//--------------------------------------------------------------------- // <copyright file="RelationshipEndCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.EntityModel.SchemaObjectModel { using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Metadata.Edm; using System.Diagnostics; /// <summary> /// A collection of RelationshipEnds /// </summary> internal sealed class RelationshipEndCollection : IList<IRelationshipEnd> { private Dictionary<string,IRelationshipEnd> _endLookup = null; private List<string> _keysInDefOrder = null; /// <summary> /// construct a RelationshipEndCollection /// </summary> public RelationshipEndCollection() { } /// <summary> /// How many RelationshipEnds are in the collection /// </summary> public int Count { get { return KeysInDefOrder.Count; } } /// <summary> /// Add a relationship end /// </summary> /// <param name="end">the end to add</param> public void Add(IRelationshipEnd end) { Debug.Assert(end != null, "end parameter is null"); SchemaElement endElement = end as SchemaElement; Debug.Assert(endElement != null, "end is not a SchemaElement"); // this should have been caught before this, just ignore it if ( !IsEndValid(end) ) return; if ( !ValidateUniqueName(endElement, end.Name)) return; EndLookup.Add(end.Name,end); KeysInDefOrder.Add(end.Name); } /// <summary> /// See if an end can be added to the collection /// </summary> /// <param name="end">the end to add</param> /// <returns>true if the end is valid, false otherwise</returns> private static bool IsEndValid(IRelationshipEnd end) { return !string.IsNullOrEmpty(end.Name); } /// <summary> /// /// </summary> /// <param name="end"></param> /// <param name="name"></param> /// <returns></returns> private bool ValidateUniqueName(SchemaElement end, string name) { if ( EndLookup.ContainsKey(name) ) { end.AddError( ErrorCode.AlreadyDefined, EdmSchemaErrorSeverity.Error, System.Data.Entity.Strings.EndNameAlreadyDefinedDuplicate(name)); return false; } return true; } /// <summary> /// Remove a relationship end /// </summary> /// <param name="end">the end to remove</param> /// <returns>true if item was in list</returns> public bool Remove(IRelationshipEnd end) { Debug.Assert(end != null, "end parameter is null"); if ( !IsEndValid(end) ) return false; KeysInDefOrder.Remove(end.Name); bool wasInList = EndLookup.Remove(end.Name); return wasInList; } /// <summary> /// See if a relationship end is in the collection /// </summary> /// <param name="name">the name of the end</param> /// <returns>true if the end name is in the collection</returns> public bool Contains(string name) { return EndLookup.ContainsKey(name); } /// <summary> /// See if a relationship end is in the collection /// </summary> /// <param name="end">the name of the end</param> /// <returns>true if the end is in the collection</returns> public bool Contains(IRelationshipEnd end) { Debug.Assert(end != null, "end parameter is null"); return Contains(end.Name); } public IRelationshipEnd this[int index] { get { return EndLookup[KeysInDefOrder[index]]; } set { throw EntityUtil.NotSupported(); } } /// <summary> /// get a typed enumerator for the collection /// </summary> /// <returns>the enumerator</returns> public IEnumerator<IRelationshipEnd> GetEnumerator() { return new Enumerator(EndLookup,KeysInDefOrder); } public bool TryGetEnd( string name, out IRelationshipEnd end ) { return EndLookup.TryGetValue( name, out end ); } /// <summary> /// get an un-typed enumerator for the collection /// </summary> /// <returns>the enumerator</returns> IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(EndLookup,KeysInDefOrder); } /// <summary> /// The data for the collection /// </summary> private Dictionary<string,IRelationshipEnd> EndLookup { get { if ( _endLookup == null ) _endLookup = new Dictionary<string, IRelationshipEnd>(StringComparer.Ordinal); return _endLookup; } } /// <summary> /// the definition order collection /// </summary> private List<string> KeysInDefOrder { get { if ( _keysInDefOrder == null ) _keysInDefOrder = new List<string>(); return _keysInDefOrder; } } /// <summary> /// remove all elements from the collection /// </summary> public void Clear() { EndLookup.Clear(); KeysInDefOrder.Clear(); } /// <summary> /// can the collection be modified /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Not supported /// </summary> /// <param name="end">the end</param> /// <returns>nothing</returns> int IList<IRelationshipEnd>.IndexOf(IRelationshipEnd end) { throw EntityUtil.NotSupported(); } /// <summary> /// Not supported /// </summary> /// <param name="index">the index</param> /// <param name="end">the end</param> void IList<IRelationshipEnd>.Insert(int index, IRelationshipEnd end) { throw EntityUtil.NotSupported(); } /// <summary> /// Not supported /// </summary> /// <param name="index">the index</param> void IList<IRelationshipEnd>.RemoveAt(int index) { throw EntityUtil.NotSupported(); } /// <summary> /// copy all elements to an array /// </summary> /// <param name="ends">array to copy to</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public void CopyTo(IRelationshipEnd[] ends, int index ) { Debug.Assert(ends.Length-index >= Count); foreach ( IRelationshipEnd end in this ) ends[index++] = end; } /// <summary> /// enumerator for the RelationshipEnd collection /// the ends as traversed in the order in which they were added /// </summary> private sealed class Enumerator : IEnumerator<IRelationshipEnd> { private List<string>.Enumerator _Enumerator; private Dictionary<string,IRelationshipEnd> _Data = null; /// <summary> /// construct the enumerator /// </summary> /// <param name="data">the real data</param> /// <param name="keysInDefOrder">the keys to the real data in inserted order</param> public Enumerator(Dictionary<string, IRelationshipEnd> data, List<string> keysInDefOrder) { Debug.Assert(data != null); Debug.Assert(keysInDefOrder != null); _Enumerator = keysInDefOrder.GetEnumerator(); _Data = data; } /// <summary> /// reset the enumerator /// </summary> public void Reset() { // reset is implemented explicitly ((IEnumerator)_Enumerator).Reset(); } /// <summary> /// get current relationship end from the enumerator /// </summary> public IRelationshipEnd Current { get { return _Data[_Enumerator.Current]; } } /// <summary> /// get current relationship end from the enumerator /// </summary> object System.Collections.IEnumerator.Current { get { return _Data[_Enumerator.Current]; } } /// <summary> /// move to the next element in the collection /// </summary> /// <returns>true if there is a next, false if not</returns> public bool MoveNext() { return _Enumerator.MoveNext(); } /// <summary> /// dispose of the enumerator /// </summary> public void Dispose() { } } } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Xml; using System.Text; using OpenSource.UPnP; using System.Reflection; using System.Collections; using OpenSource.Utilities; using System.Globalization; using System.Runtime.Serialization; namespace OpenSource.UPnP.AV.CdsMetadata { /// <summary> /// Class can represent any ContentDirectory approved /// upnp or dublin-core metadata elements that are /// simple DateTime values without any attributes. /// </summary> [Serializable()] public sealed class PropertyDateTime : ICdsElement, IToXmlData, IDeserializationCallback { /// <summary> /// Returns same value as StringValue /// </summary> /// <returns></returns> public override string ToString() { return this.StringValue; } /// <summary> /// Returns an empty list. /// </summary> /// <returns></returns> public static IList GetPossibleAttributes() { return new object[0]; } /// <summary> /// Returns an empty list. /// </summary> /// <returns></returns> public IList PossibleAttributes { get { return GetPossibleAttributes(); } } /// <summary> /// Returns an empty list. /// </summary> /// <returns></returns> public IList ValidAttributes { get { return GetPossibleAttributes(); } } /// <summary> /// No attributes, so always returns null /// </summary> /// <param name="attribute"></param> /// <returns></returns> public IComparable ExtractAttribute(string attribute) { return null; } /// <summary> /// Returns the underlying DateTime value. /// </summary> public IComparable ComparableValue { get { return m_value; } } /// <summary> /// Returns the underlying DateTime value. /// </summary> public object Value { get { return m_value; } } /// <summary> /// Returns the string representation of the date, /// formatted to ContentDirectory conventions. /// </summary> public string StringValue { get { InitFormatInfo(); return this.m_value.ToString(FormatInfo.SortableDateTimePattern); } } /// <summary> /// Prints the XML representation of the metadata element. /// <para> /// Implementation calls the <see cref="ToXmlData.ToXml"/> /// method for its implementation. /// </para> /// </summary> /// <param name="formatter"> /// A <see cref="ToXmlFormatter"/> object that /// specifies method implementations for printing /// media objects. /// </param> /// <param name="data"> /// This object should be a <see cref="ToXmlData"/> /// object that contains additional instructions used /// by the "formatter" argument. /// </param> /// <param name="xmlWriter"> /// The <see cref="XmlTextWriter"/> object that /// will format the representation in an XML /// valid way. /// </param> /// <exception cref="InvalidCastException"> /// Thrown if the "data" argument is not a <see cref="ToXmlData"/> object. /// </exception> public void ToXml (ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter) { ToXmlData.ToXml(this, formatter, (ToXmlData) data, xmlWriter); } /// <summary> /// Instructs the "xmlWriter" argument to start the metadata element. /// </summary> /// <param name="formatter"> /// A <see cref="ToXmlFormatter"/> object that /// specifies method implementations for printing /// media objects and metadata. /// </param> /// <param name="data"> /// This object should be a <see cref="ToXmlData"/> /// object that contains additional instructions used /// by the "formatter" argument. /// </param> /// <param name="xmlWriter"> /// The <see cref="XmlTextWriter"/> object that /// will format the representation in an XML /// valid way. /// </param> public void StartElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter) { xmlWriter.WriteStartElement(this.ns_tag); } /// <summary> /// Instructs the "xmlWriter" argument to write the value of /// the metadata element. /// </summary> /// <param name="formatter"> /// A <see cref="ToXmlFormatter"/> object that /// specifies method implementations for printing /// media objects and metadata. /// </param> /// <param name="data"> /// This object should be a <see cref="ToXmlData"/> /// object that contains additional instructions used /// by the "formatter" argument. /// </param> /// <param name="xmlWriter"> /// The <see cref="XmlTextWriter"/> object that /// will format the representation in an XML /// valid way. /// </param> public void WriteValue(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter) { xmlWriter.WriteString(this.StringValue); } /// <summary> /// Instructs the "xmlWriter" argument to close the metadata element. /// </summary> /// <param name="formatter"> /// A <see cref="ToXmlFormatter"/> object that /// specifies method implementations for printing /// media objects and metadata. /// </param> /// <param name="data"> /// This object should be a <see cref="ToXmlData"/> /// object that contains additional instructions used /// by the "formatter" argument. /// </param> /// <param name="xmlWriter"> /// The <see cref="XmlTextWriter"/> object that /// will format the representation in an XML /// valid way. /// </param> public void EndElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter) { xmlWriter.WriteEndElement(); } /// <summary> /// Empty - this element has no child xml elements. /// </summary> /// <param name="formatter"> /// A <see cref="ToXmlFormatter"/> object that /// specifies method implementations for printing /// media objects and metadata. /// </param> /// <param name="data"> /// This object should be a <see cref="ToXmlData"/> /// object that contains additional instructions used /// by the "formatter" argument. /// </param> /// <param name="xmlWriter"> /// The <see cref="XmlTextWriter"/> object that /// will format the representation in an XML /// valid way. /// </param> public void WriteInnerXml(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter) { } /// <summary> /// Attempts to case compareToThis as an DateTime /// to do the comparison. If the cast /// fails, then it compares the current /// value against DateTime.MinValue. /// </summary> /// <param name="compareToThis"></param> /// <returns></returns> public int CompareTo (object compareToThis) { System.Type type = compareToThis.GetType(); DateTime compareTo = DateTime.MinValue; try { if (type == typeof(PropertyDateTime)) { compareTo = ((PropertyDateTime)compareToThis).m_value; } else if (type == typeof(string)) { compareTo = PropertyDateTime.ParseIso8601((string)compareToThis); } else { compareTo = (DateTime) compareToThis; } } catch { compareTo = DateTime.MinValue; } return this.m_value.CompareTo(compareTo); } /// <summary> /// Extracts the Name of the element and uses /// the InnerText as the value. /// </summary> /// <param name="element"></param> public PropertyDateTime(XmlElement element) { this.m_value = ParseIso8601(element.InnerText); this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(element.Name); } /// <summary> /// Instantiates a new property that can represent an xml element with /// a DateTime as its value. /// </summary> /// <param name="namespace_tag">property obtained from Tags[CommonPropertyNames.value]</param> /// <param name="val"></param> public PropertyDateTime (string namespace_tag, DateTime val) { this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(namespace_tag); this.m_value = val; } /// <summary> /// Assume the name has been read. /// </summary> /// <param name="reader"></param> public PropertyDateTime(XmlReader reader) { this.m_value = ParseIso8601(reader.Value); this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(reader.Name); } /// <summary> /// Sets the formatting info to match ContentDirectory speicification. /// </summary> private static void InitFormatInfo() { if (FormatInfo == null) { FormatInfo = new System.Globalization.DateTimeFormatInfo(); FormatInfo.ShortDatePattern = "yyyy-MM-dd"; } } /// <summary> /// Parses the date string as an ISO8601 form. /// </summary> /// <param name="date"></param> /// <returns></returns> private static DateTime ParseIso8601(string date) { InitFormatInfo(); string[] formats = { FormatInfo.ShortDatePattern, FormatInfo.SortableDateTimePattern }; DateTime newDate = DateTime.ParseExact(date, formats, FormatInfo, DateTimeStyles.None); return newDate; } /// <summary> /// Share the same formatting info for all instances. /// </summary> private static DateTimeFormatInfo FormatInfo = null; /// <summary> /// Returns the cloned formatting info if its desired. /// </summary> /// <returns></returns> public static DateTimeFormatInfo GetFormatInfo() { InitFormatInfo(); return (DateTimeFormatInfo) FormatInfo.Clone(); } /// <summary> /// Underlying DateTime value. /// </summary> public DateTime _Value { get { return this.m_value; } } internal DateTime m_value; /// <summary> /// the namespace and element name to represent /// </summary> private string ns_tag; public void OnDeserialization(object sender) { this.ns_tag = (string) CdsMetadataCaches.Didl.CacheThis(this.ns_tag); } } }
// 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; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class GetIntTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; NameValueCollection nvc; // simple string values string[] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count // initialize IntStrings intl = new IntlStrings(); // [] NameValueCollection is constructed as expected //----------------------------------------------------------------- nvc = new NameValueCollection(); // [] Get(int) on empty collection // Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(-1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(0); }); // [] Get(int) on collection filled with simple strings // cnt = nvc.Count; int len = values.Length; for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } if (nvc.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length)); } // for (int i = 0; i < len; i++) { if (String.Compare(nvc.Get(i), values[i]) != 0) { Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc.Get(i), values[i])); } } // // Intl strings // [] Get(int) on collection filled with Intl strings // string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant()) caseInsensitive = true; } nvc.Clear(); for (int i = 0; i < len; i++) { nvc.Add(intlValues[i + len], intlValues[i]); } if (nvc.Count != (len)) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len)); } for (int i = 0; i < len; i++) { // if (String.Compare(nvc.Get(i), intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.Get(i), intlValues[i])); } } // // [] Case sensitivity // string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } nvc.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings } // for (int i = 0; i < len; i++) { // if (String.Compare(nvc.Get(i), intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.Get(i), intlValues[i])); } if (!caseInsensitive && String.Compare(nvc.Get(i), intlValuesLower[i]) == 0) { Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i)); } } // [] Get(int) on filled collection with multiple items with the same key // nvc.Clear(); len = values.Length; string k = "keykey"; string k1 = "hm1"; string exp = ""; string exp1 = ""; for (int i = 0; i < len; i++) { nvc.Add(k, "Value" + i); nvc.Add(k1, "iTem" + i); if (i < len - 1) { exp += "Value" + i + ","; exp1 += "iTem" + i + ","; } else { exp += "Value" + i; exp1 += "iTem" + i; } } if (nvc.Count != 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2)); } if (String.Compare(nvc.Get(0), exp) != 0) { Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.Get(0), exp)); } if (String.Compare(nvc.Get(1), exp1) != 0) { Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.Get(1), exp1)); } // // [] Get(-1) // cnt = nvc.Count; Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(-1); }); // // [] Get(count) // if (nvc.Count < 1) { for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } } cnt = nvc.Count; Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(cnt); }); // // [] Get(count+1) // if (nvc.Count < 1) { for (int i = 0; i < len; i++) { nvc.Add(keys[i], values[i]); } } cnt = nvc.Count; Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(cnt + 1); }); // // Get(null) - calls other overloaded version of Get - Get(string) - no exception // [] Get(null) // string res = nvc.Get(null); if (res != null) { Assert.False(true, "Error, returned non-null "); } } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.Data.SqlServerCe; using System.Text; using MLifter.DAL.Interfaces; using MLifter.DAL.Interfaces.DB; using MLifter.DAL.Tools; namespace MLifter.DAL.DB.MsSqlCe { /// <summary> /// MsSqlCeCardConnector /// </summary> /// <remarks>Documented by Dev08, 2009-01-09</remarks> class MsSqlCeCardConnector : IDbCardConnector { private static Dictionary<ConnectionStringStruct, MsSqlCeCardConnector> instances = new Dictionary<ConnectionStringStruct, MsSqlCeCardConnector>(); public static MsSqlCeCardConnector GetInstance(ParentClass parentClass) { lock (instances) { ConnectionStringStruct connection = parentClass.CurrentUser.ConnectionString; if (!instances.ContainsKey(connection)) instances.Add(connection, new MsSqlCeCardConnector(parentClass)); return instances[connection]; } } private ParentClass parent; private MsSqlCeCardConnector(ParentClass parentClass) { parent = parentClass; parent.DictionaryClosed += new EventHandler(parent_DictionaryClosed); } void parent_DictionaryClosed(object sender, EventArgs e) { IParent parent = sender as IParent; instances.Remove(parent.Parent.CurrentUser.ConnectionString); } #region IDbCardConnector Members /// <summary> /// Checks if the card exists and throws an IdAccessException if not. /// </summary> /// <param name="id">The card id.</param> /// <remarks>Documented by Dev03, 2008-08-06</remarks> /// <remarks>Documented by Dev08, 2009-01-09</remarks> public void CheckCardId(int id) { List<int> cardIdsCache = parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardIdsList, 0)] as List<int>; if (cardIdsCache != null && cardIdsCache.Contains(id)) return; using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { cmd.CommandText = "(SELECT lm_id FROM \"LearningModules_Cards\" WHERE cards_id=@id)"; cmd.Parameters.Add("@id", id); int lmId = Convert.ToInt32(MSSQLCEConn.ExecuteScalar(cmd)); cmd.Parameters.Clear(); cmd.CommandText = "SELECT id FROM \"Cards\" WHERE id IN " + "(SELECT cards_id FROM \"LearningModules_Cards\" WHERE lm_id=@lm_id)"; cmd.Parameters.Add("@lm_id", lmId); SqlCeDataReader reader; try { reader = MSSQLCEConn.ExecuteReader(cmd); } catch { throw new IdAccessException(id); } List<int> cardIds = new List<int>(); while (reader.Read()) cardIds.Add(Convert.ToInt32(reader["id"])); reader.Close(); parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.CardIdsList, 0)] = cardIds; } } /// <summary> /// Gets the chapter for a card. /// </summary> /// <param name="id">The card id.</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2008-08-06</remarks> /// <remarks>Documented by Dev08, 2009-01-09</remarks> public int GetChapter(int id) { Dictionary<int, int> cardChaptersCache = parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardChapterList, 0)] as Dictionary<int, int>; if (cardChaptersCache != null && cardChaptersCache.ContainsKey(id)) return cardChaptersCache[id]; using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { cmd.CommandText = "(SELECT lm_id FROM \"LearningModules_Cards\" WHERE cards_id=@id)"; cmd.Parameters.Add("@id", id); int lmid = Convert.ToInt32(MSSQLCEConn.ExecuteScalar(cmd)); cmd.Parameters.Clear(); cmd.CommandText = "SELECT chapters_id, cards_id FROM Chapters_Cards WHERE chapters_id IN " + "(SELECT chapters_id FROM Chapters WHERE lm_id=@lmid)"; cmd.Parameters.Add("@lmid", lmid); SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd); Dictionary<int, int> cardChapters = new Dictionary<int, int>(); while (reader.Read()) { object[] chapters = new object[2]; reader.GetValues(chapters); int chid = Convert.ToInt32(chapters[0]); int cid = Convert.ToInt32(chapters[1]); if (!cardChapters.ContainsKey(cid)) cardChapters[cid] = chid; } reader.Close(); // this should fix the bug where for some reason a card didn't have chapter assigned [ML-1708] (and similar) int chapterId = 0; if (!cardChapters.TryGetValue(id, out chapterId)) { lock (cardChapters) { foreach (int c in cardChapters.Values) { chapterId = c; break; } SetChapter(id, chapterId); cardChapters.Add(id, chapterId); } } parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.CardChapterList, 0, new TimeSpan(23, 59, 59))] = cardChapters; return chapterId; } } /// <summary> /// Sets the chapter for a card. /// </summary> /// <param name="id">The card id.</param> /// <param name="chapter">The chapter id.</param> /// <remarks>Documented by Dev03, 2008-08-06</remarks> /// <remarks>Documented by Dev08, 2009-01-09</remarks> public void SetChapter(int id, int chapter) { using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { SqlCeTransaction transaction = cmd.Connection.BeginTransaction(); cmd.CommandText = "SELECT count(*) FROM \"Chapters\" WHERE id=@chapterid"; cmd.Parameters.Add("chapterid", chapter); if (Convert.ToInt32(MSSQLCEConn.ExecuteScalar(cmd)) < 1) throw new IdAccessException(chapter); Dictionary<int, int> cardChapterCache = parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardChapterList, 0)] as Dictionary<int, int>; if (cardChapterCache != null) cardChapterCache[id] = chapter; using (SqlCeCommand cmd2 = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { cmd2.CommandText = "DELETE FROM \"Chapters_Cards\" WHERE cards_id=@id; "; cmd2.CommandText += "INSERT INTO \"Chapters_Cards\" (chapters_id, cards_id) VALUES (@chapterid, @id);"; cmd2.CommandText += "UPDATE Cards SET chapters_id=@chapterid WHERE id=@id;"; cmd2.Parameters.Add("@chapterid", chapter); cmd2.Parameters.Add("@id", id); MSSQLCEConn.ExecuteNonQuery(cmd2); } transaction.Commit(); } } /// <summary> /// Gets the settings. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-09</remarks> public ISettings GetSettings(int id) { int? cardSettingsId = parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardSetting, id)] as int?; if (cardSettingsId.HasValue) return new DbSettings(cardSettingsId.Value, false, parent); using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { cmd.CommandText = "SELECT settings_id FROM \"Cards\" WHERE id=@id"; cmd.Parameters.Add("@id", id); int? sid = MSSQLCEConn.ExecuteScalar<int>(cmd); if (sid.HasValue) { parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.CardSetting, id)] = sid; return new DbSettings(sid.Value, false, parent); } else return null; } } /// <summary> /// Sets the settings. /// </summary> /// <param name="id">The id.</param> /// <param name="Settings">The settings.</param> /// <remarks>Documented by Dev08, 2009-01-09</remarks> public void SetSettings(int id, MLifter.DAL.Interfaces.ISettings Settings) { throw new NotAllowedInDbModeException(); //using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) //{ // cmd.CommandText = "UPDATE \"Cards\" SET settings_id=@value WHERE id=@id"; // cmd.Parameters.Add("@id", id); // cmd.Parameters.Add("@value", (Settings as DbSettings).Id); // MSSQLCEConn.ExecuteNonQuery(cmd); //} } /// <summary> /// Gets the box. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-09</remarks> public int GetBox(int id) { CardState? state = parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardState, id)] as CardState?; if (state.HasValue) return state.Value.Box; ReadCardState(id); return (parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardState, id)] as CardState?).Value.Box; } /// <summary> /// Sets the box. /// </summary> /// <param name="id">The id.</param> /// <param name="box">The box.</param> /// <remarks>Documented by Dev08, 2009-01-09</remarks> public void SetBox(int id, int box) { SetCardState(parent.CurrentUser.Id, id, box, GetActive(id), GetTimestamp(id)); parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardState, id)); parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.Score, parent.GetParentDictionary().Id)); parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.BoxSizes, parent.CurrentUser.ConnectionString.LmId)); parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CurrentBoxSizes, parent.CurrentUser.ConnectionString.LmId)); } /// <summary> /// Gets the active. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-09</remarks> public bool GetActive(int id) { CardState? state = parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardState, id)] as CardState?; if (state.HasValue) return state.Value.Active; ReadCardState(id); return (parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardState, id)] as CardState?).Value.Active; } /// <summary> /// Sets the active. /// </summary> /// <param name="id">The id.</param> /// <param name="active">if set to <c>true</c> [active].</param> /// <remarks> /// Documented by FabThe, 9.1.2009 /// </remarks> public void SetActive(int id, bool active) { SetCardState(parent.CurrentUser.Id, id, GetBox(id), active, GetTimestamp(id)); parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardState, id)); } /// <summary> /// Gets the timestamp. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> /// <remarks>Documented by Dev08, 2009-01-09</remarks> public DateTime GetTimestamp(int id) { CardState? state = parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardState, id)] as CardState?; if (state.HasValue) return state.Value.TimeStamp; ReadCardState(id); return (parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardState, id)] as CardState?).Value.TimeStamp; } /// <summary> /// Sets the timestamp. /// </summary> /// <param name="id">The id.</param> /// <param name="timestamp">The timestamp.</param> /// <remarks> /// Documented by FabThe, 9.1.2009 /// </remarks> public void SetTimestamp(int id, DateTime timestamp) { SetCardState(parent.CurrentUser.Id, id, GetBox(id), GetActive(id), timestamp); parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(CacheObject.CardState, id)); } #endregion /// <summary> /// Reads the state of the card. /// </summary> /// <param name="id">The id.</param> /// <remarks>Documented by Dev08, 2009-01-09</remarks> private void ReadCardState(int id) { int? cnt; using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { cmd.CommandText = "SELECT count(*) FROM \"UserCardState\" WHERE user_id = @param_user_id and cards_id = @param_cards_id;"; cmd.Parameters.Add("@param_user_id", parent.CurrentUser.Id); cmd.Parameters.Add("@param_cards_id", id); cnt = MSSQLCEConn.ExecuteScalar<int>(cmd); } if (!cnt.HasValue || cnt.Value < 1) { using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { cmd.CommandText = "INSERT INTO \"UserCardState\" (user_id, cards_id, box, active) VALUES (@param_user_id, @param_cards_id, 0, 1);"; cmd.Parameters.Add("@param_user_id", parent.CurrentUser.Id); cmd.Parameters.Add("@param_cards_id", id); MSSQLCEConn.ExecuteNonQuery(cmd); } } using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { cmd.CommandText = "SELECT timestamp, box, active FROM \"UserCardState\" WHERE user_id = @param_user_id and cards_id = @param_cards_id;"; cmd.Parameters.Add("@param_user_id", parent.CurrentUser.Id); cmd.Parameters.Add("@param_cards_id", id); SqlCeDataReader reader = MSSQLCEConn.ExecuteReader(cmd); reader.Read(); object ts = reader["timestamp"]; DateTime timestamp = ts is DBNull ? new DateTime(1901, 1, 1) : Convert.ToDateTime(ts); parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.CardState, id)] = new CardState(Convert.ToInt32(reader["box"]), Convert.ToBoolean(reader["active"]), timestamp); reader.Close(); } } /// <summary> /// C# Function which replaces the SetCardState(..) procedure of pgsql /// </summary> /// <param name="id">The id.</param> /// <param name="card">The card.</param> /// <param name="box">The box.</param> /// <param name="active">if set to <c>true</c> [active].</param> /// <param name="timestamp">The timestamp.</param> /// <remarks>Documented by Dev08, 2009-01-09</remarks> private void SetCardState(int id, int card, int box, bool active, DateTime timestamp) { int? cnt; using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { cmd.CommandText = "SELECT count(*) AS cnt FROM \"UserCardState\" WHERE user_id=@param_user_id and cards_id=@param_cards_id;"; cmd.Parameters.Add("@param_user_id", id); cmd.Parameters.Add("@param_cards_id", card); cnt = MSSQLCEConn.ExecuteScalar<int>(cmd); } using (SqlCeCommand cmd = MSSQLCEConn.CreateCommand(parent.CurrentUser)) { if (!cnt.HasValue || cnt.Value < 1) { cmd.CommandText = "INSERT INTO \"UserCardState\" (user_id, cards_id, box, active, timestamp) VALUES (@param_user_id, @param_cards_id, @param_box, @param_active, @param_timestamp);"; cmd.Parameters.Add("@param_user_id", id); cmd.Parameters.Add("@param_cards_id", card); cmd.Parameters.Add("@param_box", box); cmd.Parameters.Add("@param_active", active); cmd.Parameters.Add("@param_timestamp", timestamp); MSSQLCEConn.ExecuteNonQuery(cmd); } else { cmd.CommandText = "UPDATE \"UserCardState\" SET box=@param_box, active=@param_active, timestamp=@param_timestamp WHERE user_id=@param_user_id and cards_id=@param_cards_id;"; cmd.Parameters.Add("@param_user_id", id); cmd.Parameters.Add("@param_cards_id", card); cmd.Parameters.Add("@param_box", box); cmd.Parameters.Add("@param_active", active); cmd.Parameters.Add("@param_timestamp", timestamp); MSSQLCEConn.ExecuteNonQuery(cmd); } } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// BrandRegistrationResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Messaging.V1 { public class BrandRegistrationResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum Pending = new StatusEnum("PENDING"); public static readonly StatusEnum Approved = new StatusEnum("APPROVED"); public static readonly StatusEnum Failed = new StatusEnum("FAILED"); public static readonly StatusEnum InReview = new StatusEnum("IN_REVIEW"); public static readonly StatusEnum Deleted = new StatusEnum("DELETED"); } public sealed class IdentityStatusEnum : StringEnum { private IdentityStatusEnum(string value) : base(value) {} public IdentityStatusEnum() {} public static implicit operator IdentityStatusEnum(string value) { return new IdentityStatusEnum(value); } public static readonly IdentityStatusEnum SelfDeclared = new IdentityStatusEnum("SELF_DECLARED"); public static readonly IdentityStatusEnum Unverified = new IdentityStatusEnum("UNVERIFIED"); public static readonly IdentityStatusEnum Verified = new IdentityStatusEnum("VERIFIED"); public static readonly IdentityStatusEnum VettedVerified = new IdentityStatusEnum("VETTED_VERIFIED"); } public sealed class BrandFeedbackEnum : StringEnum { private BrandFeedbackEnum(string value) : base(value) {} public BrandFeedbackEnum() {} public static implicit operator BrandFeedbackEnum(string value) { return new BrandFeedbackEnum(value); } public static readonly BrandFeedbackEnum TaxId = new BrandFeedbackEnum("TAX_ID"); public static readonly BrandFeedbackEnum StockSymbol = new BrandFeedbackEnum("STOCK_SYMBOL"); public static readonly BrandFeedbackEnum Nonprofit = new BrandFeedbackEnum("NONPROFIT"); public static readonly BrandFeedbackEnum GovernmentEntity = new BrandFeedbackEnum("GOVERNMENT_ENTITY"); public static readonly BrandFeedbackEnum Others = new BrandFeedbackEnum("OTHERS"); } private static Request BuildFetchRequest(FetchBrandRegistrationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Messaging, "/v1/a2p/BrandRegistrations/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch BrandRegistration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of BrandRegistration </returns> public static BrandRegistrationResource Fetch(FetchBrandRegistrationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch BrandRegistration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of BrandRegistration </returns> public static async System.Threading.Tasks.Task<BrandRegistrationResource> FetchAsync(FetchBrandRegistrationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of BrandRegistration </returns> public static BrandRegistrationResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchBrandRegistrationOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of BrandRegistration </returns> public static async System.Threading.Tasks.Task<BrandRegistrationResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchBrandRegistrationOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadBrandRegistrationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Messaging, "/v1/a2p/BrandRegistrations", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read BrandRegistration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of BrandRegistration </returns> public static ResourceSet<BrandRegistrationResource> Read(ReadBrandRegistrationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<BrandRegistrationResource>.FromJson("data", response.Content); return new ResourceSet<BrandRegistrationResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read BrandRegistration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of BrandRegistration </returns> public static async System.Threading.Tasks.Task<ResourceSet<BrandRegistrationResource>> ReadAsync(ReadBrandRegistrationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<BrandRegistrationResource>.FromJson("data", response.Content); return new ResourceSet<BrandRegistrationResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of BrandRegistration </returns> public static ResourceSet<BrandRegistrationResource> Read(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadBrandRegistrationOptions(){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of BrandRegistration </returns> public static async System.Threading.Tasks.Task<ResourceSet<BrandRegistrationResource>> ReadAsync(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadBrandRegistrationOptions(){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<BrandRegistrationResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<BrandRegistrationResource>.FromJson("data", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<BrandRegistrationResource> NextPage(Page<BrandRegistrationResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Messaging) ); var response = client.Request(request); return Page<BrandRegistrationResource>.FromJson("data", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<BrandRegistrationResource> PreviousPage(Page<BrandRegistrationResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Messaging) ); var response = client.Request(request); return Page<BrandRegistrationResource>.FromJson("data", response.Content); } private static Request BuildCreateRequest(CreateBrandRegistrationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Messaging, "/v1/a2p/BrandRegistrations", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create BrandRegistration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of BrandRegistration </returns> public static BrandRegistrationResource Create(CreateBrandRegistrationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create BrandRegistration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of BrandRegistration </returns> public static async System.Threading.Tasks.Task<BrandRegistrationResource> CreateAsync(CreateBrandRegistrationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="customerProfileBundleSid"> Customer Profile Bundle Sid </param> /// <param name="a2PProfileBundleSid"> A2P Messaging Profile Bundle Sid </param> /// <param name="brandType"> Type of brand being created. One of: "STANDARD", "STARTER". </param> /// <param name="mock"> A boolean that specifies whether brand should be a mock or not. If true, brand will be /// registered as a mock brand. Defaults to false if no value is provided. </param> /// <param name="skipAutomaticSecVet"> Skip Automatic Secondary Vetting </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of BrandRegistration </returns> public static BrandRegistrationResource Create(string customerProfileBundleSid, string a2PProfileBundleSid, string brandType = null, bool? mock = null, bool? skipAutomaticSecVet = null, ITwilioRestClient client = null) { var options = new CreateBrandRegistrationOptions(customerProfileBundleSid, a2PProfileBundleSid){BrandType = brandType, Mock = mock, SkipAutomaticSecVet = skipAutomaticSecVet}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="customerProfileBundleSid"> Customer Profile Bundle Sid </param> /// <param name="a2PProfileBundleSid"> A2P Messaging Profile Bundle Sid </param> /// <param name="brandType"> Type of brand being created. One of: "STANDARD", "STARTER". </param> /// <param name="mock"> A boolean that specifies whether brand should be a mock or not. If true, brand will be /// registered as a mock brand. Defaults to false if no value is provided. </param> /// <param name="skipAutomaticSecVet"> Skip Automatic Secondary Vetting </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of BrandRegistration </returns> public static async System.Threading.Tasks.Task<BrandRegistrationResource> CreateAsync(string customerProfileBundleSid, string a2PProfileBundleSid, string brandType = null, bool? mock = null, bool? skipAutomaticSecVet = null, ITwilioRestClient client = null) { var options = new CreateBrandRegistrationOptions(customerProfileBundleSid, a2PProfileBundleSid){BrandType = brandType, Mock = mock, SkipAutomaticSecVet = skipAutomaticSecVet}; return await CreateAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateBrandRegistrationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Messaging, "/v1/a2p/BrandRegistrations/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update BrandRegistration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of BrandRegistration </returns> public static BrandRegistrationResource Update(UpdateBrandRegistrationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update BrandRegistration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of BrandRegistration </returns> public static async System.Threading.Tasks.Task<BrandRegistrationResource> UpdateAsync(UpdateBrandRegistrationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathSid"> The SID that identifies the resource to update </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of BrandRegistration </returns> public static BrandRegistrationResource Update(string pathSid, ITwilioRestClient client = null) { var options = new UpdateBrandRegistrationOptions(pathSid); return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathSid"> The SID that identifies the resource to update </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of BrandRegistration </returns> public static async System.Threading.Tasks.Task<BrandRegistrationResource> UpdateAsync(string pathSid, ITwilioRestClient client = null) { var options = new UpdateBrandRegistrationOptions(pathSid); return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a BrandRegistrationResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> BrandRegistrationResource object represented by the provided JSON </returns> public static BrandRegistrationResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<BrandRegistrationResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// A2P BrandRegistration Sid /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// A2P Messaging Profile Bundle BundleSid /// </summary> [JsonProperty("customer_profile_bundle_sid")] public string CustomerProfileBundleSid { get; private set; } /// <summary> /// A2P Messaging Profile Bundle BundleSid /// </summary> [JsonProperty("a2p_profile_bundle_sid")] public string A2PProfileBundleSid { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// Type of brand. One of: "STANDARD", "STARTER". /// </summary> [JsonProperty("brand_type")] public string BrandType { get; private set; } /// <summary> /// Brand Registration status. /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public BrandRegistrationResource.StatusEnum Status { get; private set; } /// <summary> /// Campaign Registry (TCR) Brand ID /// </summary> [JsonProperty("tcr_id")] public string TcrId { get; private set; } /// <summary> /// A reason why brand registration has failed /// </summary> [JsonProperty("failure_reason")] public string FailureReason { get; private set; } /// <summary> /// The absolute URL of the Brand Registration /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// Brand score /// </summary> [JsonProperty("brand_score")] public int? BrandScore { get; private set; } /// <summary> /// Brand feedback /// </summary> [JsonProperty("brand_feedback")] [JsonConverter(typeof(StringEnumConverter))] public List<BrandRegistrationResource.BrandFeedbackEnum> BrandFeedback { get; private set; } /// <summary> /// Identity Status /// </summary> [JsonProperty("identity_status")] [JsonConverter(typeof(StringEnumConverter))] public BrandRegistrationResource.IdentityStatusEnum IdentityStatus { get; private set; } /// <summary> /// Russell 3000 /// </summary> [JsonProperty("russell_3000")] public bool? Russell3000 { get; private set; } /// <summary> /// Government Entity /// </summary> [JsonProperty("government_entity")] public bool? GovernmentEntity { get; private set; } /// <summary> /// Tax Exempt Status /// </summary> [JsonProperty("tax_exempt_status")] public string TaxExemptStatus { get; private set; } /// <summary> /// Skip Automatic Secondary Vetting /// </summary> [JsonProperty("skip_automatic_sec_vet")] public bool? SkipAutomaticSecVet { get; private set; } /// <summary> /// A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. /// </summary> [JsonProperty("mock")] public bool? Mock { get; private set; } /// <summary> /// The links /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private BrandRegistrationResource() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections.Generic; using System.Reflection.TypeLoading; using RuntimeTypeInfo = System.Reflection.TypeLoading.RoType; namespace System.Reflection.Runtime.BindingFlagSupport { /// <summary> /// This class encapsulates the minimum set of arcane desktop CLR policies needed to implement the Get*(BindingFlags) apis. /// In particular, it encapsulates behaviors such as what exactly determines the "visibility" of a property and event, and /// what determines whether and how they are overridden. /// </summary> internal abstract class MemberPolicies<M> where M : MemberInfo { // Subclasses for specific MemberInfo types must override these: // // Returns all of the directly declared members on the given TypeInfo. // public abstract IEnumerable<M> GetDeclaredMembers(TypeInfo typeInfo); // // Returns all of the directly declared members on the given TypeInfo whose name matches filter. If filter is null, // returns all directly declared members. // public abstract IEnumerable<M> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter filter, RuntimeTypeInfo reflectedType); // // Policy to decide whether a member is considered "virtual", "virtual new" and what its member visibility is. // (For "visibility", we reuse the MethodAttributes enum since Reflection lacks an element-agnostic enum for this. // Only the MemberAccessMask bits are set.) // public abstract void GetMemberAttributes(M member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot); // // Policy to decide whether "derivedMember" is a virtual override of "baseMember." Used to implement MethodInfo.GetBaseDefinition(), // parent chain traversal for discovering inherited custom attributes, and suppressing lookup results in the Type.Get*() api family. // // Does not consider explicit overrides (methodimpls.) Does not consider "overrides" of interface methods. // public abstract bool ImplicitlyOverrides(M baseMember, M derivedMember); // // Policy to decide how BindingFlags should be reinterpreted for a given member type. // This is overridden for nested types which all match on any combination Instance | Static and are never inherited. // It is also overridden for constructors which are never inherited. // public virtual BindingFlags ModifyBindingFlags(BindingFlags bindingFlags) { return bindingFlags; } // // Policy to decide if BindingFlags is always interpreted as having set DeclaredOnly. // public abstract bool AlwaysTreatAsDeclaredOnly { get; } // // Policy to decide how or if members in more derived types hide same-named members in base types. // Due to desktop compat concerns, the definitions are a bit more arbitrary than we'd like. // public abstract bool IsSuppressedByMoreDerivedMember(M member, M[] priorMembers, int startIndex, int endIndex); // // Policy to decide whether to throw an AmbiguousMatchException on an ambiguous Type.Get*() call. // Does not apply to GetConstructor/GetMethod/GetProperty calls that have a non-null Type[] array passed to it. // // If method returns true, the Get() api will pick the member that's in the most derived type. // If method returns false, the Get() api throws AmbiguousMatchException. // public abstract bool OkToIgnoreAmbiguity(M m1, M m2); // // Helper method for determining whether two methods are signature-compatible. // protected static bool AreNamesAndSignaturesEqual(MethodInfo method1, MethodInfo method2) { if (method1.Name != method2.Name) return false; ParameterInfo[] p1 = method1.GetParametersNoCopy(); ParameterInfo[] p2 = method2.GetParametersNoCopy(); if (p1.Length != p2.Length) return false; bool isGenericMethod1 = method1.IsGenericMethodDefinition; bool isGenericMethod2 = method2.IsGenericMethodDefinition; if (isGenericMethod1 != isGenericMethod2) return false; if (!isGenericMethod1) { for (int i = 0; i < p1.Length; i++) { Type parameterType1 = p1[i].ParameterType; Type parameterType2 = p2[i].ParameterType; if (!(parameterType1.Equals(parameterType2))) { return false; } } } else { if (method1.GetGenericArguments().Length != method2.GetGenericArguments().Length) return false; for (int i = 0; i < p1.Length; i++) { Type parameterType1 = p1[i].ParameterType; Type parameterType2 = p2[i].ParameterType; if (!GenericMethodAwareAreParameterTypesEqual(parameterType1, parameterType2)) { return false; } } } return true; } // // This helper compares the types of the corresponding parameters of two methods to see if one method is signature equivalent to the other. // This is needed when comparing the signatures of two generic methods as Type.Equals() is not up to that job. // private static bool GenericMethodAwareAreParameterTypesEqual(Type t1, Type t2) { // Fast-path - if Reflection has already deemed them equivalent, we can trust its result. if (t1.Equals(t2)) return true; // If we got here, Reflection determined the types not equivalent. Most of the time, that's the result we want. // There is however, one wrinkle. If the type is or embeds a generic method parameter type, Reflection will always report them // non-equivalent, since generic parameter type comparison always compares both the position and the declaring method. For our purposes, though, // we only want to consider the position. // Fast-path: if the types don't embed any generic parameters, we can go ahead and use Reflection's result. if (!(t1.ContainsGenericParameters && t2.ContainsGenericParameters)) return false; if ((t1.IsArray && t2.IsArray) || (t1.IsByRef && t2.IsByRef) || (t1.IsPointer && t2.IsPointer)) { if (t1.IsSZArray() != t2.IsSZArray()) return false; if (t1.IsArray && (t1.GetArrayRank() != t2.GetArrayRank())) return false; return GenericMethodAwareAreParameterTypesEqual(t1.GetElementType(), t2.GetElementType()); } if (t1.IsConstructedGenericType) { // We can use regular old Equals() rather than recursing into GenericMethodAwareAreParameterTypesEqual() since the // generic type definition will always be a plain old named type and won't embed any generic method parameters. if (!(t1.GetGenericTypeDefinition().Equals(t2.GetGenericTypeDefinition()))) return false; Type[] ga1 = t1.GenericTypeArguments; Type[] ga2 = t2.GenericTypeArguments; if (ga1.Length != ga2.Length) return false; for (int i = 0; i < ga1.Length; i++) { if (!GenericMethodAwareAreParameterTypesEqual(ga1[i], ga2[i])) return false; } return true; } if (t1.IsGenericMethodParameter() && t2.IsGenericMethodParameter()) { // A generic method parameter. The DeclaringMethods will be different but we don't care about that - we can assume that // the declaring method will be the method that declared the parameter's whose type we're testing. We only need to // compare the positions. return t1.GenericParameterPosition == t2.GenericParameterPosition; } // If we got here, either t1 and t2 are different flavors of types or they are both simple named types or both generic type parameters. // Either way, we can trust Reflection's result here. return false; } static MemberPolicies() { Type t = typeof(M); if (t.Equals(typeof(FieldInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Field; Default = (MemberPolicies<M>)(Object)(new FieldPolicies()); } else if (t.Equals(typeof(MethodInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Method; Default = (MemberPolicies<M>)(Object)(new MethodPolicies()); } else if (t.Equals(typeof(ConstructorInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Constructor; Default = (MemberPolicies<M>)(Object)(new ConstructorPolicies()); } else if (t.Equals(typeof(PropertyInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Property; ; Default = (MemberPolicies<M>)(Object)(new PropertyPolicies()); } else if (t.Equals(typeof(EventInfo))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.Event; Default = (MemberPolicies<M>)(Object)(new EventPolicies()); } else if (t.Equals(typeof(Type))) { MemberTypeIndex = BindingFlagSupport.MemberTypeIndex.NestedType; Default = (MemberPolicies<M>)(Object)(new NestedTypePolicies()); } else { Debug.Fail("Unknown MemberInfo type."); } } // // This is a singleton class one for each MemberInfo category: Return the appropriate one. // public static readonly MemberPolicies<M> Default; // // This returns a fixed value from 0 to MemberIndex.Count-1 with each possible type of M // being assigned a unique index (see the MemberTypeIndex for possible values). This is useful // for converting a type reference to M to an array index or switch case label. // public static readonly int MemberTypeIndex; } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Management.Automation.Host; using System.Reflection; using System.Runtime.Serialization; using System.Security; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// Encodes and decodes data types and exceptions for transmission across /// the wire. Used for transmitting remote host method call parameters, return /// values, and exceptions. The convention is that EncodeObject converts the /// objects into a type that can be serialized and deserialized without losing /// fidelity. For example, EncodeObject converts Version objects to string, /// and converts more complex classes into property bags on PSObjects. This /// guarantees that transmitting on the wire will not change the encoded /// object's type. /// </summary> internal static class RemoteHostEncoder { /// <summary> /// Is known type. /// </summary> private static bool IsKnownType(Type type) { TypeSerializationInfo info = KnownTypes.GetTypeSerializationInfo(type); return (info != null); } /// <summary> /// Is encoding allowed for class or struct. /// </summary> private static bool IsEncodingAllowedForClassOrStruct(Type type) { // To enable encoding and decoding for a class or struct, add it here. return // Struct types. type == typeof(KeyInfo) || type == typeof(Coordinates) || type == typeof(Size) || type == typeof(BufferCell) || type == typeof(Rectangle) || // Class types. type == typeof(ProgressRecord) || type == typeof(FieldDescription) || type == typeof(ChoiceDescription) || type == typeof(HostInfo) || type == typeof(HostDefaultData) || type == typeof(RemoteSessionCapability); } /// <summary> /// Encode class or struct. /// </summary> private static PSObject EncodeClassOrStruct(object obj) { PSObject psObject = RemotingEncoder.CreateEmptyPSObject(); FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // Add all the non-null field values to the ps object. foreach (FieldInfo fieldInfo in fieldInfos) { object fieldValue = fieldInfo.GetValue(obj); if (fieldValue == null) { continue; } object encodedFieldValue = EncodeObject(fieldValue); psObject.Properties.Add(new PSNoteProperty(fieldInfo.Name, encodedFieldValue)); } return psObject; } /// <summary> /// Decode class or struct. /// </summary> private static object DecodeClassOrStruct(PSObject psObject, Type type) { object obj = FormatterServices.GetUninitializedObject(type); // Field values cannot be null - because for null fields we simply don't transport them. foreach (PSPropertyInfo propertyInfo in psObject.Properties) { FieldInfo fieldInfo = type.GetField(propertyInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (propertyInfo.Value == null) { throw RemoteHostExceptions.NewDecodingFailedException(); } object fieldValue = DecodeObject(propertyInfo.Value, fieldInfo.FieldType); if (fieldValue == null) { throw RemoteHostExceptions.NewDecodingFailedException(); } fieldInfo.SetValue(obj, fieldValue); } return obj; } /// <summary> /// Is collection. /// </summary> private static bool IsCollection(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Collection<>)); } private static bool IsGenericIEnumerableOfInt(Type type) { return type.Equals(typeof(IEnumerable<int>)); } /// <summary> /// Encode collection. /// </summary> private static PSObject EncodeCollection(IList collection) { ArrayList arrayList = new ArrayList(); foreach (object obj in collection) { arrayList.Add(EncodeObject(obj)); } return new PSObject(arrayList); } /// <summary> /// Decode collection. /// </summary> private static IList DecodeCollection(PSObject psObject, Type collectionType) { // Get the element type. Type[] elementTypes = collectionType.GetGenericArguments(); Dbg.Assert(elementTypes.Length == 1, "Expected elementTypes.Length == 1"); Type elementType = elementTypes[0]; // Rehydrate the collection from the array list. ArrayList arrayList = SafelyGetBaseObject<ArrayList>(psObject); IList collection = (IList)Activator.CreateInstance(collectionType); foreach (object element in arrayList) { collection.Add(DecodeObject(element, elementType)); } return collection; } /// <summary> /// Is dictionary. /// </summary> private static bool IsDictionary(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Dictionary<,>)); } /// <summary> /// Encode dictionary. /// </summary> private static PSObject EncodeDictionary(IDictionary dictionary) { // If element type is object then encode as object-dictionary. if (IsObjectDictionaryType(dictionary.GetType())) { return EncodeObjectDictionary(dictionary); } Hashtable hashtable = new Hashtable(); foreach (object key in dictionary.Keys) { hashtable.Add(EncodeObject(key), EncodeObject(dictionary[key])); } return new PSObject(hashtable); } /// <summary> /// Decode dictionary. /// </summary> private static IDictionary DecodeDictionary(PSObject psObject, Type dictionaryType) { // If element type is object then decode as object-dictionary. if (IsObjectDictionaryType(dictionaryType)) { return DecodeObjectDictionary(psObject, dictionaryType); } // Get the element type. Type[] elementTypes = dictionaryType.GetGenericArguments(); Dbg.Assert(elementTypes.Length == 2, "Expected elementTypes.Length == 2"); Type keyType = elementTypes[0]; Type valueType = elementTypes[1]; // Rehydrate the dictionary from the hashtable. Hashtable hashtable = SafelyGetBaseObject<Hashtable>(psObject); IDictionary dictionary = (IDictionary)Activator.CreateInstance(dictionaryType); foreach (object key in hashtable.Keys) { dictionary.Add( DecodeObject(key, keyType), DecodeObject(hashtable[key], valueType)); } return dictionary; } /// <summary> /// Encode ps object. /// </summary> private static PSObject EncodePSObject(PSObject psObject) { // We are not encoding the contents of the PSObject since these can be // arbitrarily complex. Only objects that can be serialized and deserialized // correctly should be wrapped in PSObjects. This logic should also just do // the right thing with PSObject subclasses. Note: This method might seem // trivial but it must exist in order to maintain the symmetry with // DecodePSObject. There is no perf penalty because: (a) the compiler should // inline it, and (b) perf optimization should be based on profiling; // premature optimization is the root of all evil. return psObject; } /// <summary> /// Decode ps object. /// </summary> private static PSObject DecodePSObject(object obj) { if (obj is PSObject) { return (PSObject)obj; } else { // If this is not a PSObject, wrap it in one. This case needs to be handled // because the serializer converts Dictionary<string,PSObject> to a Hashtable // mapping strings to strings, when the PSObject is a simple wrapper around // string. return new PSObject(obj); } } /// <summary> /// Encode exception. /// </summary> private static PSObject EncodeException(Exception exception) { // We are encoding exceptions as ErrorRecord objects because exceptions written // to the wire are lost during serialization. By sending across ErrorRecord objects // we are able to preserve the exception as well as the stack trace. ErrorRecord errorRecord = null; IContainsErrorRecord containsErrorRecord = exception as IContainsErrorRecord; if (containsErrorRecord == null) { // If this is a .NET exception then wrap in an ErrorRecord. errorRecord = new ErrorRecord(exception, "RemoteHostExecutionException", ErrorCategory.NotSpecified, null); } else { // Exception inside the error record is ParentContainsErrorRecordException which // doesn't have stack trace. Replace it with top level exception. errorRecord = containsErrorRecord.ErrorRecord; errorRecord = new ErrorRecord(errorRecord, exception); } PSObject errorRecordPSObject = RemotingEncoder.CreateEmptyPSObject(); errorRecord.ToPSObjectForRemoting(errorRecordPSObject); return errorRecordPSObject; } /// <summary> /// Decode exception. /// </summary> private static Exception DecodeException(PSObject psObject) { ErrorRecord errorRecord = ErrorRecord.FromPSObjectForRemoting(psObject); if (errorRecord == null) { throw RemoteHostExceptions.NewDecodingErrorForErrorRecordException(); } else return errorRecord.Exception; } /// <summary> /// Upcast field description subclass and drop attributes. /// </summary> private static FieldDescription UpcastFieldDescriptionSubclassAndDropAttributes(FieldDescription fieldDescription1) { // Upcasts derived types back to FieldDescription type and throws away attributes. // Create a new field description object. FieldDescription fieldDescription2 = new FieldDescription(fieldDescription1.Name); // Copy the fields not initialized during construction. fieldDescription2.Label = fieldDescription1.Label; fieldDescription2.HelpMessage = fieldDescription1.HelpMessage; fieldDescription2.IsMandatory = fieldDescription1.IsMandatory; fieldDescription2.DefaultValue = fieldDescription1.DefaultValue; // Set the type related fields. fieldDescription2.SetParameterTypeName(fieldDescription1.ParameterTypeName); fieldDescription2.SetParameterTypeFullName(fieldDescription1.ParameterTypeFullName); fieldDescription2.SetParameterAssemblyFullName(fieldDescription1.ParameterAssemblyFullName); return fieldDescription2; } /// <summary> /// Encode object. /// </summary> internal static object EncodeObject(object obj) { if (obj == null) { return null; } Type type = obj.GetType(); if (obj is PSObject) { // The "is" keyword takes care of PSObject and subclasses. return EncodePSObject((PSObject)obj); } else if (obj is ProgressRecord) { return ((ProgressRecord)obj).ToPSObjectForRemoting(); } else if (IsKnownType(type)) { return obj; } else if (type.IsEnum) { return (int)obj; } else if (obj is CultureInfo) { // The "is" keyword takes care of CultureInfo and subclasses. return obj.ToString(); } else if (obj is Exception) { return EncodeException((Exception)obj); } else if (type == typeof(object[])) { return EncodeObjectArray((object[])obj); } else if (type.IsArray) { return EncodeArray((Array)obj); } else if (obj is IList && IsCollection(type)) { return EncodeCollection((IList)obj); } else if (obj is IDictionary && IsDictionary(type)) { return EncodeDictionary((IDictionary)obj); } else if (type.IsSubclassOf(typeof(FieldDescription)) || type == typeof(FieldDescription)) { // The upcasting removes the Attributes, so we want to do this both when it // is a subclass and when it is a FieldDescription object. return EncodeClassOrStruct(UpcastFieldDescriptionSubclassAndDropAttributes((FieldDescription)obj)); } else if (IsEncodingAllowedForClassOrStruct(type)) { return EncodeClassOrStruct(obj); } else if (obj is RemoteHostCall) { return ((RemoteHostCall)obj).Encode(); } else if (obj is RemoteHostResponse) { return ((RemoteHostResponse)obj).Encode(); } else if (obj is SecureString) { return obj; } else if (obj is PSCredential) { return obj; } else if (IsGenericIEnumerableOfInt(type)) { return EncodeCollection((IList)obj); } else { throw RemoteHostExceptions.NewRemoteHostDataEncodingNotSupportedException(type); } } /// <summary> /// Decode object. /// </summary> internal static object DecodeObject(object obj, Type type) { if (obj == null) { return null; } Dbg.Assert(type != null, "Expected type != null"); if (type == typeof(PSObject)) { return DecodePSObject(obj); } else if (type == typeof(ProgressRecord)) { return ProgressRecord.FromPSObjectForRemoting(PSObject.AsPSObject(obj)); } else if (IsKnownType(type)) { return obj; } else if (obj is SecureString) { return obj; } else if (obj is PSCredential) { return obj; } else if (obj is PSObject && type == typeof(PSCredential)) { // BUGBUG: The following piece of code is a workaround // because custom serialization is busted. If rehydration // works correctly then PSCredential should be available PSObject objAsPSObject = (PSObject)obj; PSCredential cred = null; try { cred = new PSCredential((string)objAsPSObject.Properties["UserName"].Value, (SecureString)objAsPSObject.Properties["Password"].Value); } catch (GetValueException) { cred = null; } return cred; } else if (obj is int && type.IsEnum) { return Enum.ToObject(type, (int)obj); } else if (obj is string && type == typeof(CultureInfo)) { return new CultureInfo((string)obj); } else if (obj is PSObject && type == typeof(Exception)) { return DecodeException((PSObject)obj); } else if (obj is PSObject && type == typeof(object[])) { return DecodeObjectArray((PSObject)obj); } else if (obj is PSObject && type.IsArray) { return DecodeArray((PSObject)obj, type); } else if (obj is PSObject && IsCollection(type)) { return DecodeCollection((PSObject)obj, type); } else if (obj is PSObject && IsDictionary(type)) { return DecodeDictionary((PSObject)obj, type); } else if (obj is PSObject && IsEncodingAllowedForClassOrStruct(type)) { return DecodeClassOrStruct((PSObject)obj, type); } else if (obj is PSObject && IsGenericIEnumerableOfInt(type)) { // we cannot create an instance of interface type like IEnumerable // Since a Collection implements IEnumerable, falling back to use // that. return DecodeCollection((PSObject)obj, typeof(Collection<int>)); } else if (obj is PSObject && type == typeof(RemoteHostCall)) { return RemoteHostCall.Decode((PSObject)obj); } else if (obj is PSObject && type == typeof(RemoteHostResponse)) { return RemoteHostResponse.Decode((PSObject)obj); } else { throw RemoteHostExceptions.NewRemoteHostDataDecodingNotSupportedException(type); } } /// <summary> /// Encode and add as property. /// </summary> internal static void EncodeAndAddAsProperty(PSObject psObject, string propertyName, object propertyValue) { Dbg.Assert(psObject != null, "Expected psObject != null"); Dbg.Assert(propertyName != null, "Expected propertyName != null"); if (propertyValue == null) { return; } psObject.Properties.Add(new PSNoteProperty(propertyName, EncodeObject(propertyValue))); } /// <summary> /// Decode property value. /// </summary> internal static object DecodePropertyValue(PSObject psObject, string propertyName, Type propertyValueType) { Dbg.Assert(psObject != null, "Expected psObject != null"); Dbg.Assert(propertyName != null, "Expected propertyName != null"); Dbg.Assert(propertyValueType != null, "Expected propertyValueType != null"); ReadOnlyPSMemberInfoCollection<PSPropertyInfo> matches = psObject.Properties.Match(propertyName); if (matches.Count == 0) { return null; } Dbg.Assert(matches.Count == 1, "Expected matches.Count == 1"); return DecodeObject(matches[0].Value, propertyValueType); } /// <summary> /// Encode object array. /// </summary> private static PSObject EncodeObjectArray(object[] objects) { ArrayList arrayList = new ArrayList(); foreach (object obj in objects) { arrayList.Add(EncodeObjectWithType(obj)); } return new PSObject(arrayList); } /// <summary> /// Decode object array. /// </summary> private static object[] DecodeObjectArray(PSObject psObject) { // Rehydrate the array from the array list. ArrayList arrayList = SafelyGetBaseObject<ArrayList>(psObject); object[] objects = new object[arrayList.Count]; for (int i = 0; i < arrayList.Count; ++i) { objects[i] = DecodeObjectWithType(arrayList[i]); } return objects; } /// <summary> /// Encode object with type. /// </summary> private static PSObject EncodeObjectWithType(object obj) { if (obj == null) { return null; } PSObject psObject = RemotingEncoder.CreateEmptyPSObject(); psObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ObjectType, obj.GetType().ToString())); psObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ObjectValue, EncodeObject(obj))); return psObject; } /// <summary> /// Decode object with type. /// </summary> private static object DecodeObjectWithType(object obj) { if (obj == null) { return null; } PSObject psObject = SafelyCastObject<PSObject>(obj); string typeName = SafelyGetPropertyValue<string>(psObject, RemoteDataNameStrings.ObjectType); Type type = LanguagePrimitives.ConvertTo<Type>(typeName); object val = SafelyGetPropertyValue<object>(psObject, RemoteDataNameStrings.ObjectValue); return DecodeObject(val, type); } /// <summary> /// Array is zero based. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static bool ArrayIsZeroBased(Array array) { int rank = array.Rank; for (int i = 0; i < rank; ++i) { if (array.GetLowerBound(i) != 0) { return false; } } return true; } /// <summary> /// Encode array. /// </summary> private static PSObject EncodeArray(Array array) { Dbg.Assert(array != null, "Expected array != null"); Dbg.Assert(ArrayIsZeroBased(array), "Expected ArrayIsZeroBased(array)"); Type arrayType = array.GetType(); Type elementType = arrayType.GetElementType(); int rank = array.Rank; int[] lengths = new int[rank]; for (int i = 0; i < rank; ++i) { lengths[i] = array.GetUpperBound(i) + 1; } Indexer indexer = new Indexer(lengths); ArrayList elements = new ArrayList(); foreach (int[] index in indexer) { object elementValue = array.GetValue(index); elements.Add(EncodeObject(elementValue)); } PSObject psObject = RemotingEncoder.CreateEmptyPSObject(); psObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodArrayElements, elements)); psObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodArrayLengths, lengths)); return psObject; } /// <summary> /// Decode array. /// </summary> private static Array DecodeArray(PSObject psObject, Type type) { // Extract the type. Dbg.Assert(type.IsArray, "Expected type.IsArray"); Type elementType = type.GetElementType(); // Extract elements from psObject. PSObject psObjectContainingElements = SafelyGetPropertyValue<PSObject>(psObject, RemoteDataNameStrings.MethodArrayElements); ArrayList elements = SafelyGetBaseObject<ArrayList>(psObjectContainingElements); // Extract lengths from psObject. PSObject psObjectContainingLengths = SafelyGetPropertyValue<PSObject>(psObject, RemoteDataNameStrings.MethodArrayLengths); ArrayList lengthsArrayList = SafelyGetBaseObject<ArrayList>(psObjectContainingLengths); int[] lengths = (int[])lengthsArrayList.ToArray(typeof(int)); // Reconstitute the array. Indexer indexer = new Indexer(lengths); Array array = Array.CreateInstance(elementType, lengths); int elementIndex = 0; foreach (int[] index in indexer) { object elementValue = DecodeObject(elements[elementIndex++], elementType); array.SetValue(elementValue, index); } return array; } /// <summary> /// Is object dictionary type. /// </summary> private static bool IsObjectDictionaryType(Type dictionaryType) { // True if the value-type of the dictionary is object; false otherwise. if (!IsDictionary(dictionaryType)) { return false; } Type[] elementTypes = dictionaryType.GetGenericArguments(); if (elementTypes.Length != 2) { return false; } Type valueType = elementTypes[1]; return valueType == typeof(object); } /// <summary> /// Encode object dictionary. /// </summary> private static PSObject EncodeObjectDictionary(IDictionary dictionary) { Dbg.Assert(IsObjectDictionaryType(dictionary.GetType()), "Expected IsObjectDictionaryType(dictionary.GetType())"); // Encode the dictionary as a hashtable. Hashtable hashtable = new Hashtable(); foreach (object key in dictionary.Keys) { hashtable.Add(EncodeObject(key), EncodeObjectWithType(dictionary[key])); } return new PSObject(hashtable); } /// <summary> /// Decode object dictionary. /// </summary> private static IDictionary DecodeObjectDictionary(PSObject psObject, Type dictionaryType) { Dbg.Assert(IsObjectDictionaryType(dictionaryType), "Expected IsObjectDictionaryType(dictionaryType)"); // Get the element type. Type[] elementTypes = dictionaryType.GetGenericArguments(); Dbg.Assert(elementTypes.Length == 2, "Expected elementTypes.Length == 2"); Type keyType = elementTypes[0]; Type valueType = elementTypes[1]; Dbg.Assert(valueType == typeof(object), "Expected valueType == typeof(object)"); // Rehydrate the dictionary from the hashtable. Hashtable hashtable = SafelyGetBaseObject<Hashtable>(psObject); IDictionary dictionary = (IDictionary)Activator.CreateInstance(dictionaryType); foreach (object key in hashtable.Keys) { dictionary.Add( DecodeObject(key, keyType), DecodeObjectWithType(hashtable[key])); } return dictionary; } /// <summary> /// Safely get base object. /// </summary> private static T SafelyGetBaseObject<T>(PSObject psObject) { if (psObject == null || psObject.BaseObject == null || psObject.BaseObject is not T) { throw RemoteHostExceptions.NewDecodingFailedException(); } return (T)psObject.BaseObject; } /// <summary> /// Safely cast object. /// </summary> private static T SafelyCastObject<T>(object obj) { if (obj is T) { return (T)obj; } throw RemoteHostExceptions.NewDecodingFailedException(); } /// <summary> /// Safely get property value. /// </summary> private static T SafelyGetPropertyValue<T>(PSObject psObject, string key) { PSPropertyInfo propertyInfo = psObject.Properties[key]; if (propertyInfo == null || propertyInfo.Value == null || propertyInfo.Value is not T) { throw RemoteHostExceptions.NewDecodingFailedException(); } return (T)propertyInfo.Value; } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Runtime.InteropServices; using Grpc.Core; namespace Grpc.Core.Internal { /// <summary> /// grpcsharp_batch_context /// </summary> internal class BatchContextSafeHandle : SafeHandleZeroIsInvalid { [DllImport("grpc_csharp_ext.dll")] static extern BatchContextSafeHandle grpcsharp_batch_context_create(); [DllImport("grpc_csharp_ext.dll")] static extern IntPtr grpcsharp_batch_context_recv_initial_metadata(BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern IntPtr grpcsharp_batch_context_recv_message_length(BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern void grpcsharp_batch_context_recv_message_to_buffer(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen); [DllImport("grpc_csharp_ext.dll")] static extern StatusCode grpcsharp_batch_context_recv_status_on_client_status(BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern IntPtr grpcsharp_batch_context_recv_status_on_client_details(BatchContextSafeHandle ctx); // returns const char* [DllImport("grpc_csharp_ext.dll")] static extern IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata(BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern CallSafeHandle grpcsharp_batch_context_server_rpc_new_call(BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern IntPtr grpcsharp_batch_context_server_rpc_new_method(BatchContextSafeHandle ctx); // returns const char* [DllImport("grpc_csharp_ext.dll")] static extern IntPtr grpcsharp_batch_context_server_rpc_new_host(BatchContextSafeHandle ctx); // returns const char* [DllImport("grpc_csharp_ext.dll")] static extern Timespec grpcsharp_batch_context_server_rpc_new_deadline(BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern IntPtr grpcsharp_batch_context_server_rpc_new_request_metadata(BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern int grpcsharp_batch_context_recv_close_on_server_cancelled(BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern void grpcsharp_batch_context_destroy(IntPtr ctx); private BatchContextSafeHandle() { } public static BatchContextSafeHandle Create() { return grpcsharp_batch_context_create(); } public IntPtr Handle { get { return handle; } } // Gets data of recv_initial_metadata completion. public Metadata GetReceivedInitialMetadata() { IntPtr metadataArrayPtr = grpcsharp_batch_context_recv_initial_metadata(this); return MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr); } // Gets data of recv_status_on_client completion. public ClientSideStatus GetReceivedStatusOnClient() { string details = Marshal.PtrToStringAnsi(grpcsharp_batch_context_recv_status_on_client_details(this)); var status = new Status(grpcsharp_batch_context_recv_status_on_client_status(this), details); IntPtr metadataArrayPtr = grpcsharp_batch_context_recv_status_on_client_trailing_metadata(this); var metadata = MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr); return new ClientSideStatus(status, metadata); } // Gets data of recv_message completion. public byte[] GetReceivedMessage() { IntPtr len = grpcsharp_batch_context_recv_message_length(this); if (len == new IntPtr(-1)) { return null; } byte[] data = new byte[(int)len]; grpcsharp_batch_context_recv_message_to_buffer(this, data, new UIntPtr((ulong)data.Length)); return data; } // Gets data of server_rpc_new completion. public ServerRpcNew GetServerRpcNew() { var call = grpcsharp_batch_context_server_rpc_new_call(this); var method = Marshal.PtrToStringAnsi(grpcsharp_batch_context_server_rpc_new_method(this)); var host = Marshal.PtrToStringAnsi(grpcsharp_batch_context_server_rpc_new_host(this)); var deadline = grpcsharp_batch_context_server_rpc_new_deadline(this); IntPtr metadataArrayPtr = grpcsharp_batch_context_server_rpc_new_request_metadata(this); var metadata = MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr); return new ServerRpcNew(call, method, host, deadline, metadata); } // Gets data of receive_close_on_server completion. public bool GetReceivedCloseOnServerCancelled() { return grpcsharp_batch_context_recv_close_on_server_cancelled(this) != 0; } protected override bool ReleaseHandle() { grpcsharp_batch_context_destroy(handle); return true; } } /// <summary> /// Status + metadata received on client side when call finishes. /// (when receive_status_on_client operation finishes). /// </summary> internal struct ClientSideStatus { readonly Status status; readonly Metadata trailers; public ClientSideStatus(Status status, Metadata trailers) { this.status = status; this.trailers = trailers; } public Status Status { get { return this.status; } } public Metadata Trailers { get { return this.trailers; } } } /// <summary> /// Details of a newly received RPC. /// </summary> internal struct ServerRpcNew { readonly CallSafeHandle call; readonly string method; readonly string host; readonly Timespec deadline; readonly Metadata requestMetadata; public ServerRpcNew(CallSafeHandle call, string method, string host, Timespec deadline, Metadata requestMetadata) { this.call = call; this.method = method; this.host = host; this.deadline = deadline; this.requestMetadata = requestMetadata; } public CallSafeHandle Call { get { return this.call; } } public string Method { get { return this.method; } } public string Host { get { return this.host; } } public Timespec Deadline { get { return this.deadline; } } public Metadata RequestMetadata { get { return this.requestMetadata; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// VirtualNetworkGatewaysOperations operations. /// </summary> public partial interface IVirtualNetworkGatewaysOperations { /// <summary> /// The Put VirtualNetworkGateway operation creates/updates a virtual /// network gateway in the specified resource group through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network /// Gateway operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualNetworkGateway>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Put VirtualNetworkGateway operation creates/updates a virtual /// network gateway in the specified resource group through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network /// Gateway operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualNetworkGateway>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Get VirtualNetworkGateway operation retrieves information /// about the specified virtual network gateway through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualNetworkGateway>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Delete VirtualNetworkGateway operation deletes the specified /// virtual network Gateway through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Delete VirtualNetworkGateway operation deletes the specified /// virtual network Gateway through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List VirtualNetworkGateways operation retrieves all the /// virtual network gateways stored. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Reset VirtualNetworkGateway operation resets the primary of /// the virtual network gateway in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway /// operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualNetworkGateway>> ResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Reset VirtualNetworkGateway operation resets the primary of /// the virtual network gateway in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway /// operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<VirtualNetworkGateway>> BeginResetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VirtualNetworkGateway parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Generatevpnclientpackage operation generates Vpn client /// package for P2S client of the virtual network gateway in the /// specified resource group through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Generating Virtual Network /// Gateway Vpn client package operation through Network resource /// provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<string>> GeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List VirtualNetworkGateways operation retrieves all the /// virtual network gateways stored. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<VirtualNetworkGateway>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * Created by SharpDevelop. * User: Alle * Date: 30.01.2006 * Time: 23:39 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Globalization; namespace LoksimUtil { /// <summary> /// Description of Class1. /// </summary> public class LoksimHelper { public const int KEY_SIFA = 1; public const int KEY_INDUSI = 2; public const int KEY_FREIINDUSI = 3; public const int KEY_LZB = 4; public const int KEY_LICHT = 5; public const int KEY_FERNLICHT = 6; public const int KEY_HAUPTSCHALTER = 7; public const int KEY_PFIFF = 8; public const int KEY_GLOCKE = 9; public const int KEY_AFBVZIELANZEIGEN = 10; public const int KEY_TUEREN = 11; public const int KEY_SANDEN = 12; public const int KEY_AFB = 13; public const int KEY_STUP = 14; public const int KEY_STDOWN = 15; public const int KEY_STLEFT = 16; public const int KEY_STRIGHT = 17; public const int KEY_BREMSEN0 = 18; public const int KEY_BREMSEN1 = 19; public const int KEY_BREMSEN2 = 20; public const int KEY_BREMSEN3 = 21; public const int KEY_BREMSEN4 = 22; public const int KEY_BREMSEN5 = 23; public const int KEY_BREMSEN6 = 24; public const int KEY_BREMSEN7 = 25; public const int KEY_BREMSEN8 = 26; public const int KEY_BREMSEN9 = 27; public const int KEY_SPEICHERBREMSE = 28; public const int KEY_STNULLSTELLUNG = 29; public const int KEY_ZUGKRAFTSTELLER = 30; public const int KEY_BEFEHLINDUSI = 31; public const int KEY_HALTANSAGE = 32; public const int KEY_BUEGEL = 33; public const int KEY_FAHRTENSCHREIBER = 34; public const int KEY_BUCHFAHRPLAN = 35; public const int KEY_BREMSZETTEL = 36; public const int KEY_FAHRZEITENHEFT = 37; public const int KEY_LOKINFO = 38; public const int KEY_LUEFTER = 39; public const int KEY_FREIWACHSAM = 40; public const int KEY_VSOLLAFBLZB = 41; public const int KEY_MAGNETBREMSE = 42; public const int KEY_RICHTUNGSWALZE = 43; public const int KEY_SONDSOUND1 = 44; public const int KEY_SONDSOUND2 = 45; public const int KEY_RICHTUNGSWALZE_V = 46; public const int KEY_RICHTUNGSWALZE_N = 47; public const int KEY_RICHTUNGSWALZE_R = 48; public const int KEY_STOERSCHALTER_INDUSI = 49; public const int KEY_WEGMESSUNG = 50; //OleParameter public const char cParamSeparator = '|'; public const char cKeyValueSeparator = '='; //Float public const string cLOK_COMMON_ACTSPEED = "LOK.COMMON.ACTSPEED"; public const string cLOK_COMMON_MAXSPEED = "LOK.COMMON.MAXSPEED"; public const string cLOK_COMMON_ZUGSICHERUNG = "LOK.COMMON.ZUGSICHERUNGSSYSTEME"; public const string cLOK_SYSTEM_INDUSIHZ1000 = "LOK.SYSTEM.1000HZUEBERWACHUNG"; public const string cLOK_SYSTEM_INDUSIHZ500 = "LOK.SYSTEM.500HZUEBERWACHUNG"; //Bool Variablen public const string cLOK_ANZEIGE_SCHLEUDERN = "LOK.ANZEIGE.SCHLEUDERN"; public const string cLOK_ANZEIGE_SANDEN = "LOK.ANZEIGE.SANDEN"; public const string cLOK_ANZEIGE_HAUPTSCHALTER = "LOK.ANZEIGE.HAUPTSCHALTER"; public const string cLOK_ANZEIGE_SIFA = "LOK.ANZEIGE.SIFA"; public const string cLOK_ANZEIGE_INDUSIHZ1000 = "LOK.ANZEIGE.INDUSIHZ1000"; public const string cLOK_ANZEIGE_INDUSIHZ500 = "LOK.ANZEIGE.INDUSIHZ500"; public const string cLOK_ANZEIGE_INDUSI95 = "LOK.ANZEIGE.INDUSI95"; public const string cLOK_ANZEIGE_INDUSI75 = "LOK.ANZEIGE.INDUSI75"; public const string cLOK_ANZEIGE_INDUSI60 = "LOK.ANZEIGE.INDUSI60"; public const string cLOK_ANZEIGE_INDUSIWECHSELBLINKEN = "LOK.ANZEIGE.WECHSELBLINKEN"; public const string cLOK_ANZEIGE_INDUSIBEFEHL = "LOK.ANZEIGE.INDUSIBEFEHL"; public const string cLOK_ANZEIGE_LZBBETRIEB = "LOK.ANZEIGE.LZBBETRIEB"; public const string cLOK_ANZEIGE_LZBG = "LOK.ANZEIGE.LZBG"; public const string cLOK_ANZEIGE_LZBU = "LOK.ANZEIGE.LZBU"; public const string cLOK_ANZEIGE_LZBENDE = "LOK.ANZEIGE.LZBENDE"; public const string cLOK_ANZEIGE_SCHNELLBREMSUNG = "LOK.ANZEIGE.SCHNELLBREMSUNG"; public const string cLOK_ANZEIGE_MAGNETBREMSE = "LOK.ANZEIGE.MAGNETBREMSE"; public const string cLOK_ANZEIGE_HOHEABBREMSUNGVORH = "LOK.ANZEIGE.HOHEABBREMSUNGVORH"; public const string cLOK_ANZEIGE_TUER1 = "LOK.ANZEIGE.TUER1"; public const string cLOK_ANZEIGE_TUER2 = "LOK.ANZEIGE.TUER2"; public const string cLOK_ANZEIGE_TUERVERRIEGELUNG = "LOK.ANZEIGE.TUERVERRIEGELUNG"; public const string cLOK_ANZEIGE_LICHT = "LOK.ANZEIGE.LICHT"; public const string cLOK_ANZEIGE_MESS = "LOK.ANZEIGE.MESS"; public const string cLOK_ANZEIGE_AFB = "LOK.ANZEIGE.AFB"; public const string cLOK_ANZEIGE_TRAKTIONGESPERRT = "LOK.ANZEIGE.TRAKTIONGESPERRT"; public const string cLOK_ANZEIGE_FEDERSPEICHERBREMSE = "LOK.ANZEIGE.FEDERSPEICHERBREMSE"; public const string cLOK_ANZEIGE_ZUGKRAFTSTELLERAKTIV = "LOK.ANZEIGE.ZUGKRAFTSTELLERAKTIV"; public const string cLOK_ANZEIGE_BUEGELPANTO = "LOK.ANZEIGE.BUEGELPANTO"; //Float Variablen public const string cLOK_INSTRUMENT_TACHO = "LOK.INSTRUMENT.TACHO"; public const string cLOK_INSTRUMENT_LZBVZIEL = "LOK.INSTRUMENT.LZBVZIEL"; public const string cLOK_INSTRUMENT_LZBVZIELABSTANDDIGITAL = "LOK.INSTRUMENT.LZBVZIELABSTANDDIGITAL"; public const string cLOK_INSTRUMENT_LZBVZIELABSTANDBALKEN = "LOK.INSTRUMENT.LZBVZIELABSTANDBALKEN"; public const string cLOK_INSTRUMENT_AFB = "LOK.INSTRUMENT.AFB"; public const string cLOK_INSTRUMENT_BREMSDRUCK = "LOK.INSTRUMENT.BREMSDRUCK"; public const string cLOK_INSTRUMENT_BREMSZYLINDERDRUCK = "LOK.INSTRUMENT.BREMSZYLINDERDRUCK"; public const string cLOK_INSTRUMENT_2BREMSZYLINDERDR = "LOK.INSTRUMENT.2BREMSZYLINDERDR"; public const string cLOK_INSTRUMENT_DYNBREMSSTUFE = "LOK.INSTRUMENT.DYNBREMSSTUFE"; public const string cLOK_INSTRUMENT_ISTSTUFE = "LOK.INSTRUMENT.ISTSTUFE"; public const string cLOK_INSTRUMENT_SOLLSTUFE = "LOK.INSTRUMENT.SOLLSTUFE"; public const string cLOK_INSTRUMENT_MOTORSTROM = "LOK.INSTRUMENT.MOTORSTROM"; public const string cLOK_INSTRUMENT_OBERSTROM = "LOK.INSTRUMENT.OBERSTROM"; public const string cLOK_INSTRUMENT_KRAFT = "LOK.INSTRUMENT.KRAFT"; public const string cLOK_INSTRUMENT_ZUGKRAFTSTELLER = "LOK.INSTRUMENT.ZUGKRAFTSTELLER"; public const string cLOK_INSTRUMENT_VSOLLSTELLER = "LOK.INSTRUMENT.VSOLLSTELLER"; public const string cLOK_INSTRUMENT_FAHRSPANNUNG = "LOK.INSTRUMENT.FAHRSPANNUNG"; //Float public const string cSIM_COMMON_SIMTIME = "SIM.COMMON.SIMTIME"; //Zeit die in der Simulation vergangen ist in Sekunden public static void AddParam( ref string ParamString, string ParamName) { if( ParamString != "") { ParamString = ParamString + cParamSeparator; } ParamString = ParamString + ParamName; } public static string GetParamRawString( string CodedParamString, string ParamName) { string Result = ""; string ParamPlusSep = ParamName + cKeyValueSeparator; int PosStart = CodedParamString.IndexOf( ParamPlusSep); if( PosStart >= 0) { Result = CodedParamString.Substring( PosStart + ParamPlusSep.Length); int PosEnd = Result.IndexOf( cParamSeparator); if( PosEnd >= 0) { Result = Result.Substring( 0, PosEnd); } } return Result; } public static bool GetParamBool( string CodedParamString, string ParamName) { string Ret = GetParamRawString( CodedParamString, ParamName); if( Ret == "TRUE") { return true; } else { return false; } } public static double GetParamFloat( string CodedParamString, string ParamName) { string Ret = GetParamRawString( CodedParamString, ParamName); double Value; try { NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat; // Displays the same value with a blank as the separator. nfi.NumberDecimalSeparator = "."; Value = Double.Parse( Ret, nfi); } catch { Value = 0.0; } return Value; } public static string GetParamString(string CodedParamString, string ParamName) { return GetParamRawString(CodedParamString, ParamName); } public LoksimHelper() { } } }
using System; using System.Collections.Generic; using Csla; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERCLevel; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B05_CountryColl (editable child list).<br/> /// This is a generated base class of <see cref="B05_CountryColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="B04_SubContinent"/> editable child object.<br/> /// The items of the collection are <see cref="B06_Country"/> objects. /// </remarks> [Serializable] public partial class B05_CountryColl : BusinessListBase<B05_CountryColl, B06_Country> { #region Collection Business Methods /// <summary> /// Removes a <see cref="B06_Country"/> item from the collection. /// </summary> /// <param name="country_ID">The Country_ID of the item to be removed.</param> public void Remove(int country_ID) { foreach (var b06_Country in this) { if (b06_Country.Country_ID == country_ID) { Remove(b06_Country); break; } } } /// <summary> /// Determines whether a <see cref="B06_Country"/> item is in the collection. /// </summary> /// <param name="country_ID">The Country_ID of the item to search for.</param> /// <returns><c>true</c> if the B06_Country is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int country_ID) { foreach (var b06_Country in this) { if (b06_Country.Country_ID == country_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="B06_Country"/> item is in the collection's DeletedList. /// </summary> /// <param name="country_ID">The Country_ID of the item to search for.</param> /// <returns><c>true</c> if the B06_Country is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int country_ID) { foreach (var b06_Country in DeletedList) { if (b06_Country.Country_ID == country_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="B06_Country"/> item of the <see cref="B05_CountryColl"/> collection, based on item key properties. /// </summary> /// <param name="country_ID">The Country_ID.</param> /// <returns>A <see cref="B06_Country"/> object.</returns> public B06_Country FindB06_CountryByParentProperties(int country_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Country_ID.Equals(country_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B05_CountryColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="B05_CountryColl"/> collection.</returns> internal static B05_CountryColl NewB05_CountryColl() { return DataPortal.CreateChild<B05_CountryColl>(); } /// <summary> /// Factory method. Loads a <see cref="B05_CountryColl"/> object from the given list of B06_CountryDto. /// </summary> /// <param name="data">The list of <see cref="B06_CountryDto"/>.</param> /// <returns>A reference to the fetched <see cref="B05_CountryColl"/> object.</returns> internal static B05_CountryColl GetB05_CountryColl(List<B06_CountryDto> data) { B05_CountryColl obj = new B05_CountryColl(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B05_CountryColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B05_CountryColl() { // 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="B05_CountryColl"/> collection items from the given list of B06_CountryDto. /// </summary> /// <param name="data">The list of <see cref="B06_CountryDto"/>.</param> private void Fetch(List<B06_CountryDto> data) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; var args = new DataPortalHookArgs(data); OnFetchPre(args); foreach (var dto in data) { Add(B06_Country.GetB06_Country(dto)); } OnFetchPost(args); RaiseListChangedEvents = rlce; } /// <summary> /// Loads <see cref="B06_Country"/> items on the B05_CountryObjects collection. /// </summary> /// <param name="collection">The grand parent <see cref="B03_SubContinentColl"/> collection.</param> internal void LoadItems(B03_SubContinentColl collection) { foreach (var item in this) { var obj = collection.FindB04_SubContinentByParentProperties(item.parent_SubContinent_ID); var rlce = obj.B05_CountryObjects.RaiseListChangedEvents; obj.B05_CountryObjects.RaiseListChangedEvents = false; obj.B05_CountryObjects.Add(item); obj.B05_CountryObjects.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 } }
using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; namespace AssetBundles { public class BuildScript { public static string overloadedDevelopmentServerURL = ""; static public string CreateAssetBundleDirectory() { // Choose the output path according to the build target. string outputPath = Path.Combine(Utility.AssetBundlesOutputPath, Utility.GetPlatformName()); if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath); return outputPath; } public static void BuildAssetBundles() { BuildAssetBundles(null); } public static void BuildAssetBundles(AssetBundleBuild[] builds) { // Choose the output path according to the build target. string outputPath = CreateAssetBundleDirectory(); var options = BuildAssetBundleOptions.None; bool shouldCheckODR = EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS; #if UNITY_TVOS shouldCheckODR |= EditorUserBuildSettings.activeBuildTarget == BuildTarget.tvOS; #endif if (shouldCheckODR) { #if ENABLE_IOS_ON_DEMAND_RESOURCES if (PlayerSettings.iOS.useOnDemandResources) options |= BuildAssetBundleOptions.UncompressedAssetBundle; #endif #if ENABLE_IOS_APP_SLICING options |= BuildAssetBundleOptions.UncompressedAssetBundle; #endif } if (builds == null || builds.Length == 0) { //@TODO: use append hash... (Make sure pipeline works correctly with it.) BuildPipeline.BuildAssetBundles(outputPath, options, EditorUserBuildSettings.activeBuildTarget); } else { BuildPipeline.BuildAssetBundles(outputPath, builds, options, EditorUserBuildSettings.activeBuildTarget); } } public static void WriteServerURL() { string downloadURL; if (string.IsNullOrEmpty(overloadedDevelopmentServerURL) == false) { downloadURL = overloadedDevelopmentServerURL; } else { IPHostEntry host; string localIP = ""; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } downloadURL = "http://" + localIP + ":7888/"; } string assetBundleManagerResourcesDirectory = "Assets/AssetBundleManager/Resources"; string assetBundleUrlPath = Path.Combine(assetBundleManagerResourcesDirectory, "AssetBundleServerURL.bytes"); Directory.CreateDirectory(assetBundleManagerResourcesDirectory); File.WriteAllText(assetBundleUrlPath, downloadURL); AssetDatabase.Refresh(); } public static void BuildPlayer() { var outputPath = EditorUtility.SaveFolderPanel("Choose Location of the Built Game", "", ""); if (outputPath.Length == 0) return; string[] levels = GetLevelsFromBuildSettings(); if (levels.Length == 0) { Debug.Log("Nothing to build."); return; } string targetName = GetBuildTargetName(EditorUserBuildSettings.activeBuildTarget); if (targetName == null) return; // Build and copy AssetBundles. BuildScript.BuildAssetBundles(); WriteServerURL(); #if UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 BuildOptions option = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None; BuildPipeline.BuildPlayer(levels, outputPath + targetName, EditorUserBuildSettings.activeBuildTarget, option); #else BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); buildPlayerOptions.scenes = levels; buildPlayerOptions.locationPathName = outputPath + targetName; buildPlayerOptions.assetBundleManifestPath = GetAssetBundleManifestFilePath(); buildPlayerOptions.target = EditorUserBuildSettings.activeBuildTarget; buildPlayerOptions.options = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None; BuildPipeline.BuildPlayer(buildPlayerOptions); #endif } public static void BuildStandalonePlayer() { var outputPath = EditorUtility.SaveFolderPanel("Choose Location of the Built Game", "", ""); if (outputPath.Length == 0) return; string[] levels = GetLevelsFromBuildSettings(); if (levels.Length == 0) { Debug.Log("Nothing to build."); return; } string targetName = GetBuildTargetName(EditorUserBuildSettings.activeBuildTarget); if (targetName == null) return; // Build and copy AssetBundles. BuildScript.BuildAssetBundles(); BuildScript.CopyAssetBundlesTo(Path.Combine(Application.streamingAssetsPath, Utility.AssetBundlesOutputPath)); AssetDatabase.Refresh(); #if UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0 BuildOptions option = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None; BuildPipeline.BuildPlayer(levels, outputPath + targetName, EditorUserBuildSettings.activeBuildTarget, option); #else BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); buildPlayerOptions.scenes = levels; buildPlayerOptions.locationPathName = outputPath + targetName; buildPlayerOptions.assetBundleManifestPath = GetAssetBundleManifestFilePath(); buildPlayerOptions.target = EditorUserBuildSettings.activeBuildTarget; buildPlayerOptions.options = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None; BuildPipeline.BuildPlayer(buildPlayerOptions); #endif } public static string GetBuildTargetName(BuildTarget target) { switch (target) { case BuildTarget.Android: return "/test.apk"; case BuildTarget.StandaloneWindows: case BuildTarget.StandaloneWindows64: return "/test.exe"; case BuildTarget.StandaloneOSXIntel: case BuildTarget.StandaloneOSXIntel64: case BuildTarget.StandaloneOSXUniversal: return "/test.app"; case BuildTarget.WebPlayer: case BuildTarget.WebPlayerStreamed: case BuildTarget.WebGL: case BuildTarget.iOS: return ""; // Add more build targets for your own. default: Debug.Log("Target not implemented."); return null; } } static void CopyAssetBundlesTo(string outputPath) { // Clear streaming assets folder. FileUtil.DeleteFileOrDirectory(Application.streamingAssetsPath); Directory.CreateDirectory(outputPath); string outputFolder = Utility.GetPlatformName(); // Setup the source folder for assetbundles. var source = Path.Combine(Path.Combine(System.Environment.CurrentDirectory, Utility.AssetBundlesOutputPath), outputFolder); if (!System.IO.Directory.Exists(source)) Debug.Log("No assetBundle output folder, try to build the assetBundles first."); // Setup the destination folder for assetbundles. var destination = System.IO.Path.Combine(outputPath, outputFolder); if (System.IO.Directory.Exists(destination)) FileUtil.DeleteFileOrDirectory(destination); FileUtil.CopyFileOrDirectory(source, destination); } static string[] GetLevelsFromBuildSettings() { List<string> levels = new List<string>(); for (int i = 0; i < EditorBuildSettings.scenes.Length; ++i) { if (EditorBuildSettings.scenes[i].enabled) levels.Add(EditorBuildSettings.scenes[i].path); } return levels.ToArray(); } static string GetAssetBundleManifestFilePath() { var relativeAssetBundlesOutputPathForPlatform = Path.Combine(Utility.AssetBundlesOutputPath, Utility.GetPlatformName()); return Path.Combine(relativeAssetBundlesOutputPathForPlatform, Utility.GetPlatformName()) + ".manifest"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Xsl.XsltOld { using System.Globalization; using System.Diagnostics; using System.IO; using System.Xml.XPath; using MS.Internal.Xml.XPath; using System.Text; using System.Collections; using System.Collections.Generic; using System.Xml.Xsl.XsltOld.Debugger; using System.Reflection; using System.Security; internal sealed class Processor : IXsltProcessor { // // Static constants // private const int StackIncrement = 10; // // Execution result // internal enum ExecResult { Continue, // Continues next iteration immediately Interrupt, // Returns to caller, was processed enough Done // Execution finished } internal enum OutputResult { Continue, Interrupt, Overflow, Error, Ignore } private ExecResult _execResult; // // Compiled stylesheet // private Stylesheet _stylesheet; // Root of import tree of template managers private RootAction _rootAction; private Key[] _keyList; private List<TheQuery> _queryStore; // // Document Being transformed // private XPathNavigator _document; // // Execution action stack // private HWStack _actionStack; private HWStack _debuggerStack; // // Register for returning value from calling nested action // private StringBuilder _sharedStringBuilder; // // Output related member variables // private int _ignoreLevel; private StateMachine _xsm; private RecordBuilder _builder; private XsltOutput _output; private XmlNameTable _nameTable = new NameTable(); private XmlResolver _resolver; #pragma warning disable 618 private XsltArgumentList _args; #pragma warning restore 618 private Hashtable _scriptExtensions; private ArrayList _numberList; // // Template lookup action // private TemplateLookupAction _templateLookup = new TemplateLookupAction(); private IXsltDebugger _debugger; private Query[] _queryList; private ArrayList _sortArray; private Hashtable _documentCache; // NOTE: ValueOf() can call Matches() through XsltCompileContext.PreserveWhitespace(), // that's why we use two different contexts here, valueOfContext and matchesContext private XsltCompileContext _valueOfContext; private XsltCompileContext _matchesContext; internal XPathNavigator Current { get { ActionFrame frame = (ActionFrame)_actionStack.Peek(); return frame != null ? frame.Node : null; } } internal ExecResult ExecutionResult { get { return _execResult; } set { Debug.Assert(_execResult == ExecResult.Continue); _execResult = value; } } internal Stylesheet Stylesheet { get { return _stylesheet; } } internal XmlResolver Resolver { get { Debug.Assert(_resolver != null, "Constructor should create it if null passed"); return _resolver; } } internal ArrayList SortArray { get { Debug.Assert(_sortArray != null, "InitSortArray() wasn't called"); return _sortArray; } } internal Key[] KeyList { get { return _keyList; } } internal XPathNavigator GetNavigator(Uri ruri) { XPathNavigator result = null; if (_documentCache != null) { result = _documentCache[ruri] as XPathNavigator; if (result != null) { return result.Clone(); } } else { _documentCache = new Hashtable(); } Object input = _resolver.GetEntity(ruri, null, null); if (input is Stream) { XmlTextReaderImpl tr = new XmlTextReaderImpl(ruri.ToString(), (Stream)input); { tr.XmlResolver = _resolver; } // reader is closed by Compiler.LoadDocument() result = ((IXPathNavigable)Compiler.LoadDocument(tr)).CreateNavigator(); } else if (input is XPathNavigator) { result = (XPathNavigator)input; } else { throw XsltException.Create(SR.Xslt_CantResolve, ruri.ToString()); } _documentCache[ruri] = result.Clone(); return result; } internal void AddSort(Sort sortinfo) { Debug.Assert(_sortArray != null, "InitSortArray() wasn't called"); _sortArray.Add(sortinfo); } internal void InitSortArray() { if (_sortArray == null) { _sortArray = new ArrayList(); } else { _sortArray.Clear(); } } internal object GetGlobalParameter(XmlQualifiedName qname) { object parameter = _args.GetParam(qname.Name, qname.Namespace); if (parameter == null) { return null; } // TODO: use typecode there. if ( parameter is XPathNodeIterator || parameter is XPathNavigator || parameter is Boolean || parameter is Double || parameter is String ) { // doing nothing } else if ( parameter is Int16 || parameter is UInt16 || parameter is Int32 || parameter is UInt32 || parameter is Int64 || parameter is UInt64 || parameter is Single || parameter is Decimal ) { parameter = XmlConvert.ToXPathDouble(parameter); } else { parameter = parameter.ToString(); } return parameter; } internal object GetExtensionObject(string nsUri) { return _args.GetExtensionObject(nsUri); } internal object GetScriptObject(string nsUri) { return _scriptExtensions[nsUri]; } internal RootAction RootAction { get { return _rootAction; } } internal XPathNavigator Document { get { return _document; } } #if DEBUG private bool stringBuilderLocked = false; #endif internal StringBuilder GetSharedStringBuilder() { #if DEBUG Debug.Assert(! stringBuilderLocked); #endif if (_sharedStringBuilder == null) { _sharedStringBuilder = new StringBuilder(); } else { _sharedStringBuilder.Length = 0; } #if DEBUG stringBuilderLocked = true; #endif return _sharedStringBuilder; } internal void ReleaseSharedStringBuilder() { // don't clean stringBuilderLocked here. ToString() will happen after this call #if DEBUG stringBuilderLocked = false; #endif } internal ArrayList NumberList { get { if (_numberList == null) { _numberList = new ArrayList(); } return _numberList; } } internal IXsltDebugger Debugger { get { return _debugger; } } internal HWStack ActionStack { get { return _actionStack; } } internal RecordBuilder Builder { get { return _builder; } } internal XsltOutput Output { get { return _output; } } // // Construction // public Processor( XPathNavigator doc, XsltArgumentList args, XmlResolver resolver, Stylesheet stylesheet, List<TheQuery> queryStore, RootAction rootAction, IXsltDebugger debugger ) { _stylesheet = stylesheet; _queryStore = queryStore; _rootAction = rootAction; _queryList = new Query[queryStore.Count]; { for (int i = 0; i < queryStore.Count; i++) { _queryList[i] = Query.Clone(queryStore[i].CompiledQuery.QueryTree); } } _xsm = new StateMachine(); _document = doc; _builder = null; _actionStack = new HWStack(StackIncrement); _output = _rootAction.Output; _resolver = resolver ?? XmlNullResolver.Singleton; _args = args ?? new XsltArgumentList(); _debugger = debugger; if (_debugger != null) { _debuggerStack = new HWStack(StackIncrement, /*limit:*/1000); _templateLookup = new TemplateLookupActionDbg(); } // Clone the compile-time KeyList if (_rootAction.KeyList != null) { _keyList = new Key[_rootAction.KeyList.Count]; for (int i = 0; i < _keyList.Length; i++) { _keyList[i] = _rootAction.KeyList[i].Clone(); } } _scriptExtensions = new Hashtable(_stylesheet.ScriptObjectTypes.Count); { foreach (DictionaryEntry entry in _stylesheet.ScriptObjectTypes) { string namespaceUri = (string)entry.Key; if (GetExtensionObject(namespaceUri) != null) { throw XsltException.Create(SR.Xslt_ScriptDub, namespaceUri); } _scriptExtensions.Add(namespaceUri, Activator.CreateInstance((Type)entry.Value, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, null, null)); } } this.PushActionFrame(_rootAction, /*nodeSet:*/null); } public ReaderOutput StartReader() { ReaderOutput output = new ReaderOutput(this); _builder = new RecordBuilder(output, _nameTable); return output; } public void Execute(Stream stream) { RecordOutput recOutput = null; switch (_output.Method) { case XsltOutput.OutputMethod.Text: recOutput = new TextOnlyOutput(this, stream); break; case XsltOutput.OutputMethod.Xml: case XsltOutput.OutputMethod.Html: case XsltOutput.OutputMethod.Other: case XsltOutput.OutputMethod.Unknown: recOutput = new TextOutput(this, stream); break; } _builder = new RecordBuilder(recOutput, _nameTable); Execute(); } public void Execute(TextWriter writer) { RecordOutput recOutput = null; switch (_output.Method) { case XsltOutput.OutputMethod.Text: recOutput = new TextOnlyOutput(this, writer); break; case XsltOutput.OutputMethod.Xml: case XsltOutput.OutputMethod.Html: case XsltOutput.OutputMethod.Other: case XsltOutput.OutputMethod.Unknown: recOutput = new TextOutput(this, writer); break; } _builder = new RecordBuilder(recOutput, _nameTable); Execute(); } public void Execute(XmlWriter writer) { _builder = new RecordBuilder(new WriterOutput(this, writer), _nameTable); Execute(); } // // Execution part of processor // internal void Execute() { Debug.Assert(_actionStack != null); while (_execResult == ExecResult.Continue) { ActionFrame frame = (ActionFrame)_actionStack.Peek(); if (frame == null) { Debug.Assert(_builder != null); _builder.TheEnd(); ExecutionResult = ExecResult.Done; break; } // Execute the action which was on the top of the stack if (frame.Execute(this)) { _actionStack.Pop(); } } if (_execResult == ExecResult.Interrupt) { _execResult = ExecResult.Continue; } } // // Action frame support // internal ActionFrame PushNewFrame() { ActionFrame prent = (ActionFrame)_actionStack.Peek(); ActionFrame frame = (ActionFrame)_actionStack.Push(); if (frame == null) { frame = new ActionFrame(); _actionStack.AddToTop(frame); } Debug.Assert(frame != null); if (prent != null) { frame.Inherit(prent); } return frame; } internal void PushActionFrame(Action action, XPathNodeIterator nodeSet) { ActionFrame frame = PushNewFrame(); frame.Init(action, nodeSet); } internal void PushActionFrame(ActionFrame container) { this.PushActionFrame(container, container.NodeSet); } internal void PushActionFrame(ActionFrame container, XPathNodeIterator nodeSet) { ActionFrame frame = PushNewFrame(); frame.Init(container, nodeSet); } internal void PushTemplateLookup(XPathNodeIterator nodeSet, XmlQualifiedName mode, Stylesheet importsOf) { Debug.Assert(_templateLookup != null); _templateLookup.Initialize(mode, importsOf); PushActionFrame(_templateLookup, nodeSet); } internal string GetQueryExpression(int key) { Debug.Assert(key != Compiler.InvalidQueryKey); return _queryStore[key].CompiledQuery.Expression; } internal Query GetCompiledQuery(int key) { Debug.Assert(key != Compiler.InvalidQueryKey); TheQuery theQuery = _queryStore[key]; theQuery.CompiledQuery.CheckErrors(); Query expr = Query.Clone(_queryList[key]); expr.SetXsltContext(new XsltCompileContext(theQuery._ScopeManager, this)); return expr; } internal Query GetValueQuery(int key) { return GetValueQuery(key, null); } internal Query GetValueQuery(int key, XsltCompileContext context) { Debug.Assert(key != Compiler.InvalidQueryKey); TheQuery theQuery = _queryStore[key]; theQuery.CompiledQuery.CheckErrors(); Query expr = _queryList[key]; if (context == null) { context = new XsltCompileContext(theQuery._ScopeManager, this); } else { context.Reinitialize(theQuery._ScopeManager, this); } expr.SetXsltContext(context); return expr; } private XsltCompileContext GetValueOfContext() { if (_valueOfContext == null) { _valueOfContext = new XsltCompileContext(); } return _valueOfContext; } [Conditional("DEBUG")] private void RecycleValueOfContext() { if (_valueOfContext != null) { _valueOfContext.Recycle(); } } private XsltCompileContext GetMatchesContext() { if (_matchesContext == null) { _matchesContext = new XsltCompileContext(); } return _matchesContext; } [Conditional("DEBUG")] private void RecycleMatchesContext() { if (_matchesContext != null) { _matchesContext.Recycle(); } } internal String ValueOf(ActionFrame context, int key) { string result; Query query = this.GetValueQuery(key, GetValueOfContext()); object value = query.Evaluate(context.NodeSet); if (value is XPathNodeIterator) { XPathNavigator n = query.Advance(); result = n != null ? ValueOf(n) : string.Empty; } else { result = XmlConvert.ToXPathString(value); } RecycleValueOfContext(); return result; } internal String ValueOf(XPathNavigator n) { if (_stylesheet.Whitespace && n.NodeType == XPathNodeType.Element) { StringBuilder builder = this.GetSharedStringBuilder(); ElementValueWithoutWS(n, builder); this.ReleaseSharedStringBuilder(); return builder.ToString(); } return n.Value; } private void ElementValueWithoutWS(XPathNavigator nav, StringBuilder builder) { Debug.Assert(nav.NodeType == XPathNodeType.Element); bool preserve = this.Stylesheet.PreserveWhiteSpace(this, nav); if (nav.MoveToFirstChild()) { do { switch (nav.NodeType) { case XPathNodeType.Text: case XPathNodeType.SignificantWhitespace: builder.Append(nav.Value); break; case XPathNodeType.Whitespace: if (preserve) { builder.Append(nav.Value); } break; case XPathNodeType.Element: ElementValueWithoutWS(nav, builder); break; } } while (nav.MoveToNext()); nav.MoveToParent(); } } internal XPathNodeIterator StartQuery(XPathNodeIterator context, int key) { Query query = GetCompiledQuery(key); object result = query.Evaluate(context); if (result is XPathNodeIterator) { // ToDo: We create XPathSelectionIterator to count positions, but it's better create special query in this case at compile time. return new XPathSelectionIterator(context.Current, query); } throw XsltException.Create(SR.XPath_NodeSetExpected); } internal object Evaluate(ActionFrame context, int key) { return GetValueQuery(key).Evaluate(context.NodeSet); } internal object RunQuery(ActionFrame context, int key) { Query query = GetCompiledQuery(key); object value = query.Evaluate(context.NodeSet); XPathNodeIterator it = value as XPathNodeIterator; if (it != null) { return new XPathArrayIterator(it); } return value; } internal string EvaluateString(ActionFrame context, int key) { object objValue = Evaluate(context, key); string value = null; if (objValue != null) value = XmlConvert.ToXPathString(objValue); if (value == null) value = string.Empty; return value; } internal bool EvaluateBoolean(ActionFrame context, int key) { object objValue = Evaluate(context, key); if (objValue != null) { XPathNavigator nav = objValue as XPathNavigator; return nav != null ? Convert.ToBoolean(nav.Value, CultureInfo.InvariantCulture) : Convert.ToBoolean(objValue, CultureInfo.InvariantCulture); } else { return false; } } internal bool Matches(XPathNavigator context, int key) { // We don't use XPathNavigator.Matches() to avoid cloning of Query on each call Query query = this.GetValueQuery(key, GetMatchesContext()); try { bool result = query.MatchNode(context) != null; RecycleMatchesContext(); return result; } catch (XPathException) { throw XsltException.Create(SR.Xslt_InvalidPattern, this.GetQueryExpression(key)); } } // // Outputting part of processor // internal XmlNameTable NameTable { get { return _nameTable; } } internal bool CanContinue { get { return _execResult == ExecResult.Continue; } } internal bool ExecutionDone { get { return _execResult == ExecResult.Done; } } internal void ResetOutput() { Debug.Assert(_builder != null); _builder.Reset(); } internal bool BeginEvent(XPathNodeType nodeType, string prefix, string name, string nspace, bool empty) { return BeginEvent(nodeType, prefix, name, nspace, empty, null, true); } internal bool BeginEvent(XPathNodeType nodeType, string prefix, string name, string nspace, bool empty, Object htmlProps, bool search) { Debug.Assert(_xsm != null); int stateOutlook = _xsm.BeginOutlook(nodeType); if (_ignoreLevel > 0 || stateOutlook == StateMachine.Error) { _ignoreLevel++; return true; // We consumed the event, so pretend it was output. } switch (_builder.BeginEvent(stateOutlook, nodeType, prefix, name, nspace, empty, htmlProps, search)) { case OutputResult.Continue: _xsm.Begin(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); Debug.Assert(ExecutionResult == ExecResult.Continue); return true; case OutputResult.Interrupt: _xsm.Begin(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: _ignoreLevel++; return true; case OutputResult.Ignore: return true; default: Debug.Fail("Unexpected result of RecordBuilder.BeginEvent()"); return true; } } internal bool TextEvent(string text) { return this.TextEvent(text, false); } internal bool TextEvent(string text, bool disableOutputEscaping) { Debug.Assert(_xsm != null); if (_ignoreLevel > 0) { return true; } int stateOutlook = _xsm.BeginOutlook(XPathNodeType.Text); switch (_builder.TextEvent(stateOutlook, text, disableOutputEscaping)) { case OutputResult.Continue: _xsm.Begin(XPathNodeType.Text); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); Debug.Assert(ExecutionResult == ExecResult.Continue); return true; case OutputResult.Interrupt: _xsm.Begin(XPathNodeType.Text); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: case OutputResult.Ignore: return true; default: Debug.Fail("Unexpected result of RecordBuilder.TextEvent()"); return true; } } internal bool EndEvent(XPathNodeType nodeType) { Debug.Assert(_xsm != null); if (_ignoreLevel > 0) { _ignoreLevel--; return true; } int stateOutlook = _xsm.EndOutlook(nodeType); switch (_builder.EndEvent(stateOutlook, nodeType)) { case OutputResult.Continue: _xsm.End(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State); return true; case OutputResult.Interrupt: _xsm.End(nodeType); Debug.Assert(StateMachine.StateOnly(stateOutlook) == _xsm.State, "StateMachine.StateOnly(stateOutlook) == this.xsm.State"); ExecutionResult = ExecResult.Interrupt; return true; case OutputResult.Overflow: ExecutionResult = ExecResult.Interrupt; return false; case OutputResult.Error: case OutputResult.Ignore: default: Debug.Fail("Unexpected result of RecordBuilder.TextEvent()"); return true; } } internal bool CopyBeginEvent(XPathNavigator node, bool emptyflag) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: return BeginEvent(node.NodeType, node.Prefix, node.LocalName, node.NamespaceURI, emptyflag); case XPathNodeType.Namespace: // value instead of namespace here! return BeginEvent(XPathNodeType.Namespace, null, node.LocalName, node.Value, false); case XPathNodeType.Text: // Text will be copied in CopyContents(); break; case XPathNodeType.Root: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyBeginEvent"); break; } return true; } internal bool CopyTextEvent(XPathNavigator node) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Namespace: break; case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: case XPathNodeType.Text: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: string text = node.Value; return TextEvent(text); case XPathNodeType.Root: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyTextEvent"); break; } return true; } internal bool CopyEndEvent(XPathNavigator node) { switch (node.NodeType) { case XPathNodeType.Element: case XPathNodeType.Attribute: case XPathNodeType.ProcessingInstruction: case XPathNodeType.Comment: case XPathNodeType.Namespace: return EndEvent(node.NodeType); case XPathNodeType.Text: // Text was copied in CopyContents(); break; case XPathNodeType.Root: case XPathNodeType.Whitespace: case XPathNodeType.SignificantWhitespace: case XPathNodeType.All: break; default: Debug.Fail("Invalid XPathNodeType in CopyEndEvent"); break; } return true; } internal static bool IsRoot(XPathNavigator navigator) { Debug.Assert(navigator != null); if (navigator.NodeType == XPathNodeType.Root) { return true; } else if (navigator.NodeType == XPathNodeType.Element) { XPathNavigator clone = navigator.Clone(); clone.MoveToRoot(); return clone.IsSamePosition(navigator); } else { return false; } } // // Builder stack // internal void PushOutput(RecordOutput output) { Debug.Assert(output != null); _builder.OutputState = _xsm.State; RecordBuilder lastBuilder = _builder; _builder = new RecordBuilder(output, _nameTable); _builder.Next = lastBuilder; _xsm.Reset(); } internal RecordOutput PopOutput() { Debug.Assert(_builder != null); RecordBuilder topBuilder = _builder; _builder = topBuilder.Next; _xsm.State = _builder.OutputState; topBuilder.TheEnd(); return topBuilder.Output; } internal bool SetDefaultOutput(XsltOutput.OutputMethod method) { if (Output.Method != method) { _output = _output.CreateDerivedOutput(method); return true; } return false; } internal object GetVariableValue(VariableAction variable) { int variablekey = variable.VarKey; if (variable.IsGlobal) { ActionFrame rootFrame = (ActionFrame)_actionStack[0]; object result = rootFrame.GetVariable(variablekey); if (result == VariableAction.BeingComputedMark) { throw XsltException.Create(SR.Xslt_CircularReference, variable.NameStr); } if (result != null) { return result; } // Variable wasn't evaluated yet int saveStackSize = _actionStack.Length; ActionFrame varFrame = PushNewFrame(); varFrame.Inherit(rootFrame); varFrame.Init(variable, rootFrame.NodeSet); do { bool endOfFrame = ((ActionFrame)_actionStack.Peek()).Execute(this); if (endOfFrame) { _actionStack.Pop(); } } while (saveStackSize < _actionStack.Length); Debug.Assert(saveStackSize == _actionStack.Length); result = rootFrame.GetVariable(variablekey); Debug.Assert(result != null, "Variable was just calculated and result can't be null"); return result; } else { return ((ActionFrame)_actionStack.Peek()).GetVariable(variablekey); } } internal void SetParameter(XmlQualifiedName name, object value) { Debug.Assert(1 < _actionStack.Length); ActionFrame parentFrame = (ActionFrame)_actionStack[_actionStack.Length - 2]; parentFrame.SetParameter(name, value); } internal void ResetParams() { ActionFrame frame = (ActionFrame)_actionStack[_actionStack.Length - 1]; frame.ResetParams(); } internal object GetParameter(XmlQualifiedName name) { Debug.Assert(2 < _actionStack.Length); ActionFrame parentFrame = (ActionFrame)_actionStack[_actionStack.Length - 3]; return parentFrame.GetParameter(name); } // ---------------------- Debugger stack ----------------------- internal class DebuggerFrame { internal ActionFrame actionFrame; internal XmlQualifiedName currentMode; } internal void PushDebuggerStack() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); DebuggerFrame dbgFrame = (DebuggerFrame)_debuggerStack.Push(); if (dbgFrame == null) { dbgFrame = new DebuggerFrame(); _debuggerStack.AddToTop(dbgFrame); } dbgFrame.actionFrame = (ActionFrame)_actionStack.Peek(); // In a case of next builtIn action. } internal void PopDebuggerStack() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); _debuggerStack.Pop(); } internal void OnInstructionExecute() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); DebuggerFrame dbgFrame = (DebuggerFrame)_debuggerStack.Peek(); Debug.Assert(dbgFrame != null, "PushDebuggerStack() wasn't ever called"); dbgFrame.actionFrame = (ActionFrame)_actionStack.Peek(); this.Debugger.OnInstructionExecute((IXsltProcessor)this); } internal XmlQualifiedName GetPrevioseMode() { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); Debug.Assert(2 <= _debuggerStack.Length); return ((DebuggerFrame)_debuggerStack[_debuggerStack.Length - 2]).currentMode; } internal void SetCurrentMode(XmlQualifiedName mode) { Debug.Assert(this.Debugger != null, "We don't generate calls this function if ! debugger"); ((DebuggerFrame)_debuggerStack[_debuggerStack.Length - 1]).currentMode = mode; } // ----------------------- IXsltProcessor : -------------------- int IXsltProcessor.StackDepth { get { return _debuggerStack.Length; } } IStackFrame IXsltProcessor.GetStackFrame(int depth) { return ((DebuggerFrame)_debuggerStack[depth]).actionFrame; } } }
using System; using System.Collections; using System.Collections.Generic; using UnsafeAM.Collections; using Microsoft.VisualStudio.TestTools.UnitTesting; // ReSharper disable CollectionNeverQueried.Local // ReSharper disable CollectionNeverUpdated.Local // ReSharper disable UseObjectOrCollectionInitializer namespace UnitTests.UnsafeAM.Collections { [TestClass] public class ChunkListTest { [TestMethod] public void ChunkList_Construction_1() { ChunkList<int> list = new ChunkList<int>(); Assert.AreEqual(0, list.Count); Assert.AreEqual(0, list.Capacity); } [TestMethod] public void ChunkList_Construction_2() { ChunkList<int> list = new ChunkList<int>(1); Assert.AreEqual(0, list.Count); Assert.AreEqual(ChunkList<int>.ChunkSize, list.Capacity); } [TestMethod] public void ChunkList_Construction_3() { int chunkSize = ChunkList<int>.ChunkSize; ChunkList<int> list = new ChunkList<int>(chunkSize); Assert.AreEqual(0, list.Count); Assert.AreEqual(chunkSize, list.Capacity); } [TestMethod] public void ChunkList_Construction_4() { ChunkList<int> list = new ChunkList<int>(1025); Assert.AreEqual(0, list.Count); Assert.AreEqual(1536, list.Capacity); } [TestMethod] public void ChunkList_Add_1() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); Assert.AreEqual(1, list.Count); Assert.AreEqual(ChunkList<int>.ChunkSize, list.Capacity); } [TestMethod] public void ChunkList_Add_2() { int chunkSize = ChunkList<int>.ChunkSize; ChunkList<int> list = new ChunkList<int>(); int desiredCount = chunkSize + 1; for (int i = 0; i < desiredCount; i++) { list.Add(i); } Assert.AreEqual(desiredCount, list.Count); Assert.AreEqual(chunkSize * 2, list.Capacity); } [TestMethod] public void ChunkList_CopyTo_1() { ChunkList<int> list = new ChunkList<int>(); int[] array = new int[3]; list.CopyTo(array, 0); Assert.AreEqual(0, array[0]); Assert.AreEqual(0, array[1]); Assert.AreEqual(0, array[2]); } [TestMethod] public void ChunkList_CopyTo_2() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); int[] array = new int[3]; list.CopyTo(array, 0); Assert.AreEqual(1, array[0]); Assert.AreEqual(0, array[1]); Assert.AreEqual(0, array[2]); } [TestMethod] public void ChunkList_CopyTo_3() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(2); list.Add(3); int[] array = new int[3]; list.CopyTo(array, 0); Assert.AreEqual(1, array[0]); Assert.AreEqual(2, array[1]); Assert.AreEqual(3, array[2]); } [TestMethod] public void ChunkList_CopyTo_4() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } int[] array = new int[count * 2]; list.CopyTo(array, 0); for (int i = 0; i < count; i++) { Assert.AreEqual(i, array[i]); Assert.AreEqual(0, array[count + i]); } } [TestMethod] public void ChunkList_Clear_1() { int chunkSize = ChunkList<int>.ChunkSize; ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Clear(); Assert.AreEqual(0, list.Count); Assert.AreEqual(chunkSize, list.Capacity); } [TestMethod] public void ChunkList_Contains_1() { ChunkList<int> list = new ChunkList<int>(); Assert.IsFalse(list.Contains(2)); list.Add(1); Assert.IsFalse(list.Contains(2)); list.Add(2); Assert.IsTrue(list.Contains(2)); list.Add(2); Assert.IsTrue(list.Contains(2)); } [TestMethod] public void ChunkList_Contains_2() { ChunkList<int> list = new ChunkList<int>(); Assert.IsFalse(list.Contains(2)); for (int i = 0; i < 1025; i++) { list.Add(i); } Assert.IsTrue(list.Contains(2)); Assert.IsTrue(list.Contains(1023)); Assert.IsTrue(list.Contains(1024)); Assert.IsFalse(list.Contains(1025)); } [TestMethod] public void ChunkList_IsReadOnly_1() { ChunkList<int> list = new ChunkList<int>(); Assert.IsFalse(list.IsReadOnly); } [TestMethod] public void ChunkList_IndexOf_1() { ChunkList<int> list = new ChunkList<int>(); Assert.IsTrue(list.IndexOf(2) < 0); list.Add(1); Assert.IsTrue(list.IndexOf(2) < 0); list.Add(2); Assert.AreEqual(1, list.IndexOf(2)); list.Add(2); Assert.AreEqual(1, list.IndexOf(2)); } [TestMethod] public void ChunkList_IndexOf_2() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } for (int i = 0; i < count; i++) { Assert.AreEqual(i, list.IndexOf(i)); } Assert.IsTrue(list.IndexOf(count + 1) < 0); } [TestMethod] public void ChunkList_Indexer_1() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(2); list.Add(3); Assert.AreEqual(1, list[0]); Assert.AreEqual(2, list[1]); Assert.AreEqual(3, list[2]); } [TestMethod] public void ChunkList_Indexer_2() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } for (int i = 0; i < count; i++) { Assert.AreEqual(i, list[i]); } } [TestMethod] public void ChunkList_Indexer_3() { ChunkList<int> list = new ChunkList<int>(); list.Add(0); list.Add(0); list.Add(0); list[0] = 1; list[1] = 2; list[2] = 3; Assert.AreEqual(1, list[0]); Assert.AreEqual(2, list[1]); Assert.AreEqual(3, list[2]); } [TestMethod] public void ChunkList_Indexer_4() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(0); } for (int i = 0; i < count; i++) { list[i] = i; } for (int i = 0; i < count; i++) { Assert.AreEqual(i, list[i]); } } [TestMethod] [ExpectedException(typeof(IndexOutOfRangeException))] public void ChunkList_Indexer_5() { ChunkList<int> list = new ChunkList<int>(); Assert.AreEqual(0, list[0]); } [TestMethod] [ExpectedException(typeof(IndexOutOfRangeException))] public void ChunkList_Indexer_6() { ChunkList<int> list = new ChunkList<int>(); list[0] = 0; } [TestMethod] [ExpectedException(typeof(IndexOutOfRangeException))] public void ChunkList_Indexer_7() { ChunkList<int> list = new ChunkList<int>(); list.Add(0); list.Add(0); list.Add(0); Assert.AreEqual(0, list[1000]); } [TestMethod] [ExpectedException(typeof(IndexOutOfRangeException))] public void ChunkList_Indexer_8() { ChunkList<int> list = new ChunkList<int>(); list.Add(0); list.Add(0); list.Add(0); list[1000] = 0; } [TestMethod] public void ChunkList_GetEnumerator_1() { ChunkList<int> list = new ChunkList<int>(); IEnumerator<int> enumerator = list.GetEnumerator(); Assert.IsFalse(enumerator.MoveNext()); enumerator.Dispose(); } [TestMethod] public void ChunkList_GetEnumerator_2() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(2); list.Add(3); IEnumerator<int> enumerator = list.GetEnumerator(); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(1, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(2, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(3, enumerator.Current); Assert.IsFalse(enumerator.MoveNext()); enumerator.Dispose(); } [TestMethod] public void ChunkList_GetEnumerator_3() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } IEnumerator<int> enumerator = list.GetEnumerator(); for (int i = 0; i < count; i++) { Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(i, enumerator.Current); } Assert.IsFalse(enumerator.MoveNext()); enumerator.Dispose(); } [TestMethod] public void ChunkList_GetEnumerator_4() { IEnumerable list = new ChunkList<int>(); IEnumerator enumerator = list.GetEnumerator(); Assert.IsFalse(enumerator.MoveNext()); } [TestMethod] public void ChunkList_GetEnumerator_5() { IEnumerable list = new ChunkList<int> { 1, 2, 3 }; IEnumerator enumerator = list.GetEnumerator(); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(1, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(2, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(3, enumerator.Current); Assert.IsFalse(enumerator.MoveNext()); } [TestMethod] public void ChunkList_RemoveAt_1() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(2); list.Add(3); list.RemoveAt(1); Assert.AreEqual(2, list.Count); Assert.AreEqual(1, list[0]); Assert.AreEqual(3, list[1]); } [TestMethod] public void ChunkList_RemoveAt_2() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } list.RemoveAt(100); Assert.AreEqual(count-1, list.Count); for (int i = 0; i < 100; i++) { Assert.AreEqual(i, list[i]); } for (int i = 100; i < count - 1; i++) { Assert.AreEqual(i + 1, list[i]); } } [TestMethod] public void ChunkList_Remove_1() { ChunkList<int> list = new ChunkList<int>(); Assert.IsFalse(list.Remove(2)); list.Add(1); list.Add(2); list.Add(3); Assert.IsTrue(list.Remove(2)); Assert.AreEqual(2, list.Count); Assert.AreEqual(3, list[1]); Assert.IsFalse(list.Remove(2)); } [TestMethod] public void ChunkList_Insert_1() { ChunkList<int> list = new ChunkList<int>(); list.Insert(0, 3); list.Insert(0, 2); list.Insert(0, 1); Assert.AreEqual(3, list.Count); Assert.AreEqual(1, list[0]); Assert.AreEqual(2, list[1]); Assert.AreEqual(3, list[2]); } [TestMethod] public void ChunkList_Insert_2() { ChunkList<int> list = new ChunkList<int>(); list.Add(1); list.Add(5); list.Insert(1, 4); list.Insert(1, 3); list.Insert(1, 2); Assert.AreEqual(5, list.Count); Assert.AreEqual(1, list[0]); Assert.AreEqual(2, list[1]); Assert.AreEqual(3, list[2]); Assert.AreEqual(4, list[3]); Assert.AreEqual(5, list[4]); } [TestMethod] public void ChunkList_ToArray_1() { ChunkList<int> list = new ChunkList<int>(); int[] array = list.ToArray(); Assert.AreEqual(0, array.Length); list.Add(1); array = list.ToArray(); Assert.AreEqual(1, array.Length); Assert.AreEqual(1, array[0]); list.Add(2); array = list.ToArray(); Assert.AreEqual(2, array.Length); Assert.AreEqual(1, array[0]); Assert.AreEqual(2, array[1]); list.Add(3); array = list.ToArray(); Assert.AreEqual(3, array.Length); Assert.AreEqual(1, array[0]); Assert.AreEqual(2, array[1]); Assert.AreEqual(3, array[2]); } [TestMethod] public void ChunkList_ToArray_2() { int count = 1025; ChunkList<int> list = new ChunkList<int>(); for (int i = 0; i < count; i++) { list.Add(i); } int[] array = list.ToArray(); Assert.AreEqual(count, array.Length); for (int i = 0; i < count; i++) { Assert.AreEqual(i, array[i]); } } } }
// // FolderExport.cs // // Author: // Lorenzo Milesi <maxxer@yetopen.it> // Stephane Delcroix <stephane@delcroix.org> // Stephen Shaw <sshaw@decriptor.com> // // Copyright (C) 2008-2009 Novell, Inc. // Copyright (C) 2008 Lorenzo Milesi // Copyright (C) 2008-2009 Stephane Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /* * Copyright (C) 2005 Alessandro Gervaso <gervystar@gervystar.net> * * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 */ //This should be used to export the selected pics to an original gallery //located on a GIO location. using System; using System.IO; using Hyena; using Mono.Unix; using FSpot.Core; using FSpot.Filters; using FSpot.Settings; using FSpot.Widgets; using FSpot.Utils; using FSpot.UI.Dialog; namespace FSpot.Exporters.Folder { public class FolderExport : Extensions.IExporter { IBrowsableCollection selection; #pragma warning disable 649 [GtkBeans.Builder.Object] Gtk.Dialog dialog; [GtkBeans.Builder.Object] Gtk.ScrolledWindow thumb_scrolledwindow; [GtkBeans.Builder.Object] Gtk.Entry name_entry; [GtkBeans.Builder.Object] Gtk.Entry description_entry; [GtkBeans.Builder.Object] Gtk.CheckButton scale_check; [GtkBeans.Builder.Object] Gtk.CheckButton export_tags_check; [GtkBeans.Builder.Object] Gtk.CheckButton export_tag_icons_check; [GtkBeans.Builder.Object] Gtk.CheckButton open_check; [GtkBeans.Builder.Object] Gtk.RadioButton static_radio; [GtkBeans.Builder.Object] Gtk.RadioButton original_radio; [GtkBeans.Builder.Object] Gtk.RadioButton plain_radio; [GtkBeans.Builder.Object] Gtk.SpinButton size_spin; [GtkBeans.Builder.Object] Gtk.HBox chooser_hbox; #pragma warning restore 649 public const string EXPORT_SERVICE = "folder/"; public const string SCALE_KEY = Preferences.ExportKey + EXPORT_SERVICE + "scale"; public const string SIZE_KEY = Preferences.ExportKey + EXPORT_SERVICE + "size"; public const string OPEN_KEY = Preferences.ExportKey + EXPORT_SERVICE + "browser"; public const string EXPORT_TAGS_KEY = Preferences.ExportKey + EXPORT_SERVICE + "export_tags"; public const string EXPORT_TAG_ICONS_KEY = Preferences.ExportKey + EXPORT_SERVICE + "export_tag_icons"; public const string METHOD_KEY = Preferences.ExportKey + EXPORT_SERVICE + "method"; public const string URI_KEY = Preferences.ExportKey + EXPORT_SERVICE + "uri"; public const string SHARPEN_KEY = Preferences.ExportKey + EXPORT_SERVICE + "sharpen"; public const string INCLUDE_TARBALLS_KEY = Preferences.ExportKey + EXPORT_SERVICE + "include_tarballs"; GtkBeans.Builder builder; string dialog_name = "folder_export_dialog"; DirectoryInfo dest; Gtk.FileChooserButton uri_chooser; bool open; bool scale; bool exportTags; bool exportTagIcons; int size; string description; string gallery_name = Catalog.GetString ("Gallery"); // FIXME: this needs to be a real temp directory string gallery_path = Path.Combine (Path.GetTempPath (), "f-spot-original-" + DateTime.Now.Ticks.ToString ()); ThreadProgressDialog progress_dialog; System.Threading.Thread command_thread; public FolderExport () { } public void Run (IBrowsableCollection selection) { this.selection = selection; var view = new TrayView (selection); view.DisplayDates = false; view.DisplayTags = false; builder = new GtkBeans.Builder (null, "folder_export.ui", null); builder.Autoconnect (this); Dialog.Modal = false; Dialog.TransientFor = null; thumb_scrolledwindow.Add (view); HandleSizeActive (null, null); name_entry.Text = gallery_name; string uri_path = Path.Combine (FSpotConfiguration.HomeDirectory, "Desktop"); if (!Directory.Exists (uri_path)) uri_path = FSpotConfiguration.HomeDirectory; uri_chooser = new Gtk.FileChooserButton (Catalog.GetString ("Select Export Folder"), Gtk.FileChooserAction.SelectFolder) { LocalOnly = false }; if (!string.IsNullOrEmpty (Preferences.Get<string> (URI_KEY))) uri_chooser.SetCurrentFolderUri (Preferences.Get<string> (URI_KEY)); else uri_chooser.SetFilename (uri_path); chooser_hbox.PackStart (uri_chooser); Dialog.ShowAll (); Dialog.Response += HandleResponse; LoadPreference (SCALE_KEY); LoadPreference (SIZE_KEY); LoadPreference (OPEN_KEY); LoadPreference (EXPORT_TAGS_KEY); LoadPreference (EXPORT_TAG_ICONS_KEY); LoadPreference (METHOD_KEY); } public void HandleSizeActive (object sender, EventArgs args) { size_spin.Sensitive = scale_check.Active; } public void HandleStandaloneActive (object sender, EventArgs args) { export_tags_check.Sensitive = static_radio.Active; HandleExportTagsActive (sender, args); } public void HandleExportTagsActive (object sender, EventArgs args) { export_tag_icons_check.Sensitive = export_tags_check.Active && static_radio.Active; } public void Upload () { // FIXME: use mkstemp try { ThreadAssist.ProxyToMain (Dialog.Hide); // FIXME, guessing how this works var source = new DirectoryInfo (Path.Combine (gallery_path, gallery_name)); var target = new DirectoryInfo (Path.Combine (dest.FullName, source.Name)); //if (dest.IsNative) // gallery_path = dest.Path; progress_dialog.Message = Catalog.GetString ("Building Gallery"); progress_dialog.Fraction = 0.0; FolderGallery gallery; if (static_radio.Active) { gallery = new HtmlGallery (selection, gallery_path, gallery_name); } else if (original_radio.Active) { gallery = new OriginalGallery (selection, gallery_path, gallery_name); } else { gallery = new FolderGallery (selection, gallery_path, gallery_name); } if (scale) { Log.Debug ($"Resize Photos to {size}."); gallery.SetScale (size); } else { Log.Debug ("Exporting full size."); } if (exportTags) gallery.ExportTags = true; if (exportTagIcons) gallery.ExportTagIcons = true; gallery.Description = description; gallery.GenerateLayout (); var filter_set = new FilterSet (); if (scale) filter_set.Add (new ResizeFilter ((uint)size)); filter_set.Add (new ChmodFilter ()); filter_set.Add (new UniqueNameFilter (new SafeUri (gallery_path))); for (int photo_index = 0; photo_index < selection.Count; photo_index++) { try { progress_dialog.Message = string.Format (Catalog.GetString ("Exporting \"{0}\"..."), selection[photo_index].Name); progress_dialog.Fraction = photo_index / (double)selection.Count; gallery.ProcessImage (photo_index, filter_set); progress_dialog.ProgressText = string.Format (Catalog.GetString ("{0} of {1}"), (photo_index + 1), selection.Count); } catch (Exception e) { Log.Error (e.ToString ()); progress_dialog.Message = string.Format (Catalog.GetString ("Error Copying \"{0}\" to Gallery:{2}{1}"), selection[photo_index].Name, e.Message, Environment.NewLine); progress_dialog.ProgressText = Catalog.GetString ("Error"); if (progress_dialog.PerformRetrySkip ()) photo_index--; } } // create the zip tarballs for original if (gallery is OriginalGallery originalGallery) { bool include_tarballs; try { include_tarballs = Preferences.Get<bool> (INCLUDE_TARBALLS_KEY); } catch (NullReferenceException) { include_tarballs = true; Preferences.Set (INCLUDE_TARBALLS_KEY, true); } if (include_tarballs) originalGallery.CreateZip (); } // FIXME, This is borken // we've created the structure, now if the destination was local (native) we are done // otherwise we xfer //if (!dest.IsNative) { // Log.Debug ($"Transferring \"{source.FullName}\" to \"{target.FullName}\""); // progress_dialog.Message = string.Format (Catalog.GetString ("Transferring to \"{0}\""), target.FullName); // progress_dialog.ProgressText = Catalog.GetString ("Transferring..."); // source.CopyRecursive (target, GLib.FileCopyFlags.Overwrite, new GLib.Cancellable (), Progress); //} // No need to check result here as if result is not true, an Exception will be thrown before progress_dialog.Message = Catalog.GetString ("Export Complete."); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString ("Exporting Photos Completed."); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (open) { Log.Debug ($"Open Path \"{target.FullName}\""); ThreadAssist.ProxyToMain (() => { GtkBeans.Global.ShowUri (Dialog.Screen, target.FullName); }); } // Save these settings for next time Preferences.Set (SCALE_KEY, scale); Preferences.Set (SIZE_KEY, size); Preferences.Set (OPEN_KEY, open); Preferences.Set (EXPORT_TAGS_KEY, exportTags); Preferences.Set (EXPORT_TAG_ICONS_KEY, exportTagIcons); Preferences.Set (METHOD_KEY, static_radio.Active ? "static" : original_radio.Active ? "original" : "folder"); Preferences.Set (URI_KEY, uri_chooser.Uri); } catch (Exception e) { Log.Error (e.ToString ()); progress_dialog.Message = e.ToString (); progress_dialog.ProgressText = Catalog.GetString ("Error Transferring"); } finally { // if the destination isn't local then we want to remove the temp directory we // created. //if (!dest.IsNative) // Directory.Delete (gallery_path, true); ThreadAssist.ProxyToMain (() => { Dialog.Destroy (); }); } } void Progress (long current_num_bytes, long total_num_bytes) { if (total_num_bytes > 0) progress_dialog.Fraction = current_num_bytes / (double)total_num_bytes; } void HandleResponse (object sender, Gtk.ResponseArgs args) { if (args.ResponseId != Gtk.ResponseType.Ok) { // FIXME this is to work around a bug in gtk+ where // the filesystem events are still listened to when // a FileChooserButton is destroyed but not finalized // and an event comes in that wants to update the child widgets. Dialog.Destroy (); uri_chooser.Dispose (); uri_chooser = null; return; } dest = new DirectoryInfo (new SafeUri (uri_chooser.Uri).AbsolutePath); open = open_check.Active; scale = scale_check.Active; exportTags = export_tags_check.Active; exportTagIcons = export_tag_icons_check.Active; gallery_name = name_entry.Text; if (description_entry != null) description = description_entry.Text; if (scale) size = size_spin.ValueAsInt; command_thread = new System.Threading.Thread (new System.Threading.ThreadStart (Upload)) { Name = Catalog.GetString ("Exporting Photos") }; progress_dialog = new ThreadProgressDialog (command_thread, 1); progress_dialog.Start (); } void LoadPreference (string key) { switch (key) { case SCALE_KEY: if (scale_check.Active != Preferences.Get<bool> (key)) scale_check.Active = Preferences.Get<bool> (key); break; case SIZE_KEY: if (Preferences.TryGet (key, out int size)) size_spin.Value = (double)size; else size_spin.Value = 400; break; case OPEN_KEY: if (open_check.Active != Preferences.Get<bool> (key)) open_check.Active = Preferences.Get<bool> (key); break; case EXPORT_TAGS_KEY: if (export_tags_check.Active != Preferences.Get<bool> (key)) export_tags_check.Active = Preferences.Get<bool> (key); break; case EXPORT_TAG_ICONS_KEY: if (export_tag_icons_check.Active != Preferences.Get<bool> (key)) export_tag_icons_check.Active = Preferences.Get<bool> (key); break; case METHOD_KEY: static_radio.Active = (Preferences.Get<string> (key) == "static"); original_radio.Active = (Preferences.Get<string> (key) == "original"); plain_radio.Active = (Preferences.Get<string> (key) == "folder"); break; } } Gtk.Dialog Dialog { get { return dialog ??= new Gtk.Dialog (builder.GetRawObject (dialog_name)); } } } }
// AudioContext.cs // SaltarelleWeb/Html/Media/Audio // This source code is subject to terms and conditions of the Apache License, Version 2.0. // // Added by Timothy Fries - drysart@gmail.com using System; using System.Collections.Generic; using System.Html.Media.Graphics.WebGL; using System.Runtime.CompilerServices; using System.Text; namespace System.Html.Media.Audio { /// <summary> /// This interface represents a set of AudioNode objects and their connections. It allows for /// arbitrary routing of signals to the AudioDestinationNode (what the user ultimately hears). /// Nodes are created from the context and are then connected together. In most use cases, /// only a single AudioContext is used per document. /// </summary> /// <remarks>Once created, an AudioContext will not be garbage collected. It will live /// until the document goes away.</remarks> /// <reference>http://www.w3.org/TR/2012/WD-webaudio-20121213/#AudioContext-section</reference> [IgnoreNamespace, Imported] public class AudioContext { /// <summary> /// Create a new AudioContext. /// </summary> [InlineCode("new (window.AudioContext || " + "window.webkitAudioContext || " + "window.mozAudioContext || " + "window.msAudioContext || " + "window.oAudioContext)()")] public AudioContext() { } /// <summary> /// An AudioDestinationNode with a single input representing the final destination for all /// audio (to be rendered to the audio hardware). All AudioNodes actively rendering audio will /// directly or indirectly connect to destination. /// </summary> [IntrinsicProperty] public AudioDestinationNode Destination { get; private set; } /// <summary> /// The sample rate (in sample-frames per second) at which the AudioContext handles audio. It /// is assumed that all AudioNodes in the context run at this rate. In making this assumption, /// sample-rate converters or "varispeed" processors are not supported in real-time processing. /// </summary> [IntrinsicProperty] public float SampleRate { get; private set; } /// <summary> /// This is a time in seconds which starts at zero when the context is created and increases in /// real-time. All scheduled times are relative to it. This is not a "transport" time which can be /// started, paused, and re-positioned. It is always moving forward. A GarageBand-like timeline /// transport system can be very easily built on top of this (in JavaScript). This time corresponds /// to an ever-increasing hardware timestamp. /// </summary> [IntrinsicProperty] public double CurrentTime { get; private set; } /// <summary> /// An AudioListener which is used for 3D spatialization. /// </summary> [IntrinsicProperty] public AudioListener Listener { get; private set; } /// <summary> /// The number of AudioBufferSourceNodes that are currently playing. /// </summary> [IntrinsicProperty] public uint ActiveSourceCount { get; private set; } /// <summary> /// Creates an AudioBuffer of the given size. The audio data in the buffer will be zero-initialized /// (silent). An exception will be thrown if the numberOfChannels or sampleRate are out-of-bounds. /// </summary> /// <param name="numberOfChannels">The numberOfChannels parameter determines how many channels the /// buffer will have. An implementation must support at least 32 channels.</param> /// <param name="length">The length parameter determines the size of the buffer in sample-frames.</param> /// <param name="sampleRate">The sampleRate parameter describes the sample-rate of the linear PCM audio /// data in the buffer in sample-frames per second. An implementation must support sample-rates in at /// least the range 22050 to 96000.</param> /// <returns>Returns the newly created AudioBuffer object.</returns> public AudioBuffer CreateBuffer(uint numberOfChannels, uint length, float sampleRate) { return null; } /// <summary> /// Creates an AudioBuffer given the audio file data contained in the ArrayBuffer. The ArrayBuffer can, /// for example, be loaded from an XMLHttpRequest's response attribute after setting the responseType /// to "arraybuffer". Audio file data can be in any of the formats supported by the audio element. /// </summary> /// <param name="buffer">The buffer parameter contains the audio file data (for example from a /// .wav file).</param> /// <param name="mixToMono">The mixToMono parameter determines if a mixdown to mono will be /// performed. Normally, this would not be set.</param> /// <returns>Returns the newly created AudioBuffer object.</returns> public AudioBuffer CreateBuffer(ArrayBuffer buffer, bool mixToMono) { return null; } /// <summary> /// Asynchronously decodes the audio file data contained in the ArrayBuffer. The ArrayBuffer can, /// for example, be loaded from an XMLHttpRequest's response attribute after setting the responseType /// to "arraybuffer". Audio file data can be in any of the formats supported by the audio element. /// </summary> /// <param name="audioData">audioData is an ArrayBuffer containing audio file data.</param> /// <param name="successCallback">successCallback is a callback function which will be invoked when the /// decoding is finished. The single argument to this callback is an AudioBuffer representing the decoded /// PCM audio data.</param> public void DecodeAudioData(ArrayBuffer audioData, Action<AudioBuffer> successCallback) { } /// <summary> /// Asynchronously decodes the audio file data contained in the ArrayBuffer. The ArrayBuffer can, /// for example, be loaded from an XMLHttpRequest's response attribute after setting the responseType /// to "arraybuffer". Audio file data can be in any of the formats supported by the audio element. /// </summary> /// <param name="audioData">audioData is an ArrayBuffer containing audio file data.</param> /// <param name="successCallback">successCallback is a callback function which will be invoked when the /// decoding is finished. The single argument to this callback is an AudioBuffer representing the decoded /// PCM audio data.</param> /// <param name="errorCallback">errorCallback is a callback function which will be invoked if there is /// an error decoding the audio file data.</param> public void DecodeAudioData(ArrayBuffer audioData, Action<AudioBuffer> successCallback, Action errorCallback) { } /// <summary> /// Creates an AudioBufferSourceNode. /// </summary> /// <returns>The newly created AudioBufferSourceNode object.</returns> public AudioBufferSourceNode CreateBufferSource() { return null; } /// <summary> /// Creates a MediaElementAudioSourceNode given an HTMLMediaElement. As a consequence of calling this /// method, audio playback from the HTMLMediaElement will be re-routed into the processing graph /// of the AudioContext. /// </summary> /// <param name="mediaElement">mediaElement is an HTMLMediaElement (e.g. audio or video) whose /// audio playback should be rerouted into the AudioContext</param> /// <returns>The newly created MediaElementAudioSourceNode object.</returns> public MediaElementAudioSourceNode CreateMediaElementSource(System.Html.MediaElement mediaElement) { return null; } /// <summary> /// Creates a MediaStreamAudioSourceNode given a MediaStream. As a consequence of calling this method, /// audio playback from the MediaStream will be re-routed into the processing graph of the AudioContext. /// </summary> /// <param name="mediaStream">mediaStream is a MediaStream object whose audio playback should /// be rerouted into the AudioContext</param> /// <returns>The newly created MediaStreamAudioSourceNode object.</returns> public MediaStreamAudioSourceNode CreateMediaStreamSource(object mediaStream) { return null; } /// <summary> /// Creates a ScriptProcessorNode for direct audio processing using JavaScript. An exception will be /// thrown if bufferSize or numberOfInputChannels or numberOfOutputChannels are outside the valid range. /// </summary> /// <param name="bufferSize">The bufferSize parameter determines the buffer size in units of sample-frames. /// It must be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. This value controls /// how frequently the onaudioprocess event handler is called and how many sample-frames need to be /// processed each call. Lower values for bufferSize will result in a lower (better) latency. Higher /// values will be necessary to avoid audio breakup and glitches. The value chosen must carefully balance /// between latency and audio quality.</param> /// <returns>The newly created ScriptProcessorNode object.</returns> public ScriptProcessorNode CreateScriptProcessor(uint bufferSize) { return null; } /// <summary> /// Creates a ScriptProcessorNode for direct audio processing using JavaScript. An exception will be /// thrown if bufferSize or numberOfInputChannels or numberOfOutputChannels are outside the valid range. /// </summary> /// <param name="bufferSize">The bufferSize parameter determines the buffer size in units of sample-frames. /// It must be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. This value controls /// how frequently the onaudioprocess event handler is called and how many sample-frames need to be /// processed each call. Lower values for bufferSize will result in a lower (better) latency. Higher /// values will be necessary to avoid audio breakup and glitches. The value chosen must carefully balance /// between latency and audio quality.</param> /// <param name="numberOfInputChannels">The numberOfInputChannels parameter (defaults to 2) and determines /// the number of channels for this node's input. Values of up to 32 must be supported.</param> /// <returns>The newly created ScriptProcessorNode object.</returns> public ScriptProcessorNode CreateScriptProcessor(uint bufferSize, uint numberOfInputChannels) { return null; } /// <summary> /// Creates a ScriptProcessorNode for direct audio processing using JavaScript. An exception will be /// thrown if bufferSize or numberOfInputChannels or numberOfOutputChannels are outside the valid range. /// </summary> /// <param name="bufferSize">The bufferSize parameter determines the buffer size in units of sample-frames. /// It must be one of the following values: 256, 512, 1024, 2048, 4096, 8192, 16384. This value controls /// how frequently the onaudioprocess event handler is called and how many sample-frames need to be /// processed each call. Lower values for bufferSize will result in a lower (better) latency. Higher /// values will be necessary to avoid audio breakup and glitches. The value chosen must carefully balance /// between latency and audio quality.</param> /// <param name="numberOfInputChannels">The numberOfInputChannels parameter (defaults to 2) and determines /// the number of channels for this node's input. Values of up to 32 must be supported.</param> /// <param name="numberOfOutputChannels">The numberOfOutputChannels parameter (defaults to 2) and determines /// the number of channels for this node's output. Values of up to 32 must be supported.</param> /// <returns>The newly created ScriptProcessorNode object.</returns> public ScriptProcessorNode CreateScriptProcessor(uint bufferSize, uint numberOfInputChannels, uint numberOfOutputChannels) { return null; } /// <summary> /// Creates a AnalyserNode. /// </summary> /// <returns>The newly created AnalyserNode object.</returns> public AnalyserNode CreateAnalyser() { return null; } /// <summary> /// Creates a GainNode. /// </summary> /// <returns>The newly created GainNode object.</returns> public GainNode CreateGain() { return null; } /// <summary> /// Creates a DelayNode representing a variable delay line. The initial default delay /// time will be 0 seconds. /// </summary> /// <returns>The newly created DelayNode object.</returns> public DelayNode CreateDelay() { return null; } /// <summary> /// Creates a DelayNode representing a variable delay line. The initial default delay /// time will be 0 seconds. /// </summary> /// <param name="maxDelayTime">The maxDelayTime parameter specifies the maximum /// delay time in seconds allowed for the delay line. If specified, this value /// must be greater than zero and less than three minutes or a NOT_SUPPORTED_ERR /// exception will be thrown.</param> /// <returns>The newly created DelayNode object.</returns> public DelayNode CreateDelay(double maxDelayTime) { return null; } /// <summary> /// Creates a BiquadFilterNode representing a second order filter which can be /// configured as one of several common filter types. /// </summary> /// <returns>The newly created BiquadFilterNode object.</returns> public BiquadFilterNode CreateBiquadFilter() { return null; } /// <summary> /// Creates a WaveShaperNode representing a non-linear distortion. /// </summary> /// <returns>The newly created WaveShaperNode object.</returns> public WaveShaperNode CreateWaveShaper() { return null; } /// <summary> /// Creates a PannerNode. /// </summary> /// <returns>The newly created PannerNode object.</returns> public PannerNode CreatePanner() { return null; } /// <summary> /// Creates a ConvolverNode. /// </summary> /// <returns>The newly created ConvolverNode object.</returns> public ConvolverNode CreateConvolver() { return null; } /// <summary> /// Creates an ChannelSplitterNode representing a channel splitter. /// The default number of 6 outputs will be used. /// </summary> /// <returns>The newly created ChannelSplitterNode object.</returns> public ChannelSplitterNode CreateChannelSplitter() { return null; } /// <summary> /// Creates an ChannelSplitterNode representing a channel splitter. /// An exception will be thrown for invalid parameter values. /// </summary> /// <param name="numberOfOutputs">The numberOfOutputs parameter determines /// the number of outputs. Values of up to 32 must be supported.</param> /// <returns>The newly created ChannelSplitterNode object.</returns> public ChannelSplitterNode CreateChannelSplitter(uint numberOfOutputs) { return null; } /// <summary> /// Creates an ChannelMergerNode representing a channel merger. /// The default number of 6 inputs will be used. /// </summary> /// <returns>The newly created ChannelMergerNode object.</returns> public ChannelMergerNode CreateChannelMerger() { return null; } /// <summary> /// Creates an ChannelMergerNode representing a channel merger. /// An exception will be thrown for invalid parameter values. /// </summary> /// <param name="numberOfInputs">The numberOfInputs parameter determines the /// number of inputs. Values of up to 32 must be supported.</param> /// <returns>The newly created ChannelMergerNode object.</returns> public ChannelMergerNode CreateChannelMerger(uint numberOfInputs) { return null; } /// <summary> /// Creates a DynamicsCompressorNode. /// </summary> /// <returns>The newly created DynamicsCompressorNode object.</returns> public DynamicsCompressorNode CreateDynamicsCompressor() { return null; } /// <summary> /// Creates an OscillatorNode. /// </summary> /// <returns>The newly created OscillatorNode object.</returns> public OscillatorNode CreateOscillator() { return null; } /// <summary> /// Creates a WaveTable representing a waveform containing arbitrary harmonic content. The /// real and imag parameters specify the Fourier coefficients of a Fourier series representing the /// partials of a periodic waveform. The created WaveTable will be used with an OscillatorNode and /// will represent a normalized time-domain waveform having maximum absolute peak value of 1. Another /// way of saying this is that the generated waveform of an OscillatorNode will have maximum peak /// value at 0dBFS. Conveniently, this corresponds to the full-range of the signal values used by the /// Web Audio API. Because the WaveTable will be normalized on creation, the real and imag parameters /// represent relative values. /// </summary> /// <param name="real">The real parameter represents an array of cosine terms (traditionally /// the A terms). In audio terminology, the first element (index 0) is the DC-offset of the periodic /// waveform and is usually set to zero. The second element (index 1) represents the fundamental /// frequency. The third element represents the first overtone, and so on. /// /// The supplied Float32Array must have a length greater than zero and less than or /// equal to 4096 or an exception will be thrown.</param> /// <param name="imag">The imag parameter represents an array of sine terms (traditionally /// the B terms). The first element (index 0) should be set to zero (and will be ignored) since /// this term does not exist in the Fourier series. The second element (index 1) represents the /// fundamental frequency. The third element represents the first overtone, and so on. /// /// The supplied Float32Array must have a length greater than zero and less than or /// equal to 4096 or an exception will be thrown.</param> /// <returns>The newly created WaveTable object.</returns> public WaveTable CreateWaveTable(Float32Array real, Float32Array imag) { return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; namespace System.Runtime.InteropServices { internal class InternalTypes { internal static RuntimeTypeHandle IUnknown = typeof(System.Runtime.InteropServices.__com_IUnknown).TypeHandle; internal static RuntimeTypeHandle ICCW = typeof(System.Runtime.InteropServices.__com_ICCW).TypeHandle; internal static RuntimeTypeHandle IMarshal = typeof(System.Runtime.InteropServices.__com_IMarshal).TypeHandle; internal static RuntimeTypeHandle IDispatch = typeof(System.Runtime.InteropServices.__com_IDispatch).TypeHandle; internal static RuntimeTypeHandle IInspectable = typeof(System.Runtime.InteropServices.__com_IInspectable).TypeHandle; #if ENABLE_MIN_WINRT internal static RuntimeTypeHandle IActivationFactoryInternal = typeof(System.Runtime.InteropServices.WindowsRuntime.IActivationFactoryInternal).TypeHandle; #endif #if ENABLE_WINRT internal static RuntimeTypeHandle ICustomPropertyProvider = typeof(System.Runtime.InteropServices.__com_ICustomPropertyProvider).TypeHandle; internal static RuntimeTypeHandle IWeakReferenceSource = typeof(System.Runtime.InteropServices.__com_IWeakReferenceSource).TypeHandle; internal static RuntimeTypeHandle IWeakReference = typeof(System.Runtime.InteropServices.__com_IWeakReference).TypeHandle; internal static RuntimeTypeHandle IJupiterObject = typeof(System.Runtime.InteropServices.__com_IJupiterObject).TypeHandle; internal static RuntimeTypeHandle IStringable = typeof(System.Runtime.InteropServices.__com_IStringable).TypeHandle; internal static RuntimeTypeHandle IManagedActivationFactory = typeof(System.Runtime.InteropServices.WindowsRuntime.IManagedActivationFactory).TypeHandle; internal static RuntimeTypeHandle IRestrictedErrorInfo = typeof(System.Runtime.InteropServices.ExceptionHelpers.__com_IRestrictedErrorInfo).TypeHandle; internal static RuntimeTypeHandle HSTRING = typeof(System.Runtime.InteropServices.HSTRING).TypeHandle; internal static RuntimeTypeHandle ILanguageExceptionStackBackTrace = typeof(System.Runtime.InteropServices.ExceptionHelpers.__com_ILanguageExceptionStackBackTrace).TypeHandle; #endif } /// <summary> /// Singleton module that managed types implemented internally, rather than in MCG-generated code. /// This works together with interface implementations in StandardInterfaces.cs /// NOTE: Interfaces defined here are implemented by CCWs, but user might be able to override them /// depending on the interface /// </summary> internal class InternalModule : McgModule { // The internal module is always lower priority than all other modules. private const int PriorityForInternalModule = -1; unsafe internal InternalModule() : base( PriorityForInternalModule, s_interfaceData, null, // CCWTemplateData null, // CCWTemplateInterfaceList null, // classData, null, // boxingData, null, // additionalClassData, null, // collectionData, null, // DelegateData null, // CCWFactories null, // structMarshalData null, // unsafeStructFieldOffsetData null, // interfaceMarshalData null // hashcodeVerify ) { // Following code is disabled due to lazy static constructor dependency from McgModule which is // static eager constructor. Undo this when McgCurrentModule is using ModuleConstructorAttribute #if EAGER_CTOR_WORKAROUND for (int i = 0; i < s_interfaceData.Length; i++) { Debug.Assert((s_interfaceData[i].Flags & McgInterfaceFlags.useSharedCCW) == 0); } #endif } // IUnknown internal static McgInterfaceData s_IUnknown = new McgInterfaceData { ItfType = InternalTypes.IUnknown, ItfGuid = Interop.COM.IID_IUnknown, CcwVtable = __vtable_IUnknown.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal, }; // IInspectable internal static McgInterfaceData s_IInspectable = new McgInterfaceData { ItfType = InternalTypes.IInspectable, ItfGuid = Interop.COM.IID_IInspectable, CcwVtable = __vtable_IInspectable.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal | McgInterfaceFlags.isIInspectable, }; #if ENABLE_MIN_WINRT // IActivationFactoryInternal internal static McgInterfaceData s_IActivationFactoryInternal = new McgInterfaceData { ItfType = InternalTypes.IActivationFactoryInternal, ItfGuid = Interop.COM.IID_IActivationFactoryInternal, CcwVtable = __vtable_IActivationFactoryInternal.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal, }; #endif #if ENABLE_WINRT // ICustomPropertyProvider internal static McgInterfaceData s_ICustomPropertyProvider = new McgInterfaceData { ItfType = InternalTypes.ICustomPropertyProvider, ItfGuid = Interop.COM.IID_ICustomPropertyProvider, CcwVtable = __vtable_ICustomPropertyProvider.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal | McgInterfaceFlags.isIInspectable, }; // IWeakReferenceSource internal static McgInterfaceData s_IWeakReferenceSource = new McgInterfaceData { ItfType = InternalTypes.IWeakReferenceSource, ItfGuid = Interop.COM.IID_IWeakReferenceSource, CcwVtable = __vtable_IWeakReferenceSource.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal, }; // IWeakReference internal static McgInterfaceData s_IWeakReference = new McgInterfaceData { ItfType = InternalTypes.IWeakReference, ItfGuid = Interop.COM.IID_IWeakReference, CcwVtable = __vtable_IWeakReference.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal, }; #endif // ICCW internal static McgInterfaceData s_ICCW = new McgInterfaceData { ItfType = InternalTypes.ICCW, ItfGuid = Interop.COM.IID_ICCW, CcwVtable = __vtable_ICCW.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal, }; #if ENABLE_WINRT // IJupiterObject internal static McgInterfaceData s_IJupiterObject = new McgInterfaceData { ItfType = InternalTypes.IJupiterObject, ItfGuid = Interop.COM.IID_IJupiterObject, Flags = McgInterfaceFlags.isInternal, }; // IStringable internal static McgInterfaceData s_IStringable = new McgInterfaceData { ItfType = InternalTypes.IStringable, ItfGuid = Interop.COM.IID_IStringable, CcwVtable = __vtable_IStringable.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal, }; // IManagedActivationFactory internal static McgInterfaceData s_IManagedActivationFactory = new McgInterfaceData { ItfType = InternalTypes.IManagedActivationFactory, ItfGuid = Interop.COM.IID_IManagedActivationFactory, CcwVtable = __vtable_IManagedActivationFactory.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal, }; // IRestrictedErrorInfo internal static McgInterfaceData s_IRestrictedErrorInfo = new McgInterfaceData { ItfType = InternalTypes.IRestrictedErrorInfo, ItfGuid = Interop.COM.IID_IRestrictedErrorInfo, Flags = McgInterfaceFlags.isInternal, }; #endif // IMarshal internal static McgInterfaceData s_IMarshal = new McgInterfaceData { ItfType = InternalTypes.IMarshal, ItfGuid = Interop.COM.IID_IMarshal, CcwVtable = __vtable_IMarshal.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal, }; // IDispatch internal static McgInterfaceData s_IDispatch = new McgInterfaceData { ItfType = InternalTypes.IDispatch, ItfGuid = Interop.COM.IID_IDispatch, CcwVtable = __vtable_IDispatch.GetVtableFuncPtr(), Flags = McgInterfaceFlags.isInternal, }; #if ENABLE_WINRT // HSTRING, just needed for TypeHandle comparison internal static McgInterfaceData s_HSTRING = new McgInterfaceData { ItfType = InternalTypes.HSTRING }; // ILanguageExceptionStackBackTrace internal static McgInterfaceData s_ILanguageExceptionStackBackTrace = new McgInterfaceData { ItfType = InternalTypes.ILanguageExceptionStackBackTrace, ItfGuid = Interop.COM.IID_ILanguageExceptionStackBackTrace, Flags = McgInterfaceFlags.isInternal, CcwVtable = System.Runtime.InteropServices.ExceptionHelpers.__vtable_ILanguageExceptionStackBackTrace.GetVtableFuncPtr(), }; #endif static readonly McgInterfaceData[] s_interfaceData = new McgInterfaceData[] { s_IUnknown, s_IInspectable, #if ENABLE_WINRT s_ICustomPropertyProvider, s_IWeakReferenceSource, s_IWeakReference, #endif s_ICCW, #if ENABLE_MIN_WINRT s_IActivationFactoryInternal, #endif #if ENABLE_WINRT s_IJupiterObject, s_IStringable, s_IManagedActivationFactory, s_IRestrictedErrorInfo, #endif s_IMarshal, s_IDispatch, #if ENABLE_WINRT s_HSTRING, s_ILanguageExceptionStackBackTrace #endif }; } }
using System; using System.Collections.Generic; using System.IO; using Rhino.Mocks; using Sep.Git.Tfs.Commands; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Core.TfsInterop; using Xunit; namespace Sep.Git.Tfs.Test.Core { public class TfsWorkspaceTests { [Fact] public void Nothing_to_checkin() { IWorkspace workspace = MockRepository.GenerateStub<IWorkspace>(); string localDirectory = string.Empty; TextWriter writer = new StringWriter(); TfsChangesetInfo contextVersion = MockRepository.GenerateStub<TfsChangesetInfo>(); IGitTfsRemote remote = MockRepository.GenerateStub<IGitTfsRemote>(); CheckinOptions checkinOptions = new CheckinOptions(); ITfsHelper tfsHelper = MockRepository.GenerateStub<ITfsHelper>(); CheckinPolicyEvaluator policyEvaluator = new CheckinPolicyEvaluator(); TfsWorkspace tfsWorkspace = new TfsWorkspace(workspace, localDirectory, writer, contextVersion, remote, checkinOptions, tfsHelper, policyEvaluator); workspace.Stub(w => w.GetPendingChanges()).Return(null); var ex = Assert.Throws<GitTfsException>(() => { var result = tfsWorkspace.Checkin(checkinOptions); }); Assert.Equal("Nothing to checkin!", ex.Message); } [Fact] public void Checkin_failed() { IWorkspace workspace = MockRepository.GenerateStub<IWorkspace>(); string localDirectory = string.Empty; TextWriter writer = new StringWriter(); TfsChangesetInfo contextVersion = MockRepository.GenerateStub<TfsChangesetInfo>(); IGitTfsRemote remote = MockRepository.GenerateStub<IGitTfsRemote>(); CheckinOptions checkinOptions = new CheckinOptions(); ITfsHelper tfsHelper = MockRepository.GenerateStub<ITfsHelper>(); CheckinPolicyEvaluator policyEvaluator = new CheckinPolicyEvaluator(); TfsWorkspace tfsWorkspace = new TfsWorkspace(workspace, localDirectory, writer, contextVersion, remote, checkinOptions, tfsHelper, policyEvaluator); IPendingChange pendingChange = MockRepository.GenerateStub<IPendingChange>(); IPendingChange[] allPendingChanges = new IPendingChange[] { pendingChange }; workspace.Stub(w => w.GetPendingChanges()).Return(allPendingChanges); ICheckinEvaluationResult checkinEvaluationResult = new StubbedCheckinEvaluationResult(); workspace.Stub(w => w.EvaluateCheckin( Arg<TfsCheckinEvaluationOptions>.Is.Anything, Arg<IPendingChange[]>.Is.Anything, Arg<IPendingChange[]>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<ICheckinNote>.Is.Anything, Arg<IEnumerable<IWorkItemCheckinInfo>>.Is.Anything)) .Return(checkinEvaluationResult); workspace.Expect(w => w.Checkin( Arg<IPendingChange[]>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<ICheckinNote>.Is.Anything, Arg<IEnumerable<IWorkItemCheckinInfo>>.Is.Anything, Arg<TfsPolicyOverrideInfo>.Is.Anything, Arg<bool>.Is.Anything)) .Return(0); var ex = Assert.Throws<GitTfsException>(() => { var result = tfsWorkspace.Checkin(checkinOptions); }); Assert.Equal("Checkin failed!", ex.Message); } [Fact] public void Policy_failed() { IWorkspace workspace = MockRepository.GenerateStub<IWorkspace>(); string localDirectory = string.Empty; TextWriter writer = new StringWriter(); TfsChangesetInfo contextVersion = MockRepository.GenerateStub<TfsChangesetInfo>(); IGitTfsRemote remote = MockRepository.GenerateStub<IGitTfsRemote>(); CheckinOptions checkinOptions = new CheckinOptions(); ITfsHelper tfsHelper = MockRepository.GenerateStub<ITfsHelper>(); CheckinPolicyEvaluator policyEvaluator = new CheckinPolicyEvaluator(); TfsWorkspace tfsWorkspace = new TfsWorkspace(workspace, localDirectory, writer, contextVersion, remote, checkinOptions, tfsHelper, policyEvaluator); IPendingChange pendingChange = MockRepository.GenerateStub<IPendingChange>(); IPendingChange[] allPendingChanges = new IPendingChange[] { pendingChange }; workspace.Stub(w => w.GetPendingChanges()).Return(allPendingChanges); ICheckinEvaluationResult checkinEvaluationResult = new StubbedCheckinEvaluationResult() .WithPoilicyFailure("No work items associated."); workspace.Stub(w => w.EvaluateCheckin( Arg<TfsCheckinEvaluationOptions>.Is.Anything, Arg<IPendingChange[]>.Is.Anything, Arg<IPendingChange[]>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<ICheckinNote>.Is.Anything, Arg<IEnumerable<IWorkItemCheckinInfo>>.Is.Anything)) .Return(checkinEvaluationResult); workspace.Expect(w => w.Checkin( Arg<IPendingChange[]>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<ICheckinNote>.Is.Anything, Arg<IEnumerable<IWorkItemCheckinInfo>>.Is.Anything, Arg<TfsPolicyOverrideInfo>.Is.Anything, Arg<bool>.Is.Anything)) .Return(0); var ex = Assert.Throws<GitTfsException>(() => { var result = tfsWorkspace.Checkin(checkinOptions); }); Assert.Equal("No changes checked in.", ex.Message); Assert.Contains("[ERROR] Policy: No work items associated.", writer.ToString()); } [Fact] public void Policy_failed_and_Force_without_an_OverrideReason() { IWorkspace workspace = MockRepository.GenerateStub<IWorkspace>(); string localDirectory = string.Empty; TextWriter writer = new StringWriter(); TfsChangesetInfo contextVersion = MockRepository.GenerateStub<TfsChangesetInfo>(); IGitTfsRemote remote = MockRepository.GenerateStub<IGitTfsRemote>(); CheckinOptions checkinOptions = new CheckinOptions(); ITfsHelper tfsHelper = MockRepository.GenerateStub<ITfsHelper>(); CheckinPolicyEvaluator policyEvaluator = new CheckinPolicyEvaluator(); TfsWorkspace tfsWorkspace = new TfsWorkspace(workspace, localDirectory, writer, contextVersion, remote, checkinOptions, tfsHelper, policyEvaluator); IPendingChange pendingChange = MockRepository.GenerateStub<IPendingChange>(); IPendingChange[] allPendingChanges = new IPendingChange[] { pendingChange }; workspace.Stub(w => w.GetPendingChanges()).Return(allPendingChanges); ICheckinEvaluationResult checkinEvaluationResult = new StubbedCheckinEvaluationResult() .WithPoilicyFailure("No work items associated."); checkinOptions.Force = true; workspace.Stub(w => w.EvaluateCheckin( Arg<TfsCheckinEvaluationOptions>.Is.Anything, Arg<IPendingChange[]>.Is.Anything, Arg<IPendingChange[]>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<ICheckinNote>.Is.Anything, Arg<IEnumerable<IWorkItemCheckinInfo>>.Is.Anything)) .Return(checkinEvaluationResult); workspace.Expect(w => w.Checkin( Arg<IPendingChange[]>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<ICheckinNote>.Is.Anything, Arg<IEnumerable<IWorkItemCheckinInfo>>.Is.Anything, Arg<TfsPolicyOverrideInfo>.Is.Anything, Arg<bool>.Is.Anything)) .Return(0); var ex = Assert.Throws<GitTfsException>(() => { var result = tfsWorkspace.Checkin(checkinOptions); }); Assert.Equal("A reason must be supplied (-f REASON) to override the policy violations.", ex.Message); Assert.Contains("[ERROR] Policy: No work items associated.", writer.ToString()); } [Fact] public void Policy_failed_and_Force_with_an_OverrideReason() { IWorkspace workspace = MockRepository.GenerateStub<IWorkspace>(); string localDirectory = string.Empty; TextWriter writer = new StringWriter(); TfsChangesetInfo contextVersion = MockRepository.GenerateStub<TfsChangesetInfo>(); IGitTfsRemote remote = MockRepository.GenerateStub<IGitTfsRemote>(); CheckinOptions checkinOptions = new CheckinOptions(); ITfsHelper tfsHelper = MockRepository.GenerateStub<ITfsHelper>(); CheckinPolicyEvaluator policyEvaluator = new CheckinPolicyEvaluator(); TfsWorkspace tfsWorkspace = new TfsWorkspace(workspace, localDirectory, writer, contextVersion, remote, checkinOptions, tfsHelper, policyEvaluator); IPendingChange pendingChange = MockRepository.GenerateStub<IPendingChange>(); IPendingChange[] allPendingChanges = new IPendingChange[] { pendingChange }; workspace.Stub(w => w.GetPendingChanges()).Return(allPendingChanges); ICheckinEvaluationResult checkinEvaluationResult = new StubbedCheckinEvaluationResult() .WithPoilicyFailure("No work items associated."); checkinOptions.Force = true; checkinOptions.OverrideReason = "no work items"; workspace.Stub(w => w.EvaluateCheckin( Arg<TfsCheckinEvaluationOptions>.Is.Anything, Arg<IPendingChange[]>.Is.Anything, Arg<IPendingChange[]>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<ICheckinNote>.Is.Anything, Arg<IEnumerable<IWorkItemCheckinInfo>>.Is.Anything)) .Return(checkinEvaluationResult); workspace.Expect(w => w.Checkin( Arg<IPendingChange[]>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<ICheckinNote>.Is.Anything, Arg<IEnumerable<IWorkItemCheckinInfo>>.Is.Anything, Arg<TfsPolicyOverrideInfo>.Is.Anything, Arg<bool>.Is.Anything)) .Return(1); var result = tfsWorkspace.Checkin(checkinOptions); Assert.Contains("[OVERRIDDEN] Policy: No work items associated.", writer.ToString()); } } }
// created on 10/12/2002 at 21:11 using System; using System.Runtime.InteropServices; using NAudio.Wave; using System.Collections.Generic; namespace NAudio.Mixer { /// <summary> /// Represents a mixer control /// </summary> public abstract class MixerControl { internal MixerInterop.MIXERCONTROL mixerControl; internal MixerInterop.MIXERCONTROLDETAILS mixerControlDetails; /// <summary> /// Mixer Handle /// </summary> protected IntPtr mixerHandle; /// <summary> /// Number of Channels /// </summary> protected int nChannels; /// <summary> /// Mixer Handle Type /// </summary> protected MixerFlags mixerHandleType; /// <summary> /// Gets all the mixer controls /// </summary> /// <param name="mixerHandle"></param> /// <param name="mixerLine"></param> /// <param name="mixerHandleType"></param> /// <returns></returns> public static IList<MixerControl> GetMixerControls(IntPtr mixerHandle, MixerLine mixerLine, MixerFlags mixerHandleType) { List<MixerControl> controls = new List<MixerControl>(); if (mixerLine.ControlsCount > 0) { int mixerControlSize = Marshal.SizeOf(typeof(MixerInterop.MIXERCONTROL)); MixerInterop.MIXERLINECONTROLS mlc = new MixerInterop.MIXERLINECONTROLS(); IntPtr pmc = Marshal.AllocHGlobal(mixerControlSize * mixerLine.ControlsCount); mlc.cbStruct = Marshal.SizeOf(mlc); mlc.dwLineID = mixerLine.LineId; mlc.cControls = mixerLine.ControlsCount; mlc.pamxctrl = pmc; mlc.cbmxctrl = Marshal.SizeOf(typeof(MixerInterop.MIXERCONTROL)); MmResult err = MixerInterop.mixerGetLineControls(mixerHandle, ref mlc, MixerFlags.All | mixerHandleType); if (err != MmResult.NoError) { Marshal.FreeHGlobal(pmc); throw new MmException(err, "mixerGetLineControls"); } for (int i = 0; i < mlc.cControls; i++) { Int64 address = pmc.ToInt64() + mixerControlSize * i; MixerInterop.MIXERCONTROL mc = (MixerInterop.MIXERCONTROL)Marshal.PtrToStructure((IntPtr)address, typeof(MixerInterop.MIXERCONTROL)); MixerControl mixerControl = MixerControl.GetMixerControl(mixerHandle, mixerLine.LineId, mc.dwControlID, mixerLine.Channels, mixerHandleType); controls.Add(mixerControl); } } return controls; } /// <summary> /// Gets a specified Mixer Control /// </summary> /// <param name="mixerHandle">Mixer Handle</param> /// <param name="nLineID">Line ID</param> /// <param name="controlId">Control ID</param> /// <param name="nChannels">Number of Channels</param> /// <param name="mixerFlags">Flags to use (indicates the meaning of mixerHandle)</param> /// <returns></returns> public static MixerControl GetMixerControl(IntPtr mixerHandle, int nLineID, int controlId, int nChannels, MixerFlags mixerFlags) { MixerInterop.MIXERLINECONTROLS mlc = new MixerInterop.MIXERLINECONTROLS(); MixerInterop.MIXERCONTROL mc = new MixerInterop.MIXERCONTROL(); // set up the pointer to a structure IntPtr pMixerControl = Marshal.AllocCoTaskMem(Marshal.SizeOf(mc)); //Marshal.StructureToPtr(mc, pMixerControl, false); mlc.cbStruct = Marshal.SizeOf(mlc); mlc.cControls = 1; mlc.dwControlID = controlId; mlc.cbmxctrl = Marshal.SizeOf(mc); mlc.pamxctrl = pMixerControl; mlc.dwLineID = nLineID; MmResult err = MixerInterop.mixerGetLineControls(mixerHandle, ref mlc, MixerFlags.OneById | mixerFlags); if(err != MmResult.NoError) { Marshal.FreeCoTaskMem(pMixerControl); throw new MmException(err,"mixerGetLineControls"); } // retrieve the structure from the pointer mc = (MixerInterop.MIXERCONTROL) Marshal.PtrToStructure(mlc.pamxctrl, typeof(MixerInterop.MIXERCONTROL)); Marshal.FreeCoTaskMem(pMixerControl); if(MixerControl.IsControlBoolean(mc.dwControlType)) { return new BooleanMixerControl(mc, mixerHandle, mixerFlags, nChannels); } else if(MixerControl.IsControlSigned(mc.dwControlType)) { return new SignedMixerControl(mc, mixerHandle, mixerFlags, nChannels); } else if(MixerControl.IsControlUnsigned(mc.dwControlType)) { return new UnsignedMixerControl(mc, mixerHandle, mixerFlags, nChannels); } else if(MixerControl.IsControlListText(mc.dwControlType)) { return new ListTextMixerControl(mc, mixerHandle, mixerFlags, nChannels); } else if(MixerControl.IsControlCustom(mc.dwControlType)) { return new CustomMixerControl(mc, mixerHandle, mixerFlags, nChannels); } else { throw new InvalidOperationException(String.Format("Unknown mixer control type {0}",mc.dwControlType)); } } /// <summary> /// Gets the control details /// </summary> protected void GetControlDetails() { mixerControlDetails.cbStruct = Marshal.SizeOf(mixerControlDetails); mixerControlDetails.dwControlID = mixerControl.dwControlID; if(IsCustom) { mixerControlDetails.cChannels = 0; } else if((mixerControl.fdwControl & MixerInterop.MIXERCONTROL_CONTROLF_UNIFORM) != 0) { mixerControlDetails.cChannels = 1; } else { mixerControlDetails.cChannels = nChannels; } if((mixerControl.fdwControl & MixerInterop.MIXERCONTROL_CONTROLF_MULTIPLE) != 0) { mixerControlDetails.hwndOwner = (IntPtr)mixerControl.cMultipleItems; } else if(IsCustom) { mixerControlDetails.hwndOwner = IntPtr.Zero; // TODO: special cases } else { mixerControlDetails.hwndOwner = IntPtr.Zero; } if(IsBoolean) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_BOOLEAN()); } else if(IsListText) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_LISTTEXT()); } else if(IsSigned) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_SIGNED()); } else if(IsUnsigned) { mixerControlDetails.cbDetails = Marshal.SizeOf(new MixerInterop.MIXERCONTROLDETAILS_UNSIGNED()); } else { // must be custom mixerControlDetails.cbDetails = mixerControl.Metrics.customData; } // from the structs sample in MSDN (see MyPerson2) IntPtr buffer = Marshal.AllocCoTaskMem(mixerControlDetails.cbDetails * mixerControlDetails.cChannels); // To copy stuff in: // Marshal.StructureToPtr( theStruct, buffer, false ); mixerControlDetails.paDetails = buffer; MmResult err = MixerInterop.mixerGetControlDetails(mixerHandle, ref mixerControlDetails, MixerFlags.Value | mixerHandleType); // let the derived classes get the details before we free the handle if(err == MmResult.NoError) { GetDetails(mixerControlDetails.paDetails); } Marshal.FreeCoTaskMem(buffer); if(err != MmResult.NoError) { throw new MmException(err,"mixerGetControlDetails"); } } /// <summary> /// Gets the control details /// </summary> /// <param name="pDetails"></param> protected abstract void GetDetails(IntPtr pDetails); /// <summary> /// Mixer control name /// </summary> public String Name { get { return mixerControl.szName; } } /// <summary> /// Mixer control type /// </summary> public MixerControlType ControlType { get { return mixerControl.dwControlType; } } /// <summary> /// Returns true if this is a boolean control /// </summary> /// <param name="controlType">Control type</param> private static bool IsControlBoolean(MixerControlType controlType) { switch(controlType) { case MixerControlType.BooleanMeter: case MixerControlType.Boolean: case MixerControlType.Button: case MixerControlType.Loudness: case MixerControlType.Mono: case MixerControlType.Mute: case MixerControlType.OnOff: case MixerControlType.StereoEnhance: case MixerControlType.Mixer: case MixerControlType.MultipleSelect: case MixerControlType.Mux: case MixerControlType.SingleSelect: return true; default: return false; } } /// <summary> /// Is this a boolean control /// </summary> public bool IsBoolean { get { return MixerControl.IsControlBoolean(mixerControl.dwControlType); } } /// <summary> /// Determines whether a specified mixer control type is a list text control /// </summary> private static bool IsControlListText(MixerControlType controlType) { switch(controlType) { case MixerControlType.Equalizer: case MixerControlType.Mixer: case MixerControlType.MultipleSelect: case MixerControlType.Mux: case MixerControlType.SingleSelect: return true; default: return false; } } /// <summary> /// True if this is a list text control /// </summary> public bool IsListText { get { return MixerControl.IsControlListText(mixerControl.dwControlType); } } private static bool IsControlSigned(MixerControlType controlType) { switch(controlType) { case MixerControlType.PeakMeter: case MixerControlType.SignedMeter: case MixerControlType.Signed: case MixerControlType.Decibels: case MixerControlType.Pan: case MixerControlType.QSoundPan: case MixerControlType.Slider: return true; default: return false; } } /// <summary> /// True if this is a signed control /// </summary> public bool IsSigned { get { return MixerControl.IsControlSigned(mixerControl.dwControlType); } } private static bool IsControlUnsigned(MixerControlType controlType) { switch(controlType) { case MixerControlType.UnsignedMeter: case MixerControlType.Unsigned: case MixerControlType.Bass: case MixerControlType.Equalizer: case MixerControlType.Fader: case MixerControlType.Treble: case MixerControlType.Volume: case MixerControlType.MicroTime: case MixerControlType.MilliTime: case MixerControlType.Percent: return true; default: return false; } } /// <summary> /// True if this is an unsigned control /// </summary> public bool IsUnsigned { get { return MixerControl.IsControlUnsigned(mixerControl.dwControlType); } } private static bool IsControlCustom(MixerControlType controlType) { return (controlType == MixerControlType.Custom); } /// <summary> /// True if this is a custom control /// </summary> public bool IsCustom { get { return MixerControl.IsControlCustom(mixerControl.dwControlType); } } /// <summary> /// String representation for debug purposes /// </summary> public override string ToString() { return String.Format("{0} {1}", Name, ControlType); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.RecoveryServices.Backup; using Microsoft.Azure.Management.RecoveryServices.Backup.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RecoveryServices.Backup { /// <summary> /// The Resource Manager API includes operations for managing recovery /// points created by backup operations on the items protected by your /// Recovery Services Vault. /// </summary> internal partial class RecoveryPointOperations : IServiceOperations<RecoveryServicesBackupManagementClient>, IRecoveryPointOperations { /// <summary> /// Initializes a new instance of the RecoveryPointOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RecoveryPointOperations(RecoveryServicesBackupManagementClient client) { this._client = client; } private RecoveryServicesBackupManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RecoveryServices.Backup.RecoveryServicesBackupManagementClient. /// </summary> public RecoveryServicesBackupManagementClient Client { get { return this._client; } } /// <summary> /// Gets Info for the given recovery point of the given item protected /// by your Recovery Services Vault as specified by the recovery point /// ID passed in the arguments.This is an asynchronous operation. To /// determine whether the backend service has finished processing the /// request, call the Get Protected Item Operation Result API. /// </summary> /// <param name='resourceGroupName'> /// Required. Resource group name of your recovery services vault. /// </param> /// <param name='resourceName'> /// Required. Name of your recovery services vault. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='fabricName'> /// Optional. Fabric name of the protected item. /// </param> /// <param name='containerName'> /// Optional. Name of the container where the protected item belongs to. /// </param> /// <param name='protectedItemName'> /// Optional. Name of the protected item whose recovery points are to /// be fetched. /// </param> /// <param name='recoveryPointId'> /// Optional. ID of the recovery point whose details are to be fetched. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A single instance of a recovery point response as returned by the /// service in the list recovery points call. /// </returns> public async Task<RecoveryPointResponse> GetAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, string recoveryPointId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("recoveryPointId", recoveryPointId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/"; url = url + "vaults"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/backupFabrics/"; if (fabricName != null) { url = url + Uri.EscapeDataString(fabricName); } url = url + "/protectionContainers/"; if (containerName != null) { url = url + Uri.EscapeDataString(containerName); } url = url + "/protectedItems/"; if (protectedItemName != null) { url = url + Uri.EscapeDataString(protectedItemName); } url = url + "/recoveryPoints/"; if (recoveryPointId != null) { url = url + Uri.EscapeDataString(recoveryPointId); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-05-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RecoveryPointResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RecoveryPointResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { RecoveryPointResource recPointInstance = new RecoveryPointResource(); result.RecPoint = recPointInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string typeName = ((string)propertiesValue["objectType"]); if (typeName == "IaasVMRecoveryPoint") { RecoveryPoint recoveryPointInstance = new RecoveryPoint(); JToken recoveryPointTypeValue = propertiesValue["recoveryPointType"]; if (recoveryPointTypeValue != null && recoveryPointTypeValue.Type != JTokenType.Null) { string recoveryPointTypeInstance = ((string)recoveryPointTypeValue); recoveryPointInstance.RecoveryPointType = recoveryPointTypeInstance; } JToken recoveryPointTimeValue = propertiesValue["recoveryPointTime"]; if (recoveryPointTimeValue != null && recoveryPointTimeValue.Type != JTokenType.Null) { string recoveryPointTimeInstance = ((string)recoveryPointTimeValue); recoveryPointInstance.RecoveryPointTime = recoveryPointTimeInstance; } JToken recoveryPointAdditionalInfoValue = propertiesValue["recoveryPointAdditionalInfo"]; if (recoveryPointAdditionalInfoValue != null && recoveryPointAdditionalInfoValue.Type != JTokenType.Null) { string recoveryPointAdditionalInfoInstance = ((string)recoveryPointAdditionalInfoValue); recoveryPointInstance.RecoveryPointAdditionalInfo = recoveryPointAdditionalInfoInstance; } JToken sourceVMStorageTypeValue = propertiesValue["sourceVMStorageType"]; if (sourceVMStorageTypeValue != null && sourceVMStorageTypeValue.Type != JTokenType.Null) { string sourceVMStorageTypeInstance = ((string)sourceVMStorageTypeValue); recoveryPointInstance.SourceVMStorageType = sourceVMStorageTypeInstance; } JToken isSourceVMEncryptedValue = propertiesValue["isSourceVMEncrypted"]; if (isSourceVMEncryptedValue != null && isSourceVMEncryptedValue.Type != JTokenType.Null) { bool isSourceVMEncryptedInstance = ((bool)isSourceVMEncryptedValue); recoveryPointInstance.IsSourceVMEncrypted = isSourceVMEncryptedInstance; } JToken keyAndSecretValue = propertiesValue["keyAndSecret"]; if (keyAndSecretValue != null && keyAndSecretValue.Type != JTokenType.Null) { KeyAndSecretDetails keyAndSecretInstance = new KeyAndSecretDetails(); recoveryPointInstance.KeyAndSecret = keyAndSecretInstance; JToken kekDetailsValue = keyAndSecretValue["kekDetails"]; if (kekDetailsValue != null && kekDetailsValue.Type != JTokenType.Null) { KekDetails kekDetailsInstance = new KekDetails(); keyAndSecretInstance.KekDetails = kekDetailsInstance; JToken keyUrlValue = kekDetailsValue["keyUrl"]; if (keyUrlValue != null && keyUrlValue.Type != JTokenType.Null) { string keyUrlInstance = ((string)keyUrlValue); kekDetailsInstance.KeyUrl = keyUrlInstance; } JToken keyVaultIdValue = kekDetailsValue["keyVaultId"]; if (keyVaultIdValue != null && keyVaultIdValue.Type != JTokenType.Null) { string keyVaultIdInstance = ((string)keyVaultIdValue); kekDetailsInstance.KeyVaultId = keyVaultIdInstance; } JToken keyBackupDataValue = kekDetailsValue["keyBackupData"]; if (keyBackupDataValue != null && keyBackupDataValue.Type != JTokenType.Null) { string keyBackupDataInstance = ((string)keyBackupDataValue); kekDetailsInstance.KeyBackupData = keyBackupDataInstance; } } JToken bekDetailsValue = keyAndSecretValue["bekDetails"]; if (bekDetailsValue != null && bekDetailsValue.Type != JTokenType.Null) { BekDetails bekDetailsInstance = new BekDetails(); keyAndSecretInstance.BekDetails = bekDetailsInstance; JToken secretUrlValue = bekDetailsValue["secretUrl"]; if (secretUrlValue != null && secretUrlValue.Type != JTokenType.Null) { string secretUrlInstance = ((string)secretUrlValue); bekDetailsInstance.SecretUrl = secretUrlInstance; } JToken secretVaultIdValue = bekDetailsValue["secretVaultId"]; if (secretVaultIdValue != null && secretVaultIdValue.Type != JTokenType.Null) { string secretVaultIdInstance = ((string)secretVaultIdValue); bekDetailsInstance.SecretVaultId = secretVaultIdInstance; } JToken secretDataValue = bekDetailsValue["secretData"]; if (secretDataValue != null && secretDataValue.Type != JTokenType.Null) { string secretDataInstance = ((string)secretDataValue); bekDetailsInstance.SecretData = secretDataInstance; } } } JToken isInstantILRSessionActiveValue = propertiesValue["isInstantILRSessionActive"]; if (isInstantILRSessionActiveValue != null && isInstantILRSessionActiveValue.Type != JTokenType.Null) { bool isInstantILRSessionActiveInstance = ((bool)isInstantILRSessionActiveValue); recoveryPointInstance.IsInstantILRSessionActive = isInstantILRSessionActiveInstance; } recPointInstance.Properties = recoveryPointInstance; } if (typeName == "GenericRecoveryPoint") { GenericRecoveryPoint genericRecoveryPointInstance = new GenericRecoveryPoint(); JToken recoveryPointTypeValue2 = propertiesValue["recoveryPointType"]; if (recoveryPointTypeValue2 != null && recoveryPointTypeValue2.Type != JTokenType.Null) { string recoveryPointTypeInstance2 = ((string)recoveryPointTypeValue2); genericRecoveryPointInstance.RecoveryPointType = recoveryPointTypeInstance2; } JToken friendlyNameValue = propertiesValue["friendlyName"]; if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null) { string friendlyNameInstance = ((string)friendlyNameValue); genericRecoveryPointInstance.FriendlyName = friendlyNameInstance; } JToken recoveryPointTimeValue2 = propertiesValue["recoveryPointTime"]; if (recoveryPointTimeValue2 != null && recoveryPointTimeValue2.Type != JTokenType.Null) { string recoveryPointTimeInstance2 = ((string)recoveryPointTimeValue2); genericRecoveryPointInstance.RecoveryPointTime = recoveryPointTimeInstance2; } JToken recoveryPointAdditionalInfoValue2 = propertiesValue["recoveryPointAdditionalInfo"]; if (recoveryPointAdditionalInfoValue2 != null && recoveryPointAdditionalInfoValue2.Type != JTokenType.Null) { string recoveryPointAdditionalInfoInstance2 = ((string)recoveryPointAdditionalInfoValue2); genericRecoveryPointInstance.RecoveryPointAdditionalInfo = recoveryPointAdditionalInfoInstance2; } recPointInstance.Properties = genericRecoveryPointInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); recPointInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); recPointInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); recPointInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); recPointInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); recPointInstance.Tags.Add(tagsKey, tagsValue); } } JToken eTagValue = responseDoc["eTag"]; if (eTagValue != null && eTagValue.Type != JTokenType.Null) { string eTagInstance = ((string)eTagValue); recPointInstance.ETag = eTagInstance; } JToken locationValue2 = responseDoc["location"]; if (locationValue2 != null && locationValue2.Type != JTokenType.Null) { string locationInstance2 = ((string)locationValue2); result.Location = locationInstance2; } JToken azureAsyncOperationValue = responseDoc["azureAsyncOperation"]; if (azureAsyncOperationValue != null && azureAsyncOperationValue.Type != JTokenType.Null) { string azureAsyncOperationInstance = ((string)azureAsyncOperationValue); result.AzureAsyncOperation = azureAsyncOperationInstance; } JToken retryAfterValue = responseDoc["retryAfter"]; if (retryAfterValue != null && retryAfterValue.Type != JTokenType.Null) { string retryAfterInstance = ((string)retryAfterValue); result.RetryAfter = retryAfterInstance; } JToken statusValue = responseDoc["Status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true)); result.Status = statusInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Lists all the recovery points of the given item protected by your /// Recovery Services Vault according to the query filter supplied in /// the arguments. /// </summary> /// <param name='resourceGroupName'> /// Required. Resource group name of your recovery services vault. /// </param> /// <param name='resourceName'> /// Required. Name of your recovery services vault. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='fabricName'> /// Optional. Fabric name of the protected item. /// </param> /// <param name='containerName'> /// Optional. Name of the container where the protected item belongs to. /// </param> /// <param name='protectedItemName'> /// Optional. Name of the protected item whose recovery points are to /// be fetched. /// </param> /// <param name='queryFilter'> /// Optional. Query parameters for listing recovery points. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of recovery points as returned by the service with the list /// recovery points call. /// </returns> public async Task<RecoveryPointListResponse> ListAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string fabricName, string containerName, string protectedItemName, RecoveryPointQueryParameters queryFilter, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("resourceName", resourceName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("queryFilter", queryFilter); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/"; url = url + "vaults"; url = url + "/"; url = url + Uri.EscapeDataString(resourceName); url = url + "/backupFabrics/"; if (fabricName != null) { url = url + Uri.EscapeDataString(fabricName); } url = url + "/protectionContainers/"; if (containerName != null) { url = url + Uri.EscapeDataString(containerName); } url = url + "/protectedItems/"; if (protectedItemName != null) { url = url + Uri.EscapeDataString(protectedItemName); } url = url + "/recoveryPoints"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-05-01"); List<string> odataFilter = new List<string>(); if (queryFilter != null && queryFilter.StartDate != null) { odataFilter.Add("startDate eq '" + Uri.EscapeDataString(queryFilter.StartDate) + "'"); } if (queryFilter != null && queryFilter.EndDate != null) { odataFilter.Add("endDate eq '" + Uri.EscapeDataString(queryFilter.EndDate) + "'"); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(" and ", odataFilter)); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RecoveryPointListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RecoveryPointListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { RecoveryPointResourceList recoveryPointListInstance = new RecoveryPointResourceList(); result.RecoveryPointList = recoveryPointListInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { RecoveryPointResource recoveryPointResourceInstance = new RecoveryPointResource(); recoveryPointListInstance.RecoveryPoints.Add(recoveryPointResourceInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { string typeName = ((string)propertiesValue["objectType"]); if (typeName == "IaasVMRecoveryPoint") { RecoveryPoint recoveryPointInstance = new RecoveryPoint(); JToken recoveryPointTypeValue = propertiesValue["recoveryPointType"]; if (recoveryPointTypeValue != null && recoveryPointTypeValue.Type != JTokenType.Null) { string recoveryPointTypeInstance = ((string)recoveryPointTypeValue); recoveryPointInstance.RecoveryPointType = recoveryPointTypeInstance; } JToken recoveryPointTimeValue = propertiesValue["recoveryPointTime"]; if (recoveryPointTimeValue != null && recoveryPointTimeValue.Type != JTokenType.Null) { string recoveryPointTimeInstance = ((string)recoveryPointTimeValue); recoveryPointInstance.RecoveryPointTime = recoveryPointTimeInstance; } JToken recoveryPointAdditionalInfoValue = propertiesValue["recoveryPointAdditionalInfo"]; if (recoveryPointAdditionalInfoValue != null && recoveryPointAdditionalInfoValue.Type != JTokenType.Null) { string recoveryPointAdditionalInfoInstance = ((string)recoveryPointAdditionalInfoValue); recoveryPointInstance.RecoveryPointAdditionalInfo = recoveryPointAdditionalInfoInstance; } JToken sourceVMStorageTypeValue = propertiesValue["sourceVMStorageType"]; if (sourceVMStorageTypeValue != null && sourceVMStorageTypeValue.Type != JTokenType.Null) { string sourceVMStorageTypeInstance = ((string)sourceVMStorageTypeValue); recoveryPointInstance.SourceVMStorageType = sourceVMStorageTypeInstance; } JToken isSourceVMEncryptedValue = propertiesValue["isSourceVMEncrypted"]; if (isSourceVMEncryptedValue != null && isSourceVMEncryptedValue.Type != JTokenType.Null) { bool isSourceVMEncryptedInstance = ((bool)isSourceVMEncryptedValue); recoveryPointInstance.IsSourceVMEncrypted = isSourceVMEncryptedInstance; } JToken keyAndSecretValue = propertiesValue["keyAndSecret"]; if (keyAndSecretValue != null && keyAndSecretValue.Type != JTokenType.Null) { KeyAndSecretDetails keyAndSecretInstance = new KeyAndSecretDetails(); recoveryPointInstance.KeyAndSecret = keyAndSecretInstance; JToken kekDetailsValue = keyAndSecretValue["kekDetails"]; if (kekDetailsValue != null && kekDetailsValue.Type != JTokenType.Null) { KekDetails kekDetailsInstance = new KekDetails(); keyAndSecretInstance.KekDetails = kekDetailsInstance; JToken keyUrlValue = kekDetailsValue["keyUrl"]; if (keyUrlValue != null && keyUrlValue.Type != JTokenType.Null) { string keyUrlInstance = ((string)keyUrlValue); kekDetailsInstance.KeyUrl = keyUrlInstance; } JToken keyVaultIdValue = kekDetailsValue["keyVaultId"]; if (keyVaultIdValue != null && keyVaultIdValue.Type != JTokenType.Null) { string keyVaultIdInstance = ((string)keyVaultIdValue); kekDetailsInstance.KeyVaultId = keyVaultIdInstance; } JToken keyBackupDataValue = kekDetailsValue["keyBackupData"]; if (keyBackupDataValue != null && keyBackupDataValue.Type != JTokenType.Null) { string keyBackupDataInstance = ((string)keyBackupDataValue); kekDetailsInstance.KeyBackupData = keyBackupDataInstance; } } JToken bekDetailsValue = keyAndSecretValue["bekDetails"]; if (bekDetailsValue != null && bekDetailsValue.Type != JTokenType.Null) { BekDetails bekDetailsInstance = new BekDetails(); keyAndSecretInstance.BekDetails = bekDetailsInstance; JToken secretUrlValue = bekDetailsValue["secretUrl"]; if (secretUrlValue != null && secretUrlValue.Type != JTokenType.Null) { string secretUrlInstance = ((string)secretUrlValue); bekDetailsInstance.SecretUrl = secretUrlInstance; } JToken secretVaultIdValue = bekDetailsValue["secretVaultId"]; if (secretVaultIdValue != null && secretVaultIdValue.Type != JTokenType.Null) { string secretVaultIdInstance = ((string)secretVaultIdValue); bekDetailsInstance.SecretVaultId = secretVaultIdInstance; } JToken secretDataValue = bekDetailsValue["secretData"]; if (secretDataValue != null && secretDataValue.Type != JTokenType.Null) { string secretDataInstance = ((string)secretDataValue); bekDetailsInstance.SecretData = secretDataInstance; } } } JToken isInstantILRSessionActiveValue = propertiesValue["isInstantILRSessionActive"]; if (isInstantILRSessionActiveValue != null && isInstantILRSessionActiveValue.Type != JTokenType.Null) { bool isInstantILRSessionActiveInstance = ((bool)isInstantILRSessionActiveValue); recoveryPointInstance.IsInstantILRSessionActive = isInstantILRSessionActiveInstance; } recoveryPointResourceInstance.Properties = recoveryPointInstance; } if (typeName == "GenericRecoveryPoint") { GenericRecoveryPoint genericRecoveryPointInstance = new GenericRecoveryPoint(); JToken recoveryPointTypeValue2 = propertiesValue["recoveryPointType"]; if (recoveryPointTypeValue2 != null && recoveryPointTypeValue2.Type != JTokenType.Null) { string recoveryPointTypeInstance2 = ((string)recoveryPointTypeValue2); genericRecoveryPointInstance.RecoveryPointType = recoveryPointTypeInstance2; } JToken friendlyNameValue = propertiesValue["friendlyName"]; if (friendlyNameValue != null && friendlyNameValue.Type != JTokenType.Null) { string friendlyNameInstance = ((string)friendlyNameValue); genericRecoveryPointInstance.FriendlyName = friendlyNameInstance; } JToken recoveryPointTimeValue2 = propertiesValue["recoveryPointTime"]; if (recoveryPointTimeValue2 != null && recoveryPointTimeValue2.Type != JTokenType.Null) { string recoveryPointTimeInstance2 = ((string)recoveryPointTimeValue2); genericRecoveryPointInstance.RecoveryPointTime = recoveryPointTimeInstance2; } JToken recoveryPointAdditionalInfoValue2 = propertiesValue["recoveryPointAdditionalInfo"]; if (recoveryPointAdditionalInfoValue2 != null && recoveryPointAdditionalInfoValue2.Type != JTokenType.Null) { string recoveryPointAdditionalInfoInstance2 = ((string)recoveryPointAdditionalInfoValue2); genericRecoveryPointInstance.RecoveryPointAdditionalInfo = recoveryPointAdditionalInfoInstance2; } recoveryPointResourceInstance.Properties = genericRecoveryPointInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); recoveryPointResourceInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); recoveryPointResourceInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); recoveryPointResourceInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); recoveryPointResourceInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); recoveryPointResourceInstance.Tags.Add(tagsKey, tagsValue); } } JToken eTagValue = valueValue["eTag"]; if (eTagValue != null && eTagValue.Type != JTokenType.Null) { string eTagInstance = ((string)eTagValue); recoveryPointResourceInstance.ETag = eTagInstance; } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); recoveryPointListInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// 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.V9.Resources { /// <summary>Resource name for the <c>ConversionValueRule</c> resource.</summary> public sealed partial class ConversionValueRuleName : gax::IResourceName, sys::IEquatable<ConversionValueRuleName> { /// <summary>The possible contents of <see cref="ConversionValueRuleName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c> /// . /// </summary> CustomerConversionValueRule = 1, } private static gax::PathTemplate s_customerConversionValueRule = new gax::PathTemplate("customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}"); /// <summary>Creates a <see cref="ConversionValueRuleName"/> 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="ConversionValueRuleName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ConversionValueRuleName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ConversionValueRuleName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ConversionValueRuleName"/> with the pattern /// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversionValueRuleId"> /// The <c>ConversionValueRule</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// A new instance of <see cref="ConversionValueRuleName"/> constructed from the provided ids. /// </returns> public static ConversionValueRuleName FromCustomerConversionValueRule(string customerId, string conversionValueRuleId) => new ConversionValueRuleName(ResourceNameType.CustomerConversionValueRule, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionValueRuleId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleId, nameof(conversionValueRuleId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConversionValueRuleName"/> with pattern /// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversionValueRuleId"> /// The <c>ConversionValueRule</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ConversionValueRuleName"/> with pattern /// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>. /// </returns> public static string Format(string customerId, string conversionValueRuleId) => FormatCustomerConversionValueRule(customerId, conversionValueRuleId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConversionValueRuleName"/> with pattern /// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversionValueRuleId"> /// The <c>ConversionValueRule</c> ID. Must not be <c>null</c> or empty. /// </param> /// <returns> /// The string representation of this <see cref="ConversionValueRuleName"/> with pattern /// <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c>. /// </returns> public static string FormatCustomerConversionValueRule(string customerId, string conversionValueRuleId) => s_customerConversionValueRule.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleId, nameof(conversionValueRuleId))); /// <summary> /// Parses the given resource name string into a new <see cref="ConversionValueRuleName"/> 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}/conversionValueRules/{conversion_value_rule_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="conversionValueRuleName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ConversionValueRuleName"/> if successful.</returns> public static ConversionValueRuleName Parse(string conversionValueRuleName) => Parse(conversionValueRuleName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ConversionValueRuleName"/> 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}/conversionValueRules/{conversion_value_rule_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="conversionValueRuleName">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="ConversionValueRuleName"/> if successful.</returns> public static ConversionValueRuleName Parse(string conversionValueRuleName, bool allowUnparsed) => TryParse(conversionValueRuleName, allowUnparsed, out ConversionValueRuleName 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="ConversionValueRuleName"/> 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}/conversionValueRules/{conversion_value_rule_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="conversionValueRuleName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ConversionValueRuleName"/>, 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 conversionValueRuleName, out ConversionValueRuleName result) => TryParse(conversionValueRuleName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ConversionValueRuleName"/> 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}/conversionValueRules/{conversion_value_rule_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="conversionValueRuleName">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="ConversionValueRuleName"/>, 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 conversionValueRuleName, bool allowUnparsed, out ConversionValueRuleName result) { gax::GaxPreconditions.CheckNotNull(conversionValueRuleName, nameof(conversionValueRuleName)); gax::TemplatedResourceName resourceName; if (s_customerConversionValueRule.TryParseName(conversionValueRuleName, out resourceName)) { result = FromCustomerConversionValueRule(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(conversionValueRuleName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ConversionValueRuleName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversionValueRuleId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; ConversionValueRuleId = conversionValueRuleId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="ConversionValueRuleName"/> class from the component parts of /// pattern <c>customers/{customer_id}/conversionValueRules/{conversion_value_rule_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversionValueRuleId"> /// The <c>ConversionValueRule</c> ID. Must not be <c>null</c> or empty. /// </param> public ConversionValueRuleName(string customerId, string conversionValueRuleId) : this(ResourceNameType.CustomerConversionValueRule, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), conversionValueRuleId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversionValueRuleId, nameof(conversionValueRuleId))) { } /// <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>ConversionValueRule</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed /// resource name. /// </summary> public string ConversionValueRuleId { 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>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.CustomerConversionValueRule: return s_customerConversionValueRule.Expand(CustomerId, ConversionValueRuleId); 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 ConversionValueRuleName); /// <inheritdoc/> public bool Equals(ConversionValueRuleName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ConversionValueRuleName a, ConversionValueRuleName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ConversionValueRuleName a, ConversionValueRuleName b) => !(a == b); } public partial class ConversionValueRule { /// <summary> /// <see cref="ConversionValueRuleName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal ConversionValueRuleName ResourceNameAsConversionValueRuleName { get => string.IsNullOrEmpty(ResourceName) ? null : ConversionValueRuleName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CustomerName"/>-typed view over the <see cref="OwnerCustomer"/> resource name property. /// </summary> internal CustomerName OwnerCustomerAsCustomerName { get => string.IsNullOrEmpty(OwnerCustomer) ? null : CustomerName.Parse(OwnerCustomer, allowUnparsed: true); set => OwnerCustomer = value?.ToString() ?? ""; } } }
/* * 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 Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.Avatar { public class AvatarServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAvatarService m_AvatarService; public AvatarServerPostHandler(IAvatarService service, IServiceAuth auth) : base("POST", "/avatar", auth) { m_AvatarService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { string body; using(StreamReader sr = new StreamReader(requestData)) body = sr.ReadToEnd(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); switch (method) { case "getavatar": return GetAvatar(request); case "setavatar": return SetAvatar(request); case "resetavatar": return ResetAvatar(request); case "setitems": return SetItems(request); case "removeitems": return RemoveItems(request); } m_log.DebugFormat("[AVATAR HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.Debug("[AVATAR HANDLER]: Exception {0}" + e); } return FailureResult(); } byte[] GetAvatar(Dictionary<string, object> request) { UUID user = UUID.Zero; if (!request.ContainsKey("UserID")) return FailureResult(); if (UUID.TryParse(request["UserID"].ToString(), out user)) { AvatarData avatar = m_AvatarService.GetAvatar(user); if (avatar == null) return FailureResult(); Dictionary<string, object> result = new Dictionary<string, object>(); if (avatar == null) result["result"] = "null"; else result["result"] = avatar.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } return FailureResult(); } byte[] SetAvatar(Dictionary<string, object> request) { UUID user = UUID.Zero; if (!request.ContainsKey("UserID")) return FailureResult(); if (!UUID.TryParse(request["UserID"].ToString(), out user)) return FailureResult(); RemoveRequestParamsNotForStorage(request); AvatarData avatar = new AvatarData(request); if (m_AvatarService.SetAvatar(user, avatar)) return SuccessResult(); return FailureResult(); } byte[] ResetAvatar(Dictionary<string, object> request) { UUID user = UUID.Zero; if (!request.ContainsKey("UserID")) return FailureResult(); if (!UUID.TryParse(request["UserID"].ToString(), out user)) return FailureResult(); RemoveRequestParamsNotForStorage(request); if (m_AvatarService.ResetAvatar(user)) return SuccessResult(); return FailureResult(); } /// <summary> /// Remove parameters that were used to invoke the method and should not in themselves be persisted. /// </summary> /// <param name='request'></param> private void RemoveRequestParamsNotForStorage(Dictionary<string, object> request) { request.Remove("VERSIONMAX"); request.Remove("VERSIONMIN"); request.Remove("METHOD"); request.Remove("UserID"); } byte[] SetItems(Dictionary<string, object> request) { UUID user = UUID.Zero; string[] names, values; if (!request.ContainsKey("UserID") || !request.ContainsKey("Names") || !request.ContainsKey("Values")) return FailureResult(); if (!UUID.TryParse(request["UserID"].ToString(), out user)) return FailureResult(); if (!(request["Names"] is List<string> || request["Values"] is List<string>)) return FailureResult(); RemoveRequestParamsNotForStorage(request); List<string> _names = (List<string>)request["Names"]; names = _names.ToArray(); List<string> _values = (List<string>)request["Values"]; values = _values.ToArray(); if (m_AvatarService.SetItems(user, names, values)) return SuccessResult(); return FailureResult(); } byte[] RemoveItems(Dictionary<string, object> request) { UUID user = UUID.Zero; string[] names; if (!request.ContainsKey("UserID") || !request.ContainsKey("Names")) return FailureResult(); if (!UUID.TryParse(request["UserID"].ToString(), out user)) return FailureResult(); if (!(request["Names"] is List<string>)) return FailureResult(); List<string> _names = (List<string>)request["Names"]; names = _names.ToArray(); if (m_AvatarService.RemoveItems(user, names)) return SuccessResult(); return FailureResult(); } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] FailureResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } } }
// // SourceView.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Collections.Generic; using Gtk; using Cairo; using Mono.Unix; using Hyena; using Hyena.Gui; using Hyena.Gui.Theming; using Hyena.Gui.Theatrics; using Banshee.Configuration; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Playlist; using Banshee.Gui; namespace Banshee.Sources.Gui { // Note: This is a partial class - the drag and drop code is split // out into a separate file to make this class more manageable. // See SourceView_DragAndDrop.cs for the DnD code. public partial class SourceView : TreeView { private SourceRowRenderer renderer; private Theme theme; private Cairo.Context cr; private Stage<TreeIter> notify_stage = new Stage<TreeIter> (2000); private TreeViewColumn focus_column; private TreeIter highlight_iter = TreeIter.Zero; private SourceModel store; private int current_timeout = -1; private bool editing_row = false; private bool need_resort = false; protected SourceView (IntPtr ptr) : base (ptr) {} public SourceView () { BuildColumns (); store = new SourceModel (); store.SourceRowInserted += OnSourceRowInserted; store.SourceRowRemoved += OnSourceRowRemoved; store.RowChanged += OnRowChanged; Model = store; EnableSearch = false; ConfigureDragAndDrop (); store.Refresh (); ConnectEvents (); RowSeparatorFunc = RowSeparatorHandler; ResetSelection (); } #region Setup Methods private void BuildColumns () { // Hidden expander column TreeViewColumn col = new TreeViewColumn (); col.Visible = false; AppendColumn (col); ExpanderColumn = col; focus_column = new TreeViewColumn (); renderer = new SourceRowRenderer (); renderer.RowHeight = RowHeight.Get (); renderer.Padding = RowPadding.Get (); focus_column.PackStart (renderer, true); focus_column.SetCellDataFunc (renderer, new CellLayoutDataFunc (SourceRowRenderer.CellDataHandler)); AppendColumn (focus_column); HeadersVisible = false; } private void ConnectEvents () { ServiceManager.SourceManager.ActiveSourceChanged += delegate (SourceEventArgs args) { ThreadAssist.ProxyToMain (ResetSelection); }; ServiceManager.SourceManager.SourceUpdated += delegate (SourceEventArgs args) { ThreadAssist.ProxyToMain (delegate { lock (args.Source) { TreeIter iter = store.FindSource (args.Source); if (!TreeIter.Zero.Equals (iter)) { if (args.Source.Expanded) { Expand (args.Source); } need_resort = true; QueueDraw (); } } }); }; ServiceManager.PlaybackController.NextSourceChanged += delegate { ThreadAssist.ProxyToMain (QueueDraw); }; notify_stage.ActorStep += delegate (Actor<TreeIter> actor) { ThreadAssist.AssertInMainThread (); if (!store.IterIsValid (actor.Target)) { return false; } using (var path = store.GetPath (actor.Target) ) { Gdk.Rectangle rect = GetBackgroundArea (path, focus_column); QueueDrawArea (rect.X, rect.Y, rect.Width, rect.Height); } return true; }; ServiceManager.Get<InterfaceActionService> ().SourceActions["OpenSourceSwitcher"].Activated += delegate { new SourceSwitcherEntry (this); }; } #endregion #region Gtk.Widget Overrides protected override void OnStyleSet (Style old_style) { base.OnStyleSet (old_style); theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this); } protected override bool OnButtonPressEvent (Gdk.EventButton press) { TreePath path; TreeViewColumn column; if (press.Button == 1) { ResetHighlight (); } // If there is not a row at the click position let the base handler take care of the press if (!GetPathAtPos ((int)press.X, (int)press.Y, out path, out column)) { return base.OnButtonPressEvent (press); } Source source = store.GetSource (path); // From F-Spot's SaneTreeView class int expander_size = (int)StyleGetProperty ("expander-size"); int horizontal_separator = (int)StyleGetProperty ("horizontal-separator"); bool on_expander = press.X <= horizontal_separator * 2 + path.Depth * expander_size; if (on_expander) { bool ret = base.OnButtonPressEvent (press); // If the active source is a child of this source, and we are about to collapse it, switch // the active source to the parent. if (source == ServiceManager.SourceManager.ActiveSource.Parent && GetRowExpanded (path)) { ServiceManager.SourceManager.SetActiveSource (source); } return ret; } // For Sources that can't be activated, when they're clicked just // expand or collapse them and return. if (press.Button == 1 && !source.CanActivate) { if (!source.Expanded) { ExpandRow (path, false); } else { CollapseRow (path); } return false; } if (press.Button == 3) { TreeIter iter; if (Model.GetIter (out iter, path)) { HighlightIter (iter); OnPopupMenu (); return true; } } if (!source.CanActivate) { return false; } if (press.Button == 1) { if (ServiceManager.SourceManager.ActiveSource != source) { ServiceManager.SourceManager.SetActiveSource (source); } } if ((press.State & Gdk.ModifierType.ControlMask) != 0) { if (press.Type == Gdk.EventType.TwoButtonPress && press.Button == 1) { ActivateRow (path, null); } return true; } return base.OnButtonPressEvent (press); } protected override bool OnPopupMenu () { ServiceManager.Get<InterfaceActionService> ().SourceActions["SourceContextMenuAction"].Activate (); return true; } protected override bool OnExposeEvent (Gdk.EventExpose evnt) { if (need_resort) { need_resort = false; // Resort the tree store. This is performed in an event handler // known not to conflict with gtk_tree_view_bin_expose() to prevent // errors about corrupting the TreeView's internal state. foreach (Source dsource in ServiceManager.SourceManager.Sources) { TreeIter iter = store.FindSource (dsource); if (!TreeIter.Zero.Equals (iter) && (int)store.GetValue (iter, 1) != dsource.Order) { store.SetValue (iter, 1, dsource.Order); } } QueueDraw (); } try { cr = Gdk.CairoHelper.Create (evnt.Window); base.OnExposeEvent (evnt); if (Hyena.PlatformDetection.IsMeeGo) { theme.DrawFrameBorder (cr, new Gdk.Rectangle (0, 0, Allocation.Width, Allocation.Height)); } return true; } finally { CairoExtensions.DisposeContext (cr); cr = null; } } #endregion #region Gtk.TreeView Overrides protected override void OnRowExpanded (TreeIter iter, TreePath path) { base.OnRowExpanded (iter, path); store.GetSource (iter).Expanded = true; } protected override void OnRowCollapsed (TreeIter iter, TreePath path) { base.OnRowCollapsed (iter, path); store.GetSource (iter).Expanded = false; } protected override void OnCursorChanged () { if (current_timeout < 0) { current_timeout = (int)GLib.Timeout.Add (200, OnCursorChangedTimeout); } } private bool OnCursorChangedTimeout () { TreeIter iter; TreeModel model; current_timeout = -1; if (!Selection.GetSelected (out model, out iter)) { return false; } Source new_source = store.GetValue (iter, 0) as Source; if (ServiceManager.SourceManager.ActiveSource == new_source) { return false; } ServiceManager.SourceManager.SetActiveSource (new_source); QueueDraw (); return false; } private bool RowSeparatorHandler (TreeModel model, TreeIter iter) { return (bool)store.GetValue (iter, 2); } #endregion #region Add/Remove Sources / SourceManager interaction private void OnSourceRowInserted (object o, SourceRowEventArgs args) { args.Source.UserNotifyUpdated += OnSourceUserNotifyUpdated; if (args.Source.Parent != null && args.Source.Parent.AutoExpand == true) { Expand (args.ParentIter); } if (args.Source.Expanded || args.Source.AutoExpand == true) { Expand (args.Iter); } UpdateView (); if (args.Source.Properties.Get<bool> ("NotifyWhenAdded")) { args.Source.NotifyUser (); } } private void OnSourceRowRemoved (object o, SourceRowEventArgs args) { args.Source.UserNotifyUpdated -= OnSourceUserNotifyUpdated; UpdateView (); } private void OnRowChanged (object o, RowChangedArgs args) { QueueDraw (); } internal void Expand (Source src) { Expand (store.FindSource (src)); src.Expanded = true; } private void Expand (TreeIter iter) { using (var path = store.GetPath (iter)) { ExpandRow (path, true); } } private void OnSourceUserNotifyUpdated (object o, EventArgs args) { ThreadAssist.ProxyToMain (delegate { TreeIter iter = store.FindSource ((Source)o); if (iter.Equals (TreeIter.Zero)) { return; } notify_stage.AddOrReset (iter); }); } #endregion #region List/View Utility Methods private bool UpdateView () { for (int i = 0, m = store.IterNChildren (); i < m; i++) { TreeIter iter = TreeIter.Zero; if (!store.IterNthChild (out iter, i)) { continue; } if (store.IterNChildren (iter) > 0) { ExpanderColumn = Columns[1]; return true; } } ExpanderColumn = Columns[0]; return false; } internal void UpdateRow (TreePath path, string text) { TreeIter iter; if (!store.GetIter (out iter, path)) { return; } Source source = store.GetValue (iter, 0) as Source; source.Rename (text); } public void BeginRenameSource (Source source) { TreeIter iter = store.FindSource (source); if (iter.Equals (TreeIter.Zero)) { return; } renderer.Editable = true; using (var path = store.GetPath (iter)) { SetCursor (path, focus_column, true); } renderer.Editable = false; } private void ResetSelection () { TreeIter iter = store.FindSource (ServiceManager.SourceManager.ActiveSource); if (!iter.Equals (TreeIter.Zero)){ Selection.SelectIter (iter); } } public void HighlightIter (TreeIter iter) { highlight_iter = iter; QueueDraw (); } public void ResetHighlight () { highlight_iter = TreeIter.Zero; QueueDraw (); } #endregion #region Public Properties public Source HighlightedSource { get { if (TreeIter.Zero.Equals (highlight_iter)) { return null; } return store.GetValue (highlight_iter, 0) as Source; } } public bool EditingRow { get { return editing_row; } set { editing_row = value; QueueDraw (); } } #endregion #region Internal Properties internal TreeIter HighlightedIter { get { return highlight_iter; } } internal Cairo.Context Cr { get { return cr; } } internal Theme Theme { get { return theme; } } internal Stage<TreeIter> NotifyStage { get { return notify_stage; } } internal Source NewPlaylistSource { get { return new_playlist_source ?? (new_playlist_source = new PlaylistSource (Catalog.GetString ("New Playlist"), ServiceManager.SourceManager.MusicLibrary)); } } #endregion #region Property Schemas private static SchemaEntry<int> RowHeight = new SchemaEntry<int> ( "player_window", "source_view_row_height", 22, "The height of each source row in the SourceView. 22 is the default.", ""); private static SchemaEntry<int> RowPadding = new SchemaEntry<int> ( "player_window", "source_view_row_padding", 5, "The padding between sources in the SourceView. 5 is the default.", ""); #endregion } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Net; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Runtime; namespace Orleans { /// <summary> /// Interface for Membership Table. /// </summary> public interface IMembershipTable { /// <summary> /// Initializes the membership table, will be called before all other methods /// </summary> /// <param name="tryInitTableVersion">whether an attempt will be made to init the underlying table</param> Task InitializeMembershipTable(bool tryInitTableVersion); /// <summary> /// Deletes all table entries of the given clusterId /// </summary> Task DeleteMembershipTableEntries(string clusterId); /// <summary> /// Delete all dead silo entries older than <paramref name="beforeDate"/> /// </summary> Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate); /// <summary> /// Atomically reads the Membership Table information about a given silo. /// The returned MembershipTableData includes one MembershipEntry entry for a given silo and the /// TableVersion for this table. The MembershipEntry and the TableVersion have to be read atomically. /// </summary> /// <param name="key">The address of the silo whose membership information needs to be read.</param> /// <returns>The membership information for a given silo: MembershipTableData consisting one MembershipEntry entry and /// TableVersion, read atomically.</returns> Task<MembershipTableData> ReadRow(SiloAddress key); /// <summary> /// Atomically reads the full content of the Membership Table. /// The returned MembershipTableData includes all MembershipEntry entry for all silos in the table and the /// TableVersion for this table. The MembershipEntries and the TableVersion have to be read atomically. /// </summary> /// <returns>The membership information for a given table: MembershipTableData consisting multiple MembershipEntry entries and /// TableVersion, all read atomically.</returns> Task<MembershipTableData> ReadAll(); /// <summary> /// Atomically tries to insert (add) a new MembershipEntry for one silo and also update the TableVersion. /// If operation succeeds, the following changes would be made to the table: /// 1) New MembershipEntry will be added to the table. /// 2) The newly added MembershipEntry will also be added with the new unique automatically generated eTag. /// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version. /// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag. /// All those changes to the table, insert of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects. /// The operation should fail in each of the following conditions: /// 1) A MembershipEntry for a given silo already exist in the table /// 2) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table. /// </summary> /// <param name="entry">MembershipEntry to be inserted.</param> /// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param> /// <returns>True if the insert operation succeeded and false otherwise.</returns> Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion); /// <summary> /// Atomically tries to update the MembershipEntry for one silo and also update the TableVersion. /// If operation succeeds, the following changes would be made to the table: /// 1) The MembershipEntry for this silo will be updated to the new MembershipEntry (the old entry will be fully substituted by the new entry) /// 2) The eTag for the updated MembershipEntry will also be eTag with the new unique automatically generated eTag. /// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version. /// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag. /// All those changes to the table, update of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects. /// The operation should fail in each of the following conditions: /// 1) A MembershipEntry for a given silo does not exist in the table /// 2) A MembershipEntry for a given silo exist in the table but its etag in the table does not match the provided etag. /// 3) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table. /// </summary> /// <param name="entry">MembershipEntry to be updated.</param> /// <param name="etag">The etag for the given MembershipEntry.</param> /// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param> /// <returns>True if the update operation succeeded and false otherwise.</returns> Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion); /// <summary> /// Updates the IAmAlive part (column) of the MembershipEntry for this silo. /// This operation should only update the IAmAlive column and not change other columns. /// This operation is a "dirty write" or "in place update" and is performed without etag validation. /// With regards to eTags update: /// This operation may automatically update the eTag associated with the given silo row, but it does not have to. It can also leave the etag not changed ("dirty write"). /// With regards to TableVersion: /// this operation should not change the TableVersion of the table. It should leave it untouched. /// There is no scenario where this operation could fail due to table semantical reasons. It can only fail due to network problems or table unavailability. /// </summary> /// <param name="entry"></param> /// <returns>Task representing the successful execution of this operation. </returns> Task UpdateIAmAlive(MembershipEntry entry); } /// <summary> /// Membership table interface for system target based implementation. /// </summary> [Unordered] public interface IMembershipTableSystemTarget : IMembershipTable, ISystemTarget { } [Serializable] [Immutable] [GenerateSerializer] public class TableVersion { /// <summary> /// The version part of this TableVersion. Monotonically increasing number. /// </summary> [Id(1)] public int Version { get; private set; } /// <summary> /// The etag of this TableVersion, used for validation of table update operations. /// </summary> [Id(2)] public string VersionEtag { get; private set; } public TableVersion(int version, string eTag) { Version = version; VersionEtag = eTag; } public TableVersion Next() { return new TableVersion(Version + 1, VersionEtag); } public override string ToString() { return string.Format("<{0}, {1}>", Version, VersionEtag); } } [Serializable] [GenerateSerializer] public class MembershipTableData { [Id(1)] public IReadOnlyList<Tuple<MembershipEntry, string>> Members { get; private set; } [Id(2)] public TableVersion Version { get; private set; } public MembershipTableData(List<Tuple<MembershipEntry, string>> list, TableVersion version) { // put deads at the end, just for logging. list.Sort( (x, y) => { if (x.Item1.Status == SiloStatus.Dead) return 1; // put Deads at the end if (y.Item1.Status == SiloStatus.Dead) return -1; // put Deads at the end return String.Compare(x.Item1.SiloName, y.Item1.SiloName, StringComparison.Ordinal); }); Members = list.AsReadOnly(); Version = version; } public MembershipTableData(Tuple<MembershipEntry, string> tuple, TableVersion version) { Members = (new List<Tuple<MembershipEntry, string>> { tuple }).AsReadOnly(); Version = version; } public MembershipTableData(TableVersion version) { Members = (new List<Tuple<MembershipEntry, string>>()).AsReadOnly(); Version = version; } public Tuple<MembershipEntry, string> Get(SiloAddress silo) { return Members.First(tuple => tuple.Item1.SiloAddress.Equals(silo)); } public bool Contains(SiloAddress silo) { return Members.Any(tuple => tuple.Item1.SiloAddress.Equals(silo)); } public override string ToString() { int active = Members.Count(e => e.Item1.Status == SiloStatus.Active); int dead = Members.Count(e => e.Item1.Status == SiloStatus.Dead); int created = Members.Count(e => e.Item1.Status == SiloStatus.Created); int joining = Members.Count(e => e.Item1.Status == SiloStatus.Joining); int shuttingDown = Members.Count(e => e.Item1.Status == SiloStatus.ShuttingDown); int stopping = Members.Count(e => e.Item1.Status == SiloStatus.Stopping); string otherCounts = String.Format("{0}{1}{2}{3}", created > 0 ? (", " + created + " are Created") : "", joining > 0 ? (", " + joining + " are Joining") : "", shuttingDown > 0 ? (", " + shuttingDown + " are ShuttingDown") : "", stopping > 0 ? (", " + stopping + " are Stopping") : ""); return string.Format("{0} silos, {1} are Active, {2} are Dead{3}, Version={4}. All silos: {5}", Members.Count, active, dead, otherCounts, Version, Utils.EnumerableToString(Members, tuple => tuple.Item1.ToFullString())); } // return a copy of the table removing all dead appereances of dead nodes, except for the last one. public MembershipTableData WithoutDuplicateDeads() { var dead = new Dictionary<IPEndPoint, Tuple<MembershipEntry, string>>(); // pick only latest Dead for each instance foreach (var next in Members.Where(item => item.Item1.Status == SiloStatus.Dead)) { var ipEndPoint = next.Item1.SiloAddress.Endpoint; Tuple<MembershipEntry, string> prev; if (!dead.TryGetValue(ipEndPoint, out prev)) { dead[ipEndPoint] = next; } else { // later dead. if (next.Item1.SiloAddress.Generation.CompareTo(prev.Item1.SiloAddress.Generation) > 0) dead[ipEndPoint] = next; } } //now add back non-dead List<Tuple<MembershipEntry, string>> all = dead.Values.ToList(); all.AddRange(Members.Where(item => item.Item1.Status != SiloStatus.Dead)); return new MembershipTableData(all, Version); } internal Dictionary<SiloAddress, SiloStatus> GetSiloStatuses(Func<SiloStatus, bool> filter, bool includeMyself, SiloAddress myAddress) { var result = new Dictionary<SiloAddress, SiloStatus>(); foreach (var memberEntry in this.Members) { var entry = memberEntry.Item1; if (!includeMyself && entry.SiloAddress.Equals(myAddress)) continue; if (filter(entry.Status)) result[entry.SiloAddress] = entry.Status; } return result; } } [GenerateSerializer] [Serializable] public class MembershipEntry { /// <summary> /// The silo unique identity (ip:port:epoch). Used mainly by the Membership Protocol. /// </summary> [Id(1)] public SiloAddress SiloAddress { get; set; } /// <summary> /// The silo status. Managed by the Membership Protocol. /// </summary> [Id(2)] public SiloStatus Status { get; set; } /// <summary> /// The list of silos that suspect this silo. Managed by the Membership Protocol. /// </summary> [Id(3)] public List<Tuple<SiloAddress, DateTime>> SuspectTimes { get; set; } /// <summary> /// Silo to clients TCP port. Set on silo startup. /// </summary> [Id(4)] public int ProxyPort { get; set; } /// <summary> /// The DNS host name of the silo. Equals to Dns.GetHostName(). Set on silo startup. /// </summary> [Id(5)] public string HostName { get; set; } /// <summary> /// the name of the specific silo instance within a cluster. /// If running in Azure - the name of this role instance. Set on silo startup. /// </summary> [Id(6)] public string SiloName { get; set; } [Id(7)] public string RoleName { get; set; } // Optional - only for Azure role [Id(8)] public int UpdateZone { get; set; } // Optional - only for Azure role [Id(9)] public int FaultZone { get; set; } // Optional - only for Azure role /// <summary> /// Time this silo was started. For diagnostics and troubleshooting only. /// </summary> [Id(10)] public DateTime StartTime { get; set; } /// <summary> /// the last time this silo reported that it is alive. For diagnostics and troubleshooting only. /// </summary> [Id(11)] public DateTime IAmAliveTime { get; set; } public void AddSuspector(SiloAddress suspectingSilo, DateTime suspectingTime) { if (SuspectTimes == null) SuspectTimes = new List<Tuple<SiloAddress, DateTime>>(); var suspector = new Tuple<SiloAddress, DateTime>(suspectingSilo, suspectingTime); SuspectTimes.Add(suspector); } internal MembershipEntry Copy() { return new MembershipEntry { SiloAddress = this.SiloAddress, Status = this.Status, HostName = this.HostName, ProxyPort = this.ProxyPort, RoleName = this.RoleName, SiloName = this.SiloName, UpdateZone = this.UpdateZone, FaultZone = this.FaultZone, SuspectTimes = this.SuspectTimes is null ? null : new List<Tuple<SiloAddress, DateTime>>(this.SuspectTimes), StartTime = this.StartTime, IAmAliveTime = this.IAmAliveTime, }; } internal MembershipEntry WithStatus(SiloStatus status) { var updated = this.Copy(); updated.Status = status; return updated; } internal ImmutableList<Tuple<SiloAddress, DateTime>> GetFreshVotes(DateTime now, TimeSpan expiration) { if (this.SuspectTimes == null) return ImmutableList<Tuple<SiloAddress, DateTime>>.Empty; var result = ImmutableList.CreateBuilder<Tuple<SiloAddress, DateTime>>(); foreach (var voter in this.SuspectTimes) { // If now is smaller than otherVoterTime, than assume the otherVoterTime is fresh. // This could happen if clocks are not synchronized and the other voter clock is ahead of mine. var otherVoterTime = voter.Item2; if (now < otherVoterTime || now.Subtract(otherVoterTime) < expiration) { result.Add(voter); } } return result.ToImmutable(); } public override string ToString() { return string.Format("SiloAddress={0} SiloName={1} Status={2}", SiloAddress.ToLongString(), SiloName, Status); } public string ToFullString(bool full = false) { if (!full) return ToString(); List<SiloAddress> suspecters = SuspectTimes == null ? null : SuspectTimes.Select(tuple => tuple.Item1).ToList(); List<DateTime> timestamps = SuspectTimes == null ? null : SuspectTimes.Select(tuple => tuple.Item2).ToList(); return string.Format("[SiloAddress={0} SiloName={1} Status={2} HostName={3} ProxyPort={4} " + "RoleName={5} UpdateZone={6} FaultZone={7} StartTime = {8} IAmAliveTime = {9} {10} {11}]", SiloAddress.ToLongString(), SiloName, Status, HostName, ProxyPort, RoleName, UpdateZone, FaultZone, LogFormatter.PrintDate(StartTime), LogFormatter.PrintDate(IAmAliveTime), suspecters == null ? "" : "Suspecters = " + Utils.EnumerableToString(suspecters, sa => sa.ToLongString()), timestamps == null ? "" : "SuspectTimes = " + Utils.EnumerableToString(timestamps, LogFormatter.PrintDate) ); } } }
using System; using System.Collections; using System.Data.SqlClient; using System.Web.UI; using Rainbow.Framework; using Rainbow.Framework.Data; using Rainbow.Framework.DataTypes; using Rainbow.Framework.Settings.Cache; using Rainbow.Framework.Site.Data; using Rainbow.Framework.Web.UI.WebControls; using Rainbow.Framework.Providers.RainbowSiteMapProvider; namespace Rainbow.Content.Web.Modules { /// <summary> /// /// </summary> public partial class Pages : PortalModuleControl { /// <summary> /// /// </summary> protected ArrayList portalPages; /// <summary> /// Admin Module /// </summary> public override bool AdminModule { get { return true; } } protected override void OnLoad( EventArgs e ) { base.OnLoad( e ); portalPages = new PagesDB().GetPagesFlat( portalSettings.PortalID ); tabList.DataBind(); // Set the ImageUrl for controls from current Theme upBtn.ImageUrl = CurrentTheme.GetImage( "Buttons_Up", "Up.gif" ).ImageUrl; downBtn.ImageUrl = CurrentTheme.GetImage( "Buttons_Down", "Down.gif" ).ImageUrl; DeleteBtn.ImageUrl = CurrentTheme.GetImage( "Buttons_Delete", "Delete.gif" ).ImageUrl; EditBtn.ImageUrl = CurrentTheme.GetImage( "Buttons_Edit", "Edit.gif" ).ImageUrl; // If this is the first visit to the page, bind the tab data to the page listbox if ( !Page.IsPostBack ) { // 2/27/2003 Start - Ender Malkoc // After up or down button when the page is refreshed, // select the previously selected tab from the list. if ( Request.Params[ "selectedtabID" ] != null ) { try { int tabIndex = Int32.Parse( Request.Params[ "selectedtabID" ] ); SelectPage( tabIndex ); } catch { } } // 2/27/2003 End - Ender Malkoc } } /// <summary> /// This is where you add module settings. These settings /// are used to control the behavior of the module /// </summary> public Pages() { // EHN: Add new version control for tabs module. // Mike Stone - 19/12/2004 SettingItem PageVersion = new SettingItem( new BooleanDataType() ); PageVersion.Value = "True"; PageVersion.EnglishName = "Use Old Version?"; PageVersion.Description = "If Checked the module acts has it always did. If not it uses the new short form which allows security to be set so the new tab will not be seen by all users."; PageVersion.Order = 10; _baseSettings.Add( "TAB_VERSION", PageVersion ); } /// <summary> /// The UpDown_Click server event handler on this page is /// used to move a portal module up or down on a tab's layout pane /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param> protected void UpDown_Click( object sender, ImageClickEventArgs e ) { string cmd = ( ( ImageButton )sender ).CommandName; if ( tabList.SelectedIndex > -1 ) { int delta; // Determine the delta to apply in the order number for the module // within the list. +3 moves down one item; -3 moves up one item if ( cmd == "down" ) { delta = 3; } else { delta = -3; } PageItem t; t = ( PageItem )portalPages[tabList.SelectedIndex]; t.Order += delta; OrderPages(); Response.Redirect( HttpUrlBuilder.BuildUrl( "~/DesktopDefault.aspx", PageID, "selectedtabID=" + t.ID ) ); } } /// <summary> /// The DeleteBtn_Click server event handler is used to delete /// the selected tab from the portal /// </summary> protected void DeleteBtn_Click( object sender, ImageClickEventArgs e ) { //base.OnDelete(); if ( tabList.SelectedIndex > -1 ) { try { // must delete from database too PageItem t = ( PageItem )portalPages[tabList.SelectedIndex]; PagesDB tabs = new PagesDB(); tabs.DeletePage( t.ID ); portalPages.RemoveAt( tabList.SelectedIndex ); if ( tabList.SelectedIndex > 0 ) t = ( PageItem )portalPages[tabList.SelectedIndex - 1]; OrderPages(); Response.Redirect( HttpUrlBuilder.BuildUrl( "~/DesktopDefault.aspx", PageID, "SelectedPageID=" + t.ID ) ); } catch ( SqlException ) { Controls.Add( new LiteralControl( "<br><span class='Error'>" + General.GetString( "TAB_DELETE_FAILED", "Failed to delete Page", this ) + "<br>" ) ); } } } protected void EditBtn_Click( object sender, ImageClickEventArgs e ) { // Redirect to edit page of currently selected tab if ( tabList.SelectedIndex > -1 ) { // Redirect to module settings page PageItem t = ( PageItem )portalPages[ tabList.SelectedIndex ]; // added mID by Mario Endara <mario@softworks.com.uy> to support security check (2004/11/09) Response.Redirect( HttpUrlBuilder.BuildUrl( "~/DesktopModules/CoreModules/Pages/PageLayout.aspx", t.ID, "mID=" + ModuleID.ToString() + "&returntabid=" + Page.PageID ) ); } } /// <summary> /// The AddPage_Click server event handler is used /// to add a new tab for this portal /// </summary> /// <param name="Sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void AddPage_Click( Object Sender, EventArgs e ) { if ( Settings["TAB_VERSION"] != null ) { if ( Settings["TAB_VERSION"].ToString() == "True" ) // Use Old Version { // New tabs go to the end of the list PageItem t = new PageItem(); t.Name = General.GetString( "TAB_NAME", "New Page Name" ); //Just in case it comes to be empty t.ID = -1; t.Order = 990000; portalPages.Add( t ); // write tab to database PagesDB tabs = new PagesDB(); t.ID = tabs.AddPage( portalSettings.PortalID, t.Name, t.Order ); // Reset the order numbers for the tabs within the list OrderPages(); //Clear SiteMaps Cache RainbowSiteMapProvider.ClearAllRainbowSiteMapCaches(); // Redirect to edit page // 3_aug_2004 Cory Isakson added returntabid so that PageLayout could return to the tab it was called from. // added mID by Mario Endara <mario@softworks.com.uy> to support security check (2004/11/09) Response.Redirect( HttpUrlBuilder.BuildUrl( "~/DesktopModules/CoreModules/Pages/PageLayout.aspx", t.ID, "mID=" + ModuleID.ToString() + "&returntabid=" + Page.PageID ) ); } else { // Redirect to New Form - Mike Stone 19/12/2004 Response.Redirect( HttpUrlBuilder.BuildUrl( "~/DesktopModules/CoreModules/Pages/AddPage.aspx", "mID=" + ModuleID.ToString() + "&returntabid=" + Page.PageID ) ); } } } /// <summary> /// The OrderPages helper method is used to reset /// the display order for tabs within the portal /// </summary> private void OrderPages() { int i = 1; portalPages.Sort(); foreach ( PageItem t in portalPages ) { // number the items 1, 3, 5, etc. to provide an empty order // number when moving items up and down in the list. t.Order = i; i += 2; // rewrite tab to database PagesDB tabs = new PagesDB(); // 12/16/2002 Start - Cory Isakson tabs.UpdatePageOrder( t.ID, t.Order ); // 12/16/2002 End - Cory Isakson } //gbs: Invalidate cache, fix for bug RBM-220 CurrentCache.RemoveAll( "_PageNavigationSettings_" ); } /// <summary> /// Given the tabID of a tab, this function selects the right tab in the provided list control /// </summary> /// <param name="tabID">tabID of the tab that needs to be selected</param> private void SelectPage( int tabID ) { for ( int i = 0; i < tabList.Items.Count; i++ ) { if ( ( ( PageItem )portalPages[i] ).ID == tabID ) { if ( tabList.SelectedItem != null ) tabList.SelectedItem.Selected = false; tabList.Items[i].Selected = true; return; } } return; } /// <summary> /// GuidID /// </summary> /// <value></value> public override Guid GuidID { get { return new Guid( "{1C575D94-70FC-4A83-80C3-2087F726CBB3}" ); } } # region Install / Uninstall Implementation /// <summary> /// Unknown /// </summary> /// <param name="stateSaver"></param> public override void Install( IDictionary stateSaver ) { string currentScriptName = Server.MapPath( TemplateSourceDirectory + "/Install.sql" ); ArrayList errors = DBHelper.ExecuteScript( currentScriptName, true ); if ( errors.Count > 0 ) { // Call rollback throw new Exception( "Error occurred:" + errors[0].ToString() ); } } /// <summary> /// Unknown /// </summary> /// <param name="stateSaver"></param> public override void Uninstall( IDictionary stateSaver ) { //Cannot be uninstalled throw new Exception( "This is an essential module that can be unistalled" ); } #endregion } }
/* Copyright 2014 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Text; using DriveProxy.Utils; namespace DriveProxy.Service { internal class ServicePipeClient { protected static Pipe.Client _Pipe = null; protected static Exception _LastException = null; public static Exception LastException { get { return _LastException; } set { _LastException = value; Log.Error(_LastException, false); } } public static string LastExceptionMessage { get { if (HasException) { return LastException.Message; } return ""; } } public static bool HasException { get { if (LastException != null) { return true; } return false; } } protected static bool Open() { try { return Open(false); } catch (Exception exception) { Log.Error(exception); return false; } } protected static bool Open(string pipeName) { try { return Open(pipeName, false); } catch (Exception exception) { LastException = exception; return false; } } protected static bool Open(bool shortRetry) { try { return Open(ServicePipe.PipeName, shortRetry); } catch (Exception exception) { LastException = exception; return false; } } protected static bool Open(string pipeName, bool shortRetry) { try { Close(); Log.Warning("Attempting to open pipe '" + pipeName + "'"); _Pipe = Pipe.Client.Open(pipeName, System.IO.FileAccess.ReadWrite, shortRetry); if (_Pipe == null) { return false; } Log.Information("Successfully opened pipe '" + pipeName + "'"); return true; } catch (Exception exception) { LastException = exception; return false; } } protected static void Close() { try { if (_Pipe == null) { return; } _Pipe.Close(); } catch (Exception exception) { LastException = exception; } } public static void Dispose() { try { if (_Pipe == null) { return; } _Pipe.Dispose(); } catch (Exception exception) { LastException = exception; } finally { _Pipe = null; } } public static bool CloseServer() { try { Log.Warning("Attempting to send ServicePipe process disconnect message"); if (!Open()) { throw LastException; } string message = "disconnect"; Write(message); string result = Read(); Close(); if (result == null || result != "disconnecting") { throw new Exception("Received unexpected response from server."); } Log.Information("Successfully sent ServicePipe process disconnect message"); return true; } catch (Exception exception) { LastException = exception; return false; } finally { Close(); } } public static bool Ping() { try { return Ping(true); } catch (Exception exception) { LastException = exception; return false; } } protected static bool Ping(bool doRetry) { try { Log.Warning("Attempting to ping ServicePipe process"); if (!Open(doRetry)) { throw LastException; } string message = "ping"; Write(message); string result = Read(); Close(); if (result == null || result != "hello") { throw new Exception("Received unexpected response from server."); } Log.Information("Successfully pinged ServicePipe process"); return true; } catch (Exception exception) { LastException = exception; return false; } finally { Close(); } } public static long GetProcessCount() { try { if (!Open()) { throw LastException; } string message = "process count"; Write(message); string result = Read(); Close(); long processCount = -1; if (result == null || !long.TryParse(result, out processCount)) { throw new Exception("Received unexpected response from server."); } return processCount; } catch (Exception exception) { LastException = exception; return -1; } finally { Close(); } } public static string Execute(string[] args) { try { Log.Warning("Attempting to invoke Execute against ServicePipe process"); if (!Open()) { throw LastException; } Write("redirect"); string pipeName = Read(); Close(); if (String.IsNullOrEmpty(pipeName)) { throw new Exception("Requested redirect did not return a pipe name."); } pipeName = "DriveProxy.Service_" + pipeName; if (!Open(pipeName)) { return null; } var message = new StringBuilder(); foreach (string t in args) { if (message.Length > 0) { message.Append(","); } message.Append(t); } Write(message.ToString()); string result = Read(); Close(); Log.Information("Successfully invoked Execute against ServicePipe process"); return result; } catch (Exception exception) { LastException = exception; throw exception; } finally { Close(); } } protected static string Read() { try { Log.Information("Attempting to read message from ServicePipe process"); string result = ServicePipe.Read(_Pipe); Log.Information("Successfully read message from ServicePipe process"); return result; } catch (Exception exception) { Log.Error(exception); return null; } } protected static void Write(string message) { try { Log.Warning("Attempting to write messsage to ServicePipe process"); ServicePipe.Write(_Pipe, message); Log.Information("Successfully wrote messsage to ServicePipe process"); } catch (Exception exception) { Log.Error(exception); } } } }
using System; using Gtk; using System.Drawing; using System.Drawing.Imaging; using System.IO; namespace Interpreter { public static class Interpreter { public static void ExecuteProgram(string path) { BizMachineGUI.MainClass.ExecuteProgram (path); } } } namespace BizMachineGUI { class MainClass { static MainWindow win; private static ushort m_ScreenMemoryLocation; private static byte[] m_ScreenMemory; public static ushort ScreenMemoryLocation { get { return m_ScreenMemoryLocation; } set { m_ScreenMemoryLocation = value; } } public static void Poke(ushort Address, byte Value) { ushort MemLoc; try { MemLoc = (ushort)(Address - m_ScreenMemoryLocation); } catch (Exception) { return; } if (MemLoc < 0 || MemLoc > 3999) return; m_ScreenMemory[MemLoc] = Value; Screen_Paint (); } public static byte Peek(ushort Address) { ushort MemLoc; try { MemLoc = (ushort)(Address - m_ScreenMemoryLocation); } catch (Exception) { return (byte)0; } if (MemLoc < 0 || MemLoc > 3999) return (byte)0; return m_ScreenMemory[MemLoc]; } static int c = -1; private static void Screen_Paint() { Bitmap bmp = new Bitmap(600, 200); Graphics bmpGraphics = Graphics.FromImage(bmp); Font f = new Font("Monaco", 20f, FontStyle.Bold); int xLoc = 0; int yLoc = 0; for (int i = 0; i < 4000; i += 2) { SolidBrush bgBrush = null; SolidBrush fgBrush = null; if ((m_ScreenMemory[i + 1] & 112) == 112) { bgBrush = new SolidBrush(Color.Gray); } if ((m_ScreenMemory[i + 1] & 112) == 96) { bgBrush = new SolidBrush(Color.Brown); } if ((m_ScreenMemory[i + 1] & 112) == 80) { bgBrush = new SolidBrush(Color.Magenta); } if ((m_ScreenMemory[i + 1] & 112) == 64) { bgBrush = new SolidBrush(Color.Red); } if ((m_ScreenMemory[i + 1] & 112) == 48) { bgBrush = new SolidBrush(Color.Cyan); } if ((m_ScreenMemory[i + 1] & 112) == 32) { bgBrush = new SolidBrush(Color.Green); } if ((m_ScreenMemory[i + 1] & 112) == 16) { bgBrush = new SolidBrush(Color.Blue); } if ((m_ScreenMemory[i + 1] & 112) == 0) { bgBrush = new SolidBrush(Color.Black); } if ((m_ScreenMemory[i + 1] & 7) == 0) { if ((m_ScreenMemory[i + 1] & 8) == 8) { fgBrush = new SolidBrush(Color.Gray); } else { fgBrush = new SolidBrush(Color.Black); } } if ((m_ScreenMemory[i + 1] & 7) == 1) { if ((m_ScreenMemory[i + 1] & 8) == 8) { fgBrush = new SolidBrush(Color.LightBlue); } else { fgBrush = new SolidBrush(Color.Blue); } } if ((m_ScreenMemory[i + 1] & 7) == 2) { if ((m_ScreenMemory[i + 1] & 8) == 8) { fgBrush = new SolidBrush(Color.LightGreen); } else { fgBrush = new SolidBrush(Color.Green); } } if ((m_ScreenMemory[i + 1] & 7) == 3) { if ((m_ScreenMemory[i + 1] & 8) == 8) { fgBrush = new SolidBrush(Color.LightCyan); } else { fgBrush = new SolidBrush(Color.Cyan); } } if ((m_ScreenMemory[i + 1] & 7) == 4) { if ((m_ScreenMemory[i + 1] & 8) == 8) { fgBrush = new SolidBrush(Color.Pink); } else { fgBrush = new SolidBrush(Color.Red); } } if ((m_ScreenMemory[i + 1] & 7) == 5) { if ((m_ScreenMemory[i + 1] & 8) == 8) { fgBrush = new SolidBrush(Color.Fuchsia); } else { fgBrush = new SolidBrush(Color.Magenta); } } if ((m_ScreenMemory[i + 1] & 7) == 6) { if ((m_ScreenMemory[i + 1] & 8) == 8) { fgBrush = new SolidBrush(Color.Yellow); } else { fgBrush = new SolidBrush(Color.Brown); } } if ((m_ScreenMemory[i + 1] & 7) == 7) { if ((m_ScreenMemory[i + 1] & 8) == 8) { fgBrush = new SolidBrush(Color.White); } else { fgBrush = new SolidBrush(Color.Gray); } } if (bgBrush == null) bgBrush = new SolidBrush(Color.Black); if (fgBrush == null) fgBrush = new SolidBrush(Color.Gray); if (((xLoc % 640) == 0) && (xLoc != 0)) { yLoc += 31; xLoc = 0; } string s = System.Text.Encoding.ASCII.GetString(m_ScreenMemory, i, 1); PointF pf = new PointF(xLoc, yLoc); bmpGraphics.FillRectangle(bgBrush, xLoc, yLoc, 20f, 31f); bmpGraphics.DrawString(s, f, fgBrush, pf); xLoc += 20; } string path = "./tmp-" + (++c) + ".png"; bmp.Save (path, ImageFormat.Png); win.SetImageSrc (path); if(File.Exists(path)) { File.Delete(path); } } private static byte[] BizMemory; private static ushort StartAddr; private static ushort ExecAddr; private static ushort InstructionPointer; private static byte Register_A; private static byte Register_B; private static ushort Register_X; private static ushort Register_Y; private static ushort Register_D; private static void UpdateRegisterStatus() { string strRegisters = ""; strRegisters = "Register A = $" + Register_A.ToString("X").PadLeft(2, '0'); strRegisters += " Register B = $" + Register_B.ToString("X").PadLeft(2, '0'); strRegisters += " Register D = $" + Register_D.ToString("X").PadLeft(4, '0'); strRegisters += "\nRegister X = $" + Register_X.ToString("X").PadLeft(4, '0'); strRegisters += " Register Y = $" + Register_Y.ToString("X").PadLeft(4, '0'); strRegisters += " Instruction Pointer = $" + InstructionPointer.ToString("X").PadLeft(4, '0'); win.UpdateRegisterOutput (strRegisters); } private static void SetRegisterD() { Register_D = (ushort)(Register_A << 8 + Register_B); } private static void InterpretProgram(ushort ExecAddr, ushort ProgLength) { ProgLength = 64000; while (ProgLength > 0) { byte Instruction = BizMemory[InstructionPointer]; ProgLength--; if (Instruction == 0x01) // LDA #<value> { Register_A = BizMemory[(InstructionPointer + 1)]; SetRegisterD(); ProgLength -= 1; InstructionPointer += 2; UpdateRegisterStatus(); continue; } if (Instruction == 0x02) // LDX #<value> { Register_X = (ushort)((BizMemory[(InstructionPointer + 2)]) << 8); Register_X += BizMemory[(InstructionPointer + 1)]; ProgLength -= 2; InstructionPointer += 3; UpdateRegisterStatus(); continue; } if (Instruction == 0x03) // STA ,X { BizMemory[Register_X] = Register_A; Poke(Register_X, Register_A); ++InstructionPointer; UpdateRegisterStatus(); continue; } if (Instruction == 0x04) // END { ++InstructionPointer; UpdateRegisterStatus(); break; } } } public static void ExecuteProgram (string path) { Uri uri = new Uri(Path.Combine(Directory.GetCurrentDirectory(), path)); path = Path.GetFullPath (uri.AbsolutePath); BizMemory = new byte[65535]; StartAddr = 0; ExecAddr = 0; Register_A = 0; Register_B = 0; Register_D = 0; Register_X = 0; Register_Y = 0; UpdateRegisterStatus(); ScreenMemoryLocation = 0xA000; m_ScreenMemory = new byte[4000]; for (int i = 0; i < 4000; i += 2) { m_ScreenMemory[i] = 32; m_ScreenMemory[i + 1] = 7; } BinaryReader br; System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Open); br = new System.IO.BinaryReader(fs); // Check the magic header byte Magic1 = br.ReadByte(); byte Magic2 = br.ReadByte(); byte Magic3 = br.ReadByte(); if (Magic1 != 'B' || Magic2 != 'I' || Magic3 != 'Z') { MessageDialog md = new MessageDialog ( win, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "This is not a valid biz file!" ); md.Run (); md.Destroy(); return; } StartAddr = br.ReadUInt16(); ExecAddr = br.ReadUInt16(); ushort Counter = 0; while ((br.PeekChar() != -1)) { BizMemory[(StartAddr + Counter)] = br.ReadByte(); ++Counter; } br.Close(); fs.Close(); InstructionPointer = ExecAddr; InterpretProgram(ExecAddr, Counter); } public static void Main (string[] args) { Gtk.Application.Init (); win = new MainWindow (); win.Show (); if (args.Length == 1) { ExecuteProgram(args[0]); } Gtk.Application.Run (); } } }
using System; using LanguageExt; using System.Linq; using System.Collections.Generic; using System.Threading.Tasks; using LanguageExt.DataTypes.Serialisation; using LanguageExt.TypeClasses; using LanguageExt.ClassInstances; using static LanguageExt.Prelude; namespace LanguageExt { public static partial class OptionAsyncT { // // Collections // public static OptionAsync<Arr<B>> Traverse<A, B>(this Arr<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Arr<B>>(Go(ma, f)); async Task<(bool, Arr<B>)> Go(Arr<OptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => !d.IsSome) ? (false, default) : (true, new Arr<B>(rb.Map(d => d.Value))); } } public static OptionAsync<HashSet<B>> Traverse<A, B>(this HashSet<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<HashSet<B>>(Go(ma, f)); async Task<(bool, HashSet<B>)> Go(HashSet<OptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => !d.IsSome) ? (false, default) : (true, new HashSet<B>(rb.Map(d => d.Value))); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static OptionAsync<IEnumerable<B>> Traverse<A, B>(this IEnumerable<OptionAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static OptionAsync<IEnumerable<B>> TraverseSerial<A, B>(this IEnumerable<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<IEnumerable<B>>(Go(ma, f)); async Task<(bool, IEnumerable<B>)> Go(IEnumerable<OptionAsync<A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { var mb = await a; if (mb.IsNone) return (false, default); rb.Add(f(mb.Value)); } return (true, rb); }; } public static OptionAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<OptionAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, Sys.DefaultAsyncSequenceConcurrency, f); public static OptionAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<OptionAsync<A>> ma, int windowSize, Func<A, B> f) { return new OptionAsync<IEnumerable<B>>(Go(ma, f)); async Task<(bool, IEnumerable<B>)> Go(IEnumerable<OptionAsync<A>> ma, Func<A, B> f) { var rb = await ma.Map(a => a.Map(f).Data).WindowMap(windowSize, Prelude.identity); return rb.Exists(d => !d.IsSome) ? (false, default) : (true, rb.Map(d => d.Value)); } } [Obsolete("use SequenceSerial or SequenceParallel instead")] public static OptionAsync<IEnumerable<A>> Sequence<A>(this IEnumerable<OptionAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static OptionAsync<IEnumerable<A>> SequenceSerial<A>(this IEnumerable<OptionAsync<A>> ma) => TraverseSerial(ma, Prelude.identity); public static OptionAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<OptionAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static OptionAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<OptionAsync<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static OptionAsync<Lst<B>> Traverse<A, B>(this Lst<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Lst<B>>(Go(ma, f)); async Task<(bool, Lst<B>)> Go(Lst<OptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => !d.IsSome) ? (false, default) : (true, new Lst<B>(rb.Map(d => d.Value))); } } public static OptionAsync<Que<B>> Traverse<A, B>(this Que<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Que<B>>(Go(ma, f)); async Task<(bool, Que<B>)> Go(Que<OptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => !d.IsSome) ? (false, default) : (true, new Que<B>(rb.Map(d => d.Value))); } } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static OptionAsync<Seq<B>> Traverse<A, B>(this Seq<OptionAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static OptionAsync<Seq<B>> TraverseSerial<A, B>(this Seq<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Seq<B>>(Go(ma, f)); async Task<(bool, Seq<B>)> Go(Seq<OptionAsync<A>> ma, Func<A, B> f) { var rb = new B[ma.Count]; var ix = 0; foreach (var a in ma) { var mb = await a; if (mb.IsNone) return (false, default); rb[ix] = f(mb.Value); ix++; } return (true, Seq.FromArray<B>(rb)); }; } public static OptionAsync<Seq<B>> TraverseParallel<A, B>(this Seq<OptionAsync<A>> ma, Func<A, B> f) => TraverseParallel(ma, Sys.DefaultAsyncSequenceConcurrency, f); public static OptionAsync<Seq<B>> TraverseParallel<A, B>(this Seq<OptionAsync<A>> ma, int windowSize, Func<A, B> f) { return new OptionAsync<Seq<B>>(Go(ma, f)); async Task<(bool, Seq<B>)> Go(Seq<OptionAsync<A>> ma, Func<A, B> f) { var rb = await ma.Map(a => a.Map(f).Data).WindowMap(windowSize, Prelude.identity); return rb.Exists(d => !d.IsSome) ? (false, default) : (true, Seq.FromArray<B>(rb.Map(d => d.Value).ToArray())); } } [Obsolete("use SequenceSerial or SequenceParallel instead")] public static OptionAsync<Seq<A>> Sequence<A>(this Seq<OptionAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static OptionAsync<Seq<A>> SequenceSerial<A>(this Seq<OptionAsync<A>> ma) => TraverseSerial(ma, Prelude.identity); public static OptionAsync<Seq<A>> SequenceParallel<A>(this Seq<OptionAsync<A>> ma) => TraverseParallel(ma, Prelude.identity); public static OptionAsync<Seq<A>> SequenceParallel<A>(this Seq<OptionAsync<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static OptionAsync<Set<B>> Traverse<A, B>(this Set<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Set<B>>(Go(ma, f)); async Task<(bool, Set<B>)> Go(Set<OptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)); return rb.Exists(d => !d.IsSome) ? (false, default) : (true, new Set<B>(rb.Map(d => d.Value))); } } public static OptionAsync<Stck<B>> Traverse<A, B>(this Stck<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Stck<B>>(Go(ma, f)); async Task<(bool, Stck<B>)> Go(Stck<OptionAsync<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Reverse().Map(a => a.Map(f).Data)); return rb.Exists(d => !d.IsSome) ? (false, default) : (true, new Stck<B>(rb.Map(d => d.Value))); } } // // Async types // public static OptionAsync<EitherAsync<L, B>> Traverse<L, A, B>(this EitherAsync<L, OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<EitherAsync<L, B>>(Go(ma, f)); async Task<(bool, EitherAsync<L, B>)> Go(EitherAsync<L, OptionAsync<A>> ma, Func<A, B> f) { var da = await ma.Data; if (da.State == EitherStatus.IsBottom) return (false, default); if (da.State == EitherStatus.IsLeft) return (true, EitherAsync<L, B>.Left(da.Left)); var (isSome, value) = await da.Right.Data; if (!isSome) return (false, default); return (true, EitherAsync<L, B>.Right(f(value))); } } public static OptionAsync<OptionAsync<B>> Traverse<A, B>(this OptionAsync<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<OptionAsync<B>>(Go(ma, f)); async Task<(bool, OptionAsync<B>)> Go(OptionAsync<OptionAsync<A>> ma, Func<A, B> f) { var (isSomeA, valueA) = await ma.Data; if (!isSomeA) return (true, OptionAsync<B>.None); var (isSomeB, valueB) = await valueA.Data; if (!isSomeB) return (false, default); return (true, OptionAsync<B>.Some(f(valueB))); } } public static OptionAsync<TryAsync<B>> Traverse<A, B>(this TryAsync<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<TryAsync<B>>(Go(ma, f)); async Task<(bool, TryAsync<B>)> Go(TryAsync<OptionAsync<A>> ma, Func<A, B> f) { var resultA = await ma.Try(); if (resultA.IsBottom) return (false, default); if (resultA.IsFaulted) return (true, TryAsyncFail<B>(resultA.Exception)); var (isSome, value) = await resultA.Value.Data; if (!isSome) return (false, default); return (true, TryAsync<B>(f(value))); } } public static OptionAsync<TryOptionAsync<B>> Traverse<A, B>(this TryOptionAsync<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<TryOptionAsync<B>>(Go(ma, f)); async Task<(bool, TryOptionAsync<B>)> Go(TryOptionAsync<OptionAsync<A>> ma, Func<A, B> f) { var resultA = await ma.Try(); if (resultA.IsBottom) return (false, default); if (resultA.IsNone) return (true, TryOptionalAsync<B>(None)); if (resultA.IsFaulted) return (true, TryOptionAsyncFail<B>(resultA.Exception)); var (isSome, value) = await resultA.Value.Value.Data; if (!isSome) return (false, default); return (true, TryOptionAsync<B>(f(value))); } } public static OptionAsync<Task<B>> Traverse<A, B>(this Task<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Task<B>>(Go(ma, f)); async Task<(bool, Task<B>)> Go(Task<OptionAsync<A>> ma, Func<A, B> f) { var result = await ma; var (isSome, value) = await result.Data; if (!isSome) return (false, default); return (true, f(value).AsTask()); } } // // Sync types // public static OptionAsync<Either<L, B>> Traverse<L, A, B>(this Either<L, OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Either<L, B>>(Go(ma, f)); async Task<(bool, Either<L, B>)> Go(Either<L, OptionAsync<A>> ma, Func<A, B> f) { if(ma.IsBottom) return (false, default); if(ma.IsLeft) return (true, Left<L, B>(ma.LeftValue)); var (isSome, value) = await ma.RightValue.Data; if(!isSome) return (false, default); return (true, f(value)); } } public static OptionAsync<EitherUnsafe<L, B>> Traverse<L, A, B>(this EitherUnsafe<L, OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<EitherUnsafe<L, B>>(Go(ma, f)); async Task<(bool, EitherUnsafe<L, B>)> Go(EitherUnsafe<L, OptionAsync<A>> ma, Func<A, B> f) { if(ma.IsBottom) return (false, default); if(ma.IsLeft) return (true, LeftUnsafe<L, B>(ma.LeftValue)); var (isSome, value) = await ma.RightValue.Data; if(!isSome) return (false, default); return (true, f(value)); } } public static OptionAsync<Identity<B>> Traverse<A, B>(this Identity<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Identity<B>>(Go(ma, f)); async Task<(bool, Identity<B>)> Go(Identity<OptionAsync<A>> ma, Func<A, B> f) { if(ma.IsBottom) return (false, default); var (isSome, value) = await ma.Value.Data; if(!isSome) return (false, default); return (true, new Identity<B>(f(value))); } } public static OptionAsync<Option<B>> Traverse<A, B>(this Option<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Option<B>>(Go(ma, f)); async Task<(bool, Option<B>)> Go(Option<OptionAsync<A>> ma, Func<A, B> f) { if(ma.IsNone) return (true, Option<B>.None); var (isSome, value) = await ma.Value.Data; if(!isSome) return (false, default); return (true, Option<B>.Some(f(value))); } } public static OptionAsync<OptionUnsafe<B>> Traverse<A, B>(this OptionUnsafe<OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<OptionUnsafe<B>>(Go(ma, f)); async Task<(bool, OptionUnsafe<B>)> Go(OptionUnsafe<OptionAsync<A>> ma, Func<A, B> f) { if(ma.IsNone) return (true, OptionUnsafe<B>.None); var (isSome, value) = await ma.Value.Data; if(!isSome) return (false, default); return (true, OptionUnsafe<B>.Some(f(value))); } } public static OptionAsync<Try<B>> Traverse<A, B>(this Try<OptionAsync<A>> ma, Func<A, B> f) { try { return new OptionAsync<Try<B>>(Go(ma, f)); async Task<(bool, Try<B>)> Go(Try<OptionAsync<A>> ma, Func<A, B> f) { var ra = ma.Try(); if(ra.IsBottom) return (false, default); if (ra.IsFaulted) return (true, TryFail<B>(ra.Exception)); var (isSome, value) = await ra.Value.Data; if(!isSome) return (false, default); return (true, Try<B>(f(value))); } } catch (Exception e) { return Try<B>(e); } } public static OptionAsync<TryOption<B>> Traverse<A, B>(this TryOption<OptionAsync<A>> ma, Func<A, B> f) { try { return new OptionAsync<TryOption<B>>(Go(ma, f)); async Task<(bool, TryOption<B>)> Go(TryOption<OptionAsync<A>> ma, Func<A, B> f) { var ra = ma.Try(); if (ra.IsBottom) return (false, default); if (ra.IsNone) return (true, TryOptional<B>(None)); if (ra.IsFaulted) return (true, TryOptionFail<B>(ra.Exception)); var (isSome, value) = await ra.Value.Value.Data; if (!isSome) return (false, default); return (true, TryOption<B>(f(value))); } } catch (Exception e) { return TryOption<B>(e); } } public static OptionAsync<Validation<Fail, B>> Traverse<Fail, A, B>(this Validation<Fail, OptionAsync<A>> ma, Func<A, B> f) { return new OptionAsync<Validation<Fail, B>>(Go(ma, f)); async Task<(bool, Validation<Fail, B>)> Go(Validation<Fail, OptionAsync<A>> ma, Func<A, B> f) { if(ma.IsFail) return (true, Fail<Fail, B>(ma.FailValue)); var (isSome, value) = await ma.SuccessValue.Data; if(!isSome) return (false, default); return (true, f(value)); } } public static OptionAsync<Validation<MonoidFail, Fail, B>> Traverse<MonoidFail, Fail, A, B>(this Validation<MonoidFail, Fail, OptionAsync<A>> ma, Func<A, B> f) where MonoidFail : struct, Monoid<Fail>, Eq<Fail> { return new OptionAsync<Validation<MonoidFail, Fail, B>>(Go(ma, f)); async Task<(bool, Validation<MonoidFail, Fail, B>)> Go(Validation<MonoidFail, Fail, OptionAsync<A>> ma, Func<A, B> f) { if(ma.IsFail) return (true, Fail<MonoidFail, Fail, B>(ma.FailValue)); var (isSome, value) = await ma.SuccessValue.Data; if(!isSome) return (false, default); return (true, f(value)); } } } }
// ============================================================================ // FileName: SIPDialPlan.cs // // Description: // Represents a user dialplan that can be passed to the SIPDialPlanEngine to process // the user's calls. // // Author(s): // Aaron Clauson // // History: // 28 Sep 2008 Aaron Clauson Created. // // License: // This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php // // Copyright (c) 2006-2008 Aaron Clauson (aaronc@blueface.ie), Blue Face Ltd, Dublin, Ireland (www.blueface.ie) // 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 Blue Face Ltd. // nor the names of its contributors may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ============================================================================ using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using System.Xml; using SIPSorcery.Sys; using log4net; #if !SILVERLIGHT using System.Data; using System.Data.Linq; using System.Data.Linq.Mapping; #endif namespace SIPSorcery.SIP.App { [Table(Name = "sipdialplans")] [DataContractAttribute] public class SIPDialPlan : INotifyPropertyChanged, ISIPAsset { public const string XML_DOCUMENT_ELEMENT_NAME = "sipdialplans"; public const string XML_ELEMENT_NAME = "sipdialplan"; public const string DEFAULT_DIALPLAN_NAME = "default"; // The default name a dialplan will be assigned if the owner's first dialplan and the name is not set. public const int DEFAULT_MAXIMUM_EXECUTION_COUNT = 3; // The default value for the maximum allowed simultaneous executions of a dial plan. public const string ALL_APPS_AUTHORISED = "*"; // Used in the priviled application authorisation field when the dialplan is authorised for all applications. public const string PROPERTY_EXECUTIONCOUNT_NAME = "ExecutionCount"; private static string m_newLine = AppState.NewLine; private ILog logger = AppState.logger; public static int TimeZoneOffsetMinutes; private Guid m_id; // Dial plan id used by the system. This is the database primary key and is not important for XML. [Column(Name = "id", DbType = "varchar(36)", IsPrimaryKey = true, CanBeNull = false, UpdateCheck = UpdateCheck.Never)] [DataMember] public Guid Id { get { return m_id; } set { m_id = value; } } private string m_owner; // The username of the dialplan owner. [Column(Name = "owner", DbType = "varchar(32)", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] [DataMember] public string Owner { get { return m_owner; } set { m_owner = value; NotifyPropertyChanged("Owner"); } } [Column(Name = "adminmemberid", DbType = "varchar(32)", CanBeNull = true, UpdateCheck = UpdateCheck.Never)] public string AdminMemberId { get; set; } // If set it designates this asset as a belonging to a user with the matching adminid. private string m_dialPlanName; // The name of the dialplan assigned by the owner, owner/name combinations must be unique [Column(Name = "dialplanname", DbType = "varchar(64)", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] [DataMember] public string DialPlanName { get { return m_dialPlanName; } set { m_dialPlanName = value; NotifyPropertyChanged("DialPlanName"); } } private string m_traceEmailAddress; // Optional email address to send dialplan traces to. if empty traces will not be used. [Column(Name = "traceemailaddress", DbType = "varchar(256)", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] [DataMember] public string TraceEmailAddress { get { return m_traceEmailAddress; } set { m_traceEmailAddress = value; NotifyPropertyChanged("TraceEmailAddress"); } } private string m_dialPlanScript; // The string representing the dialplan script (or asterisk extension lines). [Column(Name = "dialplanscript", DbType = "varchar(8000)", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] [DataMember] public string DialPlanScript { get { return m_dialPlanScript; } set { m_dialPlanScript = value; NotifyPropertyChanged("DialPlanScript"); } } private string m_scriptTypeDescription; // Silverlight can't handle enum types across WCF boundaries. [Column(Name = "scripttypedescription", DbType = "varchar(12)", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] [DataMember] public string ScriptTypeDescription { get { return m_scriptTypeDescription; } set { m_scriptTypeDescription = value; NotifyPropertyChanged("ScriptTypeDescription"); } } public SIPDialPlanScriptTypesEnum ScriptType { get { return SIPDialPlanScriptTypes.GetSIPDialPlanScriptType(m_scriptTypeDescription); } } private DateTimeOffset m_lastUpdate; [Column(Name = "lastupdate", DbType = "datetimeoffset", CanBeNull = true, UpdateCheck = UpdateCheck.Never)] [DataMember] public DateTimeOffset LastUpdate { get { return m_lastUpdate; } set { m_lastUpdate = value.ToUniversalTime(); NotifyPropertyChanged("LastUpdate"); } } public DateTimeOffset LastUpdateLocal { get { return LastUpdate.AddMinutes(TimeZoneOffsetMinutes); } } private DateTimeOffset m_inserted; [Column(Name = "inserted", DbType = "datetimeoffset", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] [DataMember] public DateTimeOffset Inserted { get { return m_inserted; } set { m_inserted = value.ToUniversalTime(); } } public DateTimeOffset InsertedLocal { get { return Inserted.AddMinutes(TimeZoneOffsetMinutes); } } private int m_maxExecutionCount = DEFAULT_MAXIMUM_EXECUTION_COUNT; [DataMember] [Column(Name = "maxexecutioncount", DbType = "int", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] public int MaxExecutionCount { get { return m_maxExecutionCount; } set { m_maxExecutionCount = value;} } private int m_executionCount; [DataMember] [Column(Name = "executioncount", DbType = "int", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] public int ExecutionCount { get { return m_executionCount; } set { m_executionCount = value; } } private string m_authorisedApps; // A semi-colon delimited list of privileged apps that this dialplan is authorised to use. [DataMember] [Column(Name = "authorisedapps", DbType = "varchar(2048)", CanBeNull = true, UpdateCheck = UpdateCheck.Never)] public string AuthorisedApps { get { return m_authorisedApps; } set { m_authorisedApps = value; NotifyPropertyChanged("AuthorisedApps"); } } private bool m_acceptNonInvite = false; [Column(Name = "acceptnoninvite", DbType = "bit", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] [DataMember] public bool AcceptNonInvite { get { return m_acceptNonInvite; } set { m_acceptNonInvite = value; NotifyPropertyChanged("AcceptNonInvite"); } } private bool m_isReadOnly; [Column(Name = "isreadonly", DbType = "bit", CanBeNull = false, UpdateCheck = UpdateCheck.Never)] [DataMember] public bool IsReadOnly { get { return m_isReadOnly; } set { m_isReadOnly = value; NotifyPropertyChanged("IsReadOnly"); } } public event PropertyChangedEventHandler PropertyChanged; public SIPDialPlan() { } public SIPDialPlan(string owner, string dialPlanName, string traceEmailAddress, string script, SIPDialPlanScriptTypesEnum scriptType) { m_id = Guid.NewGuid(); m_owner = owner; m_dialPlanName = (dialPlanName != null && dialPlanName.Trim().Length > 0) ? dialPlanName : DEFAULT_DIALPLAN_NAME; m_traceEmailAddress = traceEmailAddress; m_dialPlanScript = script; m_scriptTypeDescription = scriptType.ToString(); Inserted = DateTimeOffset.UtcNow; LastUpdate = DateTimeOffset.UtcNow; } #if !SILVERLIGHT public SIPDialPlan(DataRow dialPlanRow) { Load(dialPlanRow); } public DataTable GetTable() { DataTable table = new DataTable(); table.Columns.Add(new DataColumn("id", typeof(String))); table.Columns.Add(new DataColumn("owner", typeof(String))); table.Columns.Add(new DataColumn("adminmemberid", typeof(String))); table.Columns.Add(new DataColumn("dialplanname", typeof(String))); table.Columns.Add(new DataColumn("dialplanscript", typeof(String))); table.Columns.Add(new DataColumn("scripttypedescription", typeof(String))); table.Columns.Add(new DataColumn("traceemailaddress", typeof(String))); table.Columns.Add(new DataColumn("maxexecutioncount", typeof(Int32))); table.Columns.Add(new DataColumn("executioncount", typeof(Int32))); table.Columns.Add(new DataColumn("authorisedapps", typeof(String))); table.Columns.Add(new DataColumn("inserted", typeof(DateTimeOffset))); table.Columns.Add(new DataColumn("lastupdate", typeof(DateTimeOffset))); table.Columns.Add(new DataColumn("acceptnoninvite", typeof(Boolean))); table.Columns.Add(new DataColumn("isreadonly", typeof(Boolean))); return table; } public void Load(DataRow dialPlanRow) { try { m_id = (dialPlanRow.Table.Columns.Contains("id") && dialPlanRow["id"] != null) ? new Guid(dialPlanRow["id"] as string) : Guid.NewGuid(); m_owner = dialPlanRow["owner"] as string; AdminMemberId = (dialPlanRow.Table.Columns.Contains("adminmemberid") && dialPlanRow["adminmemberid"] != null) ? dialPlanRow["adminmemberid"] as string : null; m_dialPlanName = (dialPlanRow["dialplanname"] != null && dialPlanRow["dialplanname"].ToString().Trim().Length > 0) ? dialPlanRow["dialplanname"].ToString().Trim() : null; m_traceEmailAddress = (dialPlanRow.Table.Columns.Contains("traceemailaddress") && dialPlanRow["traceemailaddress"] != null) ? dialPlanRow["traceemailaddress"] as string : null; m_dialPlanScript = (dialPlanRow["dialplanscript"] as string).Trim(); m_scriptTypeDescription = (dialPlanRow.Table.Columns.Contains("scripttypedescription") && dialPlanRow["scripttypedescription"] != null) ? SIPDialPlanScriptTypes.GetSIPDialPlanScriptType(dialPlanRow["scripttypedescription"] as string).ToString() : SIPDialPlanScriptTypesEnum.Ruby.ToString(); m_maxExecutionCount = (dialPlanRow.Table.Columns.Contains("maxexecutioncount") && dialPlanRow["maxexecutioncount"] != null) ? Convert.ToInt32(dialPlanRow["maxexecutioncount"]) : DEFAULT_MAXIMUM_EXECUTION_COUNT; m_executionCount = (dialPlanRow.Table.Columns.Contains("executioncount") && dialPlanRow["executioncount"] != null) ? Convert.ToInt32(dialPlanRow["executioncount"]) : DEFAULT_MAXIMUM_EXECUTION_COUNT; m_authorisedApps = (dialPlanRow.Table.Columns.Contains("authorisedapps") && dialPlanRow["authorisedapps"] != null) ? dialPlanRow["authorisedapps"] as string : null; Inserted = (dialPlanRow.Table.Columns.Contains("inserted") && dialPlanRow["inserted"] != null && dialPlanRow["inserted"] != DBNull.Value) ? DateTimeOffset.Parse(dialPlanRow["inserted"] as string) : DateTimeOffset.UtcNow; LastUpdate = (dialPlanRow.Table.Columns.Contains("lastupdate") && dialPlanRow["lastupdate"] != null && dialPlanRow["lastupdate"] != DBNull.Value) ? DateTimeOffset.Parse(dialPlanRow["lastupdate"] as string) : DateTimeOffset.UtcNow; m_acceptNonInvite = (dialPlanRow.Table.Columns.Contains("acceptnoninvite") && dialPlanRow["acceptnoninvite"] != null && dialPlanRow["acceptnoninvite"] != DBNull.Value) ? Convert.ToBoolean(dialPlanRow["acceptnoninvite"]) : false; m_isReadOnly = (dialPlanRow.Table.Columns.Contains("isreadonly") && dialPlanRow["isreadonly"] != DBNull.Value && dialPlanRow["isreadonly"] != null) ? Convert.ToBoolean(dialPlanRow["isreadonly"]) : false; } catch (Exception excp) { logger.Error("Exception DialPlan Load. " + excp); throw excp; } } //public Dictionary<Guid, object> Load(XmlDocument dom) //{ // return SIPAssetXMLPersistor<SIPDialPlan>.LoadAssetsFromXMLRecordSet(dom); //} #endif public string ToXML() { string dialPlanXML = " <" + XML_ELEMENT_NAME + ">" + m_newLine + ToXMLNoParent() + " </" + XML_ELEMENT_NAME + ">" + m_newLine; return dialPlanXML; } public string ToXMLNoParent() { string dialPlanXML = " <id>" + m_id + "</id>" + m_newLine + " <owner>" + m_owner + "</owner>" + m_newLine + " <adminmemberid>" + AdminMemberId + "</adminmemberid>" + m_newLine + " <dialplanname>" + m_dialPlanName + "</dialplanname>" + m_newLine + " <traceemailaddress>" + m_traceEmailAddress + "</traceemailaddress>" + m_newLine + " <dialplanscript><![CDATA[" + m_dialPlanScript + "]]></dialplanscript>" + m_newLine + " <scripttype>" + m_scriptTypeDescription + "</scripttype>" + m_newLine + " <maxexecutioncount>" + m_maxExecutionCount + "</maxexecutioncount>" + m_newLine + " <executioncount>" + m_executionCount + "</executioncount>" + m_newLine + " <authorisedapps>" + m_authorisedApps + "</authorisedapps>" + m_newLine + " <inserted>" + m_inserted.ToString("o") + "</inserted>" + m_newLine + " <lastupdate>" + m_lastUpdate.ToString("o") + "</lastupdate>" + m_newLine + " <acceptnoninvite>" + m_acceptNonInvite + "</acceptnoninvite>" + m_newLine + " <isreadonly>" + m_isReadOnly + "</isreadonly>" + m_newLine; return dialPlanXML; } public string GetXMLElementName() { return XML_ELEMENT_NAME; } public string GetXMLDocumentElementName() { return XML_DOCUMENT_ELEMENT_NAME; } private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
// // System.Collections.DictionaryBase // Test suite for System.Collections.DictionaryBase // // Authors: // Carlos Alberto Barcenilla (barce@frlp.utn.edu.ar) // using System; using System.Collections; using NUnit.Framework; namespace MonoTests.System.Collections { [TestFixture] public class DictionaryBaseTest: Assertion { static void Main(string[] args) { } public class ConcreteDictionary : DictionaryBase { public bool onInsertFired; public bool onInsertCompleteFired; public bool onValidateFired; public bool onRemoveFired; public bool onRemoveCompleteFired; public bool onClearFired; public bool onClearCompleteFired; public bool onSetFired; public bool onSetCompleteFired; public bool onGetFired; public bool onInsertMustThrowException; public bool onInsertCompleteMustThrowException; public bool onValidateMustThrowException; public bool onRemoveMustThrowException; public bool onRemoveCompleteMustThrowException; public bool onClearMustThrowException; public bool onClearCompleteMustThrowException; public bool onSetMustThrowException; public bool onSetCompleteMustThrowException; public bool onGetMustThrowException; public ConcreteDictionary() { } public ConcreteDictionary(int i) { for (int j = 0; j < i; j++) { ((IDictionary) this).Add(j, j*2); } ClearFlags(); } public IDictionary BaseDictionary { get { return this.Dictionary; } } public void ClearFlags() { onInsertFired = false; onInsertCompleteFired = false; onValidateFired = false; onRemoveFired = false; onRemoveCompleteFired = false; onClearFired = false; onClearCompleteFired = false; onSetFired = false; onSetCompleteFired = false; onGetFired = false; } protected override void OnValidate(object key, object value) { onValidateFired = true; if (onValidateMustThrowException) throw new Exception(); base.OnValidate (key, value); } protected override void OnInsert(object key, object value) { onInsertFired = true; if (onInsertMustThrowException) throw new Exception(); base.OnInsert (key, value); } protected override void OnInsertComplete(object key, object value) { onInsertCompleteFired = true; if (onInsertCompleteMustThrowException) throw new Exception(); base.OnInsertComplete (key, value); } protected override void OnRemove(object key, object value) { onRemoveFired = true; if (onRemoveMustThrowException) throw new Exception(); base.OnRemove (key, value); } protected override void OnRemoveComplete(object key, object value) { onRemoveCompleteFired = true; if (onRemoveCompleteMustThrowException) throw new Exception(); base.OnRemoveComplete (key, value); } protected override void OnClear() { onClearFired = true; if (onClearMustThrowException) throw new Exception(); base.OnClear (); } protected override void OnClearComplete() { onClearCompleteFired = true; if (onClearCompleteMustThrowException) throw new Exception(); base.OnClearComplete (); } protected override object OnGet(object key, object currentValue) { onGetFired = true; if (onGetMustThrowException) throw new Exception(); return base.OnGet (key, currentValue); } protected override void OnSet(object key, object oldValue, object newValue) { onSetFired = true; if (onSetMustThrowException) throw new Exception(); base.OnSet (key, oldValue, newValue); } protected override void OnSetComplete(object key, object oldValue, object newValue) { onSetCompleteFired = true; if (onSetCompleteMustThrowException) throw new Exception(); base.OnSetComplete (key, oldValue, newValue); } } [Test] public void Add() { ConcreteDictionary myDictionary = new ConcreteDictionary(10); myDictionary.BaseDictionary.Add(100, 1); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnInsert must be fired", myDictionary.onInsertFired); Assert("OnInsertComplete must be fired", myDictionary.onInsertCompleteFired); AssertEquals("Count", 11, myDictionary.Count); AssertEquals(1, myDictionary.BaseDictionary[100]); } [Test] public void AddOnValidateExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(30); myDictionary.onValidateMustThrowException = true; try { myDictionary.BaseDictionary.Add(111,222); } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnInsert must not be fired", !myDictionary.onInsertFired); Assert("OnInsertComplete must not be fired", !myDictionary.onInsertCompleteFired); AssertEquals("Count", 30, myDictionary.Count); } } [Test] public void AddOnInsertExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(30); myDictionary.onInsertMustThrowException = true; try { myDictionary.BaseDictionary.Add(666,222); } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnInsert must be fired", myDictionary.onInsertFired); Assert("OnInsertComplete must not be fired", !myDictionary.onInsertCompleteFired); AssertEquals("Count", 30, myDictionary.Count); } } [Test] public void AddOnInsertCompleteExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(5); myDictionary.onInsertCompleteMustThrowException = true; try { myDictionary.BaseDictionary.Add(888,999); } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnInsert must be fired", myDictionary.onInsertFired); Assert("OnInsertComplete must be fired", myDictionary.onInsertCompleteFired); AssertEquals("Count", 5, myDictionary.Count); } } [Test] public void AddNullKey() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(); try { myDictionary.BaseDictionary.Add(null, 11); } catch (ArgumentNullException) { exceptionThrown = true; } finally { Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnInsert must be fired", myDictionary.onInsertFired); Assert("OnInsertComplete must not be fired", !myDictionary.onInsertCompleteFired); Assert("ArgumentNullException must be thrown", exceptionThrown); } } [Test] public void Clear() { ConcreteDictionary myDictionary = new ConcreteDictionary(30); myDictionary.Clear(); Assert("OnClear must be fired", myDictionary.onClearFired); Assert("OnClearComplete must be fired", myDictionary.onClearCompleteFired); AssertEquals("Count", 0, myDictionary.Count); } [Test] public void ClearOnClearExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(30); myDictionary.onClearMustThrowException = true; try { myDictionary.Clear(); } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnClear must be fired", myDictionary.onClearFired); Assert("OnClearComplete must not be fired", !myDictionary.onClearCompleteFired); AssertEquals("Count", 30, myDictionary.Count); } } [Test] public void ClearOnClearCompleteExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(30); myDictionary.onClearCompleteMustThrowException = true; try { myDictionary.Clear(); } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnClear must be fired", myDictionary.onClearFired); Assert("OnClearComplete must be fired", myDictionary.onClearCompleteFired); AssertEquals("Count", 0, myDictionary.Count); } } [Test] public void Count() { ConcreteDictionary myDictionary = new ConcreteDictionary(19); AssertEquals(19, myDictionary.Count); } [Test] public void Remove() { ConcreteDictionary myDictionary = new ConcreteDictionary(8); myDictionary.BaseDictionary.Remove(5); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnRemove must be fired", myDictionary.onRemoveFired); Assert("OnRemoveComplete must be fired", myDictionary.onRemoveCompleteFired); AssertEquals("Count", 7, myDictionary.Count); AssertEquals(null, myDictionary.BaseDictionary[5]); } [Test] public void RemoveOnValidateExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(28); myDictionary.onValidateMustThrowException = true; try { myDictionary.BaseDictionary.Remove(11); } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown in this test", exceptionThrown); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnRemove must not be fired", !myDictionary.onRemoveFired); Assert("OnRemoveComplete must not be fired", !myDictionary.onRemoveCompleteFired); AssertEquals("Count", 28, myDictionary.Count); AssertEquals(22, myDictionary.BaseDictionary[11]); } } [Test] public void RemoveOnRemoveExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(28); myDictionary.onRemoveMustThrowException = true; try { myDictionary.BaseDictionary.Remove(11); } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnRemove must be fired", myDictionary.onRemoveFired); Assert("OnRemoveComplete must not be fired", !myDictionary.onRemoveCompleteFired); AssertEquals("Count", 28, myDictionary.Count); AssertEquals(22, myDictionary.BaseDictionary[11]); } } [Test] public void RemoveOnRemoveCompleteExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(28); myDictionary.onRemoveCompleteMustThrowException = true; try { myDictionary.BaseDictionary.Remove(11); } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnRemove must be fired", myDictionary.onRemoveFired); Assert("OnRemoveComplete must be fired", myDictionary.onRemoveCompleteFired); AssertEquals("Count", 27, myDictionary.Count); AssertEquals(null, myDictionary.BaseDictionary[11]); } } [Test] public void RemoveKeyNotInDictionary() { ConcreteDictionary myDictionary = new ConcreteDictionary(28); myDictionary.BaseDictionary.Remove(80); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnRemove must be fired", myDictionary.onRemoveFired); Assert("OnRemoveComplete must be fired", myDictionary.onRemoveCompleteFired); } [Test] public void Items() { ConcreteDictionary myDictionary = new ConcreteDictionary(19); for (int i = 0; i < 19; i++) { AssertEquals(i*2, (int) myDictionary.BaseDictionary[i]); } } [Test] public void Contains() { ConcreteDictionary myDictionary = new ConcreteDictionary(14); for (int i = 0; i < 14; i++) { Assert("Must contain " + i, myDictionary.BaseDictionary.Contains(i)); } for (int i = 14; i < 34; i++) { Assert("Must not contain " + i, !myDictionary.BaseDictionary.Contains(i)); } } [Test] public void GetEnumerator() { ConcreteDictionary myDictionary = new ConcreteDictionary(4); AssertNotNull(myDictionary.GetEnumerator()); } [Test] public void Keys() { ConcreteDictionary myDictionary = new ConcreteDictionary(5); ICollection keys = myDictionary.BaseDictionary.Keys; int total = 0; foreach (int i in keys) total += i; AssertEquals(10, total); AssertEquals(5, keys.Count); } [Test] public void Values() { ConcreteDictionary myDictionary = new ConcreteDictionary(5); ICollection values = myDictionary.BaseDictionary.Values; int total = 0; foreach (int i in values) total += i; AssertEquals(20, total); AssertEquals(5, values.Count); } [Test] public void Get() { ConcreteDictionary myDictionary = new ConcreteDictionary(18); int v = (int) myDictionary.BaseDictionary[10]; Assert("OnGet must be fired", myDictionary.onGetFired); AssertEquals(v, 20); } [Test] public void GetOnGetExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(18); myDictionary.onGetMustThrowException = true; try { int v = (int) myDictionary.BaseDictionary[10]; } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnGet must be fired", myDictionary.onGetFired); } } [Test] public void GetNoKey() { ConcreteDictionary myDictionary = new ConcreteDictionary(18); AssertNull(myDictionary.BaseDictionary[100]); } [Test] public void Set() { ConcreteDictionary myDictionary = new ConcreteDictionary(18); myDictionary.BaseDictionary[10] = 50; Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnSet must be fired", myDictionary.onSetFired); Assert("OnSetComplete must be fired", myDictionary.onSetCompleteFired); AssertEquals(50, myDictionary.BaseDictionary[10]); } [Test] public void SetNewKey() { ConcreteDictionary myDictionary = new ConcreteDictionary(18); myDictionary.BaseDictionary[111] = 222; Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnSet must be fired", myDictionary.onSetFired); Assert("OnSetComplete must be fired", myDictionary.onSetCompleteFired); Assert("OnInsert must not be fired", !myDictionary.onInsertFired); Assert("OnInsertComplete must not be fired", !myDictionary.onInsertCompleteFired); AssertEquals(222, myDictionary.BaseDictionary[111]); AssertEquals(19, myDictionary.Count); } [Test] public void SetOnValidateExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(18); myDictionary.onValidateMustThrowException = true; try { myDictionary.BaseDictionary[10] = 50; } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnSet must not be fired", !myDictionary.onSetFired); Assert("OnSetComplete not must be fired", !myDictionary.onSetCompleteFired); AssertEquals(20, myDictionary.BaseDictionary[10]); } } [Test] public void SetOnSetExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(18); myDictionary.onSetMustThrowException = true; try { myDictionary.BaseDictionary[10] = 50; } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnSet must be fired", myDictionary.onSetFired); Assert("OnSetComplete must not be fired", !myDictionary.onSetCompleteFired); AssertEquals(20, myDictionary.BaseDictionary[10]); } } [Test] public void SetOnSetCompleteExcept() { bool exceptionThrown = false; ConcreteDictionary myDictionary = new ConcreteDictionary(18); myDictionary.onSetCompleteMustThrowException = true; try { myDictionary.BaseDictionary[10] = 50; } catch { exceptionThrown = true; } finally { Assert("Exception must be thrown", exceptionThrown); Assert("OnValidate must be fired", myDictionary.onValidateFired); Assert("OnSet must be fired", myDictionary.onSetFired); Assert("OnSetComplete must be fired", myDictionary.onSetCompleteFired); AssertEquals(20, myDictionary.BaseDictionary[10]); } } [Test] public void IsReadOnly() { ConcreteDictionary myDictionary = new ConcreteDictionary(1); Assert(!myDictionary.BaseDictionary.IsReadOnly); } [Test] public void IsFixedSize() { ConcreteDictionary myDictionary = new ConcreteDictionary(1); Assert(!myDictionary.BaseDictionary.IsFixedSize); } [Test] public void DictionaryProperty() { ConcreteDictionary myDictionary = new ConcreteDictionary(1); AssertEquals(myDictionary, myDictionary.BaseDictionary); } } }
using Saga.Enumarations; using Saga.Map; using Saga.Packets; using Saga.PrimaryTypes; using Saga.Quests; using Saga.Shared.NetworkCore; using Saga.Structures; using Saga.Tasks; using Saga.Templates; using System.Collections.Generic; using System.Diagnostics; public static class CommonFunctions { #region NPC: Dialog Scripts public static void AcknowledgeMenuPressed(Character target, DialogType button, byte menu) { SMSG_NPCMENU spkt = new SMSG_NPCMENU(); spkt.ButtonID = (byte)button; spkt.MenuID = menu; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } public static void ShowAuction(Character target, MapObject c) { SMSG_MARKETSTART spkt = new SMSG_MARKETSTART(); spkt.Unknown = 1; spkt.Actor = c.id; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } public static void ShowWarpOptions(Character target, MapObject source, IEnumerable<ushort> warplocations) { Saga.Factory.Warps.Info WarpInfo; SMSG_WARPDIALOG spkt = new SMSG_WARPDIALOG(); spkt.ActorId = source.id; spkt.SessionId = target.id; foreach (ushort i in warplocations) if (Singleton.Warps.TryFind(i, out WarpInfo)) spkt.AddItem(i, WarpInfo.price); target.client.Send((byte[])spkt); } #endregion NPC: Dialog Scripts #region Special Operations public static void UpdateCharacterInfo(Character target, byte update) { SMSG_CHARSTATUS spkt = new SMSG_CHARSTATUS(); spkt.Job = target.job; spkt.Exp = target.Cexp; spkt.JobExp = target.Jexp; spkt.LC = target._status.CurrentOxygen; spkt.MaxLC = target._status.MaximumOxygen; spkt.HP = target.HP; spkt.MaxHP = target.HPMAX; spkt.SP = target.SP; spkt.MaxSP = target.SPMAX; spkt.LP = target._status.CurrentLp; spkt.MaxLP = 7; spkt.FieldOfSight = update; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } public static void UpdateZeny(Character target) { SMSG_SENDZENY spkt = new SMSG_SENDZENY(); spkt.Zeny = target.ZENY; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } public static void UpdateShopZeny(Character target) { BaseNPC targetA = target.Target as BaseNPC; if (targetA != null) { SMSG_SHOPZENYUPDATE spkt = new SMSG_SHOPZENYUPDATE(); spkt.Actor = target.Target.id; spkt.Zeny = targetA.Zeny; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } } #endregion Special Operations #region SomeJunk private static IEnumerable<uint> CheckQuest(Character target, IEnumerable<uint> id) { foreach (uint c in id) if (target.QuestObjectives[c] == null) yield return c; } public static void SendRebuylist(Character target) { SMSG_REBUYLIST spkt = new SMSG_REBUYLIST(); spkt.SessionId = target.id; byte i = 0; foreach (Rag2Item item in target.REBUY) { spkt.Count = ++i; spkt.Add(item.info.item, (byte)item.count); } target.client.Send((byte[])spkt); } #endregion SomeJunk #region More Junk public static void SendExchangeStatus(Character target, uint addition, uint time) { SMSG_ADDITIONBEGIN spkt = new SMSG_ADDITIONBEGIN(); spkt.Duration = time; spkt.SourceActor = target.id; spkt.StatusID = addition; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } public static void SendDeleteStatus(Character target, uint addition) { SMSG_ADDITIONEND spkt = new SMSG_ADDITIONEND(); spkt.SourceActor = target.id; spkt.StatusID = addition; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } public static void SendBattleStatus(Character character) { SMSG_BATTLESTATS spkt = new SMSG_BATTLESTATS(); spkt.SpiritResistance = character._status.SpiritResistance; spkt.WindResistance = character._status.ThunderResistance; spkt.DarkResistance = character._status.DarkResistance; spkt.FireResistance = character._status.FireResistance; spkt.GhostResistance = character._status.GhostResitance; spkt.HolyResistance = character._status.HolyResistance; spkt.IceResistance = character._status.IceResistance; spkt.MagicalAttackMax = (ushort)character._status.BaseMinMAttack; spkt.MagicalAttackMin = (ushort)character._status.BaseMinMAttack; spkt.MagicalDefense = (ushort)character._status.DefenceMagical; spkt.MagicalEvasion = (ushort)character._status.BaseMEvasionrate; spkt.PhysicalAttackMax = (ushort)(character._status.BaseMaxPAttack + character._status.MaxWPAttack); spkt.PhysicalAttackMin = (ushort)(character._status.BaseMinPAttack); spkt.PhysicalDefense = (ushort)character._status.DefencePhysical; spkt.PhysicalEvasion = (ushort)character._status.BasePEvasionrate; spkt.PhysicalRangedAttackMax = (ushort)character._status.BaseMaxRAttack; spkt.PhysicalRangedAttackMin = (ushort)character._status.BaseMinRAttack; spkt.PhysicalRangedDefense = (ushort)character._status.DefenceRanged; spkt.PhysicalRangedEvasion = (ushort)character._status.BaseREvasionrate; spkt.SessionId = character.id; character.client.Send((byte[])spkt); } public static void SendExtStats(Character character) { SMSG_EXTSTATS spkt = new SMSG_EXTSTATS(); spkt.base_stats_1 = character.stats.BASE; spkt.base_stats_2 = character.stats.CHARACTER; spkt.base_stats_jobs = character.stats.EQUIPMENT; spkt.base_stats_bonus = character.stats.ENCHANTMENT; spkt.statpoints = character.stats.REMAINING; spkt.SessionId = character.id; character.client.Send((byte[])spkt); } public static Client GetClient(Character target) { //Only temp... return target.client; } #endregion More Junk #region More Junk public static void UpdateState(Character target) { Regiontree tree = target.currentzone.Regiontree; foreach (Character regionObject in tree.SearchActors(target, SearchFlags.Characters)) Common.Actions.UpdateStance(regionObject, target); } internal static void SendOxygenTakeDamage(Character c, uint p) { /* * This functions sends a oxygen damage packet * * Where the damage is already already decided. And take from * the character. */ SMSG_TAKEDAMAGE spkt = new SMSG_TAKEDAMAGE(); spkt.Damage = p; spkt.Reason = c.HP > 0 ? (byte)TakeDamageReason.Oxygen : (byte)TakeDamageReason.Suffocated; spkt.SessionId = c.id; c.client.Send((byte[])spkt); } public static void UpdateTimeWeather(Character character) { /* * This function updates the time and Weather for the * selected player. */ SMSG_TIMEWEATHER spkt = new SMSG_TIMEWEATHER(); spkt.weather = (byte)character.currentzone.Weather; spkt.day = Saga.Tasks.WorldTime.Time[0]; spkt.hour = Saga.Tasks.WorldTime.Time[1]; spkt.min = Saga.Tasks.WorldTime.Time[2]; spkt.SessionId = character.id; character.client.Send((byte[])spkt); } #endregion More Junk public static void RefreshPersonalRequests(Character target) { if (target != null) { Dictionary<uint, uint> tmp = new Dictionary<uint, uint>(); QuestBase PersonalQuest = target.QuestObjectives.PersonalQuest; uint PersonalQuestId = (PersonalQuest != null) ? PersonalQuest.QuestId : 0; foreach (KeyValuePair<uint, uint> pair in Singleton.Database.GetPersonalAvailableQuestsByRegion(target, (byte)target.currentzone.RegionCode, PersonalQuestId)) tmp.Add(pair.Value, pair.Key); lock (target.client.AvailablePersonalRequests) target.client.AvailablePersonalRequests = tmp; } } public static void UpdateNpcIcons(Character target) { foreach (MapObject myObject in target.currentzone.GetObjectsInRegionalRange(target)) { if (MapObject.IsNotMonster(myObject) && target.currentzone.IsInSightRangeBySquare(target.Position, myObject.Position)) { BaseMob temp = myObject as BaseMob; if (temp != null) Common.Actions.UpdateIcon(target, temp); } } } #region Chat - Functions public static void Broadcast(Character sender, string message) { string nmessage = message != null ? message : string.Empty; foreach (Character target in LifeCycle.Characters) { SMSG_SENDCHAT spkt = new SMSG_SENDCHAT(); spkt.Message = nmessage; spkt.Name = sender.Name; spkt.MessageType = SMSG_SENDCHAT.MESSAGE_TYPE.SYSTEM_MESSAGE; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } } public static void Broadcast(Character sender, Character target, string message) { SMSG_SENDCHAT spkt = new SMSG_SENDCHAT(); spkt.Message = message != null ? message : string.Empty; spkt.Name = sender.Name; spkt.MessageType = SMSG_SENDCHAT.MESSAGE_TYPE.SYSTEM_MESSAGE; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } public static void SystemMessage(Character sender, string message) { string nmessage = message != null ? message : string.Empty; foreach (Character target in LifeCycle.Characters) { SMSG_SENDCHAT spkt = new SMSG_SENDCHAT(); spkt.Message = nmessage; spkt.Name = sender.Name; spkt.MessageType = SMSG_SENDCHAT.MESSAGE_TYPE.SYSTEM_MESSAGE_RED; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } } public static void SystemMessage(Character sender, Character target, string message) { SMSG_SENDCHAT spkt = new SMSG_SENDCHAT(); spkt.Message = message != null ? message : string.Empty; spkt.Name = sender.Name; spkt.MessageType = SMSG_SENDCHAT.MESSAGE_TYPE.SYSTEM_MESSAGE_RED; spkt.SessionId = target.id; target.client.Send((byte[])spkt); } #endregion Chat - Functions #region Warp - Functions public static bool Warp(Character target) { return Warp(target, target.savelocation.map, target.savelocation.coords); } public static bool Warp(Character target, byte zone) { Zone NewZone; if (Singleton.Zones.TryGetZone(zone, out NewZone)) { if (NewZone.CathelayaLocation.map == zone) return Warp(target, NewZone.CathelayaLocation.coords, NewZone); else return Warp(target, new Point(0, 0, 0), NewZone); } else { return false; } } public static bool Warp(Character target, byte zone, Point destination) { Zone NewZone; if (Singleton.Zones.TryGetZone(zone, out NewZone)) { return Warp(target, destination, NewZone); } else { return false; } } public static bool Warp(Character target, Point destination, Zone NewZoneInstance) { if (target.client.isloaded == true) { if (target.map > 0 && NewZoneInstance.Map > 0) { if (target.map != NewZoneInstance.Map) { #region Not the same Zone if (target.currentzone.Type != ZoneType.Dungeon) { WorldCoordinate worldcoord; worldcoord.coords = target.Position; worldcoord.map = target.currentzone.Map; target.lastlocation = worldcoord; } //Start loading target.client.isloaded = false; Zone currentZone = target.currentzone; target.currentzone.OnLeave(target); lock (target) { //Unregister currentZone.Regiontree.Unsubscribe(target); //Set position to the new location target.map = NewZoneInstance.Map; //Set new position target.Position = new Point( destination.x, destination.y, destination.z ); } //Update party members if (target.sessionParty != null) foreach (Character partyTarget in target.sessionParty) { //switch the map SMSG_PARTYMEMBERMAPCHANGE spkt4 = new SMSG_PARTYMEMBERMAPCHANGE(); spkt4.Index = 1; spkt4.ActorId = target.id; spkt4.Unknown = (byte)(target.map + 0x065); spkt4.Zone = target.map; spkt4.SessionId = partyTarget.id; partyTarget.client.Send((byte[])spkt4); } //Set zone instance target.currentzone = NewZoneInstance; //Send over load packet SMSG_SENDSTART spkt = new SMSG_SENDSTART(); spkt.SessionId = target.id; spkt.X = destination.x; spkt.Y = destination.y; spkt.Z = destination.z; spkt.MapId = NewZoneInstance.Map; spkt.Unknown = (byte)(target.map + 0x65); spkt.Channel = 1; target.client.Send((byte[])spkt); return true; #endregion Not the same Zone } else { #region Notify People That Actor Disapears Point origin = target.Position; Regiontree tree; tree = target.currentzone.Regiontree; foreach (MapObject c in tree.SearchActors(target, SearchFlags.DynamicObjects)) { bool insightrangeold = Point.IsInSightRangeByRadius(origin, c.Position); bool insightrangenew = Point.IsInSightRangeByRadius(destination, c.Position); if (c.id == target.id) continue; //If vible from old postion but not from new position hide if (insightrangeold && !insightrangenew) { double distance = Point.GetDistance3D(destination, c.Position); //CROSS NOTIFY PLAYERS ACTORS DISAPPPEARS if (MapObject.IsPlayer(c)) { Character targetChar = c as Character; targetChar.HideObject(target); } c.HideObject(target); c.Disappear(target); } } #endregion Notify People That Actor Disapears #region Update Region target.Position = new Point(destination.x, destination.y, destination.z); Regiontree.UpdateRegion(target); #endregion Update Region #region Teleport SMSG_ACTORTELEPORT spkt = new SMSG_ACTORTELEPORT(); spkt.SessionId = target.id; spkt.x = destination.x; spkt.y = destination.y; spkt.Z = destination.z; target.client.Send((byte[])spkt); #endregion Teleport #region Reset State target.ISONBATTLE = false; target.stance = (byte)StancePosition.Reborn; target._targetid = 0; SMSG_ACTORCHANGESTATE spkt4 = new SMSG_ACTORCHANGESTATE(); spkt4.SessionId = target.id; spkt4.Stance = target.stance; spkt4.TargetActor = target._targetid; spkt4.State = (target.ISONBATTLE == true) ? (byte)1 : (byte)0; spkt4.ActorID = target.id; target.client.Send((byte[])spkt4); #endregion Reset State #region Notify People That the Actor Appears tree = target.currentzone.Regiontree; foreach (MapObject myObject in tree.SearchActors(target, SearchFlags.DynamicObjects)) { bool insightrangeold = Point.IsInSightRangeByRadius(origin, myObject.Position); bool insightrangenew = Point.IsInSightRangeByRadius(destination, myObject.Position); double distance = Point.GetDistance3D(destination, myObject.Position); //If visible from new postion but not from old postion if (insightrangenew && !insightrangeold) { myObject.ShowObject(target); myObject.Appears(target); if (MapObject.IsPlayer(myObject)) { Character current = (Character)myObject; if (current.client.isloaded == false) continue; target.ShowObject(current); } } } #endregion Notify People That the Actor Appears #region Notify Party Members if (target.sessionParty != null) { foreach (Character partyTarget in target.sessionParty) { if (partyTarget.id == target.id) continue; SMSG_PARTYMEMBERLOCATION spkt3 = new SMSG_PARTYMEMBERLOCATION(); spkt3.Index = 1; spkt3.ActorId = target.id; spkt3.SessionId = partyTarget.id; spkt3.X = (destination.x / 1000); spkt3.Y = (destination.y / 1000); partyTarget.client.Send((byte[])spkt3); } } #endregion Notify Party Members return true; } } else { Trace.TraceError("Warping player {0} to unsupported map {1}", target.Name, 0); return false; } } else { return false; } } #endregion Warp - Functions internal static void SendQuestList(Character target, MapObject source, IEnumerable<uint> iEnumerable) { SMSG_SENDQUESTLIST spkt = new SMSG_SENDQUESTLIST(); spkt.SessionId = target.id; spkt.SetQuests(iEnumerable); spkt.SourceActor = source.id; target.client.Send((byte[])spkt); } }
/* ==================================================================== Licensed To the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file To You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed To in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System.Diagnostics; using NPOI.SS.Formula.Atp; namespace NPOI.SS.Formula { using System; using System.Collections; using NPOI.SS.Formula; using NPOI.SS.Formula.Eval; using NPOI.SS.Util; using NPOI.SS.Formula.Functions; using NPOI.SS.Formula.Udf; using System.Collections.Generic; using NPOI.SS.UserModel; using NPOI.SS.Formula.PTG; using NPOI.Util; using NPOI.SS.Formula.Function; /** * Evaluates formula cells.<p/> * * For performance reasons, this class keeps a cache of all previously calculated intermediate * cell values. Be sure To call {@link #ClearCache()} if any workbook cells are Changed between * calls To evaluate~ methods on this class.<br/> * * For POI internal use only * * @author Josh Micich */ public class WorkbookEvaluator { private IEvaluationWorkbook _workbook; private EvaluationCache _cache; private int _workbookIx; private IEvaluationListener _evaluationListener; private Hashtable _sheetIndexesBySheet; private Dictionary<String, int> _sheetIndexesByName; private CollaboratingWorkbooksEnvironment _collaboratingWorkbookEnvironment; private IStabilityClassifier _stabilityClassifier; private UDFFinder _udfFinder; private bool _ignoreMissingWorkbooks = false; public WorkbookEvaluator(IEvaluationWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) : this(workbook, null, stabilityClassifier, udfFinder) { } public WorkbookEvaluator(IEvaluationWorkbook workbook, IEvaluationListener evaluationListener, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { _workbook = workbook; _evaluationListener = evaluationListener; _cache = new EvaluationCache(evaluationListener); _sheetIndexesBySheet = new Hashtable(); _sheetIndexesByName = new Dictionary<string, int>(); _collaboratingWorkbookEnvironment = CollaboratingWorkbooksEnvironment.EMPTY; _workbookIx = 0; _stabilityClassifier = stabilityClassifier; AggregatingUDFFinder defaultToolkit = // workbook can be null in unit tests workbook == null ? null : (AggregatingUDFFinder)workbook.GetUDFFinder(); if (defaultToolkit != null && udfFinder != null) { defaultToolkit.Add(udfFinder); } _udfFinder = defaultToolkit; } /** * also for debug use. Used in ToString methods */ /* package */ public String GetSheetName(int sheetIndex) { return _workbook.GetSheetName(sheetIndex); } public WorkbookEvaluator GetOtherWorkbookEvaluator(String workbookName) { return _collaboratingWorkbookEnvironment.GetWorkbookEvaluator(workbookName); } internal IEvaluationWorkbook Workbook { get { return _workbook; } } internal IEvaluationSheet GetSheet(int sheetIndex) { return _workbook.GetSheet(sheetIndex); } /* package */ internal IEvaluationName GetName(String name, int sheetIndex) { IEvaluationName evalName = _workbook.GetName(name, sheetIndex); return evalName; } private static bool IsDebugLogEnabled() { #if DEBUG return true; #else return false; #endif } private static bool IsInfoLogEnabled() { #if TRACE return true; #else return false; #endif } private static void LogDebug(String s) { if (IsDebugLogEnabled()) { Debug.WriteLine(s); } } private static void LogInfo(String s) { if (IsInfoLogEnabled()) { Trace.WriteLine(s); } } /* package */ public void AttachToEnvironment(CollaboratingWorkbooksEnvironment collaboratingWorkbooksEnvironment, EvaluationCache cache, int workbookIx) { _collaboratingWorkbookEnvironment = collaboratingWorkbooksEnvironment; _cache = cache; _workbookIx = workbookIx; } /* package */ public CollaboratingWorkbooksEnvironment GetEnvironment() { return _collaboratingWorkbookEnvironment; } /* package */ public void DetachFromEnvironment() { _collaboratingWorkbookEnvironment = CollaboratingWorkbooksEnvironment.EMPTY; _cache = new EvaluationCache(_evaluationListener); _workbookIx = 0; } /* package */ public IEvaluationListener GetEvaluationListener() { return _evaluationListener; } /** * Should be called whenever there are Changes To input cells in the evaluated workbook. * Failure To call this method after changing cell values will cause incorrect behaviour * of the evaluate~ methods of this class */ public void ClearAllCachedResultValues() { _cache.Clear(); _sheetIndexesBySheet.Clear(); } /** * Should be called To tell the cell value cache that the specified (value or formula) cell * Has Changed. */ public void NotifyUpdateCell(IEvaluationCell cell) { int sheetIndex = GetSheetIndex(cell.Sheet); _cache.NotifyUpdateCell(_workbookIx, sheetIndex, cell); } /** * Should be called To tell the cell value cache that the specified cell Has just been * deleted. */ public void NotifyDeleteCell(IEvaluationCell cell) { int sheetIndex = GetSheetIndex(cell.Sheet); _cache.NotifyDeleteCell(_workbookIx, sheetIndex, cell); } public int GetSheetIndex(IEvaluationSheet sheet) { object result = _sheetIndexesBySheet[sheet]; if (result == null) { int sheetIndex = _workbook.GetSheetIndex(sheet); if (sheetIndex < 0) { throw new Exception("Specified sheet from a different book"); } result = sheetIndex; _sheetIndexesBySheet[sheet] = result; } return (int)result; } /* package */ internal int GetSheetIndexByExternIndex(int externSheetIndex) { return _workbook.ConvertFromExternSheetIndex(externSheetIndex); } /** * Case-insensitive. * @return -1 if sheet with specified name does not exist */ /* package */ public int GetSheetIndex(String sheetName) { int result; if (_sheetIndexesByName.ContainsKey(sheetName)) { result = _sheetIndexesByName[sheetName]; } else { int sheetIndex = _workbook.GetSheetIndex(sheetName); if (sheetIndex < 0) { return -1; } result = sheetIndex; _sheetIndexesByName[sheetName] = result; } return result; } public ValueEval Evaluate(IEvaluationCell srcCell) { int sheetIndex = GetSheetIndex(srcCell.Sheet); return EvaluateAny(srcCell, sheetIndex, srcCell.RowIndex, srcCell.ColumnIndex, new EvaluationTracker(_cache)); } /** * @return never <c>null</c>, never {@link BlankEval} */ private ValueEval EvaluateAny(IEvaluationCell srcCell, int sheetIndex, int rowIndex, int columnIndex, EvaluationTracker tracker) { bool shouldCellDependencyBeRecorded = _stabilityClassifier == null ? true : !_stabilityClassifier.IsCellFinal(sheetIndex, rowIndex, columnIndex); ValueEval result; if (srcCell == null || srcCell.CellType != CellType.Formula) { result = GetValueFromNonFormulaCell(srcCell); if (shouldCellDependencyBeRecorded) { tracker.AcceptPlainValueDependency(_workbookIx, sheetIndex, rowIndex, columnIndex, result); } return result; } FormulaCellCacheEntry cce = _cache.GetOrCreateFormulaCellEntry(srcCell); if (shouldCellDependencyBeRecorded || cce.IsInputSensitive) { tracker.AcceptFormulaDependency(cce); } IEvaluationListener evalListener = _evaluationListener; if (cce.GetValue() == null) { if (!tracker.StartEvaluate(cce)) { return ErrorEval.CIRCULAR_REF_ERROR; } OperationEvaluationContext ec = new OperationEvaluationContext(this, _workbook, sheetIndex, rowIndex, columnIndex, tracker); try { Ptg[] ptgs = _workbook.GetFormulaTokens(srcCell); if (evalListener == null) { result = EvaluateFormula(ec, ptgs); } else { evalListener.OnStartEvaluate(srcCell, cce); result = EvaluateFormula(ec, ptgs); evalListener.OnEndEvaluate(cce, result); } tracker.UpdateCacheResult(result); } catch (NotImplementedException e) { throw AddExceptionInfo(e, sheetIndex, rowIndex, columnIndex); } catch (RuntimeException re) { if (re.InnerException is WorkbookNotFoundException && _ignoreMissingWorkbooks) { LogInfo(re.InnerException.Message + " - Continuing with cached value!"); switch (srcCell.CachedFormulaResultType) { case CellType.Numeric: result = new NumberEval(srcCell.NumericCellValue); break; case CellType.String: result = new StringEval(srcCell.StringCellValue); break; case CellType.Blank: result = BlankEval.instance; break; case CellType.Boolean: result = BoolEval.ValueOf(srcCell.BooleanCellValue); break; case CellType.Error: result = ErrorEval.ValueOf(srcCell.ErrorCellValue); break; case CellType.Formula: default: throw new RuntimeException("Unexpected cell type '" + srcCell.CellType + "' found!"); } } else { throw re; } } finally { tracker.EndEvaluate(cce); } } else { if (evalListener != null) { evalListener.OnCacheHit(sheetIndex, rowIndex, columnIndex, cce.GetValue()); } return cce.GetValue(); } if (IsDebugLogEnabled()) { String sheetName = GetSheetName(sheetIndex); CellReference cr = new CellReference(rowIndex, columnIndex); LogDebug("Evaluated " + sheetName + "!" + cr.FormatAsString() + " To " + cce.GetValue()); } // Usually (result === cce.getValue()) // But sometimes: (result==ErrorEval.CIRCULAR_REF_ERROR, cce.getValue()==null) // When circular references are detected, the cache entry is only updated for // the top evaluation frame //return cce.GetValue(); return result; } /** * Adds the current cell reference to the exception for easier debugging. * Would be nice to get the formula text as well, but that seems to require * too much digging around and casting to get the FormulaRenderingWorkbook. */ private NotImplementedException AddExceptionInfo(NotImplementedException inner, int sheetIndex, int rowIndex, int columnIndex) { try { String sheetName = _workbook.GetSheetName(sheetIndex); CellReference cr = new CellReference(sheetName, rowIndex, columnIndex, false, false); String msg = "Error evaluating cell " + cr.FormatAsString(); return new NotImplementedException(msg, inner); } catch (Exception) { // avoid bombing out during exception handling //e.printStackTrace(); return inner; // preserve original exception } } /** * Gets the value from a non-formula cell. * @param cell may be <c>null</c> * @return {@link BlankEval} if cell is <c>null</c> or blank, never <c>null</c> */ /* package */ internal static ValueEval GetValueFromNonFormulaCell(IEvaluationCell cell) { if (cell == null) { return BlankEval.instance; } CellType cellType = cell.CellType; switch (cellType) { case CellType.Numeric: return new NumberEval(cell.NumericCellValue); case CellType.String: return new StringEval(cell.StringCellValue); case CellType.Boolean: return BoolEval.ValueOf(cell.BooleanCellValue); case CellType.Blank: return BlankEval.instance; case CellType.Error: return ErrorEval.ValueOf(cell.ErrorCellValue); } throw new Exception("Unexpected cell type (" + cellType + ")"); } /** * whether print detailed messages about the next formula evaluation */ private bool dbgEvaluationOutputForNextEval = false; // special logger for formula evaluation output (because of possibly very large output) private POILogger EVAL_LOG = POILogFactory.GetLogger("POI.FormulaEval"); // current indent level for evalution; negative value for no output private int dbgEvaluationOutputIndent = -1; // visibility raised for testing /* package */ public ValueEval EvaluateFormula(OperationEvaluationContext ec, Ptg[] ptgs) { String dbgIndentStr = ""; // always init. to non-null just for defensive avoiding NPE if (dbgEvaluationOutputForNextEval) { // first evaluation call when ouput is desired, so iit. this evaluator instance dbgEvaluationOutputIndent = 1; dbgEvaluationOutputForNextEval = false; } if (dbgEvaluationOutputIndent > 0) { // init. indent string to needed spaces (create as substring vom very long space-only string; // limit indendation for deep recursions) dbgIndentStr = " "; dbgIndentStr = dbgIndentStr.Substring(0, Math.Min(dbgIndentStr.Length, dbgEvaluationOutputIndent * 2)); EVAL_LOG.Log(POILogger.WARN, dbgIndentStr + "- evaluateFormula('" + ec.GetRefEvaluatorForCurrentSheet().SheetNameRange + "'/" + new CellReference(ec.RowIndex, ec.ColumnIndex).FormatAsString() + "): " + Arrays.ToString(ptgs).Replace("\\Qorg.apache.poi.ss.formula.ptg.\\E", "")); dbgEvaluationOutputIndent++; } Stack<ValueEval> stack = new Stack<ValueEval>(); for (int i = 0, iSize = ptgs.Length; i < iSize; i++) { // since we don't know how To handle these yet :( Ptg ptg = ptgs[i]; if (dbgEvaluationOutputIndent > 0) { EVAL_LOG.Log(POILogger.INFO, dbgIndentStr + " * ptg " + i + ": " + ptg.ToString()); } if (ptg is AttrPtg) { AttrPtg attrPtg = (AttrPtg)ptg; if (attrPtg.IsSum) { // Excel prefers To encode 'SUM()' as a tAttr Token, but this evaluator // expects the equivalent function Token //byte nArgs = 1; // tAttrSum always Has 1 parameter ptg = FuncVarPtg.SUM;//.Create("SUM", nArgs); } if (attrPtg.IsOptimizedChoose) { ValueEval arg0 = stack.Pop(); int[] jumpTable = attrPtg.JumpTable; int dist; int nChoices = jumpTable.Length; try { int switchIndex = Choose.EvaluateFirstArg(arg0, ec.RowIndex, ec.ColumnIndex); if (switchIndex < 1 || switchIndex > nChoices) { stack.Push(ErrorEval.VALUE_INVALID); dist = attrPtg.ChooseFuncOffset + 4; // +4 for tFuncFar(CHOOSE) } else { dist = jumpTable[switchIndex - 1]; } } catch (EvaluationException e) { stack.Push(e.GetErrorEval()); dist = attrPtg.ChooseFuncOffset + 4; // +4 for tFuncFar(CHOOSE) } // Encoded dist for tAttrChoose includes size of jump table, but // countTokensToBeSkipped() does not (it counts whole tokens). dist -= nChoices * 2 + 2; // subtract jump table size i += CountTokensToBeSkipped(ptgs, i, dist); continue; } if (attrPtg.IsOptimizedIf) { ValueEval arg0 = stack.Pop(); bool evaluatedPredicate; try { evaluatedPredicate = If.EvaluateFirstArg(arg0, ec.RowIndex, ec.ColumnIndex); } catch (EvaluationException e) { stack.Push(e.GetErrorEval()); int dist = attrPtg.Data; i += CountTokensToBeSkipped(ptgs, i, dist); attrPtg = (AttrPtg)ptgs[i]; dist = attrPtg.Data + 1; i += CountTokensToBeSkipped(ptgs, i, dist); continue; } if (evaluatedPredicate) { // nothing to skip - true param folows } else { int dist = attrPtg.Data; i += CountTokensToBeSkipped(ptgs, i, dist); Ptg nextPtg = ptgs[i + 1]; if (ptgs[i] is AttrPtg && nextPtg is FuncVarPtg && // in order to verify that there is no third param, we need to check // if we really have the IF next or some other FuncVarPtg as third param, e.g. ROW()/COLUMN()! ((FuncVarPtg)nextPtg).FunctionIndex == FunctionMetadataRegistry.FUNCTION_INDEX_IF) { // this is an if statement without a false param (as opposed to MissingArgPtg as the false param) i++; stack.Push(BoolEval.FALSE); } } continue; } if (attrPtg.IsSkip) { int dist = attrPtg.Data + 1; i += CountTokensToBeSkipped(ptgs, i, dist); if (stack.Peek() == MissingArgEval.instance) { stack.Pop(); stack.Push(BlankEval.instance); } continue; } } if (ptg is ControlPtg) { // skip Parentheses, Attr, etc continue; } if (ptg is MemFuncPtg|| ptg is MemAreaPtg) { // can ignore, rest of Tokens for this expression are in OK RPN order continue; } if (ptg is MemErrPtg) { continue; } ValueEval opResult; if (ptg is OperationPtg) { OperationPtg optg = (OperationPtg)ptg; if (optg is UnionPtg) { continue; } int numops = optg.NumberOfOperands; ValueEval[] ops = new ValueEval[numops]; // storing the ops in reverse order since they are popping for (int j = numops - 1; j >= 0; j--) { ValueEval p = (ValueEval)stack.Pop(); ops[j] = p; } // logDebug("Invoke " + operation + " (nAgs=" + numops + ")"); opResult = OperationEvaluatorFactory.Evaluate(optg, ops, ec); } else { opResult = GetEvalForPtg(ptg, ec); } if (opResult == null) { throw new Exception("Evaluation result must not be null"); } // logDebug("push " + opResult); stack.Push(opResult); if (dbgEvaluationOutputIndent > 0) { EVAL_LOG.Log(POILogger.INFO, dbgIndentStr + " = " + opResult.ToString()); } } ValueEval value = ((ValueEval)stack.Pop()); if (stack.Count != 0) { throw new InvalidOperationException("evaluation stack not empty"); } ValueEval result = DereferenceResult(value, ec.RowIndex, ec.ColumnIndex); if (dbgEvaluationOutputIndent > 0) { EVAL_LOG.Log(POILogger.INFO, dbgIndentStr + "finshed eval of " + new CellReference(ec.RowIndex, ec.ColumnIndex).FormatAsString() + ": " + result.ToString()); dbgEvaluationOutputIndent--; if (dbgEvaluationOutputIndent == 1) { // this evaluation is done, reset indent to stop logging dbgEvaluationOutputIndent = -1; } } // if return result; } /** * Calculates the number of tokens that the evaluator should skip upon reaching a tAttrSkip. * * @return the number of tokens (starting from <c>startIndex+1</c>) that need to be skipped * to achieve the specified <c>distInBytes</c> skip distance. */ private static int CountTokensToBeSkipped(Ptg[] ptgs, int startIndex, int distInBytes) { int remBytes = distInBytes; int index = startIndex; while (remBytes != 0) { index++; remBytes -= ptgs[index].Size; if (remBytes < 0) { throw new Exception("Bad skip distance (wrong token size calculation)."); } if (index >= ptgs.Length) { throw new Exception("Skip distance too far (ran out of formula tokens)."); } } return index - startIndex; } /** * Dereferences a single value from any AreaEval or RefEval evaluation result. * If the supplied evaluationResult is just a plain value, it is returned as-is. * @return a <c>NumberEval</c>, <c>StringEval</c>, <c>BoolEval</c>, * <c>BlankEval</c> or <c>ErrorEval</c>. Never <c>null</c>. */ public static ValueEval DereferenceResult(ValueEval evaluationResult, int srcRowNum, int srcColNum) { ValueEval value; try { value = OperandResolver.GetSingleValue(evaluationResult, srcRowNum, srcColNum); } catch (EvaluationException e) { return e.GetErrorEval(); } if (value == BlankEval.instance) { // Note Excel behaviour here. A blank value is converted To zero. return NumberEval.ZERO; // Formulas _never_ evaluate To blank. If a formula appears To have evaluated To // blank, the actual value is empty string. This can be verified with ISBLANK(). } return value; } /** * returns an appropriate Eval impl instance for the Ptg. The Ptg must be * one of: Area3DPtg, AreaPtg, ReferencePtg, Ref3DPtg, IntPtg, NumberPtg, * StringPtg, BoolPtg <br/>special Note: OperationPtg subtypes cannot be * passed here! */ private ValueEval GetEvalForPtg(Ptg ptg, OperationEvaluationContext ec) { // consider converting all these (ptg is XxxPtg) expressions To (ptg.GetType() == XxxPtg.class) if (ptg is NamePtg) { // Named ranges, macro functions NamePtg namePtg = (NamePtg)ptg; IEvaluationName nameRecord = _workbook.GetName(namePtg); return GetEvalForNameRecord(nameRecord, ec); } if (ptg is NameXPtg) { // Externally defined named ranges or macro functions return ProcessNameEval(ec.GetNameXEval((NameXPtg)ptg), ec); } if (ptg is NameXPxg) { // Externally defined named ranges or macro functions return ProcessNameEval(ec.GetNameXEval((NameXPxg)ptg), ec); } if (ptg is IntPtg) { return new NumberEval(((IntPtg)ptg).Value); } if (ptg is NumberPtg) { return new NumberEval(((NumberPtg)ptg).Value); } if (ptg is StringPtg) { return new StringEval(((StringPtg)ptg).Value); } if (ptg is BoolPtg) { return BoolEval.ValueOf(((BoolPtg)ptg).Value); } if (ptg is ErrPtg) { return ErrorEval.ValueOf(((ErrPtg)ptg).ErrorCode); } if (ptg is MissingArgPtg) { return MissingArgEval.instance; } if (ptg is AreaErrPtg || ptg is RefErrorPtg || ptg is DeletedArea3DPtg || ptg is DeletedRef3DPtg) { return ErrorEval.REF_INVALID; } if (ptg is Ref3DPtg) { return ec.GetRef3DEval((Ref3DPtg)ptg); } if (ptg is Ref3DPxg) { return ec.GetRef3DEval((Ref3DPxg)ptg); } if (ptg is Area3DPtg) { return ec.GetArea3DEval((Area3DPtg)ptg); } if (ptg is Area3DPxg) { return ec.GetArea3DEval((Area3DPxg)ptg); } if (ptg is RefPtg) { RefPtg rptg = (RefPtg)ptg; return ec.GetRefEval(rptg.Row, rptg.Column); } if (ptg is AreaPtg) { AreaPtg aptg = (AreaPtg)ptg; return ec.GetAreaEval(aptg.FirstRow, aptg.FirstColumn, aptg.LastRow, aptg.LastColumn); } if (ptg is UnknownPtg) { // POI uses UnknownPtg when the encoded Ptg array seems To be corrupted. // This seems To occur in very rare cases (e.g. unused name formulas in bug 44774, attachment 21790) // In any case, formulas are re-parsed before execution, so UnknownPtg should not Get here throw new RuntimeException("UnknownPtg not allowed"); } if (ptg is ExpPtg) { // ExpPtg is used for array formulas and shared formulas. // it is currently unsupported, and may not even get implemented here throw new RuntimeException("ExpPtg currently not supported"); } throw new RuntimeException("Unexpected ptg class (" + ptg.GetType().Name + ")"); } private ValueEval ProcessNameEval(ValueEval eval, OperationEvaluationContext ec) { if (eval is ExternalNameEval) { IEvaluationName name = ((ExternalNameEval)eval).Name; return GetEvalForNameRecord(name, ec); } return eval; } private ValueEval GetEvalForNameRecord(IEvaluationName nameRecord, OperationEvaluationContext ec) { if (nameRecord.IsFunctionName) { return new FunctionNameEval(nameRecord.NameText); } if (nameRecord.HasFormula) { return EvaluateNameFormula(nameRecord.NameDefinition, ec); } throw new Exception("Don't now how to Evalate name '" + nameRecord.NameText + "'"); } internal ValueEval EvaluateNameFormula(Ptg[] ptgs, OperationEvaluationContext ec) { if (ptgs.Length == 1) { return GetEvalForPtg(ptgs[0], ec); } return EvaluateFormula(ec, ptgs); } /** * Used by the lazy ref evals whenever they need To Get the value of a contained cell. */ /* package */ public ValueEval EvaluateReference(IEvaluationSheet sheet, int sheetIndex, int rowIndex, int columnIndex, EvaluationTracker tracker) { IEvaluationCell cell = sheet.GetCell(rowIndex, columnIndex); return EvaluateAny(cell, sheetIndex, rowIndex, columnIndex, tracker); } public FreeRefFunction FindUserDefinedFunction(String functionName) { return _udfFinder.FindFunction(functionName); } /** * Whether to ignore missing references to external workbooks and * use cached formula results in the main workbook instead. * <p> * In some cases exetrnal workbooks referenced by formulas in the main workbook are not avaiable. * With this method you can control how POI handles such missing references: * <ul> * <li>by default ignoreMissingWorkbooks=false and POI throws {@link WorkbookNotFoundException} * if an external reference cannot be resolved</li> * <li>if ignoreMissingWorkbooks=true then POI uses cached formula result * that already exists in the main workbook</li> * </ul> *</p> * @param ignore whether to ignore missing references to external workbooks * @see <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=52575">Bug 52575 for details</a> */ public bool IgnoreMissingWorkbooks { get { return _ignoreMissingWorkbooks; } set { _ignoreMissingWorkbooks = value; } } /** * Return a collection of functions that POI can evaluate * * @return names of functions supported by POI */ public static List<String> GetSupportedFunctionNames() { List<String> lst = new List<String>(); lst.AddRange(FunctionEval.GetSupportedFunctionNames()); lst.AddRange(AnalysisToolPak.GetSupportedFunctionNames()); return lst; } /** * Return a collection of functions that POI does not support * * @return names of functions NOT supported by POI */ public static List<String> GetNotSupportedFunctionNames() { List<String> lst = new List<String>(); lst.AddRange(FunctionEval.GetNotSupportedFunctionNames()); lst.AddRange(AnalysisToolPak.GetNotSupportedFunctionNames()); return lst; } /** * Register a ATP function in runtime. * * @param name the function name * @param func the functoin to register * @throws IllegalArgumentException if the function is unknown or already registered. * @since 3.8 beta6 */ public static void RegisterFunction(String name, FreeRefFunction func) { AnalysisToolPak.RegisterFunction(name, func); } /** * Register a function in runtime. * * @param name the function name * @param func the functoin to register * @throws IllegalArgumentException if the function is unknown or already registered. * @since 3.8 beta6 */ public static void RegisterFunction(String name, Functions.Function func) { FunctionEval.RegisterFunction(name, func); } public bool DebugEvaluationOutputForNextEval { get { return dbgEvaluationOutputForNextEval; } set { dbgEvaluationOutputForNextEval = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Xml { using System; using System.IO; using System.Collections; using System.Diagnostics; using System.Collections.Generic; public class XmlNamespaceManager : IXmlNamespaceResolver, IEnumerable { private static volatile IXmlNamespaceResolver s_EmptyResolver; private struct NamespaceDeclaration { public string prefix; public string uri; public int scopeId; public int previousNsIndex; public void Set(string prefix, string uri, int scopeId, int previousNsIndex) { this.prefix = prefix; this.uri = uri; this.scopeId = scopeId; this.previousNsIndex = previousNsIndex; } } // array with namespace declarations private NamespaceDeclaration[] _nsdecls; // index of last declaration private int _lastDecl = 0; // name table private XmlNameTable _nameTable; // ID (depth) of the current scope private int _scopeId; // hash table for faster lookup when there is lots of namespaces private Dictionary<string, int> _hashTable; private bool _useHashtable; // atomized prefixes for "xml" and "xmlns" private string _xml; private string _xmlNs; // Constants private const int MinDeclsCountForHashtable = 16; internal static IXmlNamespaceResolver EmptyResolver { get { if (s_EmptyResolver == null) { // no locking; the empty resolver is immutable so it's not a problem that it may get initialized more than once s_EmptyResolver = new XmlNamespaceManager(new NameTable()); } return s_EmptyResolver; } } internal XmlNamespaceManager() { } public XmlNamespaceManager(XmlNameTable nameTable) { _nameTable = nameTable; _xml = nameTable.Add("xml"); _xmlNs = nameTable.Add("xmlns"); _nsdecls = new NamespaceDeclaration[8]; string emptyStr = nameTable.Add(string.Empty); _nsdecls[0].Set(emptyStr, emptyStr, -1, -1); _nsdecls[1].Set(_xmlNs, nameTable.Add(XmlReservedNs.NsXmlNs), -1, -1); _nsdecls[2].Set(_xml, nameTable.Add(XmlReservedNs.NsXml), 0, -1); _lastDecl = 2; _scopeId = 1; } public virtual XmlNameTable NameTable { get { return _nameTable; } } public virtual string DefaultNamespace { get { string defaultNs = LookupNamespace(string.Empty); return (defaultNs == null) ? string.Empty : defaultNs; } } public virtual void PushScope() { _scopeId++; } public virtual bool PopScope() { int decl = _lastDecl; if (_scopeId == 1) { return false; } while (_nsdecls[decl].scopeId == _scopeId) { if (_useHashtable) { _hashTable[_nsdecls[decl].prefix] = _nsdecls[decl].previousNsIndex; } decl--; Debug.Assert(decl >= 2); } _lastDecl = decl; _scopeId--; return true; } public virtual void AddNamespace(string prefix, string uri) { if (uri == null) throw new ArgumentNullException("uri"); if (prefix == null) throw new ArgumentNullException("prefix"); prefix = _nameTable.Add(prefix); uri = _nameTable.Add(uri); if ((Ref.Equal(_xml, prefix) && !uri.Equals(XmlReservedNs.NsXml))) { throw new ArgumentException(ResXml.Xml_XmlPrefix); } if (Ref.Equal(_xmlNs, prefix)) { throw new ArgumentException(ResXml.Xml_XmlnsPrefix); } int declIndex = LookupNamespaceDecl(prefix); int previousDeclIndex = -1; if (declIndex != -1) { if (_nsdecls[declIndex].scopeId == _scopeId) { // redefine if in the same scope _nsdecls[declIndex].uri = uri; return; } else { // othewise link previousDeclIndex = declIndex; } } // set new namespace declaration if (_lastDecl == _nsdecls.Length - 1) { NamespaceDeclaration[] newNsdecls = new NamespaceDeclaration[_nsdecls.Length * 2]; Array.Copy(_nsdecls, 0, newNsdecls, 0, _nsdecls.Length); _nsdecls = newNsdecls; } _nsdecls[++_lastDecl].Set(prefix, uri, _scopeId, previousDeclIndex); // add to hashTable if (_useHashtable) { _hashTable[prefix] = _lastDecl; } // or create a new hashTable if the threashold has been reached else if (_lastDecl >= MinDeclsCountForHashtable) { // add all to hash table Debug.Assert(_hashTable == null); _hashTable = new Dictionary<string, int>(_lastDecl); for (int i = 0; i <= _lastDecl; i++) { _hashTable[_nsdecls[i].prefix] = i; } _useHashtable = true; } } public virtual void RemoveNamespace(string prefix, string uri) { if (uri == null) { throw new ArgumentNullException("uri"); } if (prefix == null) { throw new ArgumentNullException("prefix"); } int declIndex = LookupNamespaceDecl(prefix); while (declIndex != -1) { if (String.Equals(_nsdecls[declIndex].uri, uri) && _nsdecls[declIndex].scopeId == _scopeId) { _nsdecls[declIndex].uri = null; } declIndex = _nsdecls[declIndex].previousNsIndex; } } public virtual IEnumerator GetEnumerator() { Dictionary<string, string> prefixes = new Dictionary<string, string>(_lastDecl + 1); for (int thisDecl = 0; thisDecl <= _lastDecl; thisDecl++) { if (_nsdecls[thisDecl].uri != null) { prefixes[_nsdecls[thisDecl].prefix] = _nsdecls[thisDecl].prefix; } } return prefixes.Keys.GetEnumerator(); } // This pragma disables a warning that the return type is not CLS-compliant, but generics are part of CLS in Whidbey. #pragma warning disable 3002 public virtual IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { #pragma warning restore 3002 int i = 0; switch (scope) { case XmlNamespaceScope.All: i = 2; break; case XmlNamespaceScope.ExcludeXml: i = 3; break; case XmlNamespaceScope.Local: i = _lastDecl; while (_nsdecls[i].scopeId == _scopeId) { i--; Debug.Assert(i >= 2); } i++; break; } Dictionary<string, string> dict = new Dictionary<string, string>(_lastDecl - i + 1); for (; i <= _lastDecl; i++) { string prefix = _nsdecls[i].prefix; string uri = _nsdecls[i].uri; Debug.Assert(prefix != null); if (uri != null) { if (uri.Length > 0 || prefix.Length > 0 || scope == XmlNamespaceScope.Local) { dict[prefix] = uri; } else { // default namespace redeclared to "" -> remove from list for all scopes other than local dict.Remove(prefix); } } } return dict; } public virtual string LookupNamespace(string prefix) { int declIndex = LookupNamespaceDecl(prefix); return (declIndex == -1) ? null : _nsdecls[declIndex].uri; } private int LookupNamespaceDecl(string prefix) { if (_useHashtable) { int declIndex; if (_hashTable.TryGetValue(prefix, out declIndex)) { while (declIndex != -1 && _nsdecls[declIndex].uri == null) { declIndex = _nsdecls[declIndex].previousNsIndex; } return declIndex; } return -1; } else { // First assume that prefix is atomized for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--) { if ((object)_nsdecls[thisDecl].prefix == (object)prefix && _nsdecls[thisDecl].uri != null) { return thisDecl; } } // Non-atomized lookup for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--) { if (String.Equals(_nsdecls[thisDecl].prefix, prefix) && _nsdecls[thisDecl].uri != null) { return thisDecl; } } } return -1; } public virtual string LookupPrefix(string uri) { // Don't assume that prefix is atomized for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--) { if (String.Equals(_nsdecls[thisDecl].uri, uri)) { string prefix = _nsdecls[thisDecl].prefix; if (String.Equals(LookupNamespace(prefix), uri)) { return prefix; } } } return null; } public virtual bool HasNamespace(string prefix) { // Don't assume that prefix is atomized for (int thisDecl = _lastDecl; _nsdecls[thisDecl].scopeId == _scopeId; thisDecl--) { if (String.Equals(_nsdecls[thisDecl].prefix, prefix) && _nsdecls[thisDecl].uri != null) { if (prefix.Length > 0 || _nsdecls[thisDecl].uri.Length > 0) { return true; } return false; } } return false; } internal bool GetNamespaceDeclaration(int idx, out string prefix, out string uri) { idx = _lastDecl - idx; if (idx < 0) { prefix = uri = null; return false; } prefix = _nsdecls[idx].prefix; uri = _nsdecls[idx].uri; return true; } } //XmlNamespaceManager }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WebApiAngularJsUploader.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System.Collections.Generic; using UnityEngine; namespace Chronos { public class RewindableParticleSystemTimeline : ComponentTimeline<ParticleSystem>, IParticleSystemTimeline { #region Fields private float absoluteSimulationTime; private float loopedSimulationTime; private float relativeStartTime; #endregion #region Properties public float playbackSpeed { get; set; } public float time { get { return (loopedSimulationTime - relativeStartTime) % component.duration; } set { loopedSimulationTime = relativeStartTime + value; } } public bool isPlaying { get { return state == State.Playing || state == State.Stopping; } } public bool isPaused { get { return state == State.Paused; } } public bool isStopped { get { return state == State.Stopped; } } #endregion #region State and Emission private enum State { Playing, Paused, Stopping, Stopped } private enum EmissionAction { EnableEmission, DisableEmission, Play, Stop } private struct StateEvent { public State state; public float time; public StateEvent(State state, float time) { this.state = state; this.time = time; } } private struct EmissionEvent { public EmissionAction action; public float time; public EmissionEvent(EmissionAction action, float time) { this.action = action; this.time = time; } } private float stateEventsTime { get { return timeline.time; } } private float emissionEventsTime { get { return absoluteSimulationTime; } } private void RegisterState(State state) { stateEvents.Add(new StateEvent(state, stateEventsTime)); } private void RegisterEmission(EmissionAction action) { emissionEvents.Add(new EmissionEvent(action, emissionEventsTime)); } public RewindableParticleSystemTimeline(Timeline timeline) : base(timeline) { emissionEvents = new List<EmissionEvent>(); stateEvents = new List<StateEvent>(); } private List<StateEvent> stateEvents; private State stateOnStart; private List<EmissionEvent> emissionEvents; private bool enableEmissionOnStart; private State _state; private State state { get { return _state; } set { if (!AssertForwardProperty("state", Severity.Error)) return; if (_state != value) { RegisterState(value); _state = value; } } } private bool _enableEmission; public bool enableEmission { get { return _enableEmission; } set { if (!AssertForwardProperty("enableEmission", Severity.Warn)) return; if (_enableEmission && !value) { RegisterEmission(EmissionAction.DisableEmission); } else if (!_enableEmission && value) { RegisterEmission(EmissionAction.EnableEmission); } _enableEmission = value; } } #endregion #region Timeline public override void CopyProperties(ParticleSystem source) { playbackSpeed = source.playbackSpeed; stateOnStart = state = source.playOnAwake ? State.Playing : State.Stopped; enableEmissionOnStart = _enableEmission = source.enableEmission; time = 0; if (source.randomSeed == 0) { source.randomSeed = (uint) Random.Range(1, int.MaxValue); } } public override void Update() { if (timeline.timeScale < 0) { // Determine state by consuming state events if (stateEvents.Count > 0) { StateEvent lastStateEvent = stateEvents[stateEvents.Count - 1]; if (stateEventsTime <= lastStateEvent.time) { stateEvents.Remove(lastStateEvent); if (stateEvents.Count > 0) { _state = stateEvents[stateEvents.Count - 1].state; } else { _state = stateOnStart; } } } // Consume emission events for (int i = emissionEvents.Count - 1; i >= 0; i--) { if (emissionEvents[i].time > emissionEventsTime) { emissionEvents.RemoveAt(i); } } } // Known issue: low time scales / speed will cause stutter // Reported here: http://fogbugz.unity3d.com/default.asp?694191_dso514lin4rf5vbg component.Simulate(0, true, true); if (loopedSimulationTime > 0) { component.enableEmission = enableEmissionOnStart; float chunkStartTime = 0; for (int i = 0; i < emissionEvents.Count; i++) { EmissionEvent current = emissionEvents[i]; component.Simulate(current.time - chunkStartTime, true, false); component.enableEmission = current.action == EmissionAction.Play || current.action == EmissionAction.EnableEmission; chunkStartTime = current.time; } component.Simulate(loopedSimulationTime - chunkStartTime, true, false); if (state == State.Stopping && component.particleCount == 0 && timeline.timeScale > 0) { state = State.Stopped; } } if (state == State.Playing || state == State.Stopping) { absoluteSimulationTime += timeline.deltaTime * playbackSpeed; // Can be performance intensive at high times. // Limit it with a loop-multiple of its time (globally configurable) float maxLoops = Timekeeper.instance.maxParticleLoops; if (maxLoops > 0 && state != State.Stopping) { loopedSimulationTime = absoluteSimulationTime % (component.duration * maxLoops); } else { loopedSimulationTime = absoluteSimulationTime; } } } #endregion #region Methods public void Play(bool withChildren = true) { if (!AssertForwardMethod("Play", Severity.Warn)) return; if (state != State.Paused) { RegisterEmission(EmissionAction.Play); relativeStartTime = loopedSimulationTime; } state = State.Playing; if (withChildren) { ExecuteOnChildren(ps => ps.Play(false), ps => ps.Play(false)); } } public void Pause(bool withChildren = true) { if (!AssertForwardMethod("Pause", Severity.Warn)) return; state = State.Paused; if (withChildren) { ExecuteOnChildren(ps => ps.Pause(false), ps => ps.Pause(false)); } } public void Stop(bool withChildren = true) { if (!AssertForwardMethod("Stop", Severity.Warn)) return; state = State.Stopping; RegisterEmission(EmissionAction.Stop); if (withChildren) { ExecuteOnChildren(ps => ps.Stop(false), ps => ps.Stop(false)); } } public bool IsAlive(bool withChildren = true) { if (state == State.Stopped) { return false; } if (withChildren) { return CheckOnChildren(ps => ps.IsAlive(false), ps => ps.IsAlive(false)); } return true; } #endregion #region Hierarchy private delegate void ChildNativeAction(ParticleSystem target); private delegate void ChildChronosAction(IParticleSystemTimeline target); private delegate bool ChildNativeCheck(ParticleSystem target); private delegate bool ChildChronosCheck(IParticleSystemTimeline target); private void ExecuteOnChildren(ChildNativeAction native, ChildChronosAction chronos) { foreach (ParticleSystem childParticleSystem in timeline.GetComponentsInChildren<ParticleSystem>()) { if (childParticleSystem == component) { continue; } Timeline childTimeline = childParticleSystem.GetComponent<Timeline>(); if (childTimeline != null) { chronos(childTimeline.particleSystem); } else { native(childParticleSystem); } } } private bool CheckOnChildren(ChildNativeCheck native, ChildChronosCheck chronos) { foreach (ParticleSystem childParticleSystem in timeline.GetComponentsInChildren<ParticleSystem>()) { if (childParticleSystem == component) { continue; } Timeline childTimeline = childParticleSystem.GetComponent<Timeline>(); if (childTimeline != null) { if (!chronos(childTimeline.particleSystem)) { return false; } } else { if (!native(childParticleSystem)) { return false; } } } return true; } #endregion #region Utility private bool AssertForwardMethod(string method, Severity severity) { if (timeline.timeScale <= 0) { if (severity == Severity.Error) { throw new ChronosException("Cannot call " + method + " on the particle system while time is paused or rewinding."); } else if (severity == Severity.Warn) { Debug.LogWarning("Trying to call " + method + " on the particle system while time is paused or rewinding, ignoring."); } } return timeline.timeScale > 0; } private bool AssertForwardProperty(string property, Severity severity) { if (timeline.timeScale <= 0) { if (severity == Severity.Error) { throw new ChronosException("Cannot set " + property + " on the particle system while time is paused or rewinding."); } else if (severity == Severity.Warn) { Debug.LogWarning("Trying to set " + property + " on the particle system while time is paused or rewinding, ignoring."); } } return timeline.timeScale > 0; } #endregion } }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- // Smoke datablock ParticleData(Smoke) { textureName = "art/shapes/particles/smoke"; dragCoefficient = 0.3; gravityCoefficient = -0.2; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 3000; lifetimeVarianceMS = 250; useInvAlpha = true; spinRandomMin = -30.0; spinRandomMax = 30.0; sizes[0] = 1.5; sizes[1] = 2.75; sizes[2] = 6.5; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(SmokeEmitter) { ejectionPeriodMS = 400; periodVarianceMS = 5; ejectionVelocity = 0.0; velocityVariance = 0.0; thetaMin = 0.0; thetaMax = 90.0; particles = Smoke; }; datablock ParticleEmitterNodeData(SmokeEmitterNode) { timeMultiple = 1; }; // Ember datablock ParticleData(EmberParticle) { textureName = "art/shapes/particles/ember"; dragCoefficient = 0.0; windCoefficient = 0.0; gravityCoefficient = -0.05; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 5000; lifetimeVarianceMS = 0; useInvAlpha = false; spinRandomMin = -90.0; spinRandomMax = 90.0; spinSpeed = 1; colors[0] = "1.000000 0.800000 0.000000 0.800000"; colors[1] = "1.000000 0.700000 0.000000 0.800000"; colors[2] = "1.000000 0.000000 0.000000 0.200000"; sizes[0] = 0.05; sizes[1] = 0.1; sizes[2] = 0.05; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(EmberEmitter) { ejectionPeriodMS = 100; periodVarianceMS = 0; ejectionVelocity = 0.75; velocityVariance = 0.00; ejectionOffset = 2.0; thetaMin = 1.0; thetaMax = 100.0; particles = "EmberParticle"; }; datablock ParticleEmitterNodeData(EmberNode) { timeMultiple = 1; }; // Fire datablock ParticleData(FireParticle) { textureName = "art/shapes/particles/smoke"; dragCoefficient = 0.0; windCoefficient = 0.0; gravityCoefficient = -0.05; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 5000; lifetimeVarianceMS = 1000; useInvAlpha = false; spinRandomMin = -90.0; spinRandomMax = 90.0; spinSpeed = 1.0; colors[0] = "0.2 0.2 0.0 0.2"; colors[1] = "0.6 0.2 0.0 0.2"; colors[2] = "0.4 0.0 0.0 0.1"; colors[3] = "0.1 0.04 0.0 0.3"; sizes[0] = 0.5; sizes[1] = 4.0; sizes[2] = 5.0; sizes[3] = 6.0; times[0] = 0.0; times[1] = 0.1; times[2] = 0.2; times[3] = 0.3; }; datablock ParticleEmitterData(FireEmitter) { ejectionPeriodMS = 50; periodVarianceMS = 0; ejectionVelocity = 0.55; velocityVariance = 0.00; ejectionOffset = 1.0; thetaMin = 1.0; thetaMax = 100.0; particles = "FireParticle"; }; datablock ParticleEmitterNodeData(FireNode) { timeMultiple = 1; }; // Torch Fire datablock ParticleData(TorchFire1) { textureName = "art/shapes/particles/smoke"; dragCoefficient = 0.0; gravityCoefficient = -0.3; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 500; lifetimeVarianceMS = 250; useInvAlpha = false; spinRandomMin = -30.0; spinRandomMax = 30.0; spinSpeed = 1; colors[0] = "0.6 0.6 0.0 0.1"; colors[1] = "0.8 0.6 0.0 0.1"; colors[2] = "0.0 0.0 0.0 0.1"; sizes[0] = 0.5; sizes[1] = 0.5; sizes[2] = 2.4; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleData(TorchFire2) { textureName = "art/shapes/particles/smoke"; dragCoefficient = 0.0; gravityCoefficient = -0.5; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 800; lifetimeVarianceMS = 150; useInvAlpha = false; spinRandomMin = -30.0; spinRandomMax = 30.0; spinSpeed = 1; colors[0] = "0.8 0.6 0.0 0.1"; colors[1] = "0.6 0.6 0.0 0.1"; colors[2] = "0.0 0.0 0.0 0.1"; sizes[0] = 0.3; sizes[1] = 0.3; sizes[2] = 0.3; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(TorchFireEmitter) { ejectionPeriodMS = 15; periodVarianceMS = 5; ejectionVelocity = 0.25; velocityVariance = 0.10; thetaMin = 0.0; thetaMax = 45.0; particles = "TorchFire1" TAB "TorchFire2"; }; datablock ParticleEmitterNodeData(TorchFireEmitterNode) { timeMultiple = 1; };
namespace EIDSS.Reports.Document.Lim.Batch { partial class BatchTestReport { #region 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(BatchTestReport)); this.DetailReportBatch = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailBatch = new DevExpress.XtraReports.UI.DetailBand(); this.ReportHeaderBatch = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.DetailReport1 = new DevExpress.XtraReports.UI.DetailReportBand(); this.Detail2 = new DevExpress.XtraReports.UI.DetailBand(); this.clinicalSignsLabel = new DevExpress.XtraReports.UI.XRLabel(); this.BatchFlexSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.DetailReport3 = new DevExpress.XtraReports.UI.DetailReportBand(); this.Detail4 = new DevExpress.XtraReports.UI.DetailBand(); this.TestDetailSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.m_TestDetailsReport = new EIDSS.Reports.Document.Lim.Batch.TestDetailsReport(); this.spRepLimBatchTestTableAdapter1 = new EIDSS.Reports.Document.Lim.Batch.BatchTestDataSetTableAdapters.spRepLimBatchTestTableAdapter(); this.batchDataSet1 = new EIDSS.Reports.Document.Lim.Batch.BatchTestDataSet(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrCrossBandBox1 = new DevExpress.XtraReports.UI.XRCrossBandBox(); ((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_TestDetailsReport)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.batchDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // resources.ApplyResources(this.cellLanguage, "cellLanguage"); this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // resources.ApplyResources(this.Detail, "Detail"); this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // resources.ApplyResources(this.ReportHeader, "ReportHeader"); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; // // cellBaseSite // resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; // // cellBaseCountry // resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry"); // // cellBaseLeftHeader // resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // DetailReportBatch // this.DetailReportBatch.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailBatch, this.ReportHeaderBatch, this.DetailReport1}); this.DetailReportBatch.DataAdapter = this.spRepLimBatchTestTableAdapter1; this.DetailReportBatch.DataMember = "spRepLimBatchTest"; this.DetailReportBatch.DataSource = this.batchDataSet1; resources.ApplyResources(this.DetailReportBatch, "DetailReportBatch"); this.DetailReportBatch.Level = 0; this.DetailReportBatch.Name = "DetailReportBatch"; this.DetailReportBatch.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); // // DetailBatch // resources.ApplyResources(this.DetailBatch, "DetailBatch"); this.DetailBatch.Expanded = false; this.DetailBatch.Name = "DetailBatch"; // // ReportHeaderBatch // this.ReportHeaderBatch.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); resources.ApplyResources(this.ReportHeaderBatch, "ReportHeaderBatch"); this.ReportHeaderBatch.Name = "ReportHeaderBatch"; this.ReportHeaderBatch.StylePriority.UseTextAlignment = false; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow2, this.xrTableRow3, this.xrTableRow5, this.xrTableRow10}); // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1, this.xrTableCell4, this.xrTableCell2, this.xrTableCell3}); resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Weight = 1D; // // xrTableCell1 // resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.Weight = 0.77548387096774185D; // // xrTableCell4 // this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.TestName")}); resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.Weight = 0.77483870967741941D; // // xrTableCell2 // resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Name = "xrTableCell2"; this.xrTableCell2.Weight = 0.67806451612903229D; // // xrTableCell3 // this.xrTableCell3.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.BatchTestID", "*{0}*")}); resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.StylePriority.UseFont = false; this.xrTableCell3.StylePriority.UseTextAlignment = false; this.xrTableCell3.Weight = 0.77161290322580645D; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell5, this.xrTableCell6, this.xrTableCell7, this.xrTableCell8}); resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); this.xrTableRow2.Name = "xrTableRow2"; this.xrTableRow2.Weight = 0.80722891566265065D; // // xrTableCell5 // resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.Weight = 0.77548387096774185D; // // xrTableCell6 // this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.LocationPerformed")}); resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.Weight = 0.77483870967741941D; // // xrTableCell7 // resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.Weight = 0.67806451612903229D; // // xrTableCell8 // this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.BatchTestID")}); resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseTextAlignment = false; this.xrTableCell8.Weight = 0.77161290322580645D; // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell9, this.xrTableCell10, this.xrTableCell11, this.xrTableCell12}); resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); this.xrTableRow3.Name = "xrTableRow3"; this.xrTableRow3.Weight = 0.4199018295403838D; // // xrTableCell9 // resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.Weight = 0.77548387096774185D; // // xrTableCell10 // resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.Weight = 0.77483870967741941D; // // xrTableCell11 // resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); this.xrTableCell11.Name = "xrTableCell11"; this.xrTableCell11.Weight = 0.67806451612903229D; // // xrTableCell12 // resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.Weight = 0.77161290322580645D; // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell17, this.xrTableCell18, this.xrTableCell19, this.xrTableCell20}); resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); this.xrTableRow5.Name = "xrTableRow5"; this.xrTableRow5.Weight = 0.78086081700539545D; // // xrTableCell17 // resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); this.xrTableCell17.Name = "xrTableCell17"; this.xrTableCell17.Weight = 0.77548387096774185D; // // xrTableCell18 // this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.ValidatedByName")}); resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); this.xrTableCell18.Name = "xrTableCell18"; this.xrTableCell18.Weight = 0.77483870967741941D; // // xrTableCell19 // resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); this.xrTableCell19.Name = "xrTableCell19"; this.xrTableCell19.Weight = 0.82725820233744962D; // // xrTableCell20 // this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.TestedDate", "{0:dd/MM/yyyy}")}); resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); this.xrTableCell20.Name = "xrTableCell20"; this.xrTableCell20.Weight = 0.62241921701738911D; // // xrTableRow10 // this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell21, this.xrTableCell22, this.xrTableCell23, this.xrTableCell24}); resources.ApplyResources(this.xrTableRow10, "xrTableRow10"); this.xrTableRow10.Name = "xrTableRow10"; this.xrTableRow10.Weight = 0.78086081700539545D; // // xrTableCell21 // resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); this.xrTableCell21.Name = "xrTableCell21"; this.xrTableCell21.Weight = 0.77548387096774185D; // // xrTableCell22 // this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.TestedByName")}); resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); this.xrTableCell22.Name = "xrTableCell22"; this.xrTableCell22.Weight = 0.77483870967741941D; // // xrTableCell23 // resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); this.xrTableCell23.Name = "xrTableCell23"; this.xrTableCell23.Weight = 0.82725820233744962D; // // xrTableCell24 // this.xrTableCell24.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.datValidatedDate", "{0:dd/MM/yyyy}")}); resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); this.xrTableCell24.Name = "xrTableCell24"; this.xrTableCell24.Weight = 0.62241921701738911D; // // DetailReport1 // this.DetailReport1.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail2, this.DetailReport3}); resources.ApplyResources(this.DetailReport1, "DetailReport1"); this.DetailReport1.Level = 0; this.DetailReport1.Name = "DetailReport1"; // // Detail2 // this.Detail2.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.clinicalSignsLabel, this.BatchFlexSubreport}); resources.ApplyResources(this.Detail2, "Detail2"); this.Detail2.Name = "Detail2"; // // clinicalSignsLabel // resources.ApplyResources(this.clinicalSignsLabel, "clinicalSignsLabel"); this.clinicalSignsLabel.Multiline = true; this.clinicalSignsLabel.Name = "clinicalSignsLabel"; this.clinicalSignsLabel.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.clinicalSignsLabel.StylePriority.UseFont = false; this.clinicalSignsLabel.StylePriority.UseTextAlignment = false; // // BatchFlexSubreport // resources.ApplyResources(this.BatchFlexSubreport, "BatchFlexSubreport"); this.BatchFlexSubreport.Name = "BatchFlexSubreport"; // // DetailReport3 // this.DetailReport3.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail4}); resources.ApplyResources(this.DetailReport3, "DetailReport3"); this.DetailReport3.Level = 0; this.DetailReport3.Name = "DetailReport3"; // // Detail4 // this.Detail4.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.TestDetailSubreport}); resources.ApplyResources(this.Detail4, "Detail4"); this.Detail4.Name = "Detail4"; // // TestDetailSubreport // resources.ApplyResources(this.TestDetailSubreport, "TestDetailSubreport"); this.TestDetailSubreport.Name = "TestDetailSubreport"; this.TestDetailSubreport.ReportSource = this.m_TestDetailsReport; // // spRepLimBatchTestTableAdapter1 // this.spRepLimBatchTestTableAdapter1.ClearBeforeFill = true; // // batchDataSet1 // this.batchDataSet1.DataSetName = "BatchDataSet"; this.batchDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell13, this.xrTableCell14, this.xrTableCell15, this.xrTableCell16}); resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); this.xrTableRow4.Name = "xrTableRow4"; this.xrTableRow4.Weight = 0.78086081700539545D; // // xrTableCell13 // resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.Weight = 0.77548387096774185D; // // xrTableCell14 // this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.TestedByName")}); resources.ApplyResources(this.xrTableCell14, "xrTableCell14"); this.xrTableCell14.Name = "xrTableCell14"; this.xrTableCell14.Weight = 0.77483870967741941D; // // xrTableCell15 // resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); this.xrTableCell15.Name = "xrTableCell15"; this.xrTableCell15.Weight = 0.67806451612903229D; // // xrTableCell16 // this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimBatchTest.TestedDate", "{0:dd/MM/yyyy}")}); resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); this.xrTableCell16.Name = "xrTableCell16"; this.xrTableCell16.Weight = 0.77161290322580645D; // // xrCrossBandBox1 // this.xrCrossBandBox1.BorderWidth = 1; resources.ApplyResources(this.xrCrossBandBox1, "xrCrossBandBox1"); this.xrCrossBandBox1.EndBand = this.Detail2; this.xrCrossBandBox1.Name = "xrCrossBandBox1"; this.xrCrossBandBox1.StartBand = this.Detail2; this.xrCrossBandBox1.WidthF = 773.8269F; // // BatchTestReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.DetailReportBatch}); this.CrossBandControls.AddRange(new DevExpress.XtraReports.UI.XRCrossBandControl[] { this.xrCrossBandBox1}); resources.ApplyResources(this, "$this"); this.Version = "11.1"; this.Controls.SetChildIndex(this.DetailReportBatch, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_TestDetailsReport)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.batchDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand DetailReportBatch; private DevExpress.XtraReports.UI.DetailBand DetailBatch; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeaderBatch; private BatchTestDataSetTableAdapters.spRepLimBatchTestTableAdapter spRepLimBatchTestTableAdapter1; private BatchTestDataSet batchDataSet1; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRSubreport BatchFlexSubreport; private DevExpress.XtraReports.UI.XRSubreport TestDetailSubreport; private TestDetailsReport m_TestDetailsReport; private DevExpress.XtraReports.UI.XRTableRow xrTableRow10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRLabel clinicalSignsLabel; private DevExpress.XtraReports.UI.XRCrossBandBox xrCrossBandBox1; private DevExpress.XtraReports.UI.DetailReportBand DetailReport1; private DevExpress.XtraReports.UI.DetailBand Detail2; private DevExpress.XtraReports.UI.DetailReportBand DetailReport3; private DevExpress.XtraReports.UI.DetailBand Detail4; } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Signum.Entities; using Signum.Utilities; using Signum.Utilities.Reflection; using Signum.Utilities.ExpressionTrees; using Signum.Entities.Reflection; using System.Linq.Expressions; using Signum.Engine.Linq; using Signum.Entities.Basics; using Signum.Engine.Basics; using Signum.Utilities.DataStructures; using System.Threading; namespace Signum.Engine.Maps { public class SchemaBuilder { Schema schema; public SchemaSettings Settings { get { return schema.Settings; } } public SchemaBuilder(bool isDefault) { schema = new Schema(new SchemaSettings()); if (isDefault) { if (TypeEntity.AlreadySet) throw new InvalidOperationException("Only one default SchemaBuilder per application allowed"); TypeEntity.SetTypeNameCallbacks( t => schema.TypeToName.GetOrThrow(t, "Type {0} not found in the schema"), cleanName => schema.NameToType.TryGetC(cleanName)); FromEnumMethodExpander.miQuery = ReflectionTools.GetMethodInfo(() => Database.Query<Entity>()).GetGenericMethodDefinition(); } Settings.AssertNotIncluded = MixinDeclarations.AssertNotIncluded = t => { if (schema.Tables.ContainsKey(t)) throw new InvalidOperationException("{0} is already included in the Schema".FormatWith(t.TypeName())); }; } protected SchemaBuilder(Schema schema) { this.schema = schema; } public SchemaBuilder(SchemaSettings settings) { schema = new Schema(settings); } public Schema Schema { get { return schema; } } public UniqueTableIndex AddUniqueIndex<T>(Expression<Func<T, object?>> fields, Expression<Func<T, bool>>? where = null, Expression<Func<T, object?>>? includeFields = null) where T : Entity { var table = Schema.Table<T>(); IColumn[] columns = IndexKeyColumns.Split(table, fields); var index = AddUniqueIndex(table, columns); if (where != null) index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table); if (includeFields != null) { index.IncludeColumns = IndexKeyColumns.Split(table, includeFields); if (table.SystemVersioned != null) { index.IncludeColumns = index.IncludeColumns.Concat(table.SystemVersioned.Columns()).ToArray(); } } return index; } public TableIndex AddIndex<T>(Expression<Func<T, object?>> fields, Expression<Func<T, bool>>? where = null, Expression<Func<T, object>>? includeFields = null) where T : Entity { var table = Schema.Table<T>(); IColumn[] columns = IndexKeyColumns.Split(table, fields); var index = new TableIndex(table, columns); if (where != null) index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table); if (includeFields != null) { index.IncludeColumns = IndexKeyColumns.Split(table, includeFields); if (table.SystemVersioned != null) { index.IncludeColumns = index.IncludeColumns.Concat(table.SystemVersioned.Columns()).ToArray(); } } AddIndex(index); return index; } public UniqueTableIndex AddUniqueIndexMList<T, V>(Expression<Func<T, MList<V>>> toMList, Expression<Func<MListElement<T, V>, object>> fields, Expression<Func<MListElement<T, V>, bool>>? where = null, Expression<Func<MListElement<T, V>, object>>? includeFields = null) where T : Entity { TableMList table = ((FieldMList)Schema.FindField(Schema.Table(typeof(T)), Reflector.GetMemberList(toMList))).TableMList; IColumn[] columns = IndexKeyColumns.Split(table, fields); var index = AddUniqueIndex(table, columns); if (where != null) index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table); if (includeFields != null) { index.IncludeColumns = IndexKeyColumns.Split(table, includeFields); if (table.SystemVersioned != null) { index.IncludeColumns = index.IncludeColumns.Concat(table.SystemVersioned.Columns()).ToArray(); } } return index; } public TableIndex AddIndexMList<T, V>(Expression<Func<T, MList<V>>> toMList, Expression<Func<MListElement<T, V>, object>> fields, Expression<Func<MListElement<T, V>, bool>>? where = null, Expression<Func<MListElement<T, V>, object>>? includeFields = null) where T : Entity { TableMList table = ((FieldMList)Schema.FindField(Schema.Table(typeof(T)), Reflector.GetMemberList(toMList))).TableMList; IColumn[] columns = IndexKeyColumns.Split(table, fields); var index = AddIndex(table, columns); if (where != null) index.Where = IndexWhereExpressionVisitor.GetIndexWhere(where, table); if (includeFields != null) { index.IncludeColumns = IndexKeyColumns.Split(table, includeFields); if (table.SystemVersioned != null) { index.IncludeColumns = index.IncludeColumns.Concat(table.SystemVersioned.Columns()).ToArray(); } } return index; } public UniqueTableIndex AddUniqueIndex(ITable table, Field[] fields) { var index = new UniqueTableIndex(table, TableIndex.GetColumnsFromFields(fields)); AddIndex(index); return index; } public UniqueTableIndex AddUniqueIndex(ITable table, IColumn[] columns) { var index = new UniqueTableIndex(table, columns); AddIndex(index); return index; } public TableIndex AddIndex(ITable table, Field[] fields) { var index = new TableIndex(table, TableIndex.GetColumnsFromFields(fields)); AddIndex(index); return index; } public TableIndex AddIndex(ITable table, IColumn[] columns) { var index = new TableIndex(table, columns); AddIndex(index); return index; } public void AddIndex(TableIndex index) { ITable table = index.Table; if (table.MultiColumnIndexes == null) table.MultiColumnIndexes = new List<TableIndex>(); table.MultiColumnIndexes.Add(index); } public FluentInclude<T> Include<T>() where T : Entity { var table = Include(typeof(T), null); return new FluentInclude<T>(table, this); } public virtual Table Include(Type type) { return Include(type, null); } internal protected virtual Table Include(Type type, PropertyRoute? route) { if (schema.Tables.TryGetValue(type, out var result)) return result; using (HeavyProfiler.LogNoStackTrace("Include", () => type.TypeName())) { if (type.IsAbstract) throw new InvalidOperationException(ErrorIncluding(route) + $"Impossible to include in the Schema the type {type} because is abstract"); if (!Reflector.IsEntity(type)) throw new InvalidOperationException(ErrorIncluding(route) + $"Impossible to include in the Schema the type {type} because is not and Entity"); foreach (var t in type.Follow(a => a.BaseType)) if (!t.IsSerializable) throw new InvalidOperationException(ErrorIncluding(route) + $"Type {t.TypeName()} is not marked as serializable"); string cleanName = schema.Settings.desambiguatedNames?.TryGetC(type) ?? Reflector.CleanTypeName(EnumEntity.Extract(type) ?? type); if (schema.NameToType.ContainsKey(cleanName)) throw new InvalidOperationException(ErrorIncluding(route) + @$"Two types have the same cleanName '{cleanName}', desambiguate using Schema.Current.Settings.Desambiguate method: {schema.NameToType[cleanName].FullName} {type.FullName}"); try { result = new Table(type); schema.Tables.Add(type, result); schema.NameToType[cleanName] = type; schema.TypeToName[type] = cleanName; Complete(result); return result; } catch (Exception) //Avoid half-cooked tables { schema.Tables.Remove(type); schema.NameToType.Remove(cleanName); schema.TypeToName.Remove(type); throw; } } } private static string? ErrorIncluding(PropertyRoute? route) { return route?.Let(r => $"Error including {r}: "); } void Complete(Table table) { using (HeavyProfiler.LogNoStackTrace("Complete", () => table.Type.Name)) using (var tr = HeavyProfiler.LogNoStackTrace("GetPrimaryKeyAttribute", () => table.Type.Name)) { Type type = table.Type; table.IdentityBehaviour = GetPrimaryKeyAttribute(type).IdentityBehaviour; tr.Switch("GenerateTableName"); table.Name = GenerateTableName(type, Settings.TypeAttribute<TableNameAttribute>(type)); tr.Switch("GenerateCleanTypeName"); table.CleanTypeName = GenerateCleanTypeName(type); tr.Switch("GenerateFields"); table.Fields = GenerateFields(PropertyRoute.Root(type), table, NameSequence.Void, forceNull: false, inMList: false); tr.Switch("GenerateMixins"); table.Mixins = GenerateMixins(PropertyRoute.Root(type), table, NameSequence.Void); tr.Switch("GenerateTemporal"); table.SystemVersioned = ToSystemVersionedInfo(Settings.TypeAttribute<SystemVersionedAttribute>(type), table.Name); tr.Switch("GenerateColumns"); table.GenerateColumns(); } } public SystemVersionedInfo? ToSystemVersionedInfo(SystemVersionedAttribute? att, ObjectName tableName) { if (att == null) return null; var isPostgres = this.schema.Settings.IsPostgres; var tn = att.TemporalTableName != null ? ObjectName.Parse(att.TemporalTableName, isPostgres) : new ObjectName(tableName.Schema, tableName.Name + "_History", isPostgres); if (isPostgres) return new SystemVersionedInfo(tn, att.PostgreeSysPeriodColumname); return new SystemVersionedInfo(tn, att.StartDateColumnName, att.EndDateColumnName); } private Dictionary<Type, FieldMixin>? GenerateMixins(PropertyRoute propertyRoute, ITable table, NameSequence nameSequence) { Dictionary<Type, FieldMixin>? mixins = null; foreach (var t in MixinDeclarations.GetMixinDeclarations(propertyRoute.Type)) { if (mixins == null) mixins = new Dictionary<Type, FieldMixin>(); mixins.Add(t, this.GenerateFieldMixin(propertyRoute.Add(t), nameSequence, table)); } return mixins; } public HeavyProfiler.Tracer? Tracer { get; set; } public HashSet<(Type type, string method)> LoadedModules = new HashSet<(Type type, string method)>(); public bool NotDefined(MethodBase? methodBase) { this.Tracer.Switch(methodBase!.DeclaringType!.Name); var methods = methodBase.DeclaringType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Where(m => !m.HasAttribute<MethodExpanderAttribute>()) .Select(m => m.GetCustomAttribute<ExpressionFieldAttribute>()?.Name) .NotNull() .ToHashSet(); var fields = methodBase.DeclaringType.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Where(f => f.Name.EndsWith("Expression") && f.FieldType.IsInstantiationOf(typeof(Expression<>))); foreach (var f in fields) { if (!methods.Contains(f.Name)) throw new InvalidOperationException($"No Method found for expression '{f.Name}' in '{methodBase.DeclaringType.Name}'"); } return LoadedModules.Add((type: methodBase.DeclaringType, method: methodBase.Name)); } public void AssertDefined(MethodBase methodBase) { var tulpe = (methodBase.DeclaringType!, methodBase.Name); if (!LoadedModules.Contains(tulpe)) throw new ApplicationException("Call {0} first".FormatWith(tulpe)); } #region Field Generator protected Dictionary<string, EntityField> GenerateFields(PropertyRoute root, ITable table, NameSequence preName, bool forceNull, bool inMList) { using (HeavyProfiler.LogNoStackTrace("SB.GenerateFields", () => root.ToString())) { Dictionary<string, EntityField> result = new Dictionary<string, EntityField>(); var type = root.Type; if (type.IsEntity()) { { PropertyRoute route = root.Add(fiId); Field field = GenerateField(table, route, preName, forceNull, inMList); result.Add(fiId.Name, new EntityField(type, fiId, field)); } TicksColumnAttribute? t = type.GetCustomAttribute<TicksColumnAttribute>(); if (t == null || t.HasTicks) { PropertyRoute route = root.Add(fiTicks); Field field = GenerateField(table, route, preName, forceNull, inMList); result.Add(fiTicks.Name, new EntityField(type, fiTicks, field)); } Expression? exp = ExpressionCleaner.GetFieldExpansion(type, EntityExpression.ToStringMethod); if (exp == null) { PropertyRoute route = root.Add(fiToStr); Field field = GenerateField(table, route, preName, forceNull, inMList); if (result.ContainsKey(fiToStr.Name)) throw new InvalidOperationException("Duplicated field with name {0} on {1}, shadowing not supported".FormatWith(fiToStr.Name, type.TypeName())); result.Add(fiToStr.Name, new EntityField(type, fiToStr, field)); } } foreach (FieldInfo fi in Reflector.InstanceFieldsInOrder(type)) { PropertyRoute route = root.Add(fi); if (Settings.FieldAttribute<IgnoreAttribute>(route) == null) { if (Reflector.TryFindPropertyInfo(fi) == null && !fi.IsPublic && !fi.HasAttribute<FieldWithoutPropertyAttribute>()) throw new InvalidOperationException("Field '{0}' of type '{1}' has no property".FormatWith(fi.Name, type.Name)); Field field = GenerateField(table, route, preName, forceNull, inMList); if (result.ContainsKey(fi.Name)) throw new InvalidOperationException("Duplicated field with name '{0}' on '{1}', shadowing not supported".FormatWith(fi.Name, type.TypeName())); var ef = new EntityField(type, fi, field); if (field is FieldMList fml) fml.TableMList.PropertyRoute = route; result.Add(fi.Name, ef); } } return result; } } static readonly FieldInfo fiToStr = ReflectionTools.GetFieldInfo((Entity o) => o.toStr); static readonly FieldInfo fiTicks = ReflectionTools.GetFieldInfo((Entity o) => o.ticks); static readonly FieldInfo fiId = ReflectionTools.GetFieldInfo((Entity o) => o.id); protected virtual Field GenerateField(ITable table, PropertyRoute route, NameSequence preName, bool forceNull, bool inMList) { using (HeavyProfiler.LogNoStackTrace("GenerateField", () => route.ToString())) { KindOfField kof = GetKindOfField(route); if (kof == KindOfField.MList && inMList) throw new InvalidOperationException("Field {0} of type {1} can not be nested in another MList".FormatWith(route, route.Type.TypeName(), kof)); //field name generation NameSequence name; ColumnNameAttribute? vc = Settings.FieldAttribute<ColumnNameAttribute>(route); if (vc != null && vc.Name.HasText()) name = NameSequence.Void.Add(vc.Name); else if (route.PropertyRouteType != PropertyRouteType.MListItems) name = preName.Add(GenerateFieldName(route, kof)); else if (kof == KindOfField.Enum || kof == KindOfField.Reference) name = preName.Add(GenerateMListFieldName(route, kof)); else name = preName; switch (kof) { case KindOfField.PrimaryKey: return GenerateFieldPrimaryKey((Table)table, route, name); case KindOfField.Ticks: return GenerateFieldTicks((Table)table, route, name); case KindOfField.Value: return GenerateFieldValue(table, route, name, forceNull); case KindOfField.Reference: { Implementations at = Settings.GetImplementations(route); if (at.IsByAll) return GenerateFieldImplementedByAll(route, table, name, forceNull); else if (at.Types.Only() == route.Type.CleanType()) return GenerateFieldReference(table, route, name, forceNull); else return GenerateFieldImplementedBy(table, route, name, forceNull, at.Types); } case KindOfField.Enum: return GenerateFieldEnum(table, route, name, forceNull); case KindOfField.Embedded: return GenerateFieldEmbedded(table, route, name, forceNull, inMList); case KindOfField.MList: return GenerateFieldMList((Table)table, route, name); default: throw new NotSupportedException(EngineMessage.NoWayOfMappingType0Found.NiceToString().FormatWith(route.Type)); } } } public enum KindOfField { PrimaryKey, Ticks, Value, Reference, Enum, Embedded, MList, } protected virtual KindOfField GetKindOfField(PropertyRoute route) { if (route.FieldInfo != null && ReflectionTools.FieldEquals(route.FieldInfo, fiId)) return KindOfField.PrimaryKey; if (route.FieldInfo != null && ReflectionTools.FieldEquals(route.FieldInfo, fiTicks)) return KindOfField.Ticks; if (Settings.TryGetSqlDbType(Settings.FieldAttribute<DbTypeAttribute>(route), route.Type) != null) return KindOfField.Value; if (route.Type.UnNullify().IsEnum) return KindOfField.Enum; if (Reflector.IsIEntity(Lite.Extract(route.Type) ?? route.Type)) return KindOfField.Reference; if (Reflector.IsEmbeddedEntity(route.Type)) return KindOfField.Embedded; if (Reflector.IsMList(route.Type)) return KindOfField.MList; if (Settings.IsPostgres && route.Type.IsArray) { if (Settings.TryGetSqlDbType(Settings.FieldAttribute<DbTypeAttribute>(route), route.Type.ElementType()!) != null) return KindOfField.Value; } throw new InvalidOperationException($"Field {route} of type {route.Type.Name} has no database representation"); } protected virtual Field GenerateFieldPrimaryKey(Table table, PropertyRoute route, NameSequence name) { var attr = GetPrimaryKeyAttribute(table.Type); PrimaryKey.PrimaryKeyType.SetDefinition(table.Type, attr.Type); DbTypePair pair = Settings.GetSqlDbType(attr, attr.Type); return table.PrimaryKey = new FieldPrimaryKey(route, table, attr.Name, attr.Type) { DbType = pair.DbType, Collation = Settings.GetCollate(attr), UserDefinedTypeName = pair.UserDefinedTypeName, Default = attr.GetDefault(Settings.IsPostgres), Identity = attr.Identity, Size = attr.HasSize ? attr.Size : (int?)null, }; } private PrimaryKeyAttribute GetPrimaryKeyAttribute(Type type) { var attr = Settings.TypeAttribute<PrimaryKeyAttribute>(type); if (attr != null) return attr; if (type.IsEnumEntity()) return new PrimaryKeyAttribute(Enum.GetUnderlyingType(type.GetGenericArguments().Single())) { Identity = false, IdentityBehaviour = false }; return Settings.DefaultPrimaryKeyAttribute; } protected virtual FieldValue GenerateFieldTicks(Table table, PropertyRoute route, NameSequence name) { var ticksAttr = Settings.TypeAttribute<TicksColumnAttribute>(table.Type); if (ticksAttr != null && !ticksAttr.HasTicks) throw new InvalidOperationException("HastTicks is false"); Type type = ticksAttr?.Type ?? route.Type; DbTypePair pair = Settings.GetSqlDbType(ticksAttr, type); string ticksName = ticksAttr?.Name ?? name.ToString(); return table.Ticks = new FieldTicks(route, type, ticksName) { DbType = pair.DbType, Collation = Settings.GetCollate(ticksAttr), UserDefinedTypeName = pair.UserDefinedTypeName, Nullable = IsNullable.No, Size = Settings.GetSqlSize(ticksAttr, null, pair.DbType), Scale = Settings.GetSqlScale(ticksAttr, null, pair.DbType), Default = ticksAttr?.GetDefault(Settings.IsPostgres), }; } protected virtual FieldValue GenerateFieldValue(ITable table, PropertyRoute route, NameSequence name, bool forceNull) { var att = Settings.FieldAttribute<DbTypeAttribute>(route); DbTypePair pair = Settings.IsPostgres && route.Type.IsArray && route.Type != typeof(byte[]) ? Settings.GetSqlDbType(att, route.Type.ElementType()!) : Settings.GetSqlDbType(att, route.Type); return new FieldValue(route, null, name.ToString()) { DbType = pair.DbType, Collation = Settings.GetCollate(att), UserDefinedTypeName = pair.UserDefinedTypeName, Nullable = Settings.GetIsNullable(route, forceNull), Size = Settings.GetSqlSize(att, route, pair.DbType), Scale = Settings.GetSqlScale(att, route, pair.DbType), Default = att?.GetDefault(Settings.IsPostgres), }.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route))); } protected virtual FieldEnum GenerateFieldEnum(ITable table, PropertyRoute route, NameSequence name, bool forceNull) { var att = Settings.FieldAttribute<DbTypeAttribute>(route); Type cleanEnum = route.Type.UnNullify(); var referenceTable = Include(EnumEntity.Generate(cleanEnum), route); return new FieldEnum(route, name.ToString(), referenceTable) { Nullable = Settings.GetIsNullable(route, forceNull), IsLite = false, AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null, Default = att?.GetDefault(Settings.IsPostgres), }.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route))); } protected virtual FieldReference GenerateFieldReference(ITable table, PropertyRoute route, NameSequence name, bool forceNull) { var referenceTable = Include(Lite.Extract(route.Type) ?? route.Type, route); var nullable = Settings.GetIsNullable(route, forceNull); return new FieldReference(route, null, name.ToString(), referenceTable) { Nullable = nullable, IsLite = route.Type.IsLite(), AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null, AvoidExpandOnRetrieving = Settings.FieldAttribute<AvoidExpandQueryAttribute>(route) != null, Default = Settings.FieldAttribute<DbTypeAttribute>(route)?.GetDefault(Settings.IsPostgres) }.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route))); } protected virtual FieldImplementedBy GenerateFieldImplementedBy(ITable table, PropertyRoute route, NameSequence name, bool forceNull, IEnumerable<Type> types) { Type cleanType = Lite.Extract(route.Type) ?? route.Type; string errors = types.Where(t => !cleanType.IsAssignableFrom(t)).ToString(t => t.TypeName(), ", "); if (errors.Length != 0) throw new InvalidOperationException("Type {0} do not implement {1}".FormatWith(errors, cleanType)); var nullable = Settings.GetIsNullable(route, forceNull); if (types.Count() > 1 && nullable == IsNullable.No) nullable = IsNullable.Forced; CombineStrategy strategy = Settings.FieldAttribute<CombineStrategyAttribute>(route)?.Strategy ?? CombineStrategy.Case; bool avoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null; var implementations = types.ToDictionary<Type, Type, ImplementationColumn>(t => t, t => { var rt = Include(t, route); string impName = name.Add(TypeLogic.GetCleanName(t)).ToString(); return new ImplementationColumn(impName, referenceTable: rt) { Nullable = nullable, AvoidForeignKey = avoidForeignKey, }; }); return new FieldImplementedBy(route, implementations) { SplitStrategy = strategy, IsLite = route.Type.IsLite(), AvoidExpandOnRetrieving = Settings.FieldAttribute<AvoidExpandQueryAttribute>(route) != null }.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route))); } protected virtual FieldImplementedByAll GenerateFieldImplementedByAll(PropertyRoute route, ITable table, NameSequence preName, bool forceNull) { var nullable = Settings.GetIsNullable(route, forceNull); var column = new ImplementationStringColumn(preName.ToString()) { Nullable = nullable, Size = Settings.DefaultImplementedBySize, }; var columnType = new ImplementationColumn(preName.Add("Type").ToString(), Include(typeof(TypeEntity), route)) { Nullable = nullable, AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null, }; return new FieldImplementedByAll(route, column, columnType) { IsLite = route.Type.IsLite(), AvoidExpandOnRetrieving = Settings.FieldAttribute<AvoidExpandQueryAttribute>(route) != null }.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route))); } protected virtual FieldMList GenerateFieldMList(Table table, PropertyRoute route, NameSequence name) { Type elementType = route.Type.ElementType()!; if (table.Ticks == null) throw new InvalidOperationException("Type '{0}' has field '{1}' but does not Ticks. MList requires concurrency control.".FormatWith(route.Parent!.Type.TypeName(), route.FieldInfo!.FieldName())); var orderAttr = Settings.FieldAttribute<PreserveOrderAttribute>(route); FieldValue? order = null; if (orderAttr != null) { var pair = Settings.GetSqlDbTypePair(typeof(int)); order = new FieldValue(route: null!, fieldType: typeof(int), orderAttr.Name ?? "Order") { DbType = pair.DbType, Collation = Settings.GetCollate(orderAttr), UserDefinedTypeName = pair.UserDefinedTypeName, Nullable = IsNullable.No, Size = Settings.GetSqlSize(orderAttr, null, pair.DbType), Scale = Settings.GetSqlScale(orderAttr, null, pair.DbType), }; } var keyAttr = Settings.FieldAttribute<PrimaryKeyAttribute>(route) ?? Settings.DefaultPrimaryKeyAttribute; TableMList.PrimaryKeyColumn primaryKey; { var pair = Settings.GetSqlDbType(keyAttr, keyAttr.Type); primaryKey = new TableMList.PrimaryKeyColumn(keyAttr.Type, keyAttr.Name) { DbType = pair.DbType, Collation = Settings.GetCollate(orderAttr), UserDefinedTypeName = pair.UserDefinedTypeName, Default = keyAttr.GetDefault(Settings.IsPostgres), Identity = keyAttr.Identity, }; } var tableName = GenerateTableNameCollection(table, name, Settings.FieldAttribute<TableNameAttribute>(route)); var backReference = new FieldReference(route: null!, fieldType: table.Type, name: GenerateBackReferenceName(table.Type, Settings.FieldAttribute<BackReferenceColumnNameAttribute>(route)), referenceTable: table ) { AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null, }; TableMList mlistTable = new TableMList(route.Type, tableName, primaryKey, backReference) { Order = order, }; mlistTable.Field = GenerateField(mlistTable, route.Add("Item"), NameSequence.Void, forceNull: false, inMList: true); var sysAttribute = Settings.FieldAttribute<SystemVersionedAttribute>(route) ?? (Settings.TypeAttribute<SystemVersionedAttribute>(table.Type) != null ? new SystemVersionedAttribute() : null); mlistTable.SystemVersioned = ToSystemVersionedInfo(sysAttribute, mlistTable.Name); mlistTable.GenerateColumns(); return new FieldMList(route, mlistTable) { TableMList = mlistTable, }; } protected virtual FieldEmbedded GenerateFieldEmbedded(ITable table, PropertyRoute route, NameSequence name, bool forceNull, bool inMList) { var nullable = Settings.GetIsNullable(route, false); var hasValue = nullable.ToBool() ? new FieldEmbedded.EmbeddedHasValueColumn(name.Add("HasValue").ToString()) : null; var embeddedFields = GenerateFields(route, table, name, forceNull: nullable.ToBool() || forceNull, inMList: inMList); var mixins = GenerateMixins(route, table, name); return new FieldEmbedded(route, hasValue, embeddedFields, mixins); } protected virtual FieldMixin GenerateFieldMixin(PropertyRoute route, NameSequence name, ITable table) { return new FieldMixin(route, table, GenerateFields(route, table, name, forceNull: false, inMList: false)); } #endregion #region Names public virtual string GenerateCleanTypeName(Type type) { type = CleanType(type); var ctn = type.GetCustomAttribute<CleanTypeNameAttribute>(); if (ctn != null) return ctn.Name; return Reflector.CleanTypeName(type); } protected static Type CleanType(Type type) { type = Lite.Extract(type) ?? type; type = EnumEntity.Extract(type) ?? type; return type; } public virtual ObjectName GenerateTableName(Type type, TableNameAttribute? tn) { var isPostgres = Schema.Settings.IsPostgres; SchemaName sn = tn != null ? GetSchemaName(tn) : SchemaName.Default(isPostgres); string name = tn?.Name ?? EnumEntity.Extract(type)?.Name ?? Reflector.CleanTypeName(type); return new ObjectName(sn, name, isPostgres); } private SchemaName GetSchemaName(TableNameAttribute tn) { var isPostgres = Schema.Settings.IsPostgres; ServerName? server = tn.ServerName == null ? null : new ServerName(tn.ServerName, isPostgres); DatabaseName? dataBase = tn.DatabaseName == null && server == null ? null : new DatabaseName(server, tn.DatabaseName!, isPostgres); SchemaName schema = tn.SchemaName == null && dataBase == null ? (tn.Name.StartsWith("#") && isPostgres ? null! : SchemaName.Default(isPostgres)) : new SchemaName(dataBase, tn.SchemaName!, isPostgres); return schema; } public virtual ObjectName GenerateTableNameCollection(Table table, NameSequence name, TableNameAttribute? tn) { var isPostgres = Schema.Settings.IsPostgres; SchemaName sn = tn != null ? GetSchemaName(tn) : SchemaName.Default(isPostgres); return new ObjectName(sn, tn?.Name ?? (table.Name.Name + name.ToString()), isPostgres); } public virtual string GenerateMListFieldName(PropertyRoute route, KindOfField kindOfField) { Type type = Lite.Extract(route.Type) ?? route.Type; switch (kindOfField) { case KindOfField.Value: case KindOfField.Embedded: return type.Name; case KindOfField.Enum: case KindOfField.Reference: return (EnumEntity.Extract(type)?.Name ?? Reflector.CleanTypeName(type)) + "ID"; default: throw new InvalidOperationException("No field name for type {0} defined".FormatWith(type)); } } public virtual string GenerateFieldName(PropertyRoute route, KindOfField kindOfField) { string name = route.PropertyInfo != null ? (route.PropertyInfo.Name.TryAfterLast('.') ?? route.PropertyInfo.Name) : route.FieldInfo!.Name; switch (kindOfField) { case KindOfField.PrimaryKey: case KindOfField.Ticks: case KindOfField.Value: case KindOfField.Embedded: case KindOfField.MList: //se usa solo para el nombre de la tabla return name; case KindOfField.Reference: case KindOfField.Enum: return name + "ID"; default: throw new InvalidOperationException("No name for {0} defined".FormatWith(route.FieldInfo!.Name)); } } public virtual string GenerateBackReferenceName(Type type, BackReferenceColumnNameAttribute? attribute) { return attribute?.Name ?? "ParentID"; } #endregion GlobalLazyManager GlobalLazyManager = new GlobalLazyManager(); public void SwitchGlobalLazyManager(GlobalLazyManager manager) { GlobalLazyManager.AsserNotUsed(); GlobalLazyManager = manager; } public ResetLazy<T> GlobalLazy<T>(Func<T> func, InvalidateWith invalidateWith, Action? onInvalidated = null, LazyThreadSafetyMode mode = LazyThreadSafetyMode.ExecutionAndPublication) where T : class { var result = Signum.Engine.GlobalLazy.WithoutInvalidations(() => { GlobalLazyManager.OnLoad(this, invalidateWith); return func(); }); GlobalLazyManager.AttachInvalidations(this, invalidateWith, (sender, args) => { result.Reset(); onInvalidated?.Invoke(); }); return result; } } public class GlobalLazyManager { bool isUsed = false; public void AsserNotUsed() { if (isUsed) throw new InvalidOperationException("GlobalLazyManager has already been used"); } public virtual void AttachInvalidations(SchemaBuilder sb, InvalidateWith invalidateWith, EventHandler invalidate) { isUsed = true; Action onInvalidation = () => { if (Transaction.InTestTransaction) { invalidate(this, EventArgs.Empty); Transaction.Rolledback += dic => invalidate(this, EventArgs.Empty); } Transaction.PostRealCommit += dic => invalidate(this, EventArgs.Empty); }; Schema schema = sb.Schema; foreach (var type in invalidateWith.Types) { giAttachInvalidations.GetInvoker(type)(schema, onInvalidation); } var dependants = DirectedGraph<Table>.Generate(invalidateWith.Types.Select(t => schema.Table(t)), t => t.DependentTables().Select(kvp => kvp.Key)).Select(t => t.Type).ToHashSet(); dependants.ExceptWith(invalidateWith.Types); foreach (var type in dependants) { giAttachInvalidationsDependant.GetInvoker(type)(schema, onInvalidation); } } static readonly GenericInvoker<Action<Schema, Action>> giAttachInvalidationsDependant = new GenericInvoker<Action<Schema, Action>>((s, a) => AttachInvalidationsDependant<Entity>(s, a)); static void AttachInvalidationsDependant<T>(Schema s, Action action) where T : Entity { var ee = s.EntityEvents<T>(); ee.Saving += e => { if (!e.IsNew && e.IsGraphModified) action(); }; ee.PreUnsafeUpdate += (u, q) => { action(); return null; }; } static readonly GenericInvoker<Action<Schema, Action>> giAttachInvalidations = new GenericInvoker<Action<Schema, Action>>((s, a) => AttachInvalidations<Entity>(s, a)); static void AttachInvalidations<T>(Schema s, Action action) where T : Entity { var ee = s.EntityEvents<T>(); ee.Saving += e => { if (e.IsGraphModified) action(); }; ee.PreUnsafeUpdate += (u, eq) => { action(); return null; }; ee.PreUnsafeDelete += (q) => { action(); return null; }; } public virtual void OnLoad(SchemaBuilder sb, InvalidateWith invalidateWith) { } } public class ViewBuilder : SchemaBuilder { public ViewBuilder(Schema schema) : base(schema) { } public override Table Include(Type type) { return Schema.Table(type); } public Table NewView(Type type) { Table table = new Table(type) { Name = GenerateTableName(type, Settings.TypeAttribute<TableNameAttribute>(type)), IsView = true }; table.Fields = GenerateFields(PropertyRoute.Root(type), table, NameSequence.Void, forceNull: false, inMList: false); table.GenerateColumns(); return table; } public override ObjectName GenerateTableName(Type type, TableNameAttribute? tn) { var name = base.GenerateTableName(type, tn); return Administrator.ReplaceViewName(name); } protected override FieldReference GenerateFieldReference(ITable table, PropertyRoute route, NameSequence name, bool forceNull) { var result = base.GenerateFieldReference(table, route, name, forceNull); if (Settings.FieldAttribute<ViewPrimaryKeyAttribute>(route) != null) result.PrimaryKey = true; return result; } protected override FieldValue GenerateFieldValue(ITable table, PropertyRoute route, NameSequence name, bool forceNull) { var result = base.GenerateFieldValue(table, route, name, forceNull); if (Settings.FieldAttribute<ViewPrimaryKeyAttribute>(route) != null) result.PrimaryKey = true; return result; } protected override FieldEnum GenerateFieldEnum(ITable table, PropertyRoute route, NameSequence name, bool forceNull) { var att = Settings.FieldAttribute<DbTypeAttribute>(route); Type cleanEnum = route.Type.UnNullify(); //var referenceTable = Include(EnumEntity.Generate(cleanEnum), route); return new FieldEnum(route, name.ToString(), null! /*referenceTable*/) { Nullable = Settings.GetIsNullable(route, forceNull), IsLite = false, AvoidForeignKey = Settings.FieldAttribute<AvoidForeignKeyAttribute>(route) != null, Default = att?.GetDefault(Settings.IsPostgres), }.Do(f => f.UniqueIndex = f.GenerateUniqueIndex(table, Settings.FieldAttribute<UniqueIndexAttribute>(route))); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using WebDemo.Areas.HelpPage.ModelDescriptions; using WebDemo.Areas.HelpPage.Models; namespace WebDemo.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using Internal.Runtime.CompilerServices; namespace System.Buffers { /// <summary> /// Provides an ArrayPool implementation meant to be used as the singleton returned from ArrayPool.Shared. /// </summary> /// <remarks> /// The implementation uses a tiered caching scheme, with a small per-thread cache for each array size, followed /// by a cache per array size shared by all threads, split into per-core stacks meant to be used by threads /// running on that core. Locks are used to protect each per-core stack, because a thread can migrate after /// checking its processor number, because multiple threads could interleave on the same core, and because /// a thread is allowed to check other core's buckets if its core's bucket is empty/full. /// </remarks> internal sealed partial class TlsOverPerCoreLockedStacksArrayPool<T> : ArrayPool<T> { // TODO: #7747: "Investigate optimizing ArrayPool heuristics" // - Explore caching in TLS more than one array per size per thread, and moving stale buffers to the global queue. // - Explore changing the size of each per-core bucket, potentially dynamically or based on other factors like array size. // - Explore changing number of buckets and what sizes of arrays are cached. // - Investigate whether false sharing is causing any issues, in particular on LockedStack's count and the contents of its array. // ... /// <summary>The number of buckets (array sizes) in the pool, one for each array length, starting from length 16.</summary> private const int NumBuckets = 17; // Utilities.SelectBucketIndex(2*1024*1024) /// <summary>Maximum number of per-core stacks to use per array size.</summary> private const int MaxPerCorePerArraySizeStacks = 64; // selected to avoid needing to worry about processor groups /// <summary>The maximum number of buffers to store in a bucket's global queue.</summary> private const int MaxBuffersPerArraySizePerCore = 8; /// <summary>The length of arrays stored in the corresponding indices in <see cref="_buckets"/> and <see cref="t_tlsBuckets"/>.</summary> private readonly int[] _bucketArraySizes; /// <summary> /// An array of per-core array stacks. The slots are lazily initialized to avoid creating /// lots of overhead for unused array sizes. /// </summary> private readonly PerCoreLockedStacks?[] _buckets = new PerCoreLockedStacks[NumBuckets]; /// <summary>A per-thread array of arrays, to cache one array per array size per thread.</summary> [ThreadStatic] private static T[]?[]? t_tlsBuckets; private int _callbackCreated; private readonly static bool s_trimBuffers = GetTrimBuffers(); /// <summary> /// Used to keep track of all thread local buckets for trimming if needed /// </summary> private static readonly ConditionalWeakTable<T[]?[], object?>? s_allTlsBuckets = s_trimBuffers ? new ConditionalWeakTable<T[]?[], object?>() : null; /// <summary>Initialize the pool.</summary> public TlsOverPerCoreLockedStacksArrayPool() { var sizes = new int[NumBuckets]; for (int i = 0; i < sizes.Length; i++) { sizes[i] = Utilities.GetMaxSizeForBucket(i); } _bucketArraySizes = sizes; } /// <summary>Allocate a new PerCoreLockedStacks and try to store it into the <see cref="_buckets"/> array.</summary> private PerCoreLockedStacks CreatePerCoreLockedStacks(int bucketIndex) { var inst = new PerCoreLockedStacks(); return Interlocked.CompareExchange(ref _buckets[bucketIndex], inst, null) ?? inst; } /// <summary>Gets an ID for the pool to use with events.</summary> private int Id => GetHashCode(); public override T[] Rent(int minimumLength) { // Arrays can't be smaller than zero. We allow requesting zero-length arrays (even though // pooling such an array isn't valuable) as it's a valid length array, and we want the pool // to be usable in general instead of using `new`, even for computed lengths. if (minimumLength < 0) { throw new ArgumentOutOfRangeException(nameof(minimumLength)); } else if (minimumLength == 0) { // No need to log the empty array. Our pool is effectively infinite // and we'll never allocate for rents and never store for returns. return Array.Empty<T>(); } ArrayPoolEventSource log = ArrayPoolEventSource.Log; T[]? buffer; // Get the bucket number for the array length int bucketIndex = Utilities.SelectBucketIndex(minimumLength); // If the array could come from a bucket... if (bucketIndex < _buckets.Length) { // First try to get it from TLS if possible. T[]?[]? tlsBuckets = t_tlsBuckets; if (tlsBuckets != null) { buffer = tlsBuckets[bucketIndex]; if (buffer != null) { tlsBuckets[bucketIndex] = null; if (log.IsEnabled()) { log.BufferRented(buffer.GetHashCode(), buffer.Length, Id, bucketIndex); } return buffer; } } // We couldn't get a buffer from TLS, so try the global stack. PerCoreLockedStacks? b = _buckets[bucketIndex]; if (b != null) { buffer = b.TryPop(); if (buffer != null) { if (log.IsEnabled()) { log.BufferRented(buffer.GetHashCode(), buffer.Length, Id, bucketIndex); } return buffer; } } // No buffer available. Allocate a new buffer with a size corresponding to the appropriate bucket. buffer = GC.AllocateUninitializedArray<T>(_bucketArraySizes[bucketIndex]); } else { // The request was for a size too large for the pool. Allocate an array of exactly the requested length. // When it's returned to the pool, we'll simply throw it away. buffer = GC.AllocateUninitializedArray<T>(minimumLength); } if (log.IsEnabled()) { int bufferId = buffer.GetHashCode(), bucketId = -1; // no bucket for an on-demand allocated buffer log.BufferRented(bufferId, buffer.Length, Id, bucketId); log.BufferAllocated(bufferId, buffer.Length, Id, bucketId, bucketIndex >= _buckets.Length ? ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted); } return buffer; } public override void Return(T[] array, bool clearArray = false) { if (array == null) { throw new ArgumentNullException(nameof(array)); } // Determine with what bucket this array length is associated int bucketIndex = Utilities.SelectBucketIndex(array.Length); // If we can tell that the buffer was allocated (or empty), drop it. Otherwise, check if we have space in the pool. if (bucketIndex < _buckets.Length) { // Clear the array if the user requests. if (clearArray) { Array.Clear(array, 0, array.Length); } // Check to see if the buffer is the correct size for this bucket if (array.Length != _bucketArraySizes[bucketIndex]) { throw new ArgumentException(SR.ArgumentException_BufferNotFromPool, nameof(array)); } // Write through the TLS bucket. If there weren't any buckets, create them // and store this array into it. If there were, store this into it, and // if there was a previous one there, push that to the global stack. This // helps to keep LIFO access such that the most recently pushed stack will // be in TLS and the first to be popped next. T[]?[]? tlsBuckets = t_tlsBuckets; if (tlsBuckets == null) { t_tlsBuckets = tlsBuckets = new T[NumBuckets][]; tlsBuckets[bucketIndex] = array; if (s_trimBuffers) { Debug.Assert(s_allTlsBuckets != null, "Should be non-null iff s_trimBuffers is true"); s_allTlsBuckets.Add(tlsBuckets, null); if (Interlocked.Exchange(ref _callbackCreated, 1) != 1) { Gen2GcCallback.Register(Gen2GcCallbackFunc, this); } } } else { T[]? prev = tlsBuckets[bucketIndex]; tlsBuckets[bucketIndex] = array; if (prev != null) { PerCoreLockedStacks stackBucket = _buckets[bucketIndex] ?? CreatePerCoreLockedStacks(bucketIndex); stackBucket.TryPush(prev); } } } // Log that the buffer was returned ArrayPoolEventSource log = ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferReturned(array.GetHashCode(), array.Length, Id); } } public bool Trim() { Debug.Assert(s_trimBuffers); Debug.Assert(s_allTlsBuckets != null); int milliseconds = Environment.TickCount; MemoryPressure pressure = GetMemoryPressure(); ArrayPoolEventSource log = ArrayPoolEventSource.Log; if (log.IsEnabled()) log.BufferTrimPoll(milliseconds, (int)pressure); PerCoreLockedStacks?[] perCoreBuckets = _buckets; for (int i = 0; i < perCoreBuckets.Length; i++) { perCoreBuckets[i]?.Trim((uint)milliseconds, Id, pressure, _bucketArraySizes[i]); } if (pressure == MemoryPressure.High) { // Under high pressure, release all thread locals if (log.IsEnabled()) { foreach (KeyValuePair<T[]?[], object?> tlsBuckets in s_allTlsBuckets) { T[]?[] buckets = tlsBuckets.Key; for (int i = 0; i < buckets.Length; i++) { T[]? buffer = Interlocked.Exchange(ref buckets[i], null); if (buffer != null) { // As we don't want to take a perf hit in the rent path it // is possible that a buffer could be rented as we "free" it. log.BufferTrimmed(buffer.GetHashCode(), buffer.Length, Id); } } } } else { foreach (KeyValuePair<T[]?[], object?> tlsBuckets in s_allTlsBuckets) { T[]?[] buckets = tlsBuckets.Key; Array.Clear(buckets, 0, buckets.Length); } } } return true; } /// <summary> /// This is the static function that is called from the gen2 GC callback. /// The input object is the instance we want the callback on. /// </summary> /// <remarks> /// The reason that we make this function static and take the instance as a parameter is that /// we would otherwise root the instance to the Gen2GcCallback object, leaking the instance even when /// the application no longer needs it. /// </remarks> private static bool Gen2GcCallbackFunc(object target) { return ((TlsOverPerCoreLockedStacksArrayPool<T>)(target)).Trim(); } private enum MemoryPressure { Low, Medium, High } private static MemoryPressure GetMemoryPressure() { const double HighPressureThreshold = .90; // Percent of GC memory pressure threshold we consider "high" const double MediumPressureThreshold = .70; // Percent of GC memory pressure threshold we consider "medium" GCMemoryInfo memoryInfo = GC.GetGCMemoryInfo(); if (memoryInfo.MemoryLoadBytes >= memoryInfo.HighMemoryLoadThresholdBytes * HighPressureThreshold) { return MemoryPressure.High; } else if (memoryInfo.MemoryLoadBytes >= memoryInfo.HighMemoryLoadThresholdBytes * MediumPressureThreshold) { return MemoryPressure.Medium; } return MemoryPressure.Low; } private static bool GetTrimBuffers() { // Environment uses ArrayPool, so we have to hit the API directly. #if !CORECLR // P/Invokes are different for CoreCLR/RT- for RT we'll not allow // enabling/disabling for now. return true; #else return CLRConfig.GetBoolValueWithFallbacks("System.Buffers.ArrayPool.TrimShared", "DOTNET_SYSTEM_BUFFERS_ARRAYPOOL_TRIMSHARED", defaultValue: true); #endif } /// <summary> /// Stores a set of stacks of arrays, with one stack per core. /// </summary> private sealed class PerCoreLockedStacks { /// <summary>The stacks.</summary> private readonly LockedStack[] _perCoreStacks; /// <summary>Initializes the stacks.</summary> public PerCoreLockedStacks() { // Create the stacks. We create as many as there are processors, limited by our max. var stacks = new LockedStack[Math.Min(Environment.ProcessorCount, MaxPerCorePerArraySizeStacks)]; for (int i = 0; i < stacks.Length; i++) { stacks[i] = new LockedStack(); } _perCoreStacks = stacks; } /// <summary>Try to push the array into the stacks. If each is full when it's tested, the array will be dropped.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void TryPush(T[] array) { // Try to push on to the associated stack first. If that fails, // round-robin through the other stacks. LockedStack[] stacks = _perCoreStacks; int index = Thread.GetCurrentProcessorId() % stacks.Length; for (int i = 0; i < stacks.Length; i++) { if (stacks[index].TryPush(array)) return; if (++index == stacks.Length) index = 0; } } /// <summary>Try to get an array from the stacks. If each is empty when it's tested, null will be returned.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[]? TryPop() { // Try to pop from the associated stack first. If that fails, // round-robin through the other stacks. T[]? arr; LockedStack[] stacks = _perCoreStacks; int index = Thread.GetCurrentProcessorId() % stacks.Length; for (int i = 0; i < stacks.Length; i++) { if ((arr = stacks[index].TryPop()) != null) return arr; if (++index == stacks.Length) index = 0; } return null; } public void Trim(uint tickCount, int id, MemoryPressure pressure, int bucketSize) { LockedStack[] stacks = _perCoreStacks; for (int i = 0; i < stacks.Length; i++) { stacks[i].Trim(tickCount, id, pressure, bucketSize); } } } /// <summary>Provides a simple stack of arrays, protected by a lock.</summary> private sealed class LockedStack { private readonly T[]?[] _arrays = new T[MaxBuffersPerArraySizePerCore][]; private int _count; private uint _firstStackItemMS; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPush(T[] array) { bool enqueued = false; Monitor.Enter(this); if (_count < MaxBuffersPerArraySizePerCore) { if (s_trimBuffers && _count == 0) { // Stash the time the bottom of the stack was filled _firstStackItemMS = (uint)Environment.TickCount; } _arrays[_count++] = array; enqueued = true; } Monitor.Exit(this); return enqueued; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[]? TryPop() { T[]? arr = null; Monitor.Enter(this); if (_count > 0) { arr = _arrays[--_count]; _arrays[_count] = null; } Monitor.Exit(this); return arr; } public void Trim(uint tickCount, int id, MemoryPressure pressure, int bucketSize) { const uint StackTrimAfterMS = 60 * 1000; // Trim after 60 seconds for low/moderate pressure const uint StackHighTrimAfterMS = 10 * 1000; // Trim after 10 seconds for high pressure const uint StackRefreshMS = StackTrimAfterMS / 4; // Time bump after trimming (1/4 trim time) const int StackLowTrimCount = 1; // Trim one item when pressure is low const int StackMediumTrimCount = 2; // Trim two items when pressure is moderate const int StackHighTrimCount = MaxBuffersPerArraySizePerCore; // Trim all items when pressure is high const int StackLargeBucket = 16384; // If the bucket is larger than this we'll trim an extra when under high pressure const int StackModerateTypeSize = 16; // If T is larger than this we'll trim an extra when under high pressure const int StackLargeTypeSize = 32; // If T is larger than this we'll trim an extra (additional) when under high pressure if (_count == 0) return; uint trimTicks = pressure == MemoryPressure.High ? StackHighTrimAfterMS : StackTrimAfterMS; lock (this) { if (_count > 0 && _firstStackItemMS > tickCount || (tickCount - _firstStackItemMS) > trimTicks) { // We've wrapped the tick count or elapsed enough time since the // first item went into the stack. Drop the top item so it can // be collected and make the stack look a little newer. ArrayPoolEventSource log = ArrayPoolEventSource.Log; int trimCount = StackLowTrimCount; switch (pressure) { case MemoryPressure.High: trimCount = StackHighTrimCount; // When pressure is high, aggressively trim larger arrays. if (bucketSize > StackLargeBucket) { trimCount++; } if (Unsafe.SizeOf<T>() > StackModerateTypeSize) { trimCount++; } if (Unsafe.SizeOf<T>() > StackLargeTypeSize) { trimCount++; } break; case MemoryPressure.Medium: trimCount = StackMediumTrimCount; break; } while (_count > 0 && trimCount-- > 0) { T[]? array = _arrays[--_count]; Debug.Assert(array != null, "No nulls should have been present in slots < _count."); _arrays[_count] = null; if (log.IsEnabled()) { log.BufferTrimmed(array.GetHashCode(), array.Length, id); } } if (_count > 0 && _firstStackItemMS < uint.MaxValue - StackRefreshMS) { // Give the remaining items a bit more time _firstStackItemMS += StackRefreshMS; } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; internal static partial class Interop { internal static partial class procfs { internal const string RootPath = "/proc/"; private const string ExeFileName = "/exe"; private const string StatFileName = "/stat"; private const string MapsFileName = "/maps"; private const string FileDescriptorDirectoryName = "/fd/"; private const string TaskDirectoryName = "/task/"; internal const string SelfExeFilePath = RootPath + "self" + ExeFileName; internal const string ProcUptimeFilePath = RootPath + "uptime"; internal struct ParsedStat { // Commented out fields are available in the stat data file but // are currently not used. If/when needed, they can be uncommented, // and the corresponding entry can be added back to StatParser, replacing // the MoveNext() with the appropriate ParseNext* call and assignment. internal int pid; internal string comm; internal char state; //internal int ppid; //internal int pgrp; internal int session; //internal int tty_nr; //internal int tpgid; //internal uint flags; //internal ulong minflt; //internal ulong cminflt; //internal ulong majflt; //internal ulong cmajflt; internal ulong utime; internal ulong stime; //internal long cutime; //internal long cstime; //internal long priority; internal long nice; //internal long num_threads; //internal long itrealvalue; internal ulong starttime; internal ulong vsize; internal long rss; internal ulong rsslim; //internal ulong startcode; //internal ulong endcode; //internal ulong startstack; //internal ulong kstkesp; //internal ulong kstkeip; //internal ulong signal; //internal ulong blocked; //internal ulong sigignore; //internal ulong sigcatch; //internal ulong wchan; //internal ulong nswap; //internal ulong cnswap; //internal int exit_signal; //internal int processor; //internal uint rt_priority; //internal uint policy; //internal ulong delayacct_blkio_ticks; //internal ulong guest_time; //internal long cguest_time; } internal struct ParsedMapsModule { internal string FileName; internal KeyValuePair<long, long> AddressRange; } internal static string GetExeFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + ExeFileName; } internal static string GetStatFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + StatFileName; } internal static string GetMapsFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + MapsFileName; } internal static string GetTaskDirectoryPathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + TaskDirectoryName; } internal static string GetFileDescriptorDirectoryPathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + FileDescriptorDirectoryName; } internal static IEnumerable<ParsedMapsModule> ParseMapsModules(int pid) { try { return ParseMapsModulesCore(File.ReadLines(GetMapsFilePathForProcess(pid))); } catch (IOException) { } catch (UnauthorizedAccessException) { } return Array.Empty<ParsedMapsModule>(); } private static IEnumerable<ParsedMapsModule> ParseMapsModulesCore(IEnumerable<string> lines) { Debug.Assert(lines != null); // Parse each line from the maps file into a ParsedMapsModule result foreach (string line in lines) { // Use a StringParser to avoid string.Split costs var parser = new StringParser(line, separator: ' ', skipEmpty: true); // Parse the address range KeyValuePair<long, long> addressRange = parser.ParseRaw(delegate (string s, ref int start, ref int end) { long startingAddress = 0, endingAddress = 0; int pos = s.IndexOf('-', start, end - start); if (pos > 0) { string startingString = s.Substring(start, pos); if (long.TryParse(startingString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out startingAddress)) { string endingString = s.Substring(pos + 1, end - (pos + 1)); long.TryParse(endingString, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out endingAddress); } } return new KeyValuePair<long, long>(startingAddress, endingAddress); }); // Parse the permissions (we only care about entries with 'r' and 'x' set) if (!parser.ParseRaw(delegate (string s, ref int start, ref int end) { bool sawRead = false, sawExec = false; for (int i = start; i < end; i++) { if (s[i] == 'r') sawRead = true; else if (s[i] == 'x') sawExec = true; } return sawRead & sawExec; })) { continue; } // Skip past the offset, dev, and inode fields parser.MoveNext(); parser.MoveNext(); parser.MoveNext(); // Parse the pathname if (!parser.MoveNext()) { continue; } string pathname = parser.ExtractCurrentToEnd(); // We only get here if a we have a non-empty pathname and // the permissions included both readability and executability. // Yield the result. yield return new ParsedMapsModule { FileName = pathname, AddressRange = addressRange }; } } private static string GetStatFilePathForThread(int pid, int tid) { // Perf note: Calling GetTaskDirectoryPathForProcess will allocate a string, // which we then use in another Concat call to produce another string. The straightforward alternative, // though, since we have five input strings, is to use the string.Concat overload that takes a params array. // This results in allocating not only the params array but also a defensive copy inside of Concat, // which means allocating two five-element arrays. This two-string approach will result not only in fewer // allocations, but also typically in less memory allocated, and it's a bit more maintainable. return GetTaskDirectoryPathForProcess(pid) + tid.ToString(CultureInfo.InvariantCulture) + StatFileName; } internal static bool TryReadStatFile(int pid, out ParsedStat result, ReusableTextReader reusableReader) { bool b = TryParseStatFile(GetStatFilePathForProcess(pid), out result, reusableReader); Debug.Assert(!b || result.pid == pid, "Expected process ID from stat file to match supplied pid"); return b; } internal static bool TryReadStatFile(int pid, int tid, out ParsedStat result, ReusableTextReader reusableReader) { bool b = TryParseStatFile(GetStatFilePathForThread(pid, tid), out result, reusableReader); // // This assert currently fails in the Windows Subsystem For Linux. See https://github.com/Microsoft/BashOnWindows/issues/967. // //Debug.Assert(!b || result.pid == tid, "Expected thread ID from stat file to match supplied tid"); return b; } internal static bool TryParseStatFile(string statFilePath, out ParsedStat result, ReusableTextReader reusableReader) { string statFileContents; try { using (var source = new FileStream(statFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1, useAsync: false)) { statFileContents = reusableReader.ReadAllText(source); } } catch (IOException) { // Between the time that we get an ID and the time that we try to read the associated stat // file(s), the process could be gone. result = default(ParsedStat); return false; } var parser = new StringParser(statFileContents, ' '); var results = default(ParsedStat); results.pid = parser.ParseNextInt32(); results.comm = parser.MoveAndExtractNextInOuterParens(); results.state = parser.ParseNextChar(); parser.MoveNextOrFail(); // ppid parser.MoveNextOrFail(); // pgrp results.session = parser.ParseNextInt32(); parser.MoveNextOrFail(); // tty_nr parser.MoveNextOrFail(); // tpgid parser.MoveNextOrFail(); // flags parser.MoveNextOrFail(); // majflt parser.MoveNextOrFail(); // cmagflt parser.MoveNextOrFail(); // minflt parser.MoveNextOrFail(); // cminflt results.utime = parser.ParseNextUInt64(); results.stime = parser.ParseNextUInt64(); parser.MoveNextOrFail(); // cutime parser.MoveNextOrFail(); // cstime parser.MoveNextOrFail(); // priority results.nice = parser.ParseNextInt64(); parser.MoveNextOrFail(); // num_threads parser.MoveNextOrFail(); // itrealvalue results.starttime = parser.ParseNextUInt64(); results.vsize = parser.ParseNextUInt64(); results.rss = parser.ParseNextInt64(); results.rsslim = parser.ParseNextUInt64(); // The following lines are commented out as there's no need to parse through // the rest of the entry (we've gotten all of the data we need). Should any // of these fields be needed in the future, uncomment all of the lines up // through and including the one that's needed. For now, these are being left // commented to document what's available in the remainder of the entry. //parser.MoveNextOrFail(); // startcode //parser.MoveNextOrFail(); // endcode //parser.MoveNextOrFail(); // startstack //parser.MoveNextOrFail(); // kstkesp //parser.MoveNextOrFail(); // kstkeip //parser.MoveNextOrFail(); // signal //parser.MoveNextOrFail(); // blocked //parser.MoveNextOrFail(); // sigignore //parser.MoveNextOrFail(); // sigcatch //parser.MoveNextOrFail(); // wchan //parser.MoveNextOrFail(); // nswap //parser.MoveNextOrFail(); // cnswap //parser.MoveNextOrFail(); // exit_signal //parser.MoveNextOrFail(); // processor //parser.MoveNextOrFail(); // rt_priority //parser.MoveNextOrFail(); // policy //parser.MoveNextOrFail(); // delayacct_blkio_ticks //parser.MoveNextOrFail(); // guest_time //parser.MoveNextOrFail(); // cguest_time result = results; return true; } } }
using System; using System.IO; using System.Net; using System.Text.RegularExpressions; using System.Web; using System.Net.Mail; using newtelligence.DasBlog.Runtime; using newtelligence.DasBlog.Web.Core; namespace newtelligence.DasBlog.Web.Services { /// <summary> /// Summary description for TrackbackHandler. /// </summary> public class TrackbackHandler : IHttpHandler { public TrackbackHandler() { // // TODO: Add constructor logic here // } public bool IsReusable { get { return true; } } public void ProcessRequest( HttpContext context ) { SiteConfig siteConfig = SiteConfig.GetSiteConfig(); string entryId; string title; string excerpt; string url; string blog_name; if ( !siteConfig.EnableTrackbackService ) { context.Response.StatusCode = 503; context.Response.Status = "503 Service Unavailable"; context.Response.End(); return; } // Try blocking them once, on the off chance they sent us a referrer string referrer = context.Request.UrlReferrer!=null?context.Request.UrlReferrer.AbsoluteUri:""; if (ReferralBlackList.IsBlockedReferrer(referrer)) { if (siteConfig.EnableReferralUrlBlackList404s) { context.Response.StatusCode = 404; context.Response.End(); return; } } entryId = context.Request.QueryString["guid"]; if ( context.Request.HttpMethod == "POST" ) { title = context.Request.Form["title"]; excerpt= context.Request.Form["excerpt"]; url = context.Request.Form["url"]; blog_name = context.Request.Form["blog_name"]; } /* GET is no longer in the Trackback spec. Keeping * this arround for testing. Just uncomment. else if ( context.Request.HttpMethod == "GET" ) { title = context.Request.QueryString["title"]; excerpt= context.Request.QueryString["excerpt"]; url = context.Request.QueryString["url"]; blog_name = context.Request.QueryString["blog_name"]; } */ else { context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig)); return; } if ( url != null && url.Length > 0 ) { try { // First line of defense, try blocking again with the URL they are tracking us back with if (ReferralBlackList.IsBlockedReferrer(url)) { if (siteConfig.EnableReferralUrlBlackList404s) { context.Response.StatusCode = 404; context.Response.End(); return; } } ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext()); IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(),logService ); Entry entry = dataService.GetEntry( entryId ); if ( entry != null ) { try { string requestBody = null; // see if this is a spammer HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; webRequest.Method="GET"; webRequest.UserAgent = SiteUtilities.GetUserAgent(); HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse; // now we want to get the page contents of the target body using (StreamReader requestReader = new StreamReader(response.GetResponseStream())) { requestBody = requestReader.ReadToEnd(); } response.Close(); // the source URL in the page could be URL encoded like the ClickThroughHandler does string urlEncodedBaseUrl = HttpUtility.UrlEncode(SiteUtilities.GetBaseUrl()); // check to see if the source's page contains a link to us if (Regex.Match(requestBody, SiteUtilities.GetBaseUrl()).Success == false && Regex.Match(requestBody, urlEncodedBaseUrl).Success == false) { logService.AddEvent(new EventDataItem( EventCodes.TrackbackBlocked, context.Request.UserHostAddress + " because it did not contain a link", SiteUtilities.GetPermaLinkUrl(entryId), url, entry.Title )); context.Response.StatusCode = 404; context.Response.End(); return; } } catch { // trackback url is not even alive logService.AddEvent(new EventDataItem( EventCodes.TrackbackBlocked, context.Request.UserHostAddress + " because the server did not return a valid response", SiteUtilities.GetPermaLinkUrl(entryId), url, entry.Title )); context.Response.StatusCode = 404; context.Response.End(); return; } // if we've gotten this far, the trackback is real and valid Tracking t = new Tracking(); t.PermaLink = url; t.Referer = context.Request.UrlReferrer != null ? context.Request.UrlReferrer.ToString() : String.Empty; t.RefererBlogName = blog_name; t.RefererExcerpt = excerpt; t.RefererTitle = title; t.RefererIPAddress = context.Request.UserHostAddress; t.TargetEntryId = entryId; t.TargetTitle = entry.Title; t.TrackingType = TrackingType.Trackback; ISpamBlockingService spamBlockingService = siteConfig.SpamBlockingService; if (spamBlockingService != null) { bool isSpam = false; try { isSpam = spamBlockingService.IsSpam(t); } catch(Exception ex) { logService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("The external spam blocking service failed for trackback from {0}. Original exception: {1}", t.PermaLink, ex), SiteUtilities.GetPermaLinkUrl(entryId))); } if (isSpam) { //TODO: maybe we can add a configuration option to moderate trackbacks. // For now, we'll just avoid saving suspected spam logService.AddEvent(new EventDataItem( EventCodes.TrackbackBlocked, context.Request.UserHostAddress + " because it was considered spam by the external blocking service.", SiteUtilities.GetPermaLinkUrl(entryId), url, entry.Title )); context.Response.StatusCode = 404; context.Response.End(); return; } } if ( siteConfig.SendTrackbacksByEmail && siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0 ) { MailMessage emailMessage = new MailMessage(); if ( siteConfig.NotificationEMailAddress != null && siteConfig.NotificationEMailAddress.Length > 0 ) { emailMessage.To.Add(siteConfig.NotificationEMailAddress); } else { emailMessage.To.Add(siteConfig.Contact); } emailMessage.Subject = String.Format("Weblog trackback by '{0}' on '{1}'", t.PermaLink, t.TargetTitle); emailMessage.Body = String.Format("You were tracked back from\n{0}\r\non your weblog entry '{1}'\n({2}\r\n\r\nDelete Trackback: {3})", t.PermaLink, t.TargetTitle, SiteUtilities.GetPermaLinkUrl(entryId), SiteUtilities.GetTrackbackDeleteUrl(entryId, t.PermaLink, t.TrackingType)); emailMessage.IsBodyHtml = false; emailMessage.BodyEncoding = System.Text.Encoding.UTF8; emailMessage.From = new MailAddress(siteConfig.Contact); SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer, siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort); dataService.AddTracking(t, sendMailInfo ); } else { dataService.AddTracking( t ); } logService.AddEvent( new EventDataItem( EventCodes.TrackbackReceived, entry.Title, SiteUtilities.GetPermaLinkUrl(entryId), url)); // return the correct Trackback response // http://www.movabletype.org/docs/mttrackback.html context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>0</error></response>"); return; } } catch (System.Threading.ThreadAbortException ex) { // absorb ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,ex); return; } catch( Exception exc ) { // absorb ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,exc); // return the correct Trackback response // http://www.movabletype.org/docs/mttrackback.html context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>1</error><message>" + exc.ToString() + "</message></response>"); return; } } if ( entryId != null && entryId.Length > 0 ) { context.Response.Redirect(SiteUtilities.GetPermaLinkUrl(siteConfig,entryId)); } else { context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig)); } } } }
#if WINDOWS || SILVERLIGHT #define MOUSE #endif #if (!WINDOWS && !SILVERLIGHT) || WINDOWS8 #define TOUCHPANEL #endif #if WINDOWS_PHONE || WINDOWS || WINDOWS8 || IPHONE || ANDROID || SILVERLIGHT #define GAMEPAD #endif #if WINDOWS_PHONE || WINDOWS || WINDOWS8 || IPHONE || ANDROID #define GESTURES #endif using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; #if SILVERLIGHT using System.Windows; using System.Windows.Input; #endif #if SILVERLIGHT namespace Microsoft.Xna.Framework.Input.Touch { // Summary: // Provides methods and properties for interacting with a touch location on // a touch screen device. Reference page contains links to related code samples. public struct TouchLocation : IEquatable<TouchLocation> { // // Summary: // Initializes a new TouchLocation with an ID, state, position, and pressure. // // Parameters: // id: // ID of the new touch location. // // state: // State of the new touch location. // // position: // Position, in screen coordinates, of the new touch location. public TouchLocation(int id, TouchLocationState state, Vector2 position) : this() { Id = id; State = state; Position = position; } // Summary: // Determines whether two TouchLocation instances are unequal. // // Parameters: // value1: // The TouchLocation to compare with the second. // // value2: // The TouchLocation to compare with the first. public static bool operator !=(TouchLocation value1, TouchLocation value2) { return !(value1 == value2); } // // Summary: // Determines whether two TouchLocation instances are equal. // // Parameters: // value1: // The TouchLocation to compare with the second. // // value2: // The TouchLocation to compare with the first. public static bool operator ==(TouchLocation value1, TouchLocation value2) { return value1.Id == value2.Id && value1.Position == value2.Position && value1.State == value2.State; } // Summary: // Gets the ID of the touch location. public int Id { get; private set; } // // Summary: // Gets the position of the touch location. public Vector2 Position { get; private set; } // // Summary: // Gets the state of the touch location. public TouchLocationState State { get; private set; } // Summary: // Determines whether the current TouchLocation is equal to the specified object. // // Parameters: // obj: // The Object to compare with the touch location. public override bool Equals(object obj) { try { var other = (TouchLocation)obj; return Id == other.Id && Position == other.Position && State == other.State; } catch { return false; } } // // Summary: // Determines whether the current TouchLocation is equal to the specified TouchLocation. // // Parameters: // other: // The TouchLocation to compare with this instance. public bool Equals(TouchLocation other) { return Id == other.Id && Position == other.Position && State == other.State; } // // Summary: // Gets the hash code for this TouchLocation. public override int GetHashCode() { return Position.GetHashCode() + Id + State.GetHashCode(); } // // Summary: // Gets a string representation of the TouchLocation. public override string ToString() { return "{Id:" + Id + ", Position:" + Position + ", State:" + State + "}"; } // // Summary: // Attempts to get the previous location of this touch location object. // // Parameters: // previousLocation: // [OutAttribute] Previous location data, as a TouchLocation. public bool TryGetPreviousLocation(out TouchLocation previousLocation) { previousLocation = new TouchLocation(); return false; } } // Summary: // Defines the possible states of a touch location. Reference page contains // links to related code samples. public enum TouchLocationState { // Summary: // This touch location position is invalid. Typically, you will encounter this // state when a new touch location attempts to get the previous state of itself. Invalid = 0, // // Summary: // This touch location position was released. Released = 1, // // Summary: // This touch location position is new. Pressed = 2, // // Summary: // This touch location position was updated or pressed at the same position. Moved = 3, } } #endif namespace GameStateManagement { public class InputService : GameComponent { #if MOUSE static MouseState _mouseState; static MouseState _oldMouseState; #if SILVERLIGHT public static bool EventOnly = false; internal static int JustPressedMouse; #endif #endif #if TOUCHPANEL List<TouchLocation> touchCollection; public bool TouchIsFromTouchPanel { get; private set; } #endif #if GAMEPAD public GamePadState CurrentGamePadState; public GamePadState LastGamePadState; #endif #if WINDOWS8 || SILVERLIGHT || WINDOWS GraphicsDeviceManager _graphics; #endif #if GESTURES public readonly List<GestureSample> Gestures = new List<GestureSample>(); #endif public InputService(Game game) : base(game) { #if MOUSE _mouseState = _oldMouseState = Mouse.GetState(); #if SILVERLIGHT JustPressedMouse = 0; #endif #endif #if TOUCHPANEL touchCollection = new List<TouchLocation>(); #endif #if GAMEPAD #if !SILVERLIGHT CurrentGamePadState = GamePad.GetState(PlayerIndex.One); #else GamePadState.MapKey(Buttons.Back, Keys.Escape); #endif LastGamePadState = CurrentGamePadState; #endif } #if WINDOWS8 || SILVERLIGHT || WINDOWS public override void Initialize() { _graphics = Game.Services.GetService(typeof(IGraphicsDeviceManager)) as GraphicsDeviceManager; base.Initialize(); } #endif public override void Update (GameTime gameTime) { XNA8DFramework.ScrollableGame.Begin(); #if MOUSE _oldMouseState = _mouseState; _mouseState = Mouse.GetState(); #if SILVERLIGHT if (JustPressedMouse > 0) JustPressedMouse--; #endif #endif #if TOUCHPANEL touchCollection.Clear(); foreach(TouchLocation touch in TouchPanel.GetState()) { if (touch.State != TouchLocationState.Invalid) { touchCollection.Add(touch); } } #endif #if GAMEPAD LastGamePadState = CurrentGamePadState; CurrentGamePadState = GamePad.GetState(PlayerIndex.One); #endif #if GESTURES // Read in any detected gestures into our list for the screens to later process Gestures.Clear(); while (TouchPanel.IsGestureAvailable) { Gestures.Add(TouchPanel.ReadGesture()); } #endif base.Update (gameTime); } public TouchLocation GetInputPoint() { #if TOUCHPANEL if (touchCollection.Count > 0) { TouchIsFromTouchPanel = true; #if WINDOWS8 || WINDOWS_PHONE var posT = touchCollection[0].Position; #if WINDOWS_PHONE float propX = Game.GraphicsDevice.Viewport.Width / (float)TouchPanel.DisplayWidth; float propY = Game.GraphicsDevice.Viewport.Height / (float)TouchPanel.DisplayHeight; posT.X *= propX; posT.Y *= propY; #endif posT.X -= Game.GraphicsDevice.Viewport.X; posT.Y -= Game.GraphicsDevice.Viewport.Y; TouchLocation previousState; touchCollection[0].TryGetPreviousLocation(out previousState); return new TouchLocation(touchCollection[0].Id, touchCollection[0].State, posT, previousState.State, previousState.Position); #else return touchCollection[0]; #endif } TouchIsFromTouchPanel = false; #endif #if !MOUSE #if WINDOWS_PHONE return new TouchLocation(-1, TouchLocationState.Invalid, Vector2.Zero); #else return new TouchLocation(-1, TouchLocationState.Invalid, Vector2.Zero, TouchLocationState.Invalid, Vector2.Zero); #endif #endif #if MOUSE var pos = new Vector2(_mouseState.X, _mouseState.Y); #if SILVERLIGHT float propX = _graphics.PreferredBackBufferWidth / (float)Game.GraphicsDevice.Viewport.Width; float propY = _graphics.PreferredBackBufferHeight / (float)Game.GraphicsDevice.Viewport.Height; pos.X *= propX; pos.Y *= propY; pos.X -= Game.GraphicsDevice.Viewport.X; pos.Y -= Game.GraphicsDevice.Viewport.Y; #endif #if WINDOWS8 || WINDOWS float propX = _graphics.PreferredBackBufferWidth / (float)Game.Window.ClientBounds.Width; float propY = _graphics.PreferredBackBufferHeight / (float)Game.Window.ClientBounds.Height; pos.X *= propX; pos.Y *= propY; pos.X -= Game.GraphicsDevice.Viewport.X; pos.Y -= Game.GraphicsDevice.Viewport.Y; #endif var touchLocationState = TouchLocationState.Invalid; if (_mouseState.LeftButton == ButtonState.Pressed && _oldMouseState.LeftButton == ButtonState.Released) touchLocationState = TouchLocationState.Pressed; else if(_mouseState.LeftButton == ButtonState.Pressed && _oldMouseState.LeftButton == ButtonState.Pressed) touchLocationState = TouchLocationState.Moved; else if(_mouseState.LeftButton == ButtonState.Released && _oldMouseState.LeftButton == ButtonState.Pressed) touchLocationState = TouchLocationState.Released; return new TouchLocation(1, touchLocationState, pos); #endif } public float ScrollWheelValue { get { #if MOUSE && !SILVERLIGHT return _mouseState.ScrollWheelValue; #else return 0; #endif } } #if SILVERLIGHT public static void Click(int X, int Y) { GameStateManagement.InputService.JustPressedMouse = 2; _mouseState = new MouseState() { X = X, Y = Y, LeftButton = ButtonState.Pressed }; } #endif } }
// #define IGNORE_VISTA // if defined in csproj compile without VISTADB // #define ENTERPRISE // if defined in csproj create com component // #define PLUGINS_FROM_SUBDIRS // if defined Plugins can also live in subdirectories of the MyMeta-bin-dir /* * PLUGINS_FROM_SUBDIRS disabled because k3b found no way to use dll-s in scrips * tried <%#REFERENCE subdir\myDll.dll %> ==> script compiler error not found * csc.exe /lib:plugins ==> script compiler error not found */ using System; using System.Text; using System.IO; using System.Xml; using System.Data; using System.Runtime.InteropServices; using System.Data.OleDb; using System.Data.Odbc; using System.Collections; using System.Reflection; using System.Diagnostics; using Npgsql; using FirebirdSql.Data.FirebirdClient; using System.Data.SQLite; using MySql.Data.MySqlClient; namespace MyMeta { #if ENTERPRISE using System.Runtime.InteropServices; using System.EnterpriseServices; /// <summary> /// MyMeta is the root of the MyMeta meta-data. MyMeta is an intrinsic object available to your script and configured based on the settings /// you have entered in the Default Settings dialog. It is already connected before you script execution begins. /// </summary> /// <remarks> /// MyMeta has 1 Collection: /// <list type="table"> /// <item><term>Databases</term><description>Contains a collection of all of the databases in your system</description></item> /// </list> /// There is a property collection on every entity in your database, you can add key/value /// pairs to the User Meta Data either through the user interface of MyGeneration or /// programmatically in your scripts. User meta data is stored in XML and never writes to your database. /// /// This can be very useful, you might need more meta data than MyMeta supplies, in fact, /// MyMeta will eventually offer extended meta data using this feature as well. The current plan /// is that any extended data added via MyGeneration will have a key that beings with "MyMeta.Something" /// where 'Something' equals the description. /// </remarks> /// <example> /// VBScript - ****** NOTE ****** You never have to actually write this code, this is for education purposes only. /// <code> /// MyMeta.Connect "SQL", "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=sa;Data Source=localhost" /// /// MyMeta.DbTarget = "SqlClient" /// MyMeta.DbTargetMappingFileName = "C:\Program Files\MyGeneration\Settings\DbTargets.xml" /// /// MyMeta.Language = "VB.NET" /// MyMeta.LanguageMappingFileName = "C:\Program Files\MyGeneration\Settings\Languages.xml" /// /// MyMeta.UserMetaDataFileName = "C:\Program Files\MyGeneration\Settings\UserMetaData.xml" /// </code> /// JScript - ****** NOTE ****** You never have to actually write this code, this is for education purposes only. /// <code> /// MyMeta.Connect("SQL", "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=sa;Data Source=localhost") /// /// MyMeta.DbTarget = "SqlClient"; /// MyMeta.DbTargetMappingFileName = "C:\Program Files\MyGeneration\Settings\DbTargets.xml"; /// /// MyMeta.Language = "VB.NET"; /// MyMeta.LanguageMappingFileName = "C:\Program Files\MyGeneration\Settings\Languages.xml"; /// /// MyMeta.UserMetaDataFileName = "C:\Program Files\MyGeneration\Settings\UserMetaData.xml"; /// </code> /// The above code is done for you long before you execute your script and the values come from the Default Settings Dialog. /// However, you can override these defaults as many of the sample scripts do. For instance, if you have a script that is for SqlClient /// only go ahead and set the MyMeta.DbTarget in your script thus overriding the Default Settings. /// </example> [GuidAttribute("6b6e4c19-a0c4-405a-8085-0676f5d5cdc3"),ClassInterface(ClassInterfaceType.AutoDual)] public class dbRoot : ServicedComponent #else public class dbRoot #endif { public dbRoot() { Access.ClassFactory.Register(); Advantage.ClassFactory.Register(); DB2.ClassFactory.Register(); Firebird.ClassFactory.Register(); ISeries.ClassFactory.Register(); MySql.ClassFactory.Register(); MySql5.ClassFactory.Register(); Oracle.ClassFactory.Register(); Pervasive.ClassFactory.Register(); PostgreSQL.ClassFactory.Register(); PostgreSQL8.ClassFactory.Register(); Sql.ClassFactory.Register(); SQLite.ClassFactory.Register(); #if !IGNORE_VISTA VistaDB.ClassFactory.Register(); #endif Reset(); } private void Reset() { UserData = null; IgnoreCase = true; requiredDatabaseName = false; requiresSchemaName = false; StripTrailingNulls = false; TrailingNull = ((char)0x0).ToString(); ClassFactory = null; _showSystemData = false; _showDefaultDatabaseOnly = false; _driver = dbDriver.None; _driverString = "NONE"; _databases = null; _connectionString = ""; _theConnection = new OleDbConnection(); _isConnected = false; _parsedConnectionString = null; _defaultDatabase = ""; _lastConnectionException = null; _lastConnectionError = string.Empty; // Language _languageMappingFileName = string.Empty; _language = string.Empty; _languageDoc = null; _languageNode = null; UserData = new XmlDocument(); UserData.AppendChild(UserData.CreateNode(XmlNodeType.Element, "MyMeta", null)); // DbTarget _dbTargetMappingFileName = string.Empty; _dbTarget = string.Empty; _dbTargetDoc = null; _dbTargetNode = null; } public object DriverSpecificData(string providerName, string key) { object o = null; if (Plugins.ContainsKey(providerName)) { o = (Plugins[providerName] as IMyMetaPlugin).GetDatabaseSpecificMetaData(null, key); } return o; } #region Properties /// <summary> /// Contains all of the databases in your DBMS system. /// </summary> public IDatabases Databases { get { if(null == _databases) { if(this.ClassFactory != null) { _databases = ClassFactory.CreateDatabases() as Databases; _databases.dbRoot = this; if (this.ShowDefaultDatabaseOnly) { _databases.LoadDefault(); } else { _databases.LoadAll(); } } } return _databases; } } public string DefaultDatabaseName { get { return _defaultDatabase; } } /// <summary> /// This is the default database as defined in your connection string, or if not provided your DBMS system may provide one. /// Finally, for single database systems like Microsoft Access it will be the default database. /// </summary> public IDatabase DefaultDatabase { get { IDatabase defDatabase = null; Databases dbases = this.Databases as Databases; if (this._defaultDatabase != null && this._defaultDatabase != "") { try { defDatabase = dbases.GetByName(this._defaultDatabase); } catch { } if (defDatabase == null) { try { defDatabase = dbases.GetByPhysicalName(this._defaultDatabase); } catch { } } } if (defDatabase == null) { if (dbases.Count == 1) { defDatabase = dbases[0]; } } return defDatabase; } } public IProviderTypes ProviderTypes { get { if(null == _providerTypes) { _providerTypes = (ProviderTypes)ClassFactory.CreateProviderTypes(); _providerTypes.dbRoot = this; _providerTypes.LoadAll(); } return _providerTypes; } } #endregion #region Connection [ComVisible(false)] public IDbConnection BuildConnection(string driver, string connectionString) { IDbConnection conn = null; switch(driver.ToUpper()) { case MyMetaDrivers.MySql2: conn = new MySqlConnection(connectionString); break; case MyMetaDrivers.PostgreSQL: case MyMetaDrivers.PostgreSQL8: conn = new Npgsql.NpgsqlConnection(connectionString); break; case MyMetaDrivers.Firebird: case MyMetaDrivers.Interbase: conn = new FirebirdSql.Data.FirebirdClient.FbConnection(connectionString); break; case MyMetaDrivers.SQLite: conn = new SQLiteConnection(connectionString); break; #if !IGNORE_VISTA case MyMetaDrivers.VistaDB: try { MyMeta.VistaDB.MetaHelper mh = new MyMeta.VistaDB.MetaHelper(); conn = mh.GetConnection(connectionString); } catch { throw new Exception("Invalid VistaDB connection or VistaDB not installed"); } break; #endif default: if (Plugins.ContainsKey(driver)) { conn = this.GetConnectionFromPlugin(driver, connectionString); } else { conn = new OleDbConnection(connectionString); } break; } return conn; } /// <summary> /// This is how you connect to your DBMS system using MyMeta. This is already called for you before your script beings execution. /// </summary> /// <param name="driver">A string as defined in the remarks below</param> /// <param name="connectionString">A valid connection string for you DBMS</param> /// <returns>True if connected, False if not</returns> /// <remarks> /// These are the supported "drivers". /// <list type="table"> /// <item><term>"ACCESS"</term><description>Microsoft Access 97 and higher</description></item> /// <item><term>"DB2"</term><description>IBM DB2</description></item> /// <item><term>"MYSQL"</term><description>Currently limited to only MySQL running on Microsoft Operating Systems</description></item> /// <item><term>"MYSQL2"</term><description>Uses MySQL Connector/Net, Supports 4.x schema info on Windows or Linux</description></item> /// <item><term>"ORACLE"</term><description>Oracle 8i - 9</description></item> /// <item><term>"SQL"</term><description>Microsoft SQL Server 2000 and higher</description></item> /// <item><term>"PERVASIVE"</term><description>Pervasive 9.00+ (might work on lower but untested)</description></item> /// <item><term>"POSTGRESQL"</term><description>PostgreSQL 7.3+ (might work on lower but untested)</description></item> /// <item><term>"POSTGRESQL8"</term><description>PostgreSQL 8.0+</description></item> /// <item><term>"FIREBIRD"</term><description>Firebird</description></item> /// <item><term>"INTERBASE"</term><description>Borland's InterBase</description></item> /// <item><term>"SQLITE"</term><description>SQLite</description></item> /// <item><term>"VISTADB"</term><description>VistaDB Database</description></item> /// <item><term>"ADVANTAGE"</term><description>Advantage Database Server</description></item> /// <item><term>"ISERIES"</term><description>iSeries (AS400)</description></item> /// </list> /// Below are some sample connection strings. However, the "Data Link" dialog available on the Default Settings dialog can help you. /// <list type="table"> /// <item><term>"ACCESS"</term><description>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\access\newnorthwind.mdb;User Id=;Password=</description></item> /// <item><term>"DB2"</term><description>Provider=IBMDADB2.1;Password=sa;User ID=DB2Admin;Data Source=MyMeta;Persist Security Info=True</description></item> /// <item><term>"MYSQL"</term><description>Provider=MySQLProv;Persist Security Info=True;Data Source=test;UID=griffo;PWD=;PORT=3306</description></item> /// <item><term>"MYSQL2"</term><description>Uses Database=Test;Data Source=Griffo;User Id=anonymous;</description></item> /// <item><term>"ORACLE"</term><description>Provider=OraOLEDB.Oracle.1;Password=sa;Persist Security Info=True;User ID=GRIFFO;Data Source=dbMeta</description></item> /// <item><term>"SQL"</term><description>Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Northwind;Data Source=localhost</description></item> /// <item><term>"PERVASIVE"</term><description>Provider=PervasiveOLEDB.8.60;Data Source=demodata;Location=Griffo;Persist Security Info=False</description></item> /// <item><term>"POSTGRESQL"</term><description>Server=www.myserver.com;Port=5432;User Id=myuser;Password=aaa;Database=mygeneration;</description></item> /// <item><term>"POSTGRESQL8"</term><description>Server=www.myserver.com;Port=5432;User Id=myuser;Password=aaa;Database=mygeneration;</description></item> /// <item><term>"FIREBIRD"</term><description>Database=C:\firebird\EMPLOYEE.GDB;User=SYSDBA;Password=wow;Dialect=3;Server=localhost</description></item> /// <item><term>"INTERBASE"</term><description>Database=C:\interbase\EMPLOYEE.GDB;User=SYSDBA;Password=wow;Dialect=3;Server=localhost</description></item> /// <item><term>"SQLITE"</term><description>Data Source=C:\SQLite\employee.db;New=False;Compress=True;Synchronous=Off;Version=3</description></item> /// <item><term>"VISTADB"</term><description>DataSource=C:\Program Files\VistaDB 2.0\Data\Northwind.vdb</description></item> /// <item><term>"ADVANTAGE"</term><description>Provider=Advantage.OLEDB.1;Password="";User ID=AdsSys;Data Source=C:\task1;Initial Catalog=aep_tutorial.add;Persist Security Info=True;Advantage Server Type=ADS_LOCAL_SERVER;Trim Trailing Spaces=TRUE</description></item> /// <item><term>"ISERIES"</term><description>PROVIDER=IBMDA400; DATA SOURCE=MY_SYSTEM_NAME;USER ID=myUserName;PASSWORD=myPwd;DEFAULT COLLECTION=MY_LIBRARY;</description></item> /// </list> /// </remarks> public bool Connect(string driverIn, string connectionString) { string driver = driverIn.ToUpper(); switch (driver) { case MyMetaDrivers.None: return true; #if !IGNORE_VISTA case MyMetaDrivers.VistaDB: #endif case MyMetaDrivers.SQL: case MyMetaDrivers.Oracle: case MyMetaDrivers.Access: case MyMetaDrivers.MySql: case MyMetaDrivers.MySql2: case MyMetaDrivers.DB2: case MyMetaDrivers.ISeries: case MyMetaDrivers.Pervasive: case MyMetaDrivers.PostgreSQL: case MyMetaDrivers.PostgreSQL8: case MyMetaDrivers.Firebird: case MyMetaDrivers.Interbase: case MyMetaDrivers.SQLite: case MyMetaDrivers.Advantage: return this.Connect( MyMetaDrivers.GetDbDriverFromName(driver), driver, connectionString); default: if (Plugins.ContainsKey(driver)) { return this.Connect(dbDriver.Plugin, driver, connectionString); } else { return false; } } } /// <summary> /// Same as <see cref="Connect(string, string)"/>(string, string) only this uses an enumeration. /// </summary> /// <param name="driver">The driver enumeration for you DBMS system</param> /// <param name="connectionString">A valid connection string for you DBMS</param> /// <returns></returns> public bool Connect(dbDriver driver, string connectionString) { return Connect(driver, string.Empty, connectionString); } /// <summary> /// Same as <see cref="Connect(string, string)"/>(string, string) only this uses an enumeration. /// </summary> /// <param name="driver">The driver enumeration for you DBMS system</param> /// <param name="pluginName">The name of the plugin</param> /// <param name="connectionString">A valid connection string for you DBMS</param> /// <returns></returns> public bool Connect(dbDriver driver, string pluginName, string connectionString) { Reset(); try { string dbName; int index; this._connectionString = connectionString.Replace("\"", ""); this._driver = driver; switch (_driver) { case dbDriver.SQL: ConnectUsingOleDb(_driver, _connectionString); this._driverString = MyMetaDrivers.SQL; this.StripTrailingNulls = false; this.requiredDatabaseName = true; ClassFactory = new MyMeta.Sql.ClassFactory(); break; case dbDriver.Oracle: ConnectUsingOleDb(_driver, _connectionString); this._driverString = MyMetaDrivers.Oracle; this.StripTrailingNulls = false; this.requiredDatabaseName = true; ClassFactory = new MyMeta.Oracle.ClassFactory(); break; case dbDriver.Access: ConnectUsingOleDb(_driver, _connectionString); this._driverString = MyMetaDrivers.Access; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.Access.ClassFactory(); break; case dbDriver.MySql: ConnectUsingOleDb(_driver, _connectionString); this._driverString = MyMetaDrivers.MySql; this.StripTrailingNulls = true; this.requiredDatabaseName = true; ClassFactory = new MyMeta.MySql.ClassFactory(); break; case dbDriver.MySql2: using (MySqlConnection mysqlconn = new MySqlConnection(_connectionString)) { mysqlconn.Close(); mysqlconn.Open(); this._defaultDatabase = mysqlconn.Database; } this._driverString = MyMetaDrivers.MySql2; this.StripTrailingNulls = true; this.requiredDatabaseName = true; ClassFactory = new MyMeta.MySql5.ClassFactory(); break; case dbDriver.DB2: ConnectUsingOleDb(_driver, _connectionString); this._driverString = MyMetaDrivers.DB2; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.DB2.ClassFactory(); break; case dbDriver.ISeries: ConnectUsingOleDb(_driver, _connectionString); this._driverString = MyMetaDrivers.ISeries; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.ISeries.ClassFactory(); break; case dbDriver.Pervasive: ConnectUsingOleDb(_driver, _connectionString); this._driverString = MyMetaDrivers.Pervasive; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.Pervasive.ClassFactory(); break; case dbDriver.PostgreSQL: using (NpgsqlConnection cn = new Npgsql.NpgsqlConnection(_connectionString)) { cn.Open(); this._defaultDatabase = cn.Database; } this._driverString = MyMetaDrivers.PostgreSQL; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.PostgreSQL.ClassFactory(); break; case dbDriver.PostgreSQL8: using (NpgsqlConnection cn8 = new Npgsql.NpgsqlConnection(_connectionString)) { cn8.Open(); this._defaultDatabase = cn8.Database; } this._driverString = MyMetaDrivers.PostgreSQL8; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.PostgreSQL8.ClassFactory(); break; case dbDriver.Firebird: using (FbConnection cn1 = new FirebirdSql.Data.FirebirdClient.FbConnection(_connectionString)) { cn1.Open(); dbName = cn1.Database; } try { index = dbName.LastIndexOfAny(new char[] { '\\' }); if (index >= 0) { this._defaultDatabase = dbName.Substring(index + 1); } } catch { } this._driverString = MyMetaDrivers.Firebird; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.Firebird.ClassFactory(); break; case dbDriver.Interbase: using (FbConnection cn2 = new FirebirdSql.Data.FirebirdClient.FbConnection(_connectionString)) { cn2.Open(); this._defaultDatabase = cn2.Database; } this._driverString = MyMetaDrivers.Interbase; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.Firebird.ClassFactory(); break; case dbDriver.SQLite: using (SQLiteConnection sqliteConn = new SQLiteConnection(_connectionString)) { sqliteConn.Open(); dbName = sqliteConn.Database; if (!string.IsNullOrEmpty(dbName)) this._defaultDatabase = dbName; } this._driverString = MyMetaDrivers.SQLite; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.SQLite.ClassFactory(); break; #if !IGNORE_VISTA case dbDriver.VistaDB: try { MyMeta.VistaDB.MetaHelper mh = new MyMeta.VistaDB.MetaHelper(); dbName = mh.LoadDatabases(_connectionString); if (dbName == "") return false; this._defaultDatabase = dbName; this._driverString = MyMetaDrivers.VistaDB; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.VistaDB.ClassFactory(); } catch { throw new Exception("Invalid VistaDB connection or VistaDB not installed"); } break; #endif case dbDriver.Advantage: ConnectUsingOleDb(_driver, _connectionString); this._driverString = MyMetaDrivers.Advantage; this.StripTrailingNulls = false; this.requiredDatabaseName = false; ClassFactory = new MyMeta.Advantage.ClassFactory(); string[] s = this._defaultDatabase.Split('.'); this._defaultDatabase = s[0]; break; case dbDriver.Plugin: IMyMetaPlugin plugin; using (IDbConnection connection = this.GetConnectionFromPlugin(pluginName, _connectionString, out plugin)) { if (connection != null) connection.Open(); dbName = connection.Database; if (!string.IsNullOrEmpty(plugin.DefaultDatabase) || string.IsNullOrEmpty(dbName)) dbName = plugin.DefaultDatabase; if (!string.IsNullOrEmpty(dbName)) this._defaultDatabase = dbName; } this._driverString = pluginName; //this.StripTrailingNulls = plugin.StripTrailingNulls; //this.requiredDatabaseName = plugin.RequiredDatabaseName; ClassFactory = new MyMeta.Plugin.ClassFactory(plugin); break; case dbDriver.None: this._driverString = MyMetaDrivers.None; break; } } catch (OleDbException ex) { this._lastConnectionException = ex; foreach (OleDbError error in ex.Errors) { if (this._lastConnectionError != string.Empty) this._lastConnectionError += Environment.NewLine; this._lastConnectionError += ex; } } catch (Exception ex) { this._lastConnectionException = ex; this._lastConnectionError = ex.Message; } _isConnected = true; return true; } private void ConnectUsingOleDb(dbDriver driver, string connectionString) { OleDbConnection cn = new OleDbConnection(connectionString.Replace("\"", "")); cn.Open(); this._defaultDatabase = GetDefaultDatabase(cn, driver); cn.Close(); } public string LastConnectionError { get { return _lastConnectionError; } } [ComVisible(false)] public Exception LastConnectionException { get { return _lastConnectionException; } } [ComVisible(false)] public System.Collections.Generic.Dictionary<string, string> UserDataDatabaseMappings { get { if (_userDataDatabaseMappings == null) _userDataDatabaseMappings = new System.Collections.Generic.Dictionary<string,string>(); return _userDataDatabaseMappings; } } [ComVisible(false)] public void ChangeDatabase(IDbConnection connection, string database) { if (this.ClassFactory != null) this.ClassFactory.ChangeDatabase(connection, database); } internal OleDbConnection TheConnection { get { if(this._theConnection.State != ConnectionState.Open) { this._theConnection.ConnectionString = this._connectionString; this._theConnection.Open(); } return this._theConnection; } } private string GetDefaultDatabase(OleDbConnection cn, dbDriver driver) { string databaseName = string.Empty; switch(driver) { case dbDriver.Access: int i = cn.DataSource.LastIndexOf(@"\"); if(i == -1) databaseName = cn.DataSource; else databaseName = cn.DataSource.Substring(++i); break; default: databaseName = cn.Database; break; } return databaseName; } /// <summary> /// True if MyMeta has been successfully connected to your DBMS, False if not. /// </summary> public bool IsConnected { get { return _isConnected; } } /// <summary> /// Returns MyMeta's current dbDriver enumeration value as defined by its current connection. /// </summary> public dbDriver Driver { get { return _driver; } } /// <summary> /// Returns MyMeta's current DriverString as defined by its current connection. /// </summary> /// <remarks> /// These are the current possible values. /// <list type="table"> /// <item><term>"ACCESS"</term><description>Microsoft Access 97 and higher</description></item> /// <item><term>"DB2"</term><description>IBM DB2</description></item> /// <item><term>"MYSQL"</term><description>Currently limited to only MySQL running on Microsoft Operating Systems</description></item> /// <item><term>"ORACLE"</term><description>Oracle 8i - 9</description></item> /// <item><term>"SQL"</term><description>Microsoft SQL Server 2000 and higher</description></item> /// <item><term>"PostgreSQL"</term><description>PostgreSQL</description></item> /// /// </list> /// </remarks> public string DriverString { get { return _driverString; } } /// <summary> /// Returns the current connection string. ** WARNING ** Currently the password is returned, the password will be stripped from this /// property in the very near future. /// </summary> public string ConnectionString { get { return _connectionString; } } internal Hashtable ParsedConnectionString { get { //Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=Northwind;Data Source=localhost if(null == _parsedConnectionString) { string[] tokens = ConnectionString.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries); _parsedConnectionString = new Hashtable(tokens.Length); string[] kv = null; for (int i = 0; i < tokens.Length; i++) { kv = tokens[i].Split('='); if (kv.Length == 2) { _parsedConnectionString.Add(kv[0].ToUpper(), kv[1]); } else if (kv.Length == 1) { _parsedConnectionString.Add(kv[0].ToUpper(), string.Empty); } } } return _parsedConnectionString; } } #endregion #region Settings /// <summary> /// Determines whether system tables and views and alike are shown, the default is False. If True, ONLY system data is shown. /// </summary> public bool ShowSystemData { get { return _showSystemData; } set { _showSystemData = value ; } } /// <summary> /// Only show the default database in the databases collection. /// </summary> public bool ShowDefaultDatabaseOnly { get { return _showDefaultDatabaseOnly; } set { if (_showDefaultDatabaseOnly != value) { this._databases = null; } _showDefaultDatabaseOnly = value; } } /// <summary> /// If this is true then four IColumn properties are actually supplied by the Domain, if the Column has an IDomain. /// The four properties are DataTypeName, DataTypeNameComplete, LanguageType, and DbTargetType. /// </summary> public bool DomainOverride { get { return _domainOverride; } set { _domainOverride = value ; } } #endregion #region Plugin Members /// <summary> /// If you want to fetch data specific to a given plugin, you can get generic info here. /// </summary> /// <param name="providerName"></param> /// <param name="key"></param> /// <returns></returns> public object PluginSpecificData(string providerName, string key) { object o = null; try { if (Plugins.ContainsKey(providerName)) { o = (Plugins[providerName] as IMyMetaPlugin).GetDatabaseSpecificMetaData(null, key); } } catch { } return o; } /// <summary> /// A Plugin ConnectionString is a special feature for external assemblies. /// </summary> /// <param name="connectionString">Sample: PluginName;Provider=SQLOLEDB.1;Persist Security Info=True;User ID=sa;Data Source=localhost</param> /// <returns></returns> private IDbConnection GetConnectionFromPlugin(string providerName, string pluginConnectionString) { IMyMetaPlugin plugin; return GetConnectionFromPlugin(providerName, pluginConnectionString, out plugin); } /// <summary> /// A Plugin ConnectionString is a special feature for external assemblies. /// </summary> /// <param name="pluginConnectionString">Sample: PluginName;Provider=SQLOLEDB.1;Persist Security Info=True;User ID=sa;Data Source=localhost</param> /// <param name="plugin">Returns the plugin object.</param> /// <returns></returns> private IDbConnection GetConnectionFromPlugin(string providerName, string pluginConnectionString, out IMyMetaPlugin plugin) { MyMetaPluginContext pluginContext = new MyMetaPluginContext(providerName, pluginConnectionString); IDbConnection connection = null; if (!Plugins.ContainsKey(providerName)) { throw new Exception("MyMeta Plugin \"" + providerName + "\" not registered."); } else { plugin = Plugins[providerName] as IMyMetaPlugin; plugin.Initialize(pluginContext); connection = plugin.NewConnection; } return connection; } private static Hashtable plugins; [ComVisible(false)] public static Hashtable Plugins { get { if (plugins == null) { plugins = new Hashtable(); FileInfo info = new FileInfo(Assembly.GetCallingAssembly().Location); if (info.Exists) { StringBuilder fileNames = new StringBuilder(); Exception err = null; #if PLUGINS_FROM_SUBDIRS // k3b allow plugins to be in its own directory foreach (FileInfo dllFile in info.Directory.GetFiles("MyMeta.Plugins.*.dll",SearchOption.AllDirectories)) #else foreach (FileInfo dllFile in info.Directory.GetFiles("MyMeta.Plugins.*.dll")) #endif { try { loadPlugin(dllFile.FullName, plugins); } catch(Exception ex) { // Fix K3b 2007-06-27 if the current plugin cannot be loaded ignore it. // i got the exception when loading a plugin that was linked against an old Interface // the chatch ensures that the rest of the application-initialisation continues ... fileNames.AppendLine(dllFile.FullName); err = ex; } } //TODO How to tell the caller that something is not ok. A Exception would result in a incomplete initialisation // if (err != null) // throw new ApplicationException("Cannot load Plugin(s) " + fileNames.ToString(), err); } } return plugins; } } private static void loadPlugin(string filename, Hashtable plugins) { #if PLUGINS_FROM_SUBDIRS if (System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) != System.IO.Path.GetDirectoryName(filename)) AppDomain.CurrentDomain.AppendPrivatePath(System.IO.Path.GetDirectoryName(filename)); #endif Assembly assembly = Assembly.LoadFile(filename); foreach (Type type in assembly.GetTypes()) { Type[] interfaces = type.GetInterfaces(); foreach (Type iface in interfaces) { if (iface == typeof(IMyMetaPlugin)) { try { ConstructorInfo[] constructors = type.GetConstructors(); ConstructorInfo constructor = constructors[0]; IMyMetaPlugin plugin = constructor.Invoke(BindingFlags.CreateInstance, null, new object[] { }, null) as IMyMetaPlugin; InternalDriver.Register(plugin.ProviderUniqueKey, new PluginDriver(plugin)); plugins[plugin.ProviderUniqueKey] = plugin; // after register because if exception in register, donot remeber plugin } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Cannot load plugin " + filename); while (ex != null) { System.Diagnostics.Trace.WriteLine(ex.Message); System.Diagnostics.Trace.WriteLine(ex.StackTrace); ex = ex.InnerException; } } } } } } static Module assembly_ModuleResolve(object sender, ResolveEventArgs e) { // throw new Exception("The method or operation is not implemented."); return null; } #endregion #region XML User Data public string UserDataXPath { get { return @"//MyMeta"; } } internal bool GetXmlNode(out XmlNode node, bool forceCreate) { node = null; bool success = false; if(null == _xmlNode) { if(!UserData.HasChildNodes) { _xmlNode = UserData.CreateNode(XmlNodeType.Element, "MyMeta", null); UserData.AppendChild(_xmlNode); } else { _xmlNode = UserData.SelectSingleNode("./MyMeta"); } } if(null != _xmlNode) { node = _xmlNode; success = true; } return success; } /// <summary> /// The full path of the XML file that contains the user defined meta data. See IPropertyCollection /// </summary> public string UserMetaDataFileName { get { return _userMetaDataFileName; } set { _userMetaDataFileName = value; try { UserData = new XmlDocument(); UserData.Load(_userMetaDataFileName); } catch { UserData = new XmlDocument(); } } } /// <summary> /// Call this method to save any user defined meta data that you may have modified. See <see cref="UserMetaDataFileName"/> /// </summary> /// <returns>True if saved, False if not</returns> public bool SaveUserMetaData() { if (null != UserData && string.Empty != _userMetaDataFileName) { FileInfo f = new FileInfo(_userMetaDataFileName); if (!f.Exists) { if (!f.Directory.Exists) f.Directory.Create(); } UserData.Save(_userMetaDataFileName); return true; } return false; } private string _userMetaDataFileName = ""; public static void MergeUserMetaDataFiles(string f1, string db1, string f2, string db2, string fm) { FileInfo f1Inf = new FileInfo(f1); FileInfo f2Inf = new FileInfo(f2); FileInfo fmInf = new FileInfo(fm); if (fmInf.Exists) fmInf.Delete(); fmInf = f1Inf.CopyTo(fmInf.FullName); XmlDocument newDoc = new XmlDocument(); newDoc.Load(fmInf.FullName); XmlNode newDocRoot = newDoc.SelectSingleNode("//MyMeta/Databases/Database[@p='" + db1 + "']"); XmlDocument otherDoc = new XmlDocument(); otherDoc.Load(f2Inf.FullName); XmlNode otherDocRoot = otherDoc.SelectSingleNode("//MyMeta/Databases/Database[@p='" + db2 + "']"); MergeXml(newDoc, newDocRoot, "//MyMeta/Databases/Database[@p='" + db1 + "']", otherDoc, otherDocRoot, "//MyMeta/Databases/Database[@p='" + db2 + "']"); newDoc.Save(fmInf.FullName); } private static void MergeXml(XmlDocument d1, XmlNode n1, string xpath1, XmlDocument d2, XmlNode n2, string xpath2) { System.Collections.Generic.Dictionary<string, XmlNode> ch1nodes = new System.Collections.Generic.Dictionary<string,XmlNode>(); foreach (XmlNode ch1 in n1.ChildNodes) { ch1nodes[GetXmlNodeKey(ch1)] = ch1; } foreach (XmlNode ch2 in n2.ChildNodes) { string ch2Key = GetXmlNodeKey(ch2); XmlNode ch1 = null; if (ch1nodes.ContainsKey(ch2Key)) { ch1 = ch1nodes[ch2Key]; if (ch2.Attributes["n"] != null && ch1.Attributes["n"] == null) ch1.Attributes.Append(ch2.Attributes["n"].Clone() as XmlAttribute); else if (ch2.Attributes["v"] != null && ch1.Attributes["v"] == null) ch1.Attributes.Append(ch2.Attributes["v"].Clone() as XmlAttribute); if (ch2.HasChildNodes) { MergeXml(d1, ch1, xpath1 + ch2Key, d2, ch2, xpath2 + ch2Key); } } else { //ch1 = ch2.CloneNode(true); ch1 = d1.ImportNode(ch2, true); n1.AppendChild(ch1); } } } private static string GetXmlNodeKey(XmlNode n) { string xpathKey = "/" + n.Name; if (n.Attributes["p"] != null) { xpathKey += "[@p='" + n.Attributes["p"].Value + "']"; } else if (n.Attributes["k"] != null) { xpathKey += "[@k='" + n.Attributes["k"].Value + "']"; } return xpathKey; } #endregion #region XML Language Mapping /// <summary> /// The full path of the XML file that contains the language mappings. The data in this file plus the value you provide /// to <see cref="Language"/> determine the value of IColumn.Language. /// </summary> public string LanguageMappingFileName { get { return _languageMappingFileName; } set { try { _languageMappingFileName = value; _languageDoc = new XmlDocument(); _languageDoc.Load(_languageMappingFileName); _language = string.Empty;; _languageNode = null; } catch {} } } /// <summary> /// Returns all of the languages currently configured for the DBMS set when Connect was called. /// </summary> /// <returns>An array with all of the possible languages.</returns> public string[] GetLanguageMappings() { return GetLanguageMappings(_driverString); } /// <summary> /// Returns all of the languages for a given driver, regardless of MyMeta's current connection /// </summary> /// <returns>An array with all of the possible languages.</returns> public string[] GetLanguageMappings(string driverString) { string[] mappings = null; if ((null != _languageDoc) && (driverString != null)) { driverString = driverString.ToUpper(); string xPath = @"//Languages/Language[@From='" + driverString + "']"; XmlNodeList nodes = _languageDoc.SelectNodes(xPath, null); if ((null != nodes) && (nodes.Count > 0)) { int nodeCount = nodes.Count; mappings = new string[nodeCount]; for(int i = 0; i < nodeCount; i++) { mappings[i] = nodes[i].Attributes["To"].Value; } } } return mappings; } /// <summary> /// Use this to choose your Language, for example, "C#". See <see cref="LanguageMappingFileName"/> for more information /// </summary> public string Language { get { return _language; } set { if(null != _languageDoc) { _language = value; string xPath = @"//Languages/Language[@From='" + _driverString + "' and @To='" + _language + "']"; _languageNode = _languageDoc.SelectSingleNode(xPath, null); } } } [ComVisible(false)] public XmlNode LanguageNode { get { return _languageNode; } } private string _languageMappingFileName = string.Empty; private string _language = string.Empty; private XmlDocument _languageDoc; private XmlNode _languageNode = null; #endregion #region XML DbTarget Mapping /// <summary> /// The full path of the XML file that contains the DbTarget mappings. The data in this file plus the value you provide /// to <see cref="DbTarget"/> determine the value of IColumn.DbTarget. /// </summary> public string DbTargetMappingFileName { get { return _dbTargetMappingFileName; } set { try { _dbTargetMappingFileName = value; _dbTargetDoc = new XmlDocument(); _dbTargetDoc.Load(_dbTargetMappingFileName); _dbTarget = string.Empty;; _dbTargetNode = null; } catch {} } } /// <summary> /// Returns all of the dbTargets currently configured for the DBMS set when Connect was called. /// </summary> /// <returns>An array with all of the possible dbTargets.</returns> public string[] GetDbTargetMappings() { return GetDbTargetMappings(_driverString); } /// <summary> /// Returns all of the dbTargets for a given driver, regardless of MyMeta's current connection /// </summary> /// <returns>An array with all of the possible dbTargets.</returns> public string[] GetDbTargetMappings(string driverString) { string[] mappings = null; if ((null != _dbTargetDoc) && (driverString != null)) { driverString = driverString.ToUpper(); string xPath = @"//DbTargets/DbTarget[@From='" + driverString + "']"; XmlNodeList nodes = _dbTargetDoc.SelectNodes(xPath, null); if(null != nodes && nodes.Count > 0) { int nodeCount = nodes.Count; mappings = new string[nodeCount]; for(int i = 0; i < nodeCount; i++) { mappings[i] = nodes[i].Attributes["To"].Value; } } } return mappings; } /// <summary> /// Use this to choose your DbTarget, for example, "SqlClient". See <see cref="DbTargetMappingFileName"/> for more information /// </summary> public string DbTarget { get { return _dbTarget; } set { if(null != _dbTargetDoc) { _dbTarget = value; string xPath = @"//DbTargets/DbTarget[@From='" + _driverString + "' and @To='" + _dbTarget + "']"; _dbTargetNode = _dbTargetDoc.SelectSingleNode(xPath, null); } } } [ComVisible(false)] public XmlNode DbTargetNode { get { return _dbTargetNode; } } private string _dbTargetMappingFileName = string.Empty; private string _dbTarget = string.Empty; private XmlDocument _dbTargetDoc; private XmlNode _dbTargetNode = null; #endregion public XmlDocument UserData = new XmlDocument(); public bool IgnoreCase = true; public bool requiredDatabaseName = false; public bool requiresSchemaName = false; public bool StripTrailingNulls = false; public string TrailingNull = null; public IClassFactory ClassFactory = null; private bool _showSystemData = false; private bool _showDefaultDatabaseOnly = false; private dbDriver _driver = dbDriver.None; private string _driverString = "NONE"; private string _defaultDatabase = ""; private Databases _databases = null; private ProviderTypes _providerTypes = null; private string _connectionString = ""; private bool _isConnected = false; private Hashtable _parsedConnectionString = null; private bool _domainOverride = true; private string _lastConnectionError = string.Empty; private Exception _lastConnectionException = null; private XmlNode _xmlNode = null; private System.Collections.Generic.Dictionary<string, string> _userDataDatabaseMappings = null; private OleDbConnection _theConnection = new OleDbConnection(); } /// <summary> /// The current list of support dbDrivers. Typically VBScript and JScript use the string version as defined by MyMeta.DriverString. /// </summary> #if ENTERPRISE [GuidAttribute("0e781bc8-b741-4d71-bd0f-8ef7303ab826")] #endif public enum dbDriver { /// <summary> /// String form is "SQL" for DriverString property /// </summary> SQL, /// <summary> /// String form is "ORACLE" for DriverString property /// </summary> Oracle, /// <summary> /// String form is "ACCESS" for DriverString property /// </summary> Access, /// <summary> /// String form is "MYSQL" for DriverString property /// </summary> MySql, /// <summary> /// String form is "MYSQL" for DriverString property /// </summary> MySql2, /// <summary> /// String form is "DB2" for DriverString property /// </summary> DB2, /// <summary> /// String form is "ISeries" for DriverString property /// </summary> ISeries, /// <summary> /// String form is "PERVASIVE" for DriverString property /// </summary> Pervasive, /// <summary> /// String form is "POSTGRESQL" for DriverString property /// </summary> PostgreSQL, /// <summary> /// String form is "POSTGRESQL8" for DriverString property /// </summary> PostgreSQL8, /// <summary> /// String form is "FIREBIRD" for DriverString property /// </summary> Firebird, /// <summary> /// String form is "INTERBASE" for DriverString property /// </summary> Interbase, /// <summary> /// String form is "SQLITE" for DriverString property /// </summary> SQLite, #if !IGNORE_VISTA /// <summary> /// String form is "VISTADB" for DriverString property /// </summary> VistaDB, #endif /// <summary> /// String form is "ADVANTAGE" for DriverString property /// </summary> Advantage, /// <summary> /// This is a placeholder for plugin providers /// </summary> Plugin, /// <summary> /// Use this if you want know connection at all /// </summary> None } #region MyMetaDrivers string Constants public static class MyMetaDrivers { public const string Access = "ACCESS"; public const string Advantage = "ADVANTAGE"; public const string DB2 = "DB2"; public const string Firebird = "FIREBIRD"; public const string Interbase = "INTERBASE"; public const string ISeries = "ISERIES"; public const string MySql = "MYSQL"; public const string MySql2 = "MYSQL2"; public const string None = "NONE"; public const string Oracle = "ORACLE"; public const string Pervasive = "PERVASIVE"; public const string PostgreSQL = "POSTGRESQL"; public const string PostgreSQL8 = "POSTGRESQL8"; public const string SQLite = "SQLITE"; public const string SQL = "SQL"; #if !IGNORE_VISTA public const string VistaDB = "VISTADB"; #endif public static dbDriver GetDbDriverFromName(string name) { switch (name) { case MyMetaDrivers.SQL: return dbDriver.SQL; case MyMetaDrivers.Oracle: return dbDriver.Oracle; case MyMetaDrivers.Access: return dbDriver.Access; case MyMetaDrivers.MySql: return dbDriver.MySql; case MyMetaDrivers.MySql2: return dbDriver.MySql2; case MyMetaDrivers.DB2: return dbDriver.DB2; case MyMetaDrivers.ISeries: return dbDriver.ISeries; case MyMetaDrivers.Pervasive: return dbDriver.Pervasive; case MyMetaDrivers.PostgreSQL: return dbDriver.PostgreSQL; case MyMetaDrivers.PostgreSQL8: return dbDriver.PostgreSQL8; case MyMetaDrivers.Firebird: return dbDriver.Firebird; case MyMetaDrivers.Interbase: return dbDriver.Interbase; case MyMetaDrivers.SQLite: return dbDriver.SQLite; #if !IGNORE_VISTA case MyMetaDrivers.VistaDB: return dbDriver.VistaDB; #endif case MyMetaDrivers.Advantage: return dbDriver.Advantage; case MyMetaDrivers.None: return dbDriver.None; default: return dbDriver.Plugin; } } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.hide001.hide001 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(28,16\).*CS0108</Expects> public class Base { public static int Status; public int this[int x] { get { Base.Status = 1; return int.MinValue; } set { Base.Status = 2; } } } public class Derived : Base { public int this[int x] { get { Base.Status = 3; return int.MaxValue; } set { if (value == int.MaxValue) Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; int xx = d[x]; if (xx != int.MaxValue || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.hide002.hide002 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(29,18\).*CS0108</Expects> public class C { } public class Base { public static int Status; public float this[C x] { get { Base.Status = 1; return float.NaN; } set { Base.Status = 2; } } } public class Derived : Base { public float this[C x] { get { Base.Status = 3; return float.NegativeInfinity; } set { if (value == float.NegativeInfinity) Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); float f = d[x]; if (f != float.NegativeInfinity || Base.Status != 3) return 1; d[x] = f; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.hide003.hide003 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class Base { public static int Status; public decimal this[C x] { get { Base.Status = 1; return decimal.One; } set { Base.Status = 2; } } } public class Derived : Base { public new decimal this[C x] { get { Base.Status = 3; return decimal.Zero; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); decimal dd = d[x]; if (dd != decimal.Zero || Base.Status != 3) return 1; d[x] = dd; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload001.overload001 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public decimal this[short x] { get { Base.Status = 1; return decimal.MinValue; } set { if (value == decimal.MinValue) Base.Status = 2; } } } public class Derived : Base { public decimal this[int x] { get { Base.Status = 3; return decimal.MaxValue; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; // should call this[Derived] decimal dd = d[x]; if (dd != decimal.MaxValue || Base.Status != 3) return 1; d[x] = dd; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload002.overload002 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public char this[short x] { get { Base.Status = 1; return 'a'; } set { Base.Status = 2; } } } public class Derived : Base { public char this[int x] { get { Base.Status = 3; return 'b'; } set { if (value == 'b') Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; char c = d[x]; if (c != 'b' || Base.Status != 3) return 1; d[x] = c; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload003.overload003 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; protected string[] this[short x] { get { Base.Status = 1; return new string[] { "foo" } ; } set { Base.Status = 2; } } } public class Derived : Base { public string[] this[int x] { get { Base.Status = 3; return new string[] { string.Empty } ; } set { if (value.Length == 1 && value[0] == string.Empty) Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; string[] ss = d[x]; if (ss.Length != 1 || ss[0] != string.Empty || Base.Status != 3) return 1; d[x] = ss; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload004.overload004 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public byte this[short x] { get { Base.Status = 1; return byte.MinValue; } set { if (value == byte.MinValue) Base.Status = 2; } } } public class Derived : Base { protected byte this[int x] { get { Base.Status = 3; return byte.MaxValue; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); var x = 3; byte bb = d[(short)x]; if (bb != byte.MinValue || Base.Status != 1) return 1; d[(short)x] = bb; if (Base.Status != 2) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload005.overload005 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public string this[short x] { get { Base.Status = 1; return "foo"; } set { if (value == "foo") Base.Status = 2; } } } public class Derived : Base { private string this[int x] { get { Base.Status = 3; return string.Empty; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); byte x = 3; string s = d[x]; if (s != "foo" || Base.Status != 1) return 1; d[x] = s; if (Base.Status != 2) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload006.overload006 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; internal float this[short x] { get { Base.Status = 1; return float.NegativeInfinity; } set { Base.Status = 2; } } } public class Derived : Base { public float this[int x] { get { Base.Status = 3; return float.NaN; } set { if (float.IsNaN(value)) Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; float f = d[x]; if (!float.IsNaN(f) || Base.Status != 3) return 1; d[x] = f; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload007.overload007 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Call methods with different accessibility level and selecting the right one.:) // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; protected internal char this[short x] { get { Base.Status = 1; return 'a'; } set { Base.Status = 2; } } } public class Derived : Base { public char this[int x] { get { Base.Status = 3; return 'b'; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; char c = d[x]; if (c != 'b' || Base.Status != 3) return 1; d[x] = c; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.overload008.overload008 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // Select the best method to call. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public int this[dynamic x] { get { Base.Status = 1; return 0; } set { Base.Status = 2; } } public int this[short x] { get { Base.Status = 3; return int.MinValue; } set { Base.Status = 4; } } } public class Derived : Base { public int this[int x] { get { Base.Status = 5; return int.MaxValue; } set { if (value == int.MaxValue) Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); dynamic x = 3; int xx = d[x]; if (xx != int.MaxValue || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr001.ovr001 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual string this[int x] { get { Base.Status = 1; return string.Empty; } set { Base.Status = 2; } } } public class Derived : Base { public override string this[int x] { get { Base.Status = 3; return "foo"; } set { Base.Status = 4; } } public string this[long l] { get { Base.Status = 5; return "bar"; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; string ss = d[x]; if (ss != "bar" || Base.Status != 5) return 1; d[x] = ss; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr002.ovr002 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual int this[int x] { get { Base.Status = 1; return int.MaxValue; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[int x] { get { Base.Status = 3; return int.MinValue; } set { Base.Status = 4; } } public int this[long l] { get { Base.Status = 5; return 0; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; int xx = d[x]; if (xx != 0 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr003.ovr003 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual string this[string x] { get { Base.Status = 1; return string.Empty; } set { Base.Status = 2; } } } public class Derived : Base { public override string this[string x] { get { Base.Status = 3; return "foo"; } set { Base.Status = 4; } } public string this[object o] { get { Base.Status = 5; return "bar"; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); string x = "3"; string ss = d[x]; if (ss != "bar" || Base.Status != 5) return 1; d[x] = ss; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr004.ovr004 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual int this[D x] { get { Base.Status = 1; return int.MaxValue; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[D x] { get { Base.Status = 3; return int.MinValue; } set { Base.Status = 4; } } public int this[C o] { get { Base.Status = 5; return 0; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); int xx = d[x]; if (xx != 0 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr005.ovr005 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual int this[D x] { get { Base.Status = 1; return int.MaxValue; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[D x] { get { Base.Status = 3; return int.MinValue; } set { Base.Status = 4; } } public int this[C o] { get { Base.Status = 5; return 0; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); D x = new D(); int xx = d[x]; if (xx != 0 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr006.ovr006 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual int this[D x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[D x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[C o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new D(); int xx = d[x]; if (xx != 5 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr007.ovr007 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class D : C { } public class Base { public static int Status; public virtual int this[int x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[int x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[string o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); int x = 3; int xx = d[x]; if (xx != 3 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr008.ovr008 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { } public class Base { public static int Status; public virtual int this[int x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[int x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[C o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); short x = 3; int xx = d[x]; if (xx != 3 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr009.ovr009 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public enum E { first, second } public class Base { public static int Status; public virtual int this[string x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[string x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[E o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); string x = "adfs"; int xx = d[x]; if (xx != 3 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr010.ovr010 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { public static implicit operator int (C c) { return 0; } } public class Base { public static int Status; public virtual int this[C x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[C x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[int o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); //This should go to Base.Status = 3 int xx = d[x]; if (xx != 5 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr011.ovr011 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class C { public static implicit operator int (C c) { return 0; } } public class Base { public static int Status; public virtual int this[C x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[C x] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } public int this[long o] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); C x = new C(); //This should go to Base.Status = 3 int xx = d[x]; if (xx != 5 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovr012.ovr012 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual int this[int x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } public virtual int this[long y] { get { Base.Status = 3; return 3; } set { Base.Status = 4; } } } public class Derived : Base { public override int this[long x] { get { Base.Status = 5; return 5; } set { Base.Status = 6; } } } public class FurtherDerived : Derived { public override int this[int y] { get { Base.Status = 7; return 7; } set { Base.Status = 8; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new FurtherDerived(); long x = 3; int xx = d[x]; if (xx != 5 || Base.Status != 5) return 1; d[x] = xx; if (Base.Status != 6) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovrdynamic001.ovrdynamic001 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual int this[object x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[dynamic x] { get { Base.Status = 3; return 2; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); Base x = new Base(); //This should go to Base.Status = 3 int xx = d[x]; if (xx != 2 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.overloadResolution.Indexers.Twoclass2indexers.ovrdynamic002.ovrdynamic002 { // <Title> Tests overload resolution for 2 class and 2 methods</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Base { public static int Status; public virtual int this[dynamic x] { get { Base.Status = 1; return 1; } set { Base.Status = 2; } } } public class Derived : Base { public override int this[object x] { get { Base.Status = 3; return 2; } set { Base.Status = 4; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new Derived(); Base x = new Base(); //This should go to Base.Status = 3 int xx = d[x]; if (xx != 2 || Base.Status != 3) return 1; d[x] = xx; if (Base.Status != 4) return 1; return 0; } } // </Code> }
////////////////////////////////////////////////////////////////////////// // Code Named: VG-Ripper // Function : Extracts Images posted on RiP forums and attempts to fetch // them to disk. // // This software is licensed under the MIT license. See license.txt for // details. // // Copyright (c) The Watcher // Partial Rights Reserved. // ////////////////////////////////////////////////////////////////////////// // This file is part of the RiP Ripper project base. using System; using System.Collections; using System.IO; using System.Net; using System.Threading; namespace Ripper { using Ripper.Core.Components; using Ripper.Core.Objects; /// <summary> /// Worker class to get images from PicTiger.com /// </summary> public class PicTiger : ServiceTemplate { public PicTiger(ref string sSavePath, ref string strURL, ref string thumbURL, ref string imageName, ref int imageNumber, ref Hashtable hashtable) : base(sSavePath, strURL, thumbURL, imageName, imageNumber, ref hashtable) { } protected override bool DoDownload() { var strImgURL = this.ImageLinkURL; if (this.EventTable.ContainsKey(strImgURL)) { return true; } var strFilePath = strImgURL.Substring(strImgURL.IndexOf("picture-hosting/") + 16); strFilePath = strFilePath.Remove(strFilePath.Length - 4, 4); try { if (!Directory.Exists(this.SavePath)) Directory.CreateDirectory(this.SavePath); } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; return false; } strFilePath = Path.Combine(this.SavePath, Utility.RemoveIllegalCharecters(strFilePath)); var CCObj = new CacheObject(); CCObj.IsDownloaded = false; CCObj.FilePath = strFilePath; CCObj.Url = strImgURL; try { this.EventTable.Add(strImgURL, CCObj); } catch (ThreadAbortException) { return true; } catch (Exception) { if (this.EventTable.ContainsKey(strImgURL)) { return false; } else { this.EventTable.Add(strImgURL, CCObj); } } var strIVPage = this.GetImageHostPage(ref strImgURL); if (strIVPage.Length < 10) { return false; } var strNewURL = string.Empty; strNewURL = strImgURL.Substring(0, strImgURL.IndexOf("/", 8) + 1); var iStartSRC = 0; var iEndSRC = 0; iStartSRC = strIVPage.IndexOf("<img id=\"mainImg\" src='"); if (iStartSRC < 0) { return false; } iStartSRC += 23; iEndSRC = strIVPage.IndexOf("' alt='", iStartSRC); if (iEndSRC < 0) { return false; } strNewURL = strIVPage.Substring(iStartSRC, iEndSRC - iStartSRC); ////////////////////////////////////////////////////////////////////////// HttpWebRequest lHttpWebRequest; HttpWebResponse lHttpWebResponse; Stream lHttpWebResponseStream; try { lHttpWebRequest = (HttpWebRequest)WebRequest.Create(strNewURL); lHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"; lHttpWebRequest.Headers.Add("Accept-Language: en-us,en;q=0.5"); lHttpWebRequest.Headers.Add("Accept-Encoding: gzip,deflate"); lHttpWebRequest.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); lHttpWebRequest.Referer = strImgURL; lHttpWebRequest.Accept = "image/png,*/*;q=0.5"; lHttpWebRequest.KeepAlive = true; lHttpWebResponse = (HttpWebResponse)lHttpWebRequest.GetResponse(); lHttpWebResponseStream = lHttpWebRequest.GetResponse().GetResponseStream(); if (lHttpWebResponse.ContentType.IndexOf("image") < 0) { // if (lFileStream != null) // lFileStream.Close(); return false; } if (lHttpWebResponse.ContentType.ToLower() == "image/jpeg") strFilePath += ".jpg"; else if (lHttpWebResponse.ContentType.ToLower() == "image/gif") strFilePath += ".gif"; else if (lHttpWebResponse.ContentType.ToLower() == "image/png") strFilePath += ".png"; lHttpWebResponseStream.Close(); var NewAlteredPath = Utility.GetSuitableName(strFilePath); if (strFilePath != NewAlteredPath) { strFilePath = NewAlteredPath; ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath; } var client = new WebClient(); client.Headers.Add("Accept-Language: en-us,en;q=0.5"); client.Headers.Add("Accept-Encoding: gzip,deflate"); client.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); client.Headers.Add("Referer: " + strImgURL); client.Headers.Add( "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6"); client.DownloadFile(strNewURL, strFilePath); } catch (ThreadAbortException) { ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return true; } catch (IOException ex) { // MainForm.DeleteMessage = ex.Message; // MainForm.Delete = true; ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return true; } catch (WebException) { ((CacheObject)this.EventTable[strImgURL]).IsDownloaded = false; ThreadManager.GetInstance().RemoveThreadbyId(this.ImageLinkURL); return false; } ((CacheObject)this.EventTable[this.ImageLinkURL]).IsDownloaded = true; // CacheController.GetInstance().u_s_LastPic = ((CacheObject)eventTable[mstrURL]).FilePath; CacheController.Instance().LastPic = ((CacheObject)this.EventTable[this.ImageLinkURL]).FilePath = strFilePath; return true; } ////////////////////////////////////////////////////////////////////////// } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERCLevel; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H07_RegionColl (editable child list).<br/> /// This is a generated base class of <see cref="H07_RegionColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="H06_Country"/> editable child object.<br/> /// The items of the collection are <see cref="H08_Region"/> objects. /// </remarks> [Serializable] public partial class H07_RegionColl : BusinessListBase<H07_RegionColl, H08_Region> { #region Collection Business Methods /// <summary> /// Removes a <see cref="H08_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 h08_Region in this) { if (h08_Region.Region_ID == region_ID) { Remove(h08_Region); break; } } } /// <summary> /// Determines whether a <see cref="H08_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 H08_Region is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int region_ID) { foreach (var h08_Region in this) { if (h08_Region.Region_ID == region_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="H08_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 H08_Region is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int region_ID) { foreach (var h08_Region in DeletedList) { if (h08_Region.Region_ID == region_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="H08_Region"/> item of the <see cref="H07_RegionColl"/> collection, based on a given Region_ID. /// </summary> /// <param name="region_ID">The Region_ID.</param> /// <returns>A <see cref="H08_Region"/> object.</returns> public H08_Region FindH08_RegionByRegion_ID(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="H07_RegionColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="H07_RegionColl"/> collection.</returns> internal static H07_RegionColl NewH07_RegionColl() { return DataPortal.CreateChild<H07_RegionColl>(); } /// <summary> /// Factory method. Loads a <see cref="H07_RegionColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_Country_ID">The Parent_Country_ID parameter of the H07_RegionColl to fetch.</param> /// <returns>A reference to the fetched <see cref="H07_RegionColl"/> collection.</returns> internal static H07_RegionColl GetH07_RegionColl(int parent_Country_ID) { return DataPortal.FetchChild<H07_RegionColl>(parent_Country_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H07_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 H07_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 a <see cref="H07_RegionColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_Country_ID">The Parent Country ID.</param> protected void Child_Fetch(int parent_Country_ID) { var args = new DataPortalHookArgs(parent_Country_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IH07_RegionCollDal>(); var data = dal.Fetch(parent_Country_ID); LoadCollection(data); } OnFetchPost(args); foreach (var item in this) { item.FetchChildren(); } } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="H07_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; while (dr.Read()) { Add(H08_Region.GetH08_Region(dr)); } 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 } }
using System.Threading; using NUnit.Framework; using StatsdClient; using Tests.Helpers; namespace Tests { [TestFixture] public class MetricIntegrationTests { private UdpListener _udpListener; private Thread _listenThread; private const int _randomUnusedLocalPort = 23483; private const string _localhostAddress = "127.0.0.1"; private MetricsConfig _defaultMetricsConfig; const string _expectedTestPrefixRegex = @"test_prefix\."; const string _expectedTimeRegEx = @"time:.\\|ms"; [TestFixtureSetUp] public void SetUpUdpListener() { _udpListener = new UdpListener(_localhostAddress, _randomUnusedLocalPort); } [TestFixtureTearDown] public void TearDownUdpListener() { _udpListener.Dispose(); } [SetUp] public void StartUdpListenerThread() { _defaultMetricsConfig = new MetricsConfig { StatsdServerName = _localhostAddress, StatsdServerPort = _randomUnusedLocalPort }; _listenThread = new Thread(_udpListener.Listen); _listenThread.Start(); } private string LastPacketMessageReceived() { // Stall until the the listener receives a message or times out. while(_listenThread.IsAlive) {} var lastMessages = _udpListener.GetAndClearLastMessages(); try { return lastMessages[0]; } catch (System.ArgumentOutOfRangeException) { return null; } } [Test] public void udp_listener_sanity_test() { var client = new StatsdUDP(_localhostAddress, _randomUnusedLocalPort); client.Send("iamnotinsane!"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("iamnotinsane!")); } public class Counter : MetricIntegrationTests { [Test] public void counter() { Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("counter:1|c")); } [Test] public void counter_with_value() { Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter", 10); Assert.That(LastPacketMessageReceived(), Is.EqualTo("counter:10|c")); } [Test] public void counter_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.counter:1|c")); } [Test] public void counter_with_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.counter:1|c")); } [Test] public void counter_with_value_and_sampleRate() { Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter", 10, 0.9999); Assert.That(LastPacketMessageReceived(), Is.EqualTo("counter:10|c|@0.9999")); } [Test] public void counter_with_no_config_setup_should_not_send_metric() { Metrics.Configure(new MetricsConfig()); Metrics.Counter("counter"); Assert.That(LastPacketMessageReceived(), Is.Null); } } public class Timer : MetricIntegrationTests { [Test] public void timer() { Metrics.Configure(_defaultMetricsConfig); Metrics.Timer("timer", 6); Assert.That(LastPacketMessageReceived(), Is.EqualTo("timer:6|ms")); } [Test] public void timer_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.Timer("timer", 6); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.timer:6|ms")); } [Test] public void timer_with_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.Timer("timer", 6); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.timer:6|ms")); } [Test] public void timer_with_no_config_setup_should_not_send_metric() { Metrics.Configure(new MetricsConfig()); Metrics.Timer("timer", 6); Assert.That(LastPacketMessageReceived(), Is.Null); } } public class Time : MetricIntegrationTests { [Test] public void time() { Metrics.Configure(_defaultMetricsConfig); Metrics.Time(() => Thread.Sleep(2), "time"); Assert.That(LastPacketMessageReceived(), Is.StringMatching(_expectedTimeRegEx)); } [Test] public void time_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.Time(() => Thread.Sleep(2), "time"); Assert.That(LastPacketMessageReceived(), Is.StringMatching(_expectedTestPrefixRegex + _expectedTimeRegEx)); } [Test] public void time_with_prefix_having_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.Time(() => Thread.Sleep(2), "time"); Assert.That(LastPacketMessageReceived(), Is.StringMatching(_expectedTestPrefixRegex + _expectedTimeRegEx)); } [Test] public void time_with_no_config_setup_should_not_send_metric_but_still_run_action() { Metrics.Configure(new MetricsConfig()); var someValue = 5; Metrics.Time(() => { someValue = 10; }, "timer"); Assert.That(someValue, Is.EqualTo(10)); Assert.That(LastPacketMessageReceived(), Is.Null); } [Test] public void time_with_return_value() { Metrics.Configure(_defaultMetricsConfig); var returnValue = Metrics.Time(() => { Thread.Sleep(2); return 5; }, "time"); Assert.That(LastPacketMessageReceived(), Is.StringMatching(_expectedTimeRegEx)); Assert.That(returnValue, Is.EqualTo(5)); } [Test] public void time_with_return_value_and_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); var returnValue = Metrics.Time(() => { Thread.Sleep(2); return 5; }, "time"); Assert.That(LastPacketMessageReceived(), Is.StringMatching(_expectedTestPrefixRegex + _expectedTimeRegEx)); Assert.That(returnValue, Is.EqualTo(5)); } [Test] public void time_with_return_value_and_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); var returnValue = Metrics.Time(() => { Thread.Sleep(2); return 5; }, "time"); Assert.That(LastPacketMessageReceived(), Is.StringMatching(_expectedTestPrefixRegex + _expectedTimeRegEx)); Assert.That(returnValue, Is.EqualTo(5)); } [Test] public void time_with_return_value_and_no_config_setup_should_not_send_metric_but_still_return_value() { Metrics.Configure(new MetricsConfig()); var returnValue = Metrics.Time(() => 5, "time"); Assert.That(LastPacketMessageReceived(), Is.Null); Assert.That(returnValue, Is.EqualTo(5)); } } public class Gauge : MetricIntegrationTests { [Test] public void gauge_with_double_value() { Metrics.Configure(_defaultMetricsConfig); const double value = 12345678901234567890; Metrics.Gauge("gauge", value); Assert.That(LastPacketMessageReceived(), Is.EqualTo("gauge:12345678901234600000.000000000000000|g")); } [Test] public void gauge_with_double_value_with_floating_point() { Metrics.Configure(_defaultMetricsConfig); const double value = 1.234567890123456; Metrics.Gauge("gauge", value); Assert.That(LastPacketMessageReceived(), Is.EqualTo("gauge:1.234567890123460|g")); } [Test] public void gauge_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.Gauge("gauge", 3); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.gauge:3.000000000000000|g")); } [Test] public void gauge_with_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.Gauge("gauge", 3); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.gauge:3.000000000000000|g")); } [Test] public void gauge_with_no_config_setup_should_not_send_metric() { Metrics.Configure(new MetricsConfig()); Metrics.Gauge("gauge", 3); Assert.That(LastPacketMessageReceived(), Is.Null); } } public class Set : MetricIntegrationTests { [Test] public void set() { Metrics.Configure(_defaultMetricsConfig); Metrics.Set("timer", "value"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("timer:value|s")); } [Test] public void set_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.Set("timer", "value"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.timer:value|s")); } [Test] public void set_with_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.Set("timer", "value"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.timer:value|s")); } [Test] public void set_with_no_config_setup_should_not_send_metric() { Metrics.Configure(new MetricsConfig()); Metrics.Set("timer", "value"); Assert.That(LastPacketMessageReceived(), Is.Null); } } } }
// 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. // // Exposes features of the Garbage Collector to managed code. // using System; using System.Threading; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics; using System.Security; using Internal.Runtime.Augments; namespace System { // !!!!!!!!!!!!!!!!!!!!!!! // Make sure you change the def in rtu\gc.h if you change this! public enum GCCollectionMode { Default = 0, Forced = 1, Optimized = 2 } public enum GCNotificationStatus { Succeeded = 0, Failed = 1, Canceled = 2, Timeout = 3, NotApplicable = 4 } internal enum InternalGCCollectionMode { NonBlocking = 0x00000001, Blocking = 0x00000002, Optimized = 0x00000004, Compacting = 0x00000008, } internal enum StartNoGCRegionStatus { Succeeded = 0, NotEnoughMemory = 1, AmountTooLarge = 2, AlreadyInProgress = 3 } internal enum EndNoGCRegionStatus { Succeeded = 0, NotInProgress = 1, GCInduced = 2, AllocationExceeded = 3 } public static class GC { public static int GetGeneration(Object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } return RuntimeImports.RhGetGeneration(obj); } /// <summary> /// Returns the current generation number of the target /// of a specified <see cref="System.WeakReference"/>. /// </summary> /// <param name="wo">The WeakReference whose target is the object /// whose generation will be returned</param> /// <returns>The generation of the target of the WeakReference</returns> /// <exception cref="ArgumentNullException">The target of the weak reference /// has already been garbage collected.</exception> public static int GetGeneration(WeakReference wo) { // note - this throws an NRE if given a null weak reference. This isn't // documented, but it's the behavior of Desktop and CoreCLR. Object handleRef = RuntimeImports.RhHandleGet(wo.m_handle); if (handleRef == null) { throw new ArgumentNullException(nameof(wo)); } int result = RuntimeImports.RhGetGeneration(handleRef); KeepAlive(wo); return result; } // Forces a collection of all generations from 0 through Generation. public static void Collect(int generation) { Collect(generation, GCCollectionMode.Default); } // Garbage collect all generations. public static void Collect() { //-1 says to GC all generations. RuntimeImports.RhCollect(-1, InternalGCCollectionMode.Blocking); } public static void Collect(int generation, GCCollectionMode mode) { Collect(generation, mode, true); } public static void Collect(int generation, GCCollectionMode mode, bool blocking) { Collect(generation, mode, blocking, false); } public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting) { if (generation < 0) { throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); } if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized)) { throw new ArgumentOutOfRangeException(nameof(mode), SR.ArgumentOutOfRange_Enum); } int iInternalModes = 0; if (mode == GCCollectionMode.Optimized) { iInternalModes |= (int)InternalGCCollectionMode.Optimized; } if (compacting) { iInternalModes |= (int)InternalGCCollectionMode.Compacting; } if (blocking) { iInternalModes |= (int)InternalGCCollectionMode.Blocking; } else if (!compacting) { iInternalModes |= (int)InternalGCCollectionMode.NonBlocking; } RuntimeImports.RhCollect(generation, (InternalGCCollectionMode)iInternalModes); } /// <summary> /// Specifies that a garbage collection notification should be raised when conditions are favorable /// for a full garbage collection and when the collection has been completed. /// </summary> /// <param name="maxGenerationThreshold">A number between 1 and 99 that specifies when the notification /// should be raised based on the objects allocated in Gen 2.</param> /// <param name="largeObjectHeapThreshold">A number between 1 and 99 that specifies when the notification /// should be raised based on the objects allocated in the large object heap.</param> /// <exception cref="ArgumentOutOfRangeException">If either of the two arguments are not between 1 and 99</exception> /// <exception cref="InvalidOperationException">If Concurrent GC is enabled</exception>" public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold) { if (maxGenerationThreshold < 1 || maxGenerationThreshold > 99) { throw new ArgumentOutOfRangeException( nameof(maxGenerationThreshold), String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } if (largeObjectHeapThreshold < 1 || largeObjectHeapThreshold > 99) { throw new ArgumentOutOfRangeException( nameof(largeObjectHeapThreshold), String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } // This is not documented on MSDN, but CoreCLR throws when the GC's // RegisterForFullGCNotification returns false if (!RuntimeImports.RhRegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold)) { throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC); } } /// <summary> /// Returns the status of a registered notification about whether a blocking garbage collection /// is imminent. May wait indefinitely for a full collection. /// </summary> /// <returns>The status of a registered full GC notification</returns> public static GCNotificationStatus WaitForFullGCApproach() { return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCApproach(-1); } /// <summary> /// Returns the status of a registered notification about whether a blocking garbage collection /// is imminent. May wait up to a given timeout for a full collection. /// </summary> /// <param name="millisecondsTimeout">The timeout on waiting for a full collection</param> /// <returns>The status of a registered full GC notification</returns> public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCApproach(millisecondsTimeout); } /// <summary> /// Returns the status of a registered notification about whether a blocking garbage collection /// has completed. May wait indefinitely for a full collection. /// </summary> /// <returns>The status of a registered full GC notification</returns> public static GCNotificationStatus WaitForFullGCComplete() { return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCComplete(-1); } /// <summary> /// Returns the status of a registered notification about whether a blocking garbage collection /// has completed. May wait up to a specified timeout for a full collection. /// </summary> /// <param name="millisecondsTimeout">The timeout on waiting for a full collection</param> /// <returns></returns> public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCComplete(millisecondsTimeout); } /// <summary> /// Cancels an outstanding full GC notification. /// </summary> /// <exception cref="InvalidOperationException">Raised if called /// with concurrent GC enabled</exception> public static void CancelFullGCNotification() { if (!RuntimeImports.RhCancelFullGCNotification()) { throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC); } } /// <summary> /// Attempts to disallow garbage collection during execution of a critical path. /// </summary> /// <param name="totalSize">Disallows garbage collection if a specified amount of /// of memory is available.</param> /// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns> /// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested /// is too large for the GC to accommodate</exception> /// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception> public static bool TryStartNoGCRegion(long totalSize) { return StartNoGCRegionWorker(totalSize, false, 0, false); } /// <summary> /// Attempts to disallow garbage collection during execution of a critical path. /// </summary> /// <param name="totalSize">Disallows garbage collection if a specified amount of /// of memory is available.</param> /// <param name="lohSize">Disallows garbagte collection if a specified amount of /// large object heap space is available.</param> /// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns> /// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested /// is too large for the GC to accomodate</exception> /// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception> public static bool TryStartNoGCRegion(long totalSize, long lohSize) { return StartNoGCRegionWorker(totalSize, true, lohSize, false); } /// <summary> /// Attempts to disallow garbage collection during execution of a critical path. /// </summary> /// <param name="totalSize">Disallows garbage collection if a specified amount of /// of memory is available.</param> /// <param name="disallowFullBlockingGC">Controls whether or not a full blocking GC /// is performed if the requested amount of memory is not available</param> /// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns> /// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested /// is too large for the GC to accomodate</exception> /// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception> public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC) { return StartNoGCRegionWorker(totalSize, false, 0, disallowFullBlockingGC); } /// <summary> /// Attempts to disallow garbage collection during execution of a critical path. /// </summary> /// <param name="totalSize">Disallows garbage collection if a specified amount of /// of memory is available.</param> /// <param name="lohSize">Disallows garbagte collection if a specified amount of /// large object heap space is available.</param> /// <param name="disallowFullBlockingGC">Controls whether or not a full blocking GC /// is performed if the requested amount of memory is not available</param> /// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns> /// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested /// is too large for the GC to accomodate</exception> /// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception> public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC) { return StartNoGCRegionWorker(totalSize, true, lohSize, disallowFullBlockingGC); } private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC) { if (totalSize <= 0) { throw new ArgumentOutOfRangeException( nameof(totalSize), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(totalSize))); } if (hasLohSize) { if (lohSize <= 0) { throw new ArgumentOutOfRangeException( nameof(lohSize), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(lohSize))); } if (lohSize > totalSize) { throw new ArgumentOutOfRangeException(nameof(lohSize), SR.ArgumentOutOfRange_NoGCLohSizeGreaterTotalSize); } } StartNoGCRegionStatus status = (StartNoGCRegionStatus)RuntimeImports.RhStartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC); switch (status) { case StartNoGCRegionStatus.NotEnoughMemory: return false; case StartNoGCRegionStatus.AlreadyInProgress: throw new InvalidOperationException(SR.InvalidOperationException_AlreadyInNoGCRegion); case StartNoGCRegionStatus.AmountTooLarge: throw new ArgumentOutOfRangeException(nameof(totalSize), SR.ArgumentOutOfRangeException_NoGCRegionSizeTooLarge); } Debug.Assert(status == StartNoGCRegionStatus.Succeeded); return true; } /// <summary> /// Exits the current no GC region. /// </summary> /// <exception cref="InvalidOperationException">If the GC is not in a no GC region</exception> /// <exception cref="InvalidOperationException">If the no GC region was exited due to an induced GC</exception> /// <exception cref="InvalidOperationException">If the no GC region was exited due to memory allocations /// exceeding the amount given to <see cref="TryStartNoGCRegion(long)"/></exception> public static void EndNoGCRegion() { EndNoGCRegionStatus status = (EndNoGCRegionStatus)RuntimeImports.RhEndNoGCRegion(); if (status == EndNoGCRegionStatus.NotInProgress) { throw new InvalidOperationException( SR.InvalidOperationException_NoGCRegionNotInProgress); } else if (status == EndNoGCRegionStatus.GCInduced) { throw new InvalidOperationException( SR.InvalidOperationException_NoGCRegionInduced); } else if (status == EndNoGCRegionStatus.AllocationExceeded) { throw new InvalidOperationException( SR.InvalidOperationException_NoGCRegionAllocationExceeded); } } // Block until the next finalization pass is complete. public static void WaitForPendingFinalizers() { RuntimeImports.RhWaitForPendingFinalizers(RuntimeThread.ReentrantWaitsEnabled); } public static void SuppressFinalize(Object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } RuntimeImports.RhSuppressFinalize(obj); } public static void ReRegisterForFinalize(Object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); RuntimeImports.RhReRegisterForFinalize(obj); } [Intrinsic] [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations public static void KeepAlive(Object obj) { } // Returns the maximum GC generation. Currently assumes only 1 heap. // public static int MaxGeneration { get { return RuntimeImports.RhGetMaxGcGeneration(); } } public static int CollectionCount(int generation) { if (generation < 0) throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive); return RuntimeImports.RhGetGcCollectionCount(generation, false); } // Support for AddMemoryPressure and RemoveMemoryPressure below. private const uint PressureCount = 4; #if BIT64 private const uint MinGCMemoryPressureBudget = 4 * 1024 * 1024; #else private const uint MinGCMemoryPressureBudget = 3 * 1024 * 1024; #endif private const uint MaxGCMemoryPressureRatio = 10; private static int[] s_gcCounts = new int[] { 0, 0, 0 }; private static long[] s_addPressure = new long[] { 0, 0, 0, 0 }; private static long[] s_removePressure = new long[] { 0, 0, 0, 0 }; private static uint s_iteration = 0; /// <summary> /// Resets the pressure accounting after a gen2 GC has occured. /// </summary> private static void CheckCollectionCount() { if (s_gcCounts[2] != CollectionCount(2)) { for (int i = 0; i < 3; i++) { s_gcCounts[i] = CollectionCount(i); } s_iteration++; uint p = s_iteration % PressureCount; s_addPressure[p] = 0; s_removePressure[p] = 0; } } private static long InterlockedAddMemoryPressure(ref long pAugend, long addend) { long oldMemValue; long newMemValue; do { oldMemValue = pAugend; newMemValue = oldMemValue + addend; // check for overflow if (newMemValue < oldMemValue) { newMemValue = long.MaxValue; } } while (Interlocked.CompareExchange(ref pAugend, newMemValue, oldMemValue) != oldMemValue); return newMemValue; } /// <summary> /// New AddMemoryPressure implementation (used by RCW and the CLRServicesImpl class) /// 1. Less sensitive than the original implementation (start budget 3 MB) /// 2. Focuses more on newly added memory pressure /// 3. Budget adjusted by effectiveness of last 3 triggered GC (add / remove ratio, max 10x) /// 4. Budget maxed with 30% of current managed GC size /// 5. If Gen2 GC is happening naturally, ignore past pressure /// /// Here's a brief description of the ideal algorithm for Add/Remove memory pressure: /// Do a GC when (HeapStart is less than X * MemPressureGrowth) where /// - HeapStart is GC Heap size after doing the last GC /// - MemPressureGrowth is the net of Add and Remove since the last GC /// - X is proportional to our guess of the ummanaged memory death rate per GC interval, /// and would be calculated based on historic data using standard exponential approximation: /// Xnew = UMDeath/UMTotal * 0.5 + Xprev /// </summary> /// <param name="bytesAllocated"></param> public static void AddMemoryPressure(long bytesAllocated) { if (bytesAllocated <= 0) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_NeedPosNum); } #if !BIT64 if (bytesAllocated > Int32.MaxValue) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); } #endif CheckCollectionCount(); uint p = s_iteration % PressureCount; long newMemValue = InterlockedAddMemoryPressure(ref s_addPressure[p], bytesAllocated); Debug.Assert(PressureCount == 4, "GC.AddMemoryPressure contains unrolled loops which depend on the PressureCount"); if (newMemValue >= MinGCMemoryPressureBudget) { long add = s_addPressure[0] + s_addPressure[1] + s_addPressure[2] + s_addPressure[3] - s_addPressure[p]; long rem = s_removePressure[0] + s_removePressure[1] + s_removePressure[2] + s_removePressure[3] - s_removePressure[p]; long budget = MinGCMemoryPressureBudget; if (s_iteration >= PressureCount) // wait until we have enough data points { // Adjust according to effectiveness of GC // Scale budget according to past m_addPressure / m_remPressure ratio if (add >= rem * MaxGCMemoryPressureRatio) { budget = MinGCMemoryPressureBudget * MaxGCMemoryPressureRatio; } else if (add > rem) { Debug.Assert(rem != 0); // Avoid overflow by calculating addPressure / remPressure as fixed point (1 = 1024) budget = (add * 1024 / rem) * budget / 1024; } } // If still over budget, check current managed heap size if (newMemValue >= budget) { long heapOver3 = RuntimeImports.RhGetCurrentObjSize() / 3; if (budget < heapOver3) //Max { budget = heapOver3; } if (newMemValue >= budget) { // last check - if we would exceed 20% of GC "duty cycle", do not trigger GC at this time if ((RuntimeImports.RhGetGCNow() - RuntimeImports.RhGetLastGCStartTime(2)) > (RuntimeImports.RhGetLastGCDuration(2) * 5)) { RuntimeImports.RhCollect(2, InternalGCCollectionMode.NonBlocking); CheckCollectionCount(); } } } } } public static void RemoveMemoryPressure(long bytesAllocated) { if (bytesAllocated <= 0) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_NeedPosNum); } #if !BIT64 if (bytesAllocated > Int32.MaxValue) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); } #endif CheckCollectionCount(); uint p = s_iteration % PressureCount; InterlockedAddMemoryPressure(ref s_removePressure[p], bytesAllocated); } public static long GetTotalMemory(bool forceFullCollection) { long size = RuntimeImports.RhGetGcTotalMemory(); if (forceFullCollection) { // If we force a full collection, we will run the finalizers on all // existing objects and do a collection until the value stabilizes. // The value is "stable" when either the value is within 5% of the // previous call to GetTotalMemory, or if we have been sitting // here for more than x times (we don't want to loop forever here). int reps = 20; // Number of iterations long diff; do { GC.WaitForPendingFinalizers(); GC.Collect(); long newSize = RuntimeImports.RhGetGcTotalMemory(); diff = (newSize - size) * 100 / size; size = newSize; } while (reps-- > 0 && !(-5 < diff && diff < 5)); } return size; } public static long GetAllocatedBytesForCurrentThread() { return RuntimeImports.RhGetAllocatedBytesForCurrentThread(); } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; using System.Collections; using System.IO; using System.Windows.Forms; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Text; using System.Threading; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.Build.Utilities; using System.Diagnostics.CodeAnalysis; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; using Microsoft.Build.Execution; using System.Linq; using Microsoft.Internal.VisualStudio.PlatformUI; namespace Microsoft.VisualStudio.FSharp.ProjectSystem { [CLSCompliant(false)] [ComVisible(true)] public class AssemblyReferenceNode : ReferenceNode { private struct AssemblyResolvedInfo { public AssemblyName AssemblyName; public AssemblyName ResolvedAssemblyName; public bool CopyLocalDefault; public bool IsNoPIA; // <EmbedInteropTypes> is true public bool IsPlatformAssembly; // simple name resolution resolved to {TargetFrameworkDirectory} public bool WasSuccessfullyResolved; } private struct AssemblyMSBuildProjectionInfo { public bool WantHintPath; public bool WantFusionName; // as opposed to simple name public bool? WantSpecificVersion; // null -> nothing in .fsproj, true/false mean serialize that value to .fsproj } private string myAssemblyPath = String.Empty; private FileChangeManager myFileChangeListener; private bool myIsDisposed = false; private AssemblyResolvedInfo resolvedInfo; private AssemblyMSBuildProjectionInfo msbuildProjectionInfo; private bool fsprojIncludeHasFilename = false; /// <summary> /// The name of the assembly this reference represents. /// </summary> /// <value></value> public System.Reflection.AssemblyName AssemblyName { get { return this.resolvedInfo.AssemblyName; } } /// <summary> /// Returns the name of the assembly this reference refers to on this specific /// machine. It can be different from the AssemblyName property because it can /// be more specific. /// </summary> public System.Reflection.AssemblyName ResolvedAssembly { get { return this.resolvedInfo.ResolvedAssemblyName; } } public override string Url { get { return this.myAssemblyPath; } } public override string SimpleName { get { if (this.resolvedInfo.WasSuccessfullyResolved) { return this.resolvedInfo.AssemblyName.Name; } else { return string.Empty; } } } public override string Caption { get { if (fsprojIncludeHasFilename) { return MSBuildItem.GetEvaluatedInclude(this.ItemNode.Item); } if (this.resolvedInfo.AssemblyName != null) { return this.resolvedInfo.AssemblyName.Name; } return MSBuildItem.GetEvaluatedInclude(this.ItemNode.Item); } } private Automation.OAAssemblyReference assemblyRef; public override object Object { get { if (null == assemblyRef) { assemblyRef = new Automation.OAAssemblyReference(this); } return assemblyRef; } } internal static AssemblyReferenceNode CreateFromProjectFile(ProjectNode root, ProjectElement element, BuildResult buildResult) { return new AssemblyReferenceNode(root, element, buildResult); } internal static AssemblyReferenceNode CreateFromFullPathViaUIAddReference(ProjectNode root, string assemblyFullPath, AddReferenceDialogTab tab) { return new AssemblyReferenceNode(root, assemblyFullPath, tab); } internal static AssemblyReferenceNode CreateFromAssemblyNameViaUIAutomation(ProjectNode root, string assemblyName) { return new AssemblyReferenceNode(0, root, assemblyName); } /// <summary> /// Creating AssemblyReferenceNode from fsproj element /// </summary> private AssemblyReferenceNode(ProjectNode root, ProjectElement element, BuildResult buildResult) : base(root, element) { BindFromBuildResult(element.Item, buildResult); } /// <summary> /// Creating AssemblyReferenceNode via VS UI ("Add Reference" or otherwise) /// </summary> private AssemblyReferenceNode(ProjectNode root, string assemblyFullPath, AddReferenceDialogTab tab) : base(root) { // Validate the input parameters. if (null == root) { throw new ArgumentNullException("root"); } if (string.IsNullOrEmpty(assemblyFullPath)) { throw new ArgumentNullException("assemblyFullPath"); } ResolveAssemblyReferenceByFullPath(assemblyFullPath, tab); this.InitializeFileChangeEvents(); } /// <summary> /// Creating AssemblyReferenceNode via automation (Cider case) /// </summary> private AssemblyReferenceNode(int dummy, ProjectNode root, string assemblyName) : base(root) { // Validate the input parameters. if (null == root) { throw new ArgumentNullException("root"); } if (string.IsNullOrEmpty(assemblyName)) { throw new ArgumentNullException("assemblyName"); } AddToProjectFileAndTryResolve(assemblyName); InitializeAssemblyName(assemblyName); if (!this.resolvedInfo.WasSuccessfullyResolved) { this.ProjectMgr.AddReferenceCouldNotBeAddedErrorMessage(assemblyName); } if (!resolvedInfo.IsPlatformAssembly) { this.msbuildProjectionInfo.WantFusionName = true; } this.InitializeFileChangeEvents(); } internal static bool IsFSharpCoreReference(ReferenceNode node) { var isFSharpCore = false; try { var assemblyName = new AssemblyName(node.ItemNode.Item.EvaluatedInclude); isFSharpCore = assemblyName.Name == "FSharp.Core"; } catch (FileLoadException) { // constructor of AssemblyName raises FileNotFoundException if supplied name cannot be parsed as valid assembly name } return isFSharpCore; } internal static bool ContainsUsagesOfTargetFSharpCoreVersionProperty(ReferenceNode node) { Debug.Assert(IsFSharpCoreReference(node)); if (node.ItemNode.Item.UnevaluatedInclude.Contains(ProjectFileConstants.TargetFSharpCoreVersionProperty)) return true; var hintPath = node.ItemNode.Item.GetMetadata(ProjectFileConstants.HintPath); return hintPath != null && hintPath.UnevaluatedValue.Contains(ProjectFileConstants.TargetFSharpCoreVersionProperty); } internal void RebindFSharpCoreAfterUpdatingVersion(BuildResult buildResult) { Debug.Assert(IsFSharpCoreReference(this)); if (!ContainsUsagesOfTargetFSharpCoreVersionProperty(this)) return; UnregisterFromFileChangeService(); ItemNode.RefreshProperties(); fsprojIncludeHasFilename = false; resolvedInfo = default(AssemblyResolvedInfo); myAssemblyPath = string.Empty; msbuildProjectionInfo = default(AssemblyMSBuildProjectionInfo); BindFromBuildResult(ItemNode.Item, buildResult); this.ReDraw(UIHierarchyElement.Icon); this.ReDraw(UIHierarchyElement.Caption); } private void BindFromBuildResult(Build.Evaluation.ProjectItem element, BuildResult buildResult) { var include = MSBuildItem.GetEvaluatedInclude(element); fsprojIncludeHasFilename = (include.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || include.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)); ResolveFromBuiltProject(include, buildResult); if (!fsprojIncludeHasFilename) { InitializeAssemblyName(include); } InitializeFileChangeEvents(); } private void InitializeAssemblyName(string assemblyName) { // AssemblyName may be less specific than ResolvedAssemblyName (e.g. not have version/publickey) if (this.resolvedInfo.WasSuccessfullyResolved) { System.Reflection.AssemblyName name = null; try { name = new System.Reflection.AssemblyName(assemblyName); } catch (Exception) { } if (name != null) { this.resolvedInfo.AssemblyName = name; } } } public override int Close() { try { this.Dispose(true); } finally { base.Close(); } return VSConstants.S_OK; } public override bool CanBeReferencedFromFSI() { // prohibit adding references to mscorlib\FSharp.Core if (IsFSharpCoreReference(this) || (resolvedInfo.WasSuccessfullyResolved && resolvedInfo.AssemblyName != null && resolvedInfo.AssemblyName.Name == "mscorlib")) { return false; } return true; } public override string GetReferenceForFSI() { if (resolvedInfo.WasSuccessfullyResolved && File.Exists(Url)) { return Url; } return null; } private bool IsSpecialFSharpCoreReference { get { return ProjectMgr.CanUseTargetFSharpCoreReference && IsFSharpCoreReference(this) && ContainsUsagesOfTargetFSharpCoreVersionProperty(this); } } public override NodeProperties CreatePropertiesObject() { if (IsSpecialFSharpCoreReference) { return new FSharpCoreAssemblyReferenceProperties(this, resolvedInfo.CopyLocalDefault); } return new AssemblyReferenceProperties(this, this.resolvedInfo.CopyLocalDefault); } /// <summary> /// Links a reference node to the project and hierarchy. /// </summary> public override void BindReferenceData() { // BindReferenceData only happens for newly created AssemblyReferenceNodes (as opposed to loaded from fsproj) Debug.Assert(this.resolvedInfo.WasSuccessfullyResolved, "assembly was not resolved, we should not be trying to link a node to put in .fsproj file"); // Logic here follows that of // \\ddindex2\sources_tfs\Dev10_Main\vsproject\langbuild\langref.cpp // AddMSBuildItem() this.ItemNode = new ProjectElement(this.ProjectMgr, this.msbuildProjectionInfo.WantFusionName ? this.resolvedInfo.AssemblyName.FullName : this.resolvedInfo.AssemblyName.Name, ProjectFileConstants.Reference); if (this.msbuildProjectionInfo.WantSpecificVersion != null) { if (this.msbuildProjectionInfo.WantSpecificVersion.Value) { // Note that we should never set <SpecificVersion>True from // UI 'add reference', as it breaks multi-targeting. User must manually // opt in to changing SV to get 'true' if desired. } else { if (this.msbuildProjectionInfo.WantFusionName) { this.ItemNode.SetMetadata(ProjectFileConstants.SpecificVersion, "False"); } } } if (this.resolvedInfo.IsNoPIA) { this.ItemNode.SetMetadata(ProjectFileConstants.EmbedInteropTypes, "True"); } if (this.msbuildProjectionInfo.WantHintPath) { this.ItemNode.SetMetadata(ProjectFileConstants.HintPath, PackageUtilities.MakeRelative(this.ProjectMgr.ProjectFolder + "\\", this.myAssemblyPath)); } if (this.resolvedInfo.CopyLocalDefault) { // In fact this is only set if CopyLocal 'is overridden', which is only as a result of explicit user action (or automation). // So simply 'add reference' should never set the metadata value ProjectFileConstants.Private } // TODO - Note that we don't currently support any logic for // LBXML_KEY_REFERENCE_ALIAS "Name" // LBXML_KEY_REFERENCE_EXTENSION "ExecutableExtension" } protected override void Dispose(bool disposing) { if (this.myIsDisposed) { return; } try { this.UnregisterFromFileChangeService(); } finally { base.Dispose(disposing); this.myIsDisposed = true; } } public override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) { // this is reference to FSharp.Core that uses value of TargetFSharpCoreVersion property - prohibit deletion if (IsSpecialFSharpCoreReference) { return false; } return base.CanDeleteItem(deleteOperation); } public override void Remove(bool removeFromStorage, bool promptSave = true) { // AssemblyReference doesn't backed by the document - its removal is simply modification of the project file // we disable IVsTrackProjectDocuments2 events to avoid confusing messages from SCC var oldFlag = ProjectMgr.EventTriggeringFlag; try { ProjectMgr.EventTriggeringFlag = oldFlag | ProjectNode.EventTriggering.DoNotTriggerTrackerEvents; base.Remove(removeFromStorage, promptSave); // invoke ComputeSourcesAndFlags to refresh compiler flags // it was the only useful thing performed by one of IVsTrackProjectDocuments2 listeners ProjectMgr.ComputeSourcesAndFlags(); } finally { ProjectMgr.EventTriggeringFlag = oldFlag; } } /// <summary> /// Determines if this is node a valid node for painting the default reference icon. /// </summary> /// <returns></returns> public override bool CanShowDefaultIcon() { if (String.IsNullOrEmpty(this.myAssemblyPath) || !File.Exists(this.myAssemblyPath)) { return false; } return true; } private string GetFullPathFromPath(string path) { if (Path.IsPathRooted(path)) { return path; } else { Uri uri = new Uri(this.ProjectMgr.BaseURI.Uri, path); if (uri != null) { return Microsoft.VisualStudio.Shell.Url.Unescape(uri.LocalPath, true); } } return String.Empty; } public void DoOneOffResolve() { var result = this.ProjectMgr.Build(MsBuildTarget.ResolveAssemblyReferences); this.ResolveReference(result); } internal override void ResolveReference(BuildResult buildResult) { Debug.Assert(this.ItemNode != null && this.ItemNode.Item != null, "called ResolveReference before initializing ItemNode"); this.ResolveFromBuiltProject(MSBuildItem.GetEvaluatedInclude(this.ItemNode.Item), buildResult); } internal static BuildResult BuildInstance(ProjectNode projectNode, ref ProjectInstance instance, string target) { var submission = projectNode.DoMSBuildSubmission(BuildKind.SYNC, target, ref instance, null); return new BuildResult(submission, instance); } private void ResolveAssemblyReferenceByFullPath(string assemblyFullPath, AddReferenceDialogTab tab) { if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return; } bool isValidPath = false; try { isValidPath = Path.IsPathRooted(assemblyFullPath); } catch (ArgumentException) { } Debug.Assert(isValidPath, string.Format("Expected assemblyFullPath to be a full path, but it was {0}", assemblyFullPath)); this.msbuildProjectionInfo.WantHintPath = false; this.msbuildProjectionInfo.WantFusionName = false; this.msbuildProjectionInfo.WantSpecificVersion = null; try { var simpleName = System.IO.Path.GetFileNameWithoutExtension(assemblyFullPath); AddToProjectFileAndTryResolve(simpleName); } catch (Exception) { } if (!this.resolvedInfo.WasSuccessfullyResolved) { this.msbuildProjectionInfo.WantHintPath = true; AddToProjectFileAndTryResolve(assemblyFullPath); } else { this.myAssemblyPath = assemblyFullPath; // we successfully resolved it via simple name if (!this.resolvedInfo.IsPlatformAssembly) { // not a platform assembly if (resolvedInfo.AssemblyName != null) { // Project file contains different reference than picked/shown in UI // code in this class tries to mimic the behavior in vsproject\langbuild\langref.cpp\785480\langref.cpp // it also uses simple name for initial resolution attempt // however after that it repopulates ComPlus attributes from the source assembly via SetComPlusAttributesFromFullPath // this part was previously skipped - as a result AssemblyName contained invalid data var assemblyName = AssemblyName.GetAssemblyName(assemblyFullPath); resolvedInfo.AssemblyName = assemblyName; resolvedInfo.ResolvedAssemblyName = assemblyName; } if (tab == AddReferenceDialogTab.DotNetTab) { // from .Net tab this.msbuildProjectionInfo.WantFusionName = true; this.msbuildProjectionInfo.WantSpecificVersion = true; } else { Debug.Assert(tab == AddReferenceDialogTab.BrowseTab); // not from .Net tab this.msbuildProjectionInfo.WantHintPath = true; } } else { // platform assemblies can just resolve to simple name // it was a platform assembly } } // TODO - not accounting for case described below // if <re-resolving fusion name with SpecificVersion fails> then // { // this is possible if this reference is being added through automation // in which case the file passed may have a different fusion name than // the assembly in the target framework/fx extensions. // in that case just add with a hint path // wantHintPath = true; // } if (this.msbuildProjectionInfo.WantHintPath) { this.msbuildProjectionInfo.WantSpecificVersion = false; } if (this.myAssemblyPath == null) { this.myAssemblyPath = assemblyFullPath; } if (!this.resolvedInfo.WasSuccessfullyResolved) { this.ProjectMgr.AddReferenceCouldNotBeAddedErrorMessage(assemblyFullPath); } // "finished: assemblyFullPath } /// <summary> /// Initialize 'resolvedInfo' by having MSBuild resolve the assembly in the context of the current project /// </summary> /// <param name="assemblyInclude">Either a full path to a file on disk, or a simple name or fusion name</param> private void AddToProjectFileAndTryResolve(string assemblyInclude) { // starting: assemblyInclude ProjectInstance instance = null; instance = this.ProjectMgr.BuildProject.CreateProjectInstance(); // use a fresh instance... instance.AddItem(ProjectFileConstants.Reference, assemblyInclude); // ...and mutate it as through there were another <Reference Include="blah"> there var result = BuildInstance(this.ProjectMgr, ref instance, MsBuildTarget.ResolveAssemblyReferences); this.ResolveFromBuiltProject(assemblyInclude, result); } private void ResolveFromBuiltProject(string assemblyInclude, BuildResult buildResult) { if (!buildResult.IsSuccessful) { // ResolveAssemblyReferences build failed. return; } System.Collections.Generic.IEnumerable<ProjectItemInstance> group = buildResult.ProjectInstance.GetItems(ProjectFileConstants.ReferencePath); if (group != null) { foreach (var item in group) { // TODO, the logic here is too brittle - if a user adds a 'logical duplicate' assembly with a different name, it may not find resolution // and then wind up with wrong diagnostic later because it failed to resolve (when in fact it would resolve if not for duplicate) if (0 == string.Compare(assemblyInclude, MSBuildItem.GetMetadataValue(item, "OriginalItemSpec"), StringComparison.Ordinal)) { var fusionName = MSBuildItem.GetMetadataValue(item, "FusionName"); if (!string.IsNullOrEmpty(fusionName)) { this.resolvedInfo.ResolvedAssemblyName = new System.Reflection.AssemblyName(fusionName); this.resolvedInfo.AssemblyName = this.resolvedInfo.ResolvedAssemblyName; } this.resolvedInfo.IsPlatformAssembly = 0 == string.Compare(MSBuildItem.GetMetadataValue(item, ProjectFileConstants.ResolvedFrom), "{TargetFrameworkDirectory}", StringComparison.OrdinalIgnoreCase); this.resolvedInfo.IsNoPIA = 0 == string.Compare(MSBuildItem.GetMetadataValue(item, ProjectFileConstants.EmbedInteropTypes), "true", StringComparison.OrdinalIgnoreCase); this.resolvedInfo.CopyLocalDefault = 0 == string.Compare(MSBuildItem.GetMetadataValue(item, ProjectFileConstants.CopyLocal), "true", StringComparison.OrdinalIgnoreCase); this.resolvedInfo.WasSuccessfullyResolved = true; this.myAssemblyPath = MSBuildItem.GetEvaluatedInclude(item); if (!Path.IsPathRooted(this.myAssemblyPath)) { this.myAssemblyPath = Path.Combine(this.ProjectMgr.ProjectFolder, this.myAssemblyPath); } // finished and found original item return; } } } // finished without finding original item } /// <summary> /// Registers with File change events /// </summary> private void InitializeFileChangeEvents() { this.myFileChangeListener = new FileChangeManager(this.ProjectMgr.Site); this.myFileChangeListener.FileChangedOnDisk += this.OnAssemblyReferenceChangedOnDisk; } /// <summary> /// Unregisters this node from file change notifications. /// </summary> private void UnregisterFromFileChangeService() { this.myFileChangeListener.FileChangedOnDisk -= this.OnAssemblyReferenceChangedOnDisk; this.myFileChangeListener.Dispose(); } /// <summary> /// Event callback. Called when one of the assembly file is changed. /// </summary> /// <param name="sender">The FileChangeManager object.</param> /// <param name="e">Event args containing the file name that was updated.</param> private void OnAssemblyReferenceChangedOnDisk(object sender, FileChangedOnDiskEventArgs e) { Debug.Assert(e != null, "No event args specified for the FileChangedOnDisk event"); // We only care about file deletes, so check for one before enumerating references. if ((e.FileChangeFlag & _VSFILECHANGEFLAGS.VSFILECHG_Del) == 0) { return; } if (NativeMethods.IsSamePath(e.FileName, this.myAssemblyPath)) { this.OnInvalidateItems(this.Parent); } } public override Guid GetBrowseLibraryGuid() { return VSConstants.guidCOMPLUSLibrary; } public override object GetProperty(int propId) { if (propId == (int)__VSHPROPID5.VSHPROPID_ProvisionalViewingStatus) { var objectBrowserGuid = VSProjectConstants.guidObjectBrowser; var logicalViewGuid = VSConstants.LOGVIEWID.Primary_guid; IVsUIShellOpenDocument3 shellOpenDocument3 = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument3; return shellOpenDocument3.GetProvisionalViewingStatusForEditor(ref objectBrowserGuid, ref logicalViewGuid); } return base.GetProperty(propId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.NetworkInformation; using System.Text; // Relevant cookie specs: // // PERSISTENT CLIENT STATE HTTP COOKIES (1996) // From <http:// web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html> // // RFC2109 HTTP State Management Mechanism (February 1997) // From <http:// tools.ietf.org/html/rfc2109> // // RFC2965 HTTP State Management Mechanism (October 2000) // From <http:// tools.ietf.org/html/rfc2965> // // RFC6265 HTTP State Management Mechanism (April 2011) // From <http:// tools.ietf.org/html/rfc6265> // // The Version attribute of the cookie header is defined and used only in RFC2109 and RFC2965 cookie // specs and specifies Version=1. The Version attribute is not used in the Netscape cookie spec // (considered as Version=0). Nor is it used in the most recent cookie spec, RFC6265, introduced in 2011. // RFC6265 deprecates all previous cookie specs including the Version attribute. // // Cookies without an explicit Domain attribute will only match a potential uri that matches the original // uri from where the cookie came from. // // For explicit Domain attribute in the cookie, the following rules apply: // // Version=0 (Netscape, RFC6265) allows the Domain attribute of the cookie to match any tail substring // of the host uri. // // Version=1 related cookie specs only allows the Domain attribute to match the host uri based on a // more restricted set of rules. // // According to RFC2109/RFC2965, the cookie will be rejected for matching if: // * The value for the Domain attribute contains no embedded dots or does not start with a dot. // * The value for the request-host does not domain-match the Domain attribute. // " The request-host is a FQDN (not IP address) and has the form HD, where D is the value of the Domain // attribute, and H is a string that contains one or more dots. // // Examples: // * A cookie from request-host y.x.foo.com for Domain=.foo.com would be rejected, because H is y.x // and contains a dot. // // * A cookie from request-host x.foo.com for Domain=.foo.com would be accepted. // // * A cookie with Domain=.com or Domain=.com., will always be rejected, because there is no embedded dot. // // * A cookie with Domain=ajax.com will be rejected because the value for Domain does not begin with a dot. namespace System.Net { internal struct HeaderVariantInfo { private readonly string _name; private readonly CookieVariant _variant; internal HeaderVariantInfo(string name, CookieVariant variant) { _name = name; _variant = variant; } internal string Name { get { return _name; } } internal CookieVariant Variant { get { return _variant; } } } // CookieContainer // // Manage cookies for a user (implicit). Based on RFC 2965. public class CookieContainer { public const int DefaultCookieLimit = 300; public const int DefaultPerDomainCookieLimit = 20; public const int DefaultCookieLengthLimit = 4096; private static readonly HeaderVariantInfo[] s_headerInfo = { new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie, CookieVariant.Rfc2109), new HeaderVariantInfo(HttpKnownHeaderNames.SetCookie2, CookieVariant.Rfc2965) }; // NOTE: all accesses of _domainTable must be performed with _domainTable locked. private Dictionary<string, PathList> _domainTable = new Dictionary<string, PathList>(); private int _maxCookieSize = DefaultCookieLengthLimit; private int _maxCookies = DefaultCookieLimit; private int _maxCookiesPerDomain = DefaultPerDomainCookieLimit; private int _count = 0; private string _fqdnMyDomain = string.Empty; public CookieContainer() { string domain = HostInformation.DomainName; if (domain != null && domain.Length > 1) { _fqdnMyDomain = '.' + domain; } // Otherwise it will remain string.Empty. } public CookieContainer(int capacity) : this() { if (capacity <= 0) { throw new ArgumentException(SR.net_toosmall, "Capacity"); } _maxCookies = capacity; } public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) : this(capacity) { if (perDomainCapacity != Int32.MaxValue && (perDomainCapacity <= 0 || perDomainCapacity > capacity)) { throw new ArgumentOutOfRangeException(nameof(perDomainCapacity), SR.Format(SR.net_cookie_capacity_range, "PerDomainCapacity", 0, capacity)); } _maxCookiesPerDomain = perDomainCapacity; if (maxCookieSize <= 0) { throw new ArgumentException(SR.net_toosmall, "MaxCookieSize"); } _maxCookieSize = maxCookieSize; } // NOTE: after shrinking the capacity, Count can become greater than Capacity. public int Capacity { get { return _maxCookies; } set { if (value <= 0 || (value < _maxCookiesPerDomain && _maxCookiesPerDomain != Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(value), SR.Format(SR.net_cookie_capacity_range, "Capacity", 0, _maxCookiesPerDomain)); } if (value < _maxCookies) { _maxCookies = value; AgeCookies(null); } _maxCookies = value; } } /// <devdoc> /// <para>Returns the total number of cookies in the container.</para> /// </devdoc> public int Count { get { return _count; } } public int MaxCookieSize { get { return _maxCookieSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _maxCookieSize = value; } } /// <devdoc> /// <para>After shrinking domain capacity, each domain will less hold than new domain capacity.</para> /// </devdoc> public int PerDomainCapacity { get { return _maxCookiesPerDomain; } set { if (value <= 0 || (value > _maxCookies && value != Int32.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(value)); } if (value < _maxCookiesPerDomain) { _maxCookiesPerDomain = value; AgeCookies(null); } _maxCookiesPerDomain = value; } } // This method will construct a faked URI: the Domain property is required for param. public void Add(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } if (cookie.Domain.Length == 0) { throw new ArgumentException(SR.net_emptystringcall, "cookie.Domain"); } Uri uri; var uriSb = new StringBuilder(); // We cannot add an invalid cookie into the container. // Trying to prepare Uri for the cookie verification. uriSb.Append(cookie.Secure ? UriScheme.Https : UriScheme.Http).Append(UriScheme.SchemeDelimiter); // If the original cookie has an explicitly set domain, copy it over to the new cookie. if (!cookie.DomainImplicit) { if (cookie.Domain[0] == '.') { uriSb.Append("0"); // URI cctor should consume this faked host. } } uriSb.Append(cookie.Domain); // Either keep Port as implicit or set it according to original cookie. if (cookie.PortList != null) { uriSb.Append(":").Append(cookie.PortList[0]); } // Path must be present, set to root by default. uriSb.Append(cookie.Path); if (!Uri.TryCreate(uriSb.ToString(), UriKind.Absolute, out uri)) throw new CookieException(SR.Format(SR.net_cookie_attribute, "Domain", cookie.Domain)); // We don't know cookie verification status, so re-create the cookie and verify it. Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), _fqdnMyDomain, true, true); Add(new_cookie, true); } // This method is called *only* when cookie verification is done, so unlike with public // Add(Cookie cookie) the cookie is in a reasonable condition. internal void Add(Cookie cookie, bool throwOnError) { PathList pathList; if (cookie.Value.Length > _maxCookieSize) { if (throwOnError) { throw new CookieException(SR.Format(SR.net_cookie_size, cookie.ToString(), _maxCookieSize)); } return; } try { lock (_domainTable) { if (!_domainTable.TryGetValue(cookie.DomainKey, out pathList)) { _domainTable[cookie.DomainKey] = (pathList = PathList.Create()); } } int domain_count = pathList.GetCookiesCount(); CookieCollection cookies; lock (pathList.SyncRoot) { cookies = pathList[cookie.Path]; if (cookies == null) { cookies = new CookieCollection(); pathList[cookie.Path] = cookies; } } if (cookie.Expired) { // Explicit removal command (Max-Age == 0) lock (cookies) { int idx = cookies.IndexOf(cookie); if (idx != -1) { cookies.RemoveAt(idx); --_count; } } } else { // This is about real cookie adding, check Capacity first if (domain_count >= _maxCookiesPerDomain && !AgeCookies(cookie.DomainKey)) { return; // Cannot age: reject new cookie } else if (_count >= _maxCookies && !AgeCookies(null)) { return; // Cannot age: reject new cookie } // About to change the collection lock (cookies) { _count += cookies.InternalAdd(cookie, true); } } } catch (OutOfMemoryException) { throw; } catch (Exception e) { if (throwOnError) { throw new CookieException(SR.net_container_add_cookie, e); } } } // This function, when called, must delete at least one cookie. // If there are expired cookies in given scope they are cleaned up. // If nothing is found the least used Collection will be found and removed // from the container. // // Also note that expired cookies are also removed during request preparation // (this.GetCookies method). // // Param. 'domain' == null means to age in the whole container. private bool AgeCookies(string domain) { // Border case: shrunk to zero if (_maxCookies == 0 || _maxCookiesPerDomain == 0) { _domainTable = new Dictionary<string, PathList>(); _count = 0; return false; } int removed = 0; DateTime oldUsed = DateTime.MaxValue; DateTime tempUsed; CookieCollection lruCc = null; string lruDomain = null; string tempDomain = null; PathList pathList; int domain_count = 0; int itemp = 0; float remainingFraction = 1.0F; // The container was shrunk, might need additional cleanup for each domain if (_count > _maxCookies) { // Means the fraction of the container to be left. // Each domain will be cut accordingly. remainingFraction = (float)_maxCookies / (float)_count; } lock (_domainTable) { foreach (KeyValuePair<string, PathList> entry in _domainTable) { if (domain == null) { tempDomain = entry.Key; pathList = entry.Value; // Aliasing to trick foreach } else { tempDomain = domain; _domainTable.TryGetValue(domain, out pathList); } domain_count = 0; // Cookies in the domain lock (pathList.SyncRoot) { foreach (KeyValuePair<string, CookieCollection> pair in pathList) { CookieCollection cc = pair.Value; itemp = ExpireCollection(cc); removed += itemp; _count -= itemp; // Update this container's count domain_count += cc.Count; // We also find the least used cookie collection in ENTIRE container. // We count the collection as LRU only if it holds 1+ elements. if (cc.Count > 0 && (tempUsed = cc.TimeStamp(CookieCollection.Stamp.Check)) < oldUsed) { lruDomain = tempDomain; lruCc = cc; oldUsed = tempUsed; } } } // Check if we have reduced to the limit of the domain by expiration only. int min_count = Math.Min((int)(domain_count * remainingFraction), Math.Min(_maxCookiesPerDomain, _maxCookies) - 1); if (domain_count > min_count) { // This case requires sorting all domain collections by timestamp. KeyValuePair<DateTime, CookieCollection>[] cookies; lock (pathList.SyncRoot) { cookies = new KeyValuePair<DateTime, CookieCollection>[pathList.Count]; foreach (KeyValuePair<string, CookieCollection> pair in pathList) { CookieCollection cc = pair.Value; cookies[itemp] = new KeyValuePair<DateTime, CookieCollection>(cc.TimeStamp(CookieCollection.Stamp.Check), cc); ++itemp; } } Array.Sort(cookies, (a, b) => a.Key.CompareTo(b.Key)); itemp = 0; for (int i = 0; i < cookies.Length; ++i) { CookieCollection cc = cookies[i].Value; lock (cc) { while (domain_count > min_count && cc.Count > 0) { cc.RemoveAt(0); --domain_count; --_count; ++removed; } } if (domain_count <= min_count) { break; } } if (domain_count > min_count && domain != null) { // Cannot complete aging of explicit domain (no cookie adding allowed). return false; } } } } // We have completed aging of the specified domain. if (domain != null) { return true; } // The rest is for entire container aging. // We must get at least one free slot. // Don't need to apply LRU if we already cleaned something. if (removed != 0) { return true; } if (oldUsed == DateTime.MaxValue) { // Something strange. Either capacity is 0 or all collections are locked with cc.Used. return false; } // Remove oldest cookies from the least used collection. lock (lruCc) { while (_count >= _maxCookies && lruCc.Count > 0) { lruCc.RemoveAt(0); --_count; } } return true; } // Return number of cookies removed from the collection. private int ExpireCollection(CookieCollection cc) { lock (cc) { int oldCount = cc.Count; int idx = oldCount - 1; // Cannot use enumerator as we are going to alter collection. while (idx >= 0) { Cookie cookie = cc[idx]; if (cookie.Expired) { cc.RemoveAt(idx); } --idx; } return oldCount - cc.Count; } } public void Add(CookieCollection cookies) { if (cookies == null) { throw new ArgumentNullException(nameof(cookies)); } foreach (Cookie c in cookies) { Add(c); } } // This will try (if needed) get the full domain name of the host given the Uri. // NEVER call this function from internal methods with 'fqdnRemote' == null. // Since this method counts security issue for DNS and hence will slow // the performance. internal bool IsLocalDomain(string host) { int dot = host.IndexOf('.'); if (dot == -1) { // No choice but to treat it as a host on the local domain. // This also covers 'localhost' and 'loopback'. return true; } // Quick test for typical cases: loopback addresses for IPv4 and IPv6. if ((host == "127.0.0.1") || (host == "::1") || (host == "0:0:0:0:0:0:0:1")) { return true; } // Test domain membership. if (string.Compare(_fqdnMyDomain, 0, host, dot, _fqdnMyDomain.Length, StringComparison.OrdinalIgnoreCase) == 0) { return true; } // Test for "127.###.###.###" without using regex. string[] ipParts = host.Split('.'); if (ipParts != null && ipParts.Length == 4 && ipParts[0] == "127") { int i; for (i = 1; i < 4; i++) { switch (ipParts[i].Length) { case 3: if (ipParts[i][2] < '0' || ipParts[i][2] > '9') { break; } goto case 2; case 2: if (ipParts[i][1] < '0' || ipParts[i][1] > '9') { break; } goto case 1; case 1: if (ipParts[i][0] < '0' || ipParts[i][0] > '9') { break; } continue; } break; } if (i == 4) { return true; } } return false; } public void Add(Uri uri, Cookie cookie) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } Cookie new_cookie = cookie.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, IsLocalDomain(uri.Host), _fqdnMyDomain, true, true); Add(new_cookie, true); } public void Add(Uri uri, CookieCollection cookies) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookies == null) { throw new ArgumentNullException(nameof(cookies)); } bool isLocalDomain = IsLocalDomain(uri.Host); foreach (Cookie c in cookies) { Cookie new_cookie = c.Clone(); new_cookie.VerifySetDefaults(new_cookie.Variant, uri, isLocalDomain, _fqdnMyDomain, true, true); Add(new_cookie, true); } } internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow) { if (GlobalLog.IsEnabled) { GlobalLog.Print("CookieContainer#" + LoggingHash.HashString(this) + "::CookieCutter() uri:" + uri + " headerName:" + headerName + " setCookieHeader:" + setCookieHeader + " isThrow:" + isThrow); } CookieCollection cookies = new CookieCollection(); CookieVariant variant = CookieVariant.Unknown; if (headerName == null) { variant = CookieVariant.Default; } else { for (int i = 0; i < s_headerInfo.Length; ++i) { if ((String.Compare(headerName, s_headerInfo[i].Name, StringComparison.OrdinalIgnoreCase) == 0)) { variant = s_headerInfo[i].Variant; } } } bool isLocalDomain = IsLocalDomain(uri.Host); try { CookieParser parser = new CookieParser(setCookieHeader); do { Cookie cookie = parser.Get(); if (GlobalLog.IsEnabled) { GlobalLog.Print("CookieContainer#" + LoggingHash.HashString(this) + "::CookieCutter() CookieParser returned cookie:" + LoggingHash.ObjectToString(cookie)); } if (cookie == null) { break; } // Parser marks invalid cookies this way if (String.IsNullOrEmpty(cookie.Name)) { if (isThrow) { throw new CookieException(SR.net_cookie_format); } // Otherwise, ignore (reject) cookie continue; } // This will set the default values from the response URI // AND will check for cookie validity if (!cookie.VerifySetDefaults(variant, uri, isLocalDomain, _fqdnMyDomain, true, isThrow)) { continue; } // If many same cookies arrive we collapse them into just one, hence setting // parameter isStrict = true below cookies.InternalAdd(cookie, true); } while (true); } catch (OutOfMemoryException) { throw; } catch (Exception e) { if (isThrow) { throw new CookieException(SR.Format(SR.net_cookie_parse_header, uri.AbsoluteUri), e); } } foreach (Cookie c in cookies) { Add(c, isThrow); } return cookies; } public CookieCollection GetCookies(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } return InternalGetCookies(uri) ?? new CookieCollection(); } internal CookieCollection InternalGetCookies(Uri uri) { bool isSecure = (uri.Scheme == UriScheme.Https); int port = uri.Port; CookieCollection cookies = null; List<string> domainAttributeMatchAnyCookieVariant = new List<string>(); List<string> domainAttributeMatchOnlyCookieVariantPlain = null; string fqdnRemote = uri.Host; // Add initial candidates to match Domain attribute of possible cookies. // For these Domains, cookie can have any CookieVariant enum value. domainAttributeMatchAnyCookieVariant.Add(fqdnRemote); domainAttributeMatchAnyCookieVariant.Add("." + fqdnRemote); int dot = fqdnRemote.IndexOf('.'); if (dot == -1) { // DNS.resolve may return short names even for other inet domains ;-( // We _don't_ know what the exact domain is, so try also grab short hostname cookies. // Grab long name from the local domain if (_fqdnMyDomain != null && _fqdnMyDomain.Length != 0) { domainAttributeMatchAnyCookieVariant.Add(fqdnRemote + _fqdnMyDomain); // Grab the local domain itself domainAttributeMatchAnyCookieVariant.Add(_fqdnMyDomain); } } else { // Grab the host domain domainAttributeMatchAnyCookieVariant.Add(fqdnRemote.Substring(dot)); // The following block is only for compatibility with Version0 spec. // Still, we'll add only Plain-Variant cookies if found under below keys if (fqdnRemote.Length > 2) { // We ignore the '.' at the end on the name int last = fqdnRemote.LastIndexOf('.', fqdnRemote.Length - 2); // AND keys with <2 dots inside. if (last > 0) { last = fqdnRemote.LastIndexOf('.', last - 1); } if (last != -1) { while ((dot < last) && (dot = fqdnRemote.IndexOf('.', dot + 1)) != -1) { if (domainAttributeMatchOnlyCookieVariantPlain == null) { domainAttributeMatchOnlyCookieVariantPlain = new List<string>(); } // These candidates can only match CookieVariant.Plain cookies. domainAttributeMatchOnlyCookieVariantPlain.Add(fqdnRemote.Substring(dot)); } } } } BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchAnyCookieVariant, false); if (domainAttributeMatchOnlyCookieVariantPlain != null) { BuildCookieCollectionFromDomainMatches(uri, isSecure, port, ref cookies, domainAttributeMatchOnlyCookieVariantPlain, true); } return cookies; } private void BuildCookieCollectionFromDomainMatches(Uri uri, bool isSecure, int port, ref CookieCollection cookies, List<string> domainAttribute, bool matchOnlyPlainCookie) { for (int i = 0; i < domainAttribute.Count; i++) { bool found = false; bool defaultAdded = false; PathList pathList; lock (_domainTable) { if (!_domainTable.TryGetValue(domainAttribute[i], out pathList)) { continue; } } lock (pathList.SyncRoot) { foreach (KeyValuePair<string, CookieCollection> pair in pathList) { string path = pair.Key; if (uri.AbsolutePath.StartsWith(CookieParser.CheckQuoted(path))) { found = true; CookieCollection cc = pair.Value; cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(ref cookies, cc, port, isSecure, matchOnlyPlainCookie); if (path == "/") { defaultAdded = true; } } else if (found) { break; } } } if (!defaultAdded) { CookieCollection cc = pathList["/"]; if (cc != null) { cc.TimeStamp(CookieCollection.Stamp.Set); MergeUpdateCollections(ref cookies, cc, port, isSecure, matchOnlyPlainCookie); } } // Remove unused domain // (This is the only place that does domain removal) if (pathList.Count == 0) { lock (_domainTable) { _domainTable.Remove(domainAttribute[i]); } } } } private void MergeUpdateCollections(ref CookieCollection destination, CookieCollection source, int port, bool isSecure, bool isPlainOnly) { lock (source) { // Cannot use foreach as we are going to update 'source' for (int idx = 0; idx < source.Count; ++idx) { bool to_add = false; Cookie cookie = source[idx]; if (cookie.Expired) { // If expired, remove from container and don't add to the destination source.RemoveAt(idx); --_count; --idx; } else { // Add only if port does match to this request URI // or was not present in the original response. if (isPlainOnly && cookie.Variant != CookieVariant.Plain) { ; // Don't add } else if (cookie.PortList != null) { foreach (int p in cookie.PortList) { if (p == port) { to_add = true; break; } } } else { // It was implicit Port, always OK to add. to_add = true; } // Refuse to add a secure cookie into an 'unsecure' destination if (cookie.Secure && !isSecure) { to_add = false; } if (to_add) { // In 'source' are already ordered. // If two same cookies come from different 'source' then they // will follow (not replace) each other. if (destination == null) { destination = new CookieCollection(); } destination.InternalAdd(cookie, false); } } } } } public string GetCookieHeader(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } string dummy; return GetCookieHeader(uri, out dummy); } internal string GetCookieHeader(Uri uri, out string optCookie2) { CookieCollection cookies = InternalGetCookies(uri); if (cookies == null) { optCookie2 = string.Empty; return string.Empty; } string delimiter = string.Empty; var builder = StringBuilderCache.Acquire(); for (int i = 0; i < cookies.Count; i++) { builder.Append(delimiter); cookies[i].ToString(builder); delimiter = "; "; } optCookie2 = cookies.IsOtherVersionSeen ? (Cookie.SpecialAttributeLiteral + Cookie.VersionAttributeName + Cookie.EqualsLiteral + Cookie.MaxSupportedVersionString) : string.Empty; return StringBuilderCache.GetStringAndRelease(builder); } public void SetCookies(Uri uri, string cookieHeader) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (cookieHeader == null) { throw new ArgumentNullException(nameof(cookieHeader)); } CookieCutter(uri, null, cookieHeader, true); // Will throw on error } } internal struct PathList { // Usage of PathList depends on it being shallowly immutable; // adding any mutable fields to it would result in breaks. private readonly SortedList<string, CookieCollection> _list; public static PathList Create() => new PathList(new SortedList<string, CookieCollection>(PathListComparer.StaticInstance)); private PathList(SortedList<string, CookieCollection> list) { Debug.Assert(list != null, $"{nameof(list)} must not be null."); _list = list; } public int Count { get { lock (SyncRoot) { return _list.Count; } } } public int GetCookiesCount() { int count = 0; lock (SyncRoot) { foreach (KeyValuePair<string, CookieCollection> pair in _list) { CookieCollection cc = pair.Value; count += cc.Count; } } return count; } public CookieCollection this[string s] { get { lock (SyncRoot) { CookieCollection value; _list.TryGetValue(s, out value); return value; } } set { lock (SyncRoot) { Debug.Assert(value != null); _list[s] = value; } } } public IEnumerator<KeyValuePair<string, CookieCollection>> GetEnumerator() { lock (SyncRoot) { return _list.GetEnumerator(); } } public object SyncRoot { get { Debug.Assert(_list != null, $"{nameof(PathList)} should never be default initialized and only ever created with {nameof(Create)}."); return _list; } } private sealed class PathListComparer : IComparer<string> { internal static readonly PathListComparer StaticInstance = new PathListComparer(); int IComparer<string>.Compare(string x, string y) { string pathLeft = CookieParser.CheckQuoted(x); string pathRight = CookieParser.CheckQuoted(y); int ll = pathLeft.Length; int lr = pathRight.Length; int length = Math.Min(ll, lr); for (int i = 0; i < length; ++i) { if (pathLeft[i] != pathRight[i]) { return pathLeft[i] - pathRight[i]; } } return lr - ll; } } } }
using System.Drawing; using System.Drawing.Imaging; namespace Hydra.Framework.ImageProcessing.Analysis.Filters { // //********************************************************************** /// <summary> /// Shrink an image - remove pixels with specified color from bounds /// </summary> //********************************************************************** // public class Shrink : IFilter { #region Private Member Variables // //********************************************************************** /// <summary> /// Colour to Remove /// </summary> //********************************************************************** // private Color colorToRemove_m = Color.FromArgb(0, 0, 0); #endregion #region Constructors // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:Shrink"/> class. /// </summary> //********************************************************************** // public Shrink() { } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:Shrink"/> class. /// </summary> /// <param name="colorToRemove">The color to remove.</param> //********************************************************************** // public Shrink(Color colorToRemove) { this.colorToRemove_m = colorToRemove; } #endregion #region Properties // //********************************************************************** /// <summary> /// Gets or sets the color to remove property. /// </summary> /// <value>The color to remove.</value> //********************************************************************** // public Color ColorToRemove { get { return colorToRemove_m; } set { colorToRemove_m = value; } } #endregion #region Public Methods // //********************************************************************** /// <summary> /// Apply filter /// </summary> /// <param name="srcImg">The SRC img.</param> /// <returns></returns> //********************************************************************** // public Bitmap Apply(Bitmap srcImg) { // // get source image size // int width = srcImg.Width; int height = srcImg.Height; PixelFormat fmt = (srcImg.PixelFormat == PixelFormat.Format8bppIndexed) ? PixelFormat.Format8bppIndexed : PixelFormat.Format24bppRgb; // // lock source bitmap data // BitmapData srcData = srcImg.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, fmt); int offset = srcData.Stride - ((fmt == PixelFormat.Format8bppIndexed) ? width : width * 3); byte r = colorToRemove_m.R; byte g = colorToRemove_m.G; byte b = colorToRemove_m.B; int minX = width; int minY = height; int maxX = 0; int maxY = 0; // // do the job (Warning Unsafe Code) // unsafe { byte * src = (byte *) srcData.Scan0.ToPointer(); if (fmt == PixelFormat.Format8bppIndexed) { // // grayscale // for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++, src ++) { if (*src != g) { if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y; } } src += offset; } } else { // // RGB // for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++, src += 3) { if ((src[RGB.R] != r) || (src[RGB.G] != g) || (src[RGB.B] != b)) { if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y; } } src += offset; } } } // // check // if ((minX == width) && (minY == height) && (maxX == 0) && (maxY == 0)) { minX = minY = 0; } int newWidth = maxX - minX + 1; int newHeight = maxY - minY + 1; // // create new image // Bitmap dstImg = (fmt == PixelFormat.Format8bppIndexed) ? Hydra.Framework.ImageProcessing.Analysis.Image.CreateGrayscaleImage(newWidth, newHeight) : new Bitmap(newWidth, newHeight, fmt); // // lock destination bitmap data // BitmapData dstData = dstImg.LockBits( new Rectangle(0, 0, newWidth, newHeight), ImageLockMode.ReadWrite, fmt); int dstStride = dstData.Stride; int srcStride = srcData.Stride; int copySize = newWidth; // // do the job (Warning Unsafe Code) // unsafe { byte * src = (byte *) srcData.Scan0.ToPointer(); byte * dst = (byte *) dstData.Scan0.ToPointer(); src += (minY * srcData.Stride); if (fmt == PixelFormat.Format8bppIndexed) { src += minX; } else { src += minX * 3; copySize *= 3; } // // copy image // for (int y = 0; y < newHeight; y++) { Win32.memcpy(dst, src, copySize); dst += dstStride; src += srcStride; } } // // unlock both images // dstImg.UnlockBits(dstData); srcImg.UnlockBits(srcData); return dstImg; } #endregion } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.ComponentModel; using System.Linq; using System.Threading; using XenAdmin.Network; using XenAPI; namespace XenAdmin.Dialogs { public interface ILicenseStatus : IDisposable { LicenseStatus.HostState CurrentState { get; } Host.Edition LicenseEdition { get; } TimeSpan LicenseExpiresIn { get; } TimeSpan LicenseExpiresExactlyIn { get; } DateTime? ExpiryDate { get; } event Action ItemUpdated; bool Updated { get; } void BeginUpdate(); Host LicensedHost { get; } string LicenseEntitlements { get; } } public class LicenseStatus : ILicenseStatus { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public enum HostState { Unknown, Expired, ExpiresSoon, RegularGrace, UpgradeGrace, Licensed, PartiallyLicensed, Free, Unavailable } private readonly EventHandlerList _events = new EventHandlerList(); private const string StatusUpdatedEventKey = "LicenseStatusStatusUpdatedEventKey"; public Host LicensedHost { get; private set; } public static bool IsInfinite(TimeSpan span) { return span.TotalDays >= 3653; } public static bool IsGraceLicence(TimeSpan span) { return span.TotalDays < 30; } private IXenObject XenObject { get; } public bool Updated { get; private set; } public LicenseStatus(IXenObject xo) { SetDefaultOptions(); XenObject = xo; if (XenObject is Host host) LicensedHost = host; if (XenObject is Pool pool) SetMinimumLicenseValueHost(pool); if (XenObject != null) { XenObject.Connection.ConnectionStateChanged -= Connection_ConnectionStateChanged; XenObject.Connection.ConnectionStateChanged += Connection_ConnectionStateChanged; } } private void Connection_ConnectionStateChanged(IXenConnection conn) { if (LicensedHost != null) { TriggerStatusUpdatedEvent(); } } private void SetMinimumLicenseValueHost(Pool pool) { LicensedHost = pool.Connection.Resolve(pool.master); if(LicensedHost == null) return; foreach (Host host in pool.Connection.Cache.Hosts) { if(host.LicenseExpiryUTC() < LicensedHost.LicenseExpiryUTC()) LicensedHost = host; } } private void SetDefaultOptions() { CurrentState = HostState.Unknown; Updated = false; LicenseExpiresExactlyIn = new TimeSpan(); } public void BeginUpdate() { SetDefaultOptions(); ThreadPool.QueueUserWorkItem(GetServerTime, LicensedHost); } private void GetServerTime(object state) { Host host = state as Host; if (host?.Connection?.Session == null) { log.Error("Will not fetch server time: host or connection could not be resolved"); return; } try { //Note we're using the get_servertime call which returns the UTC time var serverTime = Host.get_servertime(host.Connection.Session, host.opaque_ref); if (LicensedHost != null) { //ServerTime is UTC DateTime currentRefTime = serverTime; LicenseExpiresExactlyIn = LicensedHost.LicenseExpiryUTC().Subtract(currentRefTime); CurrentState = CalculateCurrentState(); Updated = true; TriggerStatusUpdatedEvent(); } } catch (Exception e) { log.Error($"Failed to fetch server time for host {host.name_label}: ", e); } } private void TriggerStatusUpdatedEvent() { if (_events[StatusUpdatedEventKey] is Action handler) handler.Invoke(); } private bool InRegularGrace { get { return LicensedHost.license_params != null && LicensedHost.license_params.ContainsKey("grace") && LicenseExpiresIn.Ticks > 0 && LicensedHost.license_params["grace"] == "regular grace"; } } private bool InUpgradeGrace { get { return LicensedHost.license_params != null && LicensedHost.license_params.ContainsKey("grace") && LicenseExpiresIn.Ticks > 0 && LicensedHost.license_params["grace"] == "upgrade grace"; } } internal static bool PoolIsMixedFreeAndExpiring(IXenObject xenObject) { if (xenObject is Pool) { if (xenObject.Connection.Cache.Hosts.Length == 1) return false; int freeCount = xenObject.Connection.Cache.Hosts.Count(h => Host.GetEdition(h.edition) == Host.Edition.Free); if (freeCount == 0 || freeCount < xenObject.Connection.Cache.Hosts.Length) return false; var expiryGroups = from Host h in xenObject.Connection.Cache.Hosts let exp = h.LicenseExpiryUTC() group h by exp into g select new { ExpiryDate = g.Key, Hosts = g }; if(expiryGroups.Count() > 1) { expiryGroups.OrderBy(g => g.ExpiryDate); if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30) return true; } } return false; } internal static bool PoolIsPartiallyLicensed(IXenObject xenObject) { if (xenObject is Pool) { if (xenObject.Connection.Cache.Hosts.Length == 1) return false; int freeCount = xenObject.Connection.Cache.Hosts.Count(h => Host.GetEdition(h.edition) == Host.Edition.Free); return freeCount > 0 && freeCount < xenObject.Connection.Cache.Hosts.Length; } return false; } internal static bool PoolHasMixedLicenses(IXenObject xenObject) { if (xenObject is Pool pool) { if (xenObject.Connection.Cache.Hosts.Length == 1) return false; if (xenObject.Connection.Cache.Hosts.Any(h => Host.GetEdition(h.edition) == Host.Edition.Free)) return false; var licenseGroups = from Host h in xenObject.Connection.Cache.Hosts let ed = Host.GetEdition(h.edition) group h by ed; return licenseGroups.Count() > 1; } return false; } private HostState CalculateCurrentState() { if (ExpiryDate.HasValue && ExpiryDate.Value.Day == 1 && ExpiryDate.Value.Month == 1 && ExpiryDate.Value.Year == 1970) { return HostState.Unavailable; } if (PoolIsPartiallyLicensed(XenObject)) return HostState.PartiallyLicensed; if (LicenseEdition == Host.Edition.Free) return HostState.Free; if (!IsGraceLicence(LicenseExpiresIn)) return HostState.Licensed; if (IsInfinite(LicenseExpiresIn)) { return HostState.Licensed; } if (LicenseExpiresIn.Ticks <= 0) { return HostState.Expired; } if (IsGraceLicence(LicenseExpiresIn)) { if (InRegularGrace) return HostState.RegularGrace; if (InUpgradeGrace) return HostState.UpgradeGrace; return HostState.ExpiresSoon; } return LicenseEdition == Host.Edition.Free ? HostState.Free : HostState.Licensed; } #region ILicenseStatus Members public event Action ItemUpdated { add => _events.AddHandler(StatusUpdatedEventKey, value); remove => _events.RemoveHandler(StatusUpdatedEventKey, value); } public Host.Edition LicenseEdition => Host.GetEdition(LicensedHost.edition); public HostState CurrentState { get; private set; } public TimeSpan LicenseExpiresExactlyIn { get; private set; } /// <summary> /// License expiry, just days, hrs, mins /// </summary> public TimeSpan LicenseExpiresIn { get { return new TimeSpan(LicenseExpiresExactlyIn.Days, LicenseExpiresExactlyIn.Hours, LicenseExpiresExactlyIn.Minutes, 0, 0); } } public DateTime? ExpiryDate { get { if (LicensedHost.license_params != null && LicensedHost.license_params.ContainsKey("expiry")) return LicensedHost.LicenseExpiryUTC().ToLocalTime(); return null; } } public string LicenseEntitlements { get { if (CurrentState == HostState.Licensed) { if (XenObject.Connection.Cache.Hosts.All(h => h.EnterpriseFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_ENTERPRISE_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopPlusFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_DESKTOP_PLUS_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_DESKTOP_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopCloudFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_DESKTOP_CLOUD_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.PremiumFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_PREMIUM_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.StandardFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_STANDARD_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.EligibleForSupport())) return Messages.LICENSE_SUPPORT_AND_STANDARD_FEATURES_ENABLED; return Messages.LICENSE_NOT_ELIGIBLE_FOR_SUPPORT; } if (CurrentState == HostState.Free) { return Messages.LICENSE_NOT_ELIGIBLE_FOR_SUPPORT; } return Messages.UNKNOWN; } } #endregion #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool disposed; public void Dispose(bool disposing) { if(!disposed) { if(disposing) { if (XenObject != null && XenObject.Connection != null) XenObject.Connection.ConnectionStateChanged -= Connection_ConnectionStateChanged; _events.Dispose(); } disposed = true; } } #endregion } }
// // PlayerEngine.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Runtime.InteropServices; using System.Threading; using Mono.Unix; using Hyena; using Hyena.Data; using Banshee.Base; using Banshee.Streaming; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Configuration; using Banshee.Preferences; namespace Banshee.GStreamer { internal enum GstState { VoidPending = 0, Null = 1, Ready = 2, Paused = 3, Playing = 4 } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerEosCallback (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerErrorCallback (IntPtr player, uint domain, int code, IntPtr error, IntPtr debug); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerStateChangedCallback (IntPtr player, GstState old_state, GstState new_state, GstState pending_state); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerBufferingCallback (IntPtr player, int buffering_progress); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerVisDataCallback (IntPtr player, int channels, int samples, IntPtr data, int bands, IntPtr spectrum); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerNextTrackStartingCallback (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerAboutToFinishCallback (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr VideoPipelineSetupHandler (IntPtr player, IntPtr bus); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void VideoPrepareWindowHandler (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerVolumeChangedCallback (IntPtr player, double newVolume); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void GstTaggerTagFoundCallback (IntPtr player, string tagName, ref GLib.Value value); public class PlayerEngine : Banshee.MediaEngine.PlayerEngine, IEqualizer, IVisualizationDataSource, ISupportClutter { internal static string reserved1 = Catalog.GetString ("Enable _gapless playback"); internal static string reserved2 = Catalog.GetString ("Eliminate the small playback gap on track change. Useful for concept albums and classical music"); private uint GST_CORE_ERROR = 0; private uint GST_LIBRARY_ERROR = 0; private uint GST_RESOURCE_ERROR = 0; private uint GST_STREAM_ERROR = 0; private HandleRef handle; private bool is_initialized; private BansheePlayerEosCallback eos_callback; private BansheePlayerErrorCallback error_callback; private BansheePlayerStateChangedCallback state_changed_callback; private BansheePlayerBufferingCallback buffering_callback; private BansheePlayerVisDataCallback vis_data_callback; private VideoPipelineSetupHandler video_pipeline_setup_callback; private VideoPrepareWindowHandler video_prepare_window_callback; private GstTaggerTagFoundCallback tag_found_callback; private BansheePlayerNextTrackStartingCallback next_track_starting_callback; private BansheePlayerAboutToFinishCallback about_to_finish_callback; private BansheePlayerVolumeChangedCallback volume_changed_callback; private bool next_track_pending; private SafeUri pending_uri; private bool buffering_finished; private bool xid_is_set = false; private uint iterate_timeout_id = 0; private bool gapless_enabled; private EventWaitHandle next_track_set; private event VisualizationDataHandler data_available = null; public event VisualizationDataHandler DataAvailable { add { if (value == null) { return; } else if (data_available == null) { bp_set_vis_data_callback (handle, vis_data_callback); } data_available += value; } remove { if (value == null) { return; } data_available -= value; if (data_available == null) { bp_set_vis_data_callback (handle, null); } } } protected override bool DelayedInitialize { get { return true; } } public PlayerEngine () { IntPtr ptr = bp_new (); if (ptr == IntPtr.Zero) { throw new ApplicationException (Catalog.GetString ("Could not initialize GStreamer library")); } handle = new HandleRef (this, ptr); bp_get_error_quarks (out GST_CORE_ERROR, out GST_LIBRARY_ERROR, out GST_RESOURCE_ERROR, out GST_STREAM_ERROR); eos_callback = new BansheePlayerEosCallback (OnEos); error_callback = new BansheePlayerErrorCallback (OnError); state_changed_callback = new BansheePlayerStateChangedCallback (OnStateChange); buffering_callback = new BansheePlayerBufferingCallback (OnBuffering); vis_data_callback = new BansheePlayerVisDataCallback (OnVisualizationData); video_pipeline_setup_callback = new VideoPipelineSetupHandler (OnVideoPipelineSetup); video_prepare_window_callback = new VideoPrepareWindowHandler (OnVideoPrepareWindow); tag_found_callback = new GstTaggerTagFoundCallback (OnTagFound); next_track_starting_callback = new BansheePlayerNextTrackStartingCallback (OnNextTrackStarting); about_to_finish_callback = new BansheePlayerAboutToFinishCallback (OnAboutToFinish); volume_changed_callback = new BansheePlayerVolumeChangedCallback (OnVolumeChanged); bp_set_eos_callback (handle, eos_callback); bp_set_error_callback (handle, error_callback); bp_set_state_changed_callback (handle, state_changed_callback); bp_set_buffering_callback (handle, buffering_callback); bp_set_tag_found_callback (handle, tag_found_callback); bp_set_next_track_starting_callback (handle, next_track_starting_callback); bp_set_video_pipeline_setup_callback (handle, video_pipeline_setup_callback); bp_set_video_prepare_window_callback (handle, video_prepare_window_callback); bp_set_volume_changed_callback (handle, volume_changed_callback); next_track_set = new EventWaitHandle (false, EventResetMode.ManualReset); } protected override void Initialize () { if (!bp_initialize_pipeline (handle)) { bp_destroy (handle); handle = new HandleRef (this, IntPtr.Zero); throw new ApplicationException (Catalog.GetString ("Could not initialize GStreamer library")); } OnStateChanged (PlayerState.Ready); InstallPreferences (); ReplayGainEnabled = ReplayGainEnabledSchema.Get (); GaplessEnabled = GaplessEnabledSchema.Get (); is_initialized = true; if (!bp_audiosink_has_volume (handle)) { Volume = (ushort)PlayerEngineService.VolumeSchema.Get (); } } public override void Dispose () { UninstallPreferences (); base.Dispose (); bp_destroy (handle); handle = new HandleRef (this, IntPtr.Zero); is_initialized = false; } public override void Close (bool fullShutdown) { bp_stop (handle, fullShutdown); base.Close (fullShutdown); } protected override void OpenUri (SafeUri uri) { // The GStreamer engine can use the XID of the main window if it ever // needs to bring up the plugin installer so it can be transient to // the main window. if (!xid_is_set) { var service = ServiceManager.Get ("GtkElementsService") as IPropertyStoreExpose; if (service != null) { bp_set_application_gdk_window (handle, service.PropertyStore.Get<IntPtr> ("PrimaryWindow.RawHandle")); } xid_is_set = true; } IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (uri.AbsoluteUri); try { if (!bp_open (handle, uri_ptr)) { throw new ApplicationException ("Could not open resource"); } } finally { GLib.Marshaller.Free (uri_ptr); } } public override void Play () { bp_play (handle); } public override void Pause () { bp_pause (handle); } public override void SetNextTrackUri (SafeUri uri) { next_track_pending = false; if (next_track_set.WaitOne (0, false)) { // We're not waiting for the next track to be set. // This means that we've missed the window for gapless. // Save this URI to be played when we receive EOS. pending_uri = uri; return; } // If there isn't a next track for us, release the block on the about-to-finish callback. if (uri == null) { next_track_set.Set (); return; } IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (uri.AbsoluteUri); try { bp_set_next_track (handle, uri_ptr); } finally { GLib.Marshaller.Free (uri_ptr); next_track_set.Set (); } } public override void VideoExpose (IntPtr window, bool direct) { bp_video_window_expose (handle, window, direct); } public override void VideoWindowRealize (IntPtr window) { bp_video_window_realize (handle, window); } public override IntPtr [] GetBaseElements () { IntPtr [] elements = new IntPtr[3]; if (bp_get_pipeline_elements (handle, out elements[0], out elements[1], out elements[2])) { return elements; } return null; } private void OnEos (IntPtr player) { Close (false); OnEventChanged (PlayerEvent.EndOfStream); if (!next_track_pending) { OnEventChanged (PlayerEvent.RequestNextTrack); } else if (pending_uri != null) { Log.Warning ("[Gapless] EOS signalled while waiting for next track. This means that Banshee " + "was too slow at calculating what track to play next. " + "If this happens frequently, please file a bug"); OnStateChanged (PlayerState.Loading); OpenUri (pending_uri); Play (); pending_uri = null; } else { // This should be unreachable - the RequestNextTrack event is delegated to the main thread // and so blocks the bus callback from delivering the EOS message. // // Playback should continue as normal from here, when the RequestNextTrack message gets handled. Log.Warning ("[Gapless] EndOfStream message received before the next track has been set. " + "If this happens frequently, please file a bug"); } } private bool OnIterate () { // Actual iteration. OnEventChanged (PlayerEvent.Iterate); // Run forever until we are stopped return true; } private void StartIterating () { if (iterate_timeout_id > 0) { GLib.Source.Remove (iterate_timeout_id); } iterate_timeout_id = GLib.Timeout.Add (200, OnIterate); } private void StopIterating () { if (iterate_timeout_id > 0) { GLib.Source.Remove (iterate_timeout_id); } } private void OnNextTrackStarting (IntPtr player) { if (GaplessEnabled) { // Must do it here because the next track is already playing. ServiceManager.PlayerEngine.IncrementLastPlayed (1.0); OnEventChanged (PlayerEvent.EndOfStream); OnEventChanged (PlayerEvent.StartOfStream); } } private void OnAboutToFinish (IntPtr player) { // This is needed to make Shuffle-by-* work. // Shuffle-by-* uses the LastPlayed field to determine what track in the grouping to play next. // Therefore, we need to update this before requesting the next track. // // This will be overridden by IncrementLastPlayed () called by // PlaybackControllerService's EndOfStream handler. CurrentTrack.UpdateLastPlayed (); next_track_set.Reset (); pending_uri = null; next_track_pending = true; OnEventChanged (PlayerEvent.RequestNextTrack); // Gapless playback with Playbin2 requires that the about-to-finish callback does not return until // the next uri has been set. Block here for a second or until the RequestNextTrack event has // finished triggering. if (!next_track_set.WaitOne (1000, false)) { Log.Debug ("[Gapless] Timed out while waiting for next_track_set to be raised"); next_track_set.Set (); } } private void OnStateChange (IntPtr player, GstState old_state, GstState new_state, GstState pending_state) { // Start by clearing any timeout we might have StopIterating (); if (CurrentState != PlayerState.Loaded && old_state == GstState.Ready && new_state == GstState.Paused && pending_state == GstState.Playing) { if (ready_timeout != 0) { Application.IdleTimeoutRemove (ready_timeout); ready_timeout = 0; } OnStateChanged (PlayerState.Loaded); return; } else if (old_state == GstState.Paused && new_state == GstState.Playing && pending_state == GstState.VoidPending) { if (CurrentState == PlayerState.Loaded) { OnEventChanged (PlayerEvent.StartOfStream); } OnStateChanged (PlayerState.Playing); // Start iterating only when going to playing StartIterating (); return; } else if (CurrentState == PlayerState.Playing && old_state == GstState.Playing && new_state == GstState.Paused) { OnStateChanged (PlayerState.Paused); return; } else if (new_state == GstState.Ready && pending_state == GstState.Playing) { if (ready_timeout == 0) { ready_timeout = Application.RunTimeout (1000, OnReadyTimeout); } return; } } private uint ready_timeout; private bool OnReadyTimeout () { ready_timeout = 0; var uri = CurrentUri; if (CurrentState == PlayerState.Loading && uri != null && uri.IsLocalPath) { // This is a dirty workaround. I was seeing the playback get stuck on track transition, // about one in 20 songs, where it would load the new track's duration, but be stuck at 0:00, // but if I moved the seek slider it would unstick it, hence setting Position... Log.WarningFormat ("Seem to be stuck loading {0}, so re-trying", uri); Position = 0; } return false; } private void OnError (IntPtr player, uint domain, int code, IntPtr error, IntPtr debug) { Close (true); string error_message = error == IntPtr.Zero ? Catalog.GetString ("Unknown Error") : GLib.Marshaller.Utf8PtrToString (error); if (domain == GST_RESOURCE_ERROR) { GstResourceError domain_code = (GstResourceError) code; if (CurrentTrack != null) { switch (domain_code) { case GstResourceError.NotFound: CurrentTrack.SavePlaybackError (StreamPlaybackError.ResourceNotFound); break; default: break; } } Log.Error (String.Format ("GStreamer resource error: {0}", domain_code), false); } else if (domain == GST_STREAM_ERROR) { GstStreamError domain_code = (GstStreamError) code; if (CurrentTrack != null) { switch (domain_code) { case GstStreamError.CodecNotFound: CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound); break; default: break; } } Log.Error (String.Format("GStreamer stream error: {0}", domain_code), false); } else if (domain == GST_CORE_ERROR) { GstCoreError domain_code = (GstCoreError) code; if (CurrentTrack != null) { switch (domain_code) { case GstCoreError.MissingPlugin: CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound); break; default: break; } } if (domain_code != GstCoreError.MissingPlugin) { Log.Error (String.Format("GStreamer core error: {0}", (GstCoreError) code), false); } } else if (domain == GST_LIBRARY_ERROR) { Log.Error (String.Format("GStreamer library error: {0}", (GstLibraryError) code), false); } OnEventChanged (new PlayerEventErrorArgs (error_message)); } private void OnBuffering (IntPtr player, int progress) { if (buffering_finished && progress >= 100) { return; } buffering_finished = progress >= 100; OnEventChanged (new PlayerEventBufferingArgs ((double) progress / 100.0)); } private void OnTagFound (IntPtr player, string tagName, ref GLib.Value value) { OnTagFound (ProcessNativeTagResult (tagName, ref value)); } private void OnVisualizationData (IntPtr player, int channels, int samples, IntPtr data, int bands, IntPtr spectrum) { VisualizationDataHandler handler = data_available; if (handler == null) { return; } float [] flat = new float[channels * samples]; Marshal.Copy (data, flat, 0, flat.Length); float [][] cbd = new float[channels][]; for (int i = 0; i < channels; i++) { float [] channel = new float[samples]; Array.Copy (flat, i * samples, channel, 0, samples); cbd[i] = channel; } float [] spec = new float[bands]; Marshal.Copy (spectrum, spec, 0, bands); try { handler (cbd, new float[][] { spec }); } catch (Exception e) { Log.Exception ("Uncaught exception during visualization data post.", e); } } private void OnVolumeChanged (IntPtr player, double newVolume) { OnEventChanged (PlayerEvent.Volume); } private static StreamTag ProcessNativeTagResult (string tagName, ref GLib.Value valueRaw) { if (tagName == String.Empty || tagName == null) { return StreamTag.Zero; } object value = null; try { value = valueRaw.Val; } catch { return StreamTag.Zero; } if (value == null) { return StreamTag.Zero; } StreamTag item; item.Name = tagName; item.Value = value; return item; } public override ushort Volume { get { return is_initialized ? (ushort)Math.Round (bp_get_volume (handle) * 100.0) : (ushort)0; } set { if (!is_initialized) { return; } bp_set_volume (handle, value / 100.0); if (!bp_audiosink_has_volume (handle)) { PlayerEngineService.VolumeSchema.Set ((int)value); } OnEventChanged (PlayerEvent.Volume); } } public override uint Position { get { return (uint)bp_get_position(handle); } set { bp_set_position (handle, (ulong)value); OnEventChanged (PlayerEvent.Seek); } } public override bool CanSeek { get { return bp_can_seek (handle); } } public override uint Length { get { return (uint)bp_get_duration (handle); } } public override string Id { get { return "gstreamer"; } } public override string Name { get { return "GStreamer 0.10"; } } private bool? supports_equalizer = null; public override bool SupportsEqualizer { get { if (supports_equalizer == null) { supports_equalizer = bp_equalizer_is_supported (handle); } return supports_equalizer.Value; } } public override VideoDisplayContextType VideoDisplayContextType { get { return bp_video_get_display_context_type (handle); } } public override IntPtr VideoDisplayContext { set { bp_video_set_display_context (handle, value); } get { return bp_video_get_display_context (handle); } } public double AmplifierLevel { set { double scale = Math.Pow (10.0, value / 20.0); bp_equalizer_set_preamp_level (handle, scale); } } public int [] BandRange { get { int min = -1; int max = -1; bp_equalizer_get_bandrange (handle, out min, out max); return new int [] { min, max }; } } public uint [] EqualizerFrequencies { get { uint count = bp_equalizer_get_nbands (handle); double [] freq = new double[count]; bp_equalizer_get_frequencies (handle, out freq); uint [] ret = new uint[count]; for (int i = 0; i < count; i++) { ret[i] = (uint)freq[i]; } return ret; } } public void SetEqualizerGain (uint band, double gain) { bp_equalizer_set_gain (handle, band, gain); } private static string [] source_capabilities = { "file", "http", "cdda" }; public override IEnumerable SourceCapabilities { get { return source_capabilities; } } private static string [] decoder_capabilities = { "ogg", "wma", "asf", "flac" }; public override IEnumerable ExplicitDecoderCapabilities { get { return decoder_capabilities; } } private bool ReplayGainEnabled { get { return bp_replaygain_get_enabled (handle); } set { bp_replaygain_set_enabled (handle, value); } } private bool GaplessEnabled { get { return gapless_enabled; } set { if (bp_supports_gapless (handle)) { gapless_enabled = value; if (value) { bp_set_about_to_finish_callback (handle, about_to_finish_callback); } else { bp_set_about_to_finish_callback (handle, null); } } else { gapless_enabled = false; } } } #region ISupportClutter private IntPtr clutter_video_sink; private IntPtr clutter_video_texture; private bool clutter_video_sink_enabled; public void EnableClutterVideoSink (IntPtr videoTexture) { clutter_video_sink_enabled = true; clutter_video_texture = videoTexture; } public void DisableClutterVideoSink () { clutter_video_sink_enabled = false; clutter_video_texture = IntPtr.Zero; } public bool IsClutterVideoSinkInitialized { get { return clutter_video_sink_enabled && clutter_video_texture != IntPtr.Zero && clutter_video_sink != IntPtr.Zero; } } private IntPtr OnVideoPipelineSetup (IntPtr player, IntPtr bus) { try { if (clutter_video_sink_enabled) { if (clutter_video_sink != IntPtr.Zero) { // FIXME: does this get unreffed by the pipeline? } clutter_video_sink = clutter_gst_video_sink_new (clutter_video_texture); } else if (!clutter_video_sink_enabled && clutter_video_sink != IntPtr.Zero) { clutter_video_sink = IntPtr.Zero; clutter_video_texture = IntPtr.Zero; } } catch (Exception e) { Log.Exception ("Clutter support could not be initialized", e); clutter_video_sink = IntPtr.Zero; clutter_video_texture = IntPtr.Zero; clutter_video_sink_enabled = false; } return clutter_video_sink; } private void OnVideoPrepareWindow (IntPtr player) { OnEventChanged (PlayerEvent.PrepareVideoWindow); } #endregion #region Preferences private PreferenceBase replaygain_preference; private PreferenceBase gapless_preference; private void InstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } replaygain_preference = service["general"]["misc"].Add (new SchemaPreference<bool> (ReplayGainEnabledSchema, Catalog.GetString ("_Enable ReplayGain correction"), Catalog.GetString ("For tracks that have ReplayGain data, automatically scale (normalize) playback volume"), delegate { ReplayGainEnabled = ReplayGainEnabledSchema.Get (); } )); if (bp_supports_gapless (handle)) { gapless_preference = service["general"]["misc"].Add (new SchemaPreference<bool> (GaplessEnabledSchema, Catalog.GetString ("Enable _gapless playback"), Catalog.GetString ("Eliminate the small playback gap on track change. Useful for concept albums and classical music."), delegate { GaplessEnabled = GaplessEnabledSchema.Get (); } )); } } private void UninstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } service["general"]["misc"].Remove (replaygain_preference); if (bp_supports_gapless (handle)) { service["general"]["misc"].Remove (gapless_preference); } replaygain_preference = null; gapless_preference = null; } public static readonly SchemaEntry<bool> ReplayGainEnabledSchema = new SchemaEntry<bool> ( "player_engine", "replay_gain_enabled", false, "Enable ReplayGain", "If ReplayGain data is present on tracks when playing, allow volume scaling" ); public static readonly SchemaEntry<bool> GaplessEnabledSchema = new SchemaEntry<bool> ( "player_engine", "gapless_playback_enabled", true, "Enable gapless playback", "Eliminate the small playback gap on track change. Useful for concept albums & classical music." ); #endregion [DllImport ("libbanshee.dll")] private static extern IntPtr bp_new (); [DllImport ("libbanshee.dll")] private static extern bool bp_initialize_pipeline (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_destroy (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_set_eos_callback (HandleRef player, BansheePlayerEosCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_error_callback (HandleRef player, BansheePlayerErrorCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_vis_data_callback (HandleRef player, BansheePlayerVisDataCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_state_changed_callback (HandleRef player, BansheePlayerStateChangedCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_buffering_callback (HandleRef player, BansheePlayerBufferingCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_video_pipeline_setup_callback (HandleRef player, VideoPipelineSetupHandler cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_tag_found_callback (HandleRef player, GstTaggerTagFoundCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_video_prepare_window_callback (HandleRef player, VideoPrepareWindowHandler cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_next_track_starting_callback (HandleRef player, BansheePlayerNextTrackStartingCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_about_to_finish_callback (HandleRef player, BansheePlayerAboutToFinishCallback cb); [DllImport ("libbanshee.dll")] private static extern bool bp_supports_gapless (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_open (HandleRef player, IntPtr uri); [DllImport ("libbanshee.dll")] private static extern void bp_stop (HandleRef player, bool nullstate); [DllImport ("libbanshee.dll")] private static extern void bp_pause (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_play (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_set_next_track (HandleRef player, IntPtr uri); [DllImport ("libbanshee.dll")] private static extern void bp_set_volume (HandleRef player, double volume); [DllImport("libbanshee.dll")] private static extern double bp_get_volume (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_set_volume_changed_callback (HandleRef player, BansheePlayerVolumeChangedCallback cb); [DllImport ("libbanshee.dll")] private static extern bool bp_can_seek (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_audiosink_has_volume (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_set_position (HandleRef player, ulong time_ms); [DllImport ("libbanshee.dll")] private static extern ulong bp_get_position (HandleRef player); [DllImport ("libbanshee.dll")] private static extern ulong bp_get_duration (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_get_pipeline_elements (HandleRef player, out IntPtr playbin, out IntPtr audiobin, out IntPtr audiotee); [DllImport ("libbanshee.dll")] private static extern void bp_set_application_gdk_window (HandleRef player, IntPtr window); [DllImport ("libbanshee.dll")] private static extern VideoDisplayContextType bp_video_get_display_context_type (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_video_set_display_context (HandleRef player, IntPtr displayContext); [DllImport ("libbanshee.dll")] private static extern IntPtr bp_video_get_display_context (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_video_window_expose (HandleRef player, IntPtr displayContext, bool direct); [DllImport ("libbanshee.dll")] private static extern void bp_video_window_realize (HandleRef player, IntPtr window); [DllImport ("libbanshee.dll")] private static extern void bp_get_error_quarks (out uint core, out uint library, out uint resource, out uint stream); [DllImport ("libbanshee.dll")] private static extern bool bp_equalizer_is_supported (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_set_preamp_level (HandleRef player, double level); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_set_gain (HandleRef player, uint bandnum, double gain); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_get_bandrange (HandleRef player, out int min, out int max); [DllImport ("libbanshee.dll")] private static extern uint bp_equalizer_get_nbands (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_get_frequencies (HandleRef player, [MarshalAs (UnmanagedType.LPArray)] out double [] freq); [DllImport ("libbanshee.dll")] private static extern void bp_replaygain_set_enabled (HandleRef player, bool enabled); [DllImport ("libbanshee.dll")] private static extern bool bp_replaygain_get_enabled (HandleRef player); [DllImport ("libbanshee.dll")] private static extern IntPtr clutter_gst_video_sink_new (IntPtr texture); } }
// // Encog(tm) Core v3.3 - .Net Version (unit test) // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.IO; using Encog.App.Analyst.Report; using Encog.App.Analyst.Script; using Encog.App.Analyst.Script.Normalize; using Encog.App.Analyst.Script.Prop; using Encog.App.Analyst.Wizard; using Encog.ML; using Encog.ML.Data; using Encog.Persist; using Encog.Util; using Encog.Util.File; using Encog.Util.Simple; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics; namespace Encog.App.Analyst { public class AnalystTestingUtility { public const int MaxIterations = 100000; public const int MaxCycles = 10; private readonly FileInfo _analystFile; private readonly FileInfo _rawFile; private readonly TempDir _tempDir = new TempDir(); public AnalystTestingUtility(String theBaseDataFile) { _tempDir.ClearContents(); BaseDataFile = theBaseDataFile; _rawFile = _tempDir.CreateFile("test.csv"); FileUtil.CopyResource(theBaseDataFile, _rawFile); _analystFile = _tempDir.CreateFile("test.ega"); EncogAnalyst = new EncogAnalyst(); FileFormat = AnalystFileFormat.DecpntComma; } public String BaseDataFile { get; set; } public EncogAnalyst EncogAnalyst { get; set; } public AnalystFileFormat FileFormat { get; set; } public void Wizard(AnalystGoal goal, WizardMethodType methodType, bool headers) { EncogAnalyst.MaxIteration = MaxIterations; var wiz = new AnalystWizard(EncogAnalyst) {Goal = goal, MethodType = methodType, EvidenceSegements = 3}; wiz.Wizard(_rawFile, headers, FileFormat); EncogAnalyst.Save(_analystFile); EncogAnalyst.Load(_analystFile); } public void Process(double maxError) { int cycles = 0; double e; EncogAnalyst.AddAnalystListener(new ConsoleAnalystListener()); do { EncogAnalyst.ExecuteTask("task-full"); e = CalculateError(); cycles++; Debug.WriteLine(cycles + ": Error = " + e); } while (cycles <= MaxCycles && e > maxError); Assert.IsTrue(cycles <= MaxCycles, "Too many cycles to perform successful train."); } public void Report() { var report = new AnalystReport(EncogAnalyst); report.ProduceReport(_tempDir.CreateFile("report.html")); } public void ValidateDataField( int i, double max, double mean, double min, double sd, String name, bool isClass, bool isComplete, bool isInteger, bool isReal) { DataField df = EncogAnalyst.Script.Fields[i]; Assert.AreEqual(max, df.Max, 0.001); Assert.AreEqual(mean, df.Mean, 0.001); Assert.AreEqual(min, df.Min, 0.001); Assert.AreEqual(sd, df.StandardDeviation, 0.001); Assert.AreEqual(name, df.Name); Assert.AreEqual(isClass, df.Class); Assert.AreEqual(isComplete, df.Complete); Assert.AreEqual(isInteger, df.Integer); Assert.AreEqual(isReal, df.Real); } public void DumpDataField(int i) { DataField df = EncogAnalyst.Script.Fields[i]; Console.Write(Format.FormatDouble(df.Max, 6)); Console.Write(@";"); Console.Write(Format.FormatDouble(df.Mean, 6)); Console.Write(@";"); Console.Write(Format.FormatDouble(df.Min, 6)); Console.Write(@";"); Console.Write(Format.FormatDouble(df.StandardDeviation, 6)); Console.Write(@";"); Console.Write(df.Name); Console.Write(@";"); Console.Write(df.Class ? '1' : '0'); Console.Write(@";"); Console.Write(df.Complete ? '1' : '0'); Console.Write(@";"); Console.Write(df.Integer ? '1' : '0'); Console.Write(@";"); Console.WriteLine(df.Real ? '1' : '0'); } public void ValidateDataClass(int i, params String[] args) { DataField df = EncogAnalyst.Script.Fields[i]; Assert.AreEqual(args.Length, df.ClassMembers.Count); for (int j = 0; j < df.ClassMembers.Count; j++) { Assert.AreEqual(args[j], df.ClassMembers[j].Name); } } /** * Obtain the ML method. * @return The method. */ public IMLMethod ObtainMethod() { ScriptProperties prop = EncogAnalyst.Script.Properties; String resourceID = prop.GetPropertyString( ScriptProperties.MlConfigMachineLearningFile); FileInfo resourceFile = EncogAnalyst.Script.ResolveFilename(resourceID); var method = (IMLMethod) EncogDirectoryPersistence .LoadObject(resourceFile); if (!(method is IMLMethod)) { throw new AnalystError( "The object to be trained must be an instance of MLMethod. " + method.GetType().Name); } return method; } /** * Obtain the training set. * @return The training set. */ private IMLDataSet ObtainTrainingSet() { ScriptProperties prop = EncogAnalyst.Script.Properties; String trainingID = prop.GetPropertyString( ScriptProperties.MlConfigTrainingFile); FileInfo trainingFile = EncogAnalyst.Script.ResolveFilename(trainingID); IMLDataSet trainingSet = EncogUtility.LoadEGB2Memory(trainingFile); return trainingSet; } public void ValidateMethodError(double targetError) { double e = CalculateError(); Assert.IsTrue(e < targetError); } public double CalculateError() { IMLMethod method = ObtainMethod(); IMLDataSet data = ObtainTrainingSet(); return ((IMLError) method).CalculateError(data); } public void DumpAnalystField(int i) { AnalystField af = EncogAnalyst.Script.Normalize.NormalizedFields[i]; Console.Write(Format.FormatDouble(af.ActualHigh, 6)); Console.Write(@";"); Console.Write(Format.FormatDouble(af.ActualLow, 6)); Console.Write(@";"); Console.Write(Format.FormatDouble(af.NormalizedHigh, 6)); Console.Write(@";"); Console.Write(Format.FormatDouble(af.NormalizedLow, 6)); Console.Write(@";"); Console.Write(af.Name); Console.Write(@";"); Console.Write(af.TimeSlice); Console.Write(@";"); Console.WriteLine(af.Action.ToString()); } public void ValidateAnalystField(int i, double high, double low, double normHigh, double normLow, String name, int timeSlice, String action) { AnalystField af = EncogAnalyst.Script.Normalize.NormalizedFields[i]; Assert.AreEqual(high, af.ActualHigh, 0.001); Assert.AreEqual(low, af.ActualLow, 0.001); Assert.AreEqual(normHigh, af.NormalizedHigh, 0.001); Assert.AreEqual(normLow, af.NormalizedLow, 0.001); Assert.AreEqual(name, af.Name); Assert.AreEqual(timeSlice, af.TimeSlice); Assert.AreEqual(action, af.Action.ToString()); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace CC.MT.Public.Sheriff.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.IMAP.Server { #region usings using System; using System.Globalization; using MIME; #endregion /// <summary> /// Provides utility methods for IMAP. /// </summary> public class IMAP_Utils { #region Methods /// <summary> /// Parses message flags from string. /// </summary> /// <param name="flagsString">Message flags string.</param> /// <returns></returns> public static IMAP_MessageFlags ParseMessageFlags(string flagsString) { IMAP_MessageFlags mFlags = 0; flagsString = flagsString.ToUpper(); if (flagsString.IndexOf("ANSWERED") > -1) { mFlags |= IMAP_MessageFlags.Answered; } if (flagsString.IndexOf("FLAGGED") > -1) { mFlags |= IMAP_MessageFlags.Flagged; } if (flagsString.IndexOf("DELETED") > -1) { mFlags |= IMAP_MessageFlags.Deleted; } if (flagsString.IndexOf("SEEN") > -1) { mFlags |= IMAP_MessageFlags.Seen; } if (flagsString.IndexOf("DRAFT") > -1) { mFlags |= IMAP_MessageFlags.Draft; } return mFlags; } /// <summary> /// Converts message flags to string. Eg. \SEEN \DELETED . /// </summary> /// <returns></returns> public static string MessageFlagsToString(IMAP_MessageFlags msgFlags) { string retVal = ""; if (((int) IMAP_MessageFlags.Answered & (int) msgFlags) != 0) { retVal += " \\ANSWERED"; } if (((int) IMAP_MessageFlags.Flagged & (int) msgFlags) != 0) { retVal += " \\FLAGGED"; } if (((int) IMAP_MessageFlags.Deleted & (int) msgFlags) != 0) { retVal += " \\DELETED"; } if (((int) IMAP_MessageFlags.Seen & (int) msgFlags) != 0) { retVal += " \\SEEN"; } if (((int) IMAP_MessageFlags.Draft & (int) msgFlags) != 0) { retVal += " \\DRAFT"; } return retVal.Trim(); } /// <summary> /// Converts IMAP_ACL_Flags to string. /// </summary> /// <param name="flags">Flags to convert.</param> /// <returns></returns> public static string ACL_to_String(IMAP_ACL_Flags flags) { string retVal = ""; if ((flags & IMAP_ACL_Flags.l) != 0) { retVal += "l"; } if ((flags & IMAP_ACL_Flags.r) != 0) { retVal += "r"; } if ((flags & IMAP_ACL_Flags.s) != 0) { retVal += "s"; } if ((flags & IMAP_ACL_Flags.w) != 0) { retVal += "w"; } if ((flags & IMAP_ACL_Flags.i) != 0) { retVal += "i"; } if ((flags & IMAP_ACL_Flags.p) != 0) { retVal += "p"; } if ((flags & IMAP_ACL_Flags.c) != 0) { retVal += "c"; } if ((flags & IMAP_ACL_Flags.d) != 0) { retVal += "d"; } if ((flags & IMAP_ACL_Flags.a) != 0) { retVal += "a"; } return retVal; } /// <summary> /// Parses IMAP_ACL_Flags from string. /// </summary> /// <param name="aclString">String from where to convert</param> /// <returns></returns> public static IMAP_ACL_Flags ACL_From_String(string aclString) { IMAP_ACL_Flags retVal = IMAP_ACL_Flags.None; aclString = aclString.ToLower(); if (aclString.IndexOf('l') > -1) { retVal |= IMAP_ACL_Flags.l; } if (aclString.IndexOf('r') > -1) { retVal |= IMAP_ACL_Flags.r; } if (aclString.IndexOf('s') > -1) { retVal |= IMAP_ACL_Flags.s; } if (aclString.IndexOf('w') > -1) { retVal |= IMAP_ACL_Flags.w; } if (aclString.IndexOf('i') > -1) { retVal |= IMAP_ACL_Flags.i; } if (aclString.IndexOf('p') > -1) { retVal |= IMAP_ACL_Flags.p; } if (aclString.IndexOf('c') > -1) { retVal |= IMAP_ACL_Flags.c; } if (aclString.IndexOf('d') > -1) { retVal |= IMAP_ACL_Flags.d; } if (aclString.IndexOf('a') > -1) { retVal |= IMAP_ACL_Flags.a; } return retVal; } /// <summary> /// Parses IMAP date time from string. /// </summary> /// <param name="date">DateTime string.</param> /// <returns>Returns parsed date-time value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>date</b> is null reference.</exception> public static DateTime ParseDate(string date) { if (date == null) { throw new ArgumentNullException("date"); } return MIME_Utils.ParseRfc2822DateTime(date); } /// <summary> /// Converts date time to IMAP date time string. /// </summary> /// <param name="date">DateTime to convert.</param> /// <returns></returns> public static string DateTimeToString(DateTime date) { string retVal = ""; retVal += date.ToString("dd-MMM-yyyy HH:mm:ss", CultureInfo.InvariantCulture); retVal += " " + date.ToString("zzz", CultureInfo.InvariantCulture).Replace(":", ""); return retVal; } /// <summary> /// Normalizes folder path. Example: /Inbox/SubFolder/ will be Inbox/SubFolder. /// </summary> /// <param name="folder">Folder path to normalize.</param> /// <returns>Returns normalized folder path.</returns> public static string NormalizeFolder(string folder) { folder = folder.Replace("\\", "/"); if (folder.StartsWith("/")) { folder = folder.Substring(1); } if (folder.EndsWith("/")) { folder = folder.Substring(0, folder.Length - 1); } return folder; } /// <summary> /// Parses [quoted] parameter from args text. Parameter may be not quoted, then parameter is /// terminated by SP. Example: argsText="string gdkga agkgs";argsText=stringValue 10. /// /// This method also removes parsed parameter from argsText. /// </summary> /// <param name="argsText">Arguments line from where to parse param.</param> /// <returns></returns> public static string ParseQuotedParam(ref string argsText) { string paramValue = ""; // Get value, it is between "" if (argsText.StartsWith("\"")) { // Find next " not escaped " char lastChar = ' '; int qIndex = -1; for (int i = 1; i < argsText.Length; i++) { if (argsText[i] == '\"' && lastChar != '\\') { qIndex = i; break; } lastChar = argsText[i]; } if (qIndex == -1) { throw new Exception("qouted-string doesn't have enclosing quote(\")"); } paramValue = argsText.Substring(1, qIndex - 1).Replace("\\\"", "\""); // Remove <string> value from argsText argsText = argsText.Substring(qIndex + 1).Trim(); } else { paramValue = argsText.Split(' ')[0]; // Remove <string> value from argsText argsText = argsText.Substring(paramValue.Length).Trim(); } return paramValue; } /// <summary> /// Parses bracket parameter from args text. Parameter may be not between (), then /// then args text is considered as value. Example: (test test);test test. /// /// This method also removes parsed parameter from argsText. /// </summary> /// <param name="argsText"></param> /// <returns></returns> public static string ParseBracketParam(ref string argsText) { string paramValue = ""; if (argsText.StartsWith("(")) { // Find matching ) char lastChar = ' '; int bIndex = -1; int nestedBracketCount = 0; for (int i = 1; i < argsText.Length; i++) { // There is nested () if (argsText[i] == '(') { nestedBracketCount++; } else if (argsText[i] == ')') { if (nestedBracketCount == 0) { bIndex = i; break; } // This was nested bracket ) else { nestedBracketCount--; } } lastChar = argsText[i]; } if (bIndex == -1) { throw new Exception("bracket doesn't have enclosing bracket ')'"); } paramValue = argsText.Substring(1, bIndex - 1); // Remove <string> value from argsText argsText = argsText.Substring(bIndex + 1).Trim(); } else { paramValue = argsText; argsText = ""; } return paramValue; } #endregion } }
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay // //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. /** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections.Generic; using System.Text; using Thrift.Protocol; namespace Netfox.SnooperMessenger.Protocol { #if !SILVERLIGHT [Serializable] #endif public partial class MNMessagesSyncClientPayload : TBase { private List<MNMessagesSyncDeltaWrapper> _Deltas; private long _FirstDeltaSeqId; private long _LastIssuedSeqId; private long _QueueEntityId; private MNMessagesSyncFailedSend _FailedSend; private string _SyncToken; private string _ErrorCode; public List<MNMessagesSyncDeltaWrapper> Deltas { get { return _Deltas; } set { __isset.Deltas = true; this._Deltas = value; } } public long FirstDeltaSeqId { get { return _FirstDeltaSeqId; } set { __isset.FirstDeltaSeqId = true; this._FirstDeltaSeqId = value; } } public long LastIssuedSeqId { get { return _LastIssuedSeqId; } set { __isset.LastIssuedSeqId = true; this._LastIssuedSeqId = value; } } public long QueueEntityId { get { return _QueueEntityId; } set { __isset.QueueEntityId = true; this._QueueEntityId = value; } } public MNMessagesSyncFailedSend FailedSend { get { return _FailedSend; } set { __isset.FailedSend = true; this._FailedSend = value; } } public string SyncToken { get { return _SyncToken; } set { __isset.SyncToken = true; this._SyncToken = value; } } public string ErrorCode { get { return _ErrorCode; } set { __isset.ErrorCode = true; this._ErrorCode = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool Deltas; public bool FirstDeltaSeqId; public bool LastIssuedSeqId; public bool QueueEntityId; public bool FailedSend; public bool SyncToken; public bool ErrorCode; } public MNMessagesSyncClientPayload() { } public void Read (TProtocol iprot) { iprot.IncrementRecursionDepth(); try { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.List) { { Deltas = new List<MNMessagesSyncDeltaWrapper>(); TList _list120 = iprot.ReadListBegin(); for( int _i121 = 0; _i121 < _list120.Count; ++_i121) { MNMessagesSyncDeltaWrapper _elem122; _elem122 = new MNMessagesSyncDeltaWrapper(); _elem122.Read(iprot); Deltas.Add(_elem122); } iprot.ReadListEnd(); } } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.I64) { FirstDeltaSeqId = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 3: if (field.Type == TType.I64) { LastIssuedSeqId = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 4: if (field.Type == TType.I64) { QueueEntityId = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 5: if (field.Type == TType.Struct) { FailedSend = new MNMessagesSyncFailedSend(); FailedSend.Read(iprot); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 6: if (field.Type == TType.String) { SyncToken = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 7: if (field.Type == TType.String) { ErrorCode = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } finally { iprot.DecrementRecursionDepth(); } } public void Write(TProtocol oprot) { oprot.IncrementRecursionDepth(); try { TStruct struc = new TStruct("MNMessagesSyncClientPayload"); oprot.WriteStructBegin(struc); TField field = new TField(); if (Deltas != null && __isset.Deltas) { field.Name = "Deltas"; field.Type = TType.List; field.ID = 1; oprot.WriteFieldBegin(field); { oprot.WriteListBegin(new TList(TType.Struct, Deltas.Count)); foreach (MNMessagesSyncDeltaWrapper _iter123 in Deltas) { _iter123.Write(oprot); } oprot.WriteListEnd(); } oprot.WriteFieldEnd(); } if (__isset.FirstDeltaSeqId) { field.Name = "FirstDeltaSeqId"; field.Type = TType.I64; field.ID = 2; oprot.WriteFieldBegin(field); oprot.WriteI64(FirstDeltaSeqId); oprot.WriteFieldEnd(); } if (__isset.LastIssuedSeqId) { field.Name = "LastIssuedSeqId"; field.Type = TType.I64; field.ID = 3; oprot.WriteFieldBegin(field); oprot.WriteI64(LastIssuedSeqId); oprot.WriteFieldEnd(); } if (__isset.QueueEntityId) { field.Name = "QueueEntityId"; field.Type = TType.I64; field.ID = 4; oprot.WriteFieldBegin(field); oprot.WriteI64(QueueEntityId); oprot.WriteFieldEnd(); } if (FailedSend != null && __isset.FailedSend) { field.Name = "FailedSend"; field.Type = TType.Struct; field.ID = 5; oprot.WriteFieldBegin(field); FailedSend.Write(oprot); oprot.WriteFieldEnd(); } if (SyncToken != null && __isset.SyncToken) { field.Name = "SyncToken"; field.Type = TType.String; field.ID = 6; oprot.WriteFieldBegin(field); oprot.WriteString(SyncToken); oprot.WriteFieldEnd(); } if (ErrorCode != null && __isset.ErrorCode) { field.Name = "ErrorCode"; field.Type = TType.String; field.ID = 7; oprot.WriteFieldBegin(field); oprot.WriteString(ErrorCode); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } finally { oprot.DecrementRecursionDepth(); } } public override string ToString() { StringBuilder __sb = new StringBuilder("MNMessagesSyncClientPayload("); bool __first = true; if (Deltas != null && __isset.Deltas) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Deltas: "); __sb.Append(Deltas); } if (__isset.FirstDeltaSeqId) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("FirstDeltaSeqId: "); __sb.Append(FirstDeltaSeqId); } if (__isset.LastIssuedSeqId) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("LastIssuedSeqId: "); __sb.Append(LastIssuedSeqId); } if (__isset.QueueEntityId) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("QueueEntityId: "); __sb.Append(QueueEntityId); } if (FailedSend != null && __isset.FailedSend) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("FailedSend: "); __sb.Append(FailedSend== null ? "<null>" : FailedSend.ToString()); } if (SyncToken != null && __isset.SyncToken) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("SyncToken: "); __sb.Append(SyncToken); } if (ErrorCode != null && __isset.ErrorCode) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("ErrorCode: "); __sb.Append(ErrorCode); } __sb.Append(")"); return __sb.ToString(); } } }
using System; using System.Net; using System.Security.Authentication; using System.Text; using Newtonsoft.Json.Linq; using RedditSharp.Things; namespace RedditSharp { public class AuthProvider { private const string AccessUrl = "https://ssl.reddit.com/api/v1/access_token"; private const string OauthGetMeUrl = "https://oauth.reddit.com/api/v1/me"; private const string RevokeUrl = "https://www.reddit.com/api/v1/revoke_token"; public static string OAuthToken { get; set; } public static string RefreshToken { get; set; } [Flags] public enum Scope { none = 0x0, identity = 0x1, edit = 0x2, flair = 0x4, history = 0x8, modconfig = 0x10, modflair = 0x20, modlog = 0x40, modposts = 0x80, modwiki = 0x100, mysubreddits = 0x200, privatemessages = 0x400, read = 0x800, report = 0x1000, save = 0x2000, submit = 0x4000, subscribe = 0x8000, vote = 0x10000, wikiedit = 0x20000, wikiread = 0x40000 } private IWebAgent _webAgent; private readonly string _redirectUri; private readonly string _clientId; private readonly string _clientSecret; /// <summary> /// Allows use of reddit's OAuth interface, using an app set up at https://ssl.reddit.com/prefs/apps/. /// </summary> /// <param name="clientId">Granted by reddit as part of app.</param> /// <param name="clientSecret">Granted by reddit as part of app.</param> /// <param name="redirectUri">Selected as part of app. Reddit will send users back here.</param> public AuthProvider(string clientId, string clientSecret, string redirectUri) { _clientId = clientId; _clientSecret = clientSecret; _redirectUri = redirectUri; _webAgent = new WebAgent(); } /// <summary> /// Allows use of reddit's OAuth interface, using an app set up at https://ssl.reddit.com/prefs/apps/. /// </summary> /// <param name="clientId">Granted by reddit as part of app.</param> /// <param name="clientSecret">Granted by reddit as part of app.</param> /// <param name="redirectUri">Selected as part of app. Reddit will send users back here.</param> /// <param name="agent">Implementation of IWebAgent to use to make requests.</param> public AuthProvider(string clientId, string clientSecret, string redirectUri,IWebAgent agent) { _clientId = clientId; _clientSecret = clientSecret; _redirectUri = redirectUri; _webAgent = agent; } /// <summary> /// Creates the reddit OAuth2 Url to redirect the user to for authorization. /// </summary> /// <param name="state">Used to verify that the user received is the user that was sent</param> /// <param name="scope">Determines what actions can be performed against the user.</param> /// <param name="permanent">Set to true for access lasting longer than one hour.</param> /// <returns></returns> public string GetAuthUrl(string state, Scope scope, bool permanent = false) { return String.Format("https://ssl.reddit.com/api/v1/authorize?client_id={0}&response_type=code&state={1}&redirect_uri={2}&duration={3}&scope={4}", _clientId, state, _redirectUri, permanent ? "permanent" : "temporary", scope.ToString().Replace(" ","")); } /// <summary> /// Gets the OAuth token for the user associated with the provided code. /// </summary> /// <param name="code">Sent by reddit as a parameter in the return uri.</param> /// <param name="isRefresh">Set to true for refresh requests.</param> /// <returns></returns> public string GetOAuthToken(string code, bool isRefresh = false) { if (Type.GetType("Mono.Runtime") != null) ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true; _webAgent.Cookies = new CookieContainer(); var request = _webAgent.CreatePost(AccessUrl); request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(_clientId + ":" + _clientSecret)); var stream = request.GetRequestStream(); if (isRefresh) { _webAgent.WritePostBody(stream, new { grant_type = "refresh_token", refresh_token = code }); } else { _webAgent.WritePostBody(stream, new { grant_type = "authorization_code", code, redirect_uri = _redirectUri }); } stream.Close(); var json = _webAgent.ExecuteRequest(request); if (json["access_token"] != null) { if (json["refresh_token"] != null) RefreshToken = json["refresh_token"].ToString(); OAuthToken = json["access_token"].ToString(); return json["access_token"].ToString(); } throw new AuthenticationException("Could not log in."); } /// <summary> /// Gets the OAuth token for the user. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The user's password.</param> /// <returns>The access token</returns> public string GetOAuthToken(string username, string password) { if (Type.GetType("Mono.Runtime") != null) ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true; _webAgent.Cookies = new CookieContainer(); var request = _webAgent.CreatePost(AccessUrl); request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(_clientId + ":" + _clientSecret)); var stream = request.GetRequestStream(); _webAgent.WritePostBody(stream, new { grant_type = "password", username, password, redirect_uri = _redirectUri }); stream.Close(); var json = _webAgent.ExecuteRequest(request); if (json["access_token"] != null) { if (json["refresh_token"] != null) RefreshToken = json["refresh_token"].ToString(); OAuthToken = json["access_token"].ToString(); return json["access_token"].ToString(); } throw new AuthenticationException("Could not log in."); } public void RevokeToken(string token, bool isRefresh) { string tokenType = isRefresh ? "refresh_token" : "access_token"; var request = _webAgent.CreatePost(RevokeUrl); request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(_clientId + ":" + _clientSecret)); var stream = request.GetRequestStream(); _webAgent.WritePostBody(stream, new { token = token, token_type = tokenType }); stream.Close(); _webAgent.ExecuteRequest(request); } /// <summary> /// Gets a user authenticated by OAuth2. /// </summary> /// <param name="accessToken">Obtained using GetOAuthToken</param> /// <returns></returns> [Obsolete("Reddit.InitOrUpdateUser is preferred")] public AuthenticatedUser GetUser(string accessToken) { var request = _webAgent.CreateGet(OauthGetMeUrl); request.Headers["Authorization"] = String.Format("bearer {0}", accessToken); var response = (HttpWebResponse)request.GetResponse(); var result = _webAgent.GetResponseString(response.GetResponseStream()); var thingjson = "{\"kind\": \"t2\", \"data\": " + result + "}"; var json = JObject.Parse(thingjson); return new AuthenticatedUser().Init(new Reddit(), json, _webAgent); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Numerics; using System.Security.Cryptography; using System.Threading; using Debug = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// This class implements get-random cmdlet. /// </summary> /// <!-- author: LukaszA --> [Cmdlet(VerbsCommon.Get, "Random", DefaultParameterSetName = GetRandomCommand.RandomNumberParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097016", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(int), typeof(long), typeof(double))] public class GetRandomCommand : PSCmdlet { #region Parameter set handling private const string RandomNumberParameterSet = "RandomNumberParameterSet"; private const string RandomListItemParameterSet = "RandomListItemParameterSet"; private const string ShuffleParameterSet = "ShuffleParameterSet"; private static readonly object[] _nullInArray = new object[] { null }; private enum MyParameterSet { Unknown, RandomNumber, RandomListItem } private MyParameterSet _effectiveParameterSet; private MyParameterSet EffectiveParameterSet { get { // cache MyParameterSet enum instead of doing string comparison every time if (_effectiveParameterSet == MyParameterSet.Unknown) { if ((MyInvocation.ExpectingInput) && (Maximum == null) && (Minimum == null)) { _effectiveParameterSet = MyParameterSet.RandomListItem; } else if (ParameterSetName == GetRandomCommand.RandomListItemParameterSet || ParameterSetName == GetRandomCommand.ShuffleParameterSet) { _effectiveParameterSet = MyParameterSet.RandomListItem; } else if (ParameterSetName.Equals(GetRandomCommand.RandomNumberParameterSet, StringComparison.OrdinalIgnoreCase)) { if ((Maximum != null) && (Maximum.GetType().IsArray)) { InputObject = (object[])Maximum; _effectiveParameterSet = MyParameterSet.RandomListItem; } else { _effectiveParameterSet = MyParameterSet.RandomNumber; } } else { Debug.Assert(false, "Unrecognized parameter set"); } } return _effectiveParameterSet; } } #endregion Parameter set handling #region Error handling private void ThrowMinGreaterThanOrEqualMax(object minValue, object maxValue) { if (minValue == null) { throw PSTraceSource.NewArgumentNullException("min"); } if (maxValue == null) { throw PSTraceSource.NewArgumentNullException("max"); } ErrorRecord errorRecord = new( new ArgumentException(string.Format( CultureInfo.InvariantCulture, GetRandomCommandStrings.MinGreaterThanOrEqualMax, minValue, maxValue)), "MinGreaterThanOrEqualMax", ErrorCategory.InvalidArgument, null); ThrowTerminatingError(errorRecord); } #endregion #region Random generator state private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new(); // 1-to-1 mapping of runspaces and random number generators private static readonly Dictionary<Guid, PolymorphicRandomNumberGenerator> s_runspaceGeneratorMap = new(); private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { switch (e.RunspaceStateInfo.State) { case RunspaceState.Broken: case RunspaceState.Closed: try { GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock(); GetRandomCommand.s_runspaceGeneratorMap.Remove(((Runspace)sender).InstanceId); } finally { GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); } break; } } private PolymorphicRandomNumberGenerator _generator; /// <summary> /// Gets and sets generator associated with the current runspace. /// </summary> private PolymorphicRandomNumberGenerator Generator { get { if (_generator == null) { Guid runspaceId = Context.CurrentRunspace.InstanceId; bool needToInitialize = false; try { GetRandomCommand.s_runspaceGeneratorMapLock.EnterReadLock(); needToInitialize = !GetRandomCommand.s_runspaceGeneratorMap.TryGetValue(runspaceId, out _generator); } finally { GetRandomCommand.s_runspaceGeneratorMapLock.ExitReadLock(); } if (needToInitialize) { Generator = new PolymorphicRandomNumberGenerator(); } } return _generator; } set { _generator = value; Runspace myRunspace = Context.CurrentRunspace; try { GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock(); if (!GetRandomCommand.s_runspaceGeneratorMap.ContainsKey(myRunspace.InstanceId)) { // make sure we won't leave the generator around after runspace exits myRunspace.StateChanged += CurrentRunspace_StateChanged; } GetRandomCommand.s_runspaceGeneratorMap[myRunspace.InstanceId] = _generator; } finally { GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); } } } #endregion #region Common parameters /// <summary> /// Seed used to reinitialize random numbers generator. /// </summary> [Parameter] [ValidateNotNull] public int? SetSeed { get; set; } #endregion Common parameters #region Parameters for RandomNumberParameterSet /// <summary> /// Maximum number to generate. /// </summary> [Parameter(ParameterSetName = RandomNumberParameterSet, Position = 0)] public object Maximum { get; set; } /// <summary> /// Minimum number to generate. /// </summary> [Parameter(ParameterSetName = RandomNumberParameterSet)] public object Minimum { get; set; } private static bool IsInt(object o) { if (o == null || o is int) { return true; } return false; } private static bool IsInt64(object o) { if (o == null || o is long) { return true; } return false; } private static object ProcessOperand(object o) { if (o == null) { return null; } PSObject pso = PSObject.AsPSObject(o); object baseObject = pso.BaseObject; if (baseObject is string) { // The type argument passed in does not decide the number type we want to convert to. ScanNumber will return // int/long/double based on the string form number passed in. baseObject = System.Management.Automation.Language.Parser.ScanNumber((string)baseObject, typeof(int)); } return baseObject; } private static double ConvertToDouble(object o, double defaultIfNull) { if (o == null) { return defaultIfNull; } double result = (double)LanguagePrimitives.ConvertTo(o, typeof(double), CultureInfo.InvariantCulture); return result; } #endregion #region Parameters and variables for RandomListItemParameterSet private List<object> _chosenListItems; private int _numberOfProcessedListItems; /// <summary> /// List from which random elements are chosen. /// </summary> [Parameter(ParameterSetName = RandomListItemParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] [Parameter(ParameterSetName = ShuffleParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] [System.Management.Automation.AllowNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] InputObject { get; set; } /// <summary> /// Number of items to output (number of list items or of numbers). /// </summary> [Parameter(ParameterSetName = RandomNumberParameterSet)] [Parameter(ParameterSetName = RandomListItemParameterSet)] [ValidateRange(1, int.MaxValue)] public int Count { get; set; } = 1; #endregion #region Shuffle parameter /// <summary> /// Gets or sets whether the command should return all input objects in randomized order. /// </summary> [Parameter(ParameterSetName = ShuffleParameterSet, Mandatory = true)] public SwitchParameter Shuffle { get; set; } #endregion #region Cmdlet processing methods private double GetRandomDouble(double minValue, double maxValue) { double randomNumber; double diff = maxValue - minValue; // I couldn't find a better fix for bug #216893 then // to test and retry if a random number falls outside the bounds // because of floating-point-arithmetic inaccuracies. // // Performance in the normal case is not impacted much. // In low-precision situations we should converge to a solution quickly // (diff gets smaller at a quick pace). if (double.IsInfinity(diff)) { do { double r = Generator.NextDouble(); randomNumber = minValue + r * maxValue - r * minValue; } while (randomNumber >= maxValue); } else { do { double r = Generator.NextDouble(); randomNumber = minValue + r * diff; diff *= r; } while (randomNumber >= maxValue); } return randomNumber; } /// <summary> /// Get a random Int64 type number. /// </summary> /// <param name="minValue"></param> /// <param name="maxValue"></param> /// <returns></returns> private long GetRandomInt64(long minValue, long maxValue) { // Randomly generate eight bytes and convert the byte array to UInt64 var buffer = new byte[sizeof(ulong)]; ulong randomUint64; BigInteger bigIntegerDiff = (BigInteger)maxValue - (BigInteger)minValue; // When the difference is less than int.MaxValue, use Random.Next(int, int) if (bigIntegerDiff <= int.MaxValue) { int randomDiff = Generator.Next(0, (int)(maxValue - minValue)); return minValue + randomDiff; } // The difference of two Int64 numbers would not exceed UInt64.MaxValue, so it can be represented by a UInt64 number. ulong uint64Diff = (ulong)bigIntegerDiff; // Calculate the number of bits to represent the diff in type UInt64 int bitsToRepresentDiff = 0; ulong diffCopy = uint64Diff; for (; diffCopy != 0; bitsToRepresentDiff++) { diffCopy >>= 1; } // Get the mask for the number of bits ulong mask = (0xffffffffffffffff >> (64 - bitsToRepresentDiff)); do { // Randomly fill the buffer Generator.NextBytes(buffer); randomUint64 = BitConverter.ToUInt64(buffer, 0); // Get the last 'bitsToRepresentDiff' number of random bits randomUint64 &= mask; } while (uint64Diff <= randomUint64); double randomNumber = minValue * 1.0 + randomUint64 * 1.0; return (long)randomNumber; } /// <summary> /// This method implements the BeginProcessing method for get-random command. /// </summary> protected override void BeginProcessing() { if (SetSeed.HasValue) { Generator = new PolymorphicRandomNumberGenerator(SetSeed.Value); } if (EffectiveParameterSet == MyParameterSet.RandomNumber) { object maxOperand = ProcessOperand(Maximum); object minOperand = ProcessOperand(Minimum); if (IsInt(maxOperand) && IsInt(minOperand)) { int minValue = minOperand != null ? (int)minOperand : 0; int maxValue = maxOperand != null ? (int)maxOperand : int.MaxValue; if (minValue >= maxValue) { ThrowMinGreaterThanOrEqualMax(minValue, maxValue); } for (int i = 0; i < Count; i++) { int randomNumber = Generator.Next(minValue, maxValue); Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); Debug.Assert(randomNumber < maxValue, "random number < upper bound"); WriteObject(randomNumber); } } else if ((IsInt64(maxOperand) || IsInt(maxOperand)) && (IsInt64(minOperand) || IsInt(minOperand))) { long minValue = minOperand != null ? ((minOperand is long) ? (long)minOperand : (int)minOperand) : 0; long maxValue = maxOperand != null ? ((maxOperand is long) ? (long)maxOperand : (int)maxOperand) : long.MaxValue; if (minValue >= maxValue) { ThrowMinGreaterThanOrEqualMax(minValue, maxValue); } for (int i = 0; i < Count; i++) { long randomNumber = GetRandomInt64(minValue, maxValue); Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); Debug.Assert(randomNumber < maxValue, "random number < upper bound"); WriteObject(randomNumber); } } else { double minValue = (minOperand is double) ? (double)minOperand : ConvertToDouble(Minimum, 0.0); double maxValue = (maxOperand is double) ? (double)maxOperand : ConvertToDouble(Maximum, double.MaxValue); if (minValue >= maxValue) { ThrowMinGreaterThanOrEqualMax(minValue, maxValue); } for (int i = 0; i < Count; i++) { double randomNumber = GetRandomDouble(minValue, maxValue); Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); Debug.Assert(randomNumber < maxValue, "random number < upper bound"); WriteObject(randomNumber); } } } else if (EffectiveParameterSet == MyParameterSet.RandomListItem) { _chosenListItems = new List<object>(); _numberOfProcessedListItems = 0; } } // rough proof that when choosing random K items out of N items // each item has got K/N probability of being included in the final list // // probability that a particular item in chosenListItems is NOT going to be replaced // when processing I-th input item [assumes I > K]: // P_one_step(I) = 1 - ((K / I) * ((K - 1) / K) + ((I - K) / I) = (I - 1) / I // <--A--> <-----B-----> <-----C-----> // A - probability that I-th element is going to be replacing an element from chosenListItems // (see (1) in the code below) // B - probability that a particular element from chosenListItems is NOT going to be replaced // (see (2) in the code below) // C - probability that I-th element is NOT going to be replacing an element from chosenListItems // (see (1) in the code below) // // probability that a particular item in chosenListItems is NOT going to be replaced // when processing input items J through N [assumes J > K] // P_removal(J) = Multiply(for I = J to N) P(I) = // = ((J - 1) / J) * (J / (J + 1)) * ... * ((N - 2) / (N - 1)) * ((N - 1) / N) = // = (J - 1) / N // // probability that when processing an element it is going to be put into chosenListItems // P_insertion(I) = 1.0 when I <= K - see (3) in the code below // P_insertion(I) = K/N otherwise - see (1) in the code below // // probability that a given element is going to be a part of the final list // P_final(I) = P_insertion(I) * P_removal(max(I + 1, K + 1)) // [for I <= K] = 1.0 * ((K + 1) - 1) / N = K / N // [otherwise] = (K / I) * ((I + 1) - 1) / N = K / N // // which proves that P_final(I) = K / N for all values of I. QED. /// <summary> /// This method implements the ProcessRecord method for get-random command. /// </summary> protected override void ProcessRecord() { if (EffectiveParameterSet == MyParameterSet.RandomListItem) { if (ParameterSetName == ShuffleParameterSet) { // this allows for $null to be in an array passed to InputObject foreach (object item in InputObject ?? _nullInArray) { _chosenListItems.Add(item); } } else { foreach (object item in InputObject ?? _nullInArray) { // (3) if (_numberOfProcessedListItems < Count) { Debug.Assert(_chosenListItems.Count == _numberOfProcessedListItems, "Initial K elements should all be included in chosenListItems"); _chosenListItems.Add(item); } else { Debug.Assert(_chosenListItems.Count == Count, "After processing K initial elements, the length of chosenItems should stay equal to K"); // (1) if (Generator.Next(_numberOfProcessedListItems + 1) < Count) { // (2) int indexToReplace = Generator.Next(_chosenListItems.Count); _chosenListItems[indexToReplace] = item; } } _numberOfProcessedListItems++; } } } } /// <summary> /// This method implements the EndProcessing method for get-random command. /// </summary> protected override void EndProcessing() { if (EffectiveParameterSet == MyParameterSet.RandomListItem) { // make sure the order is truly random // (all permutations with the same probability) // O(n) time int n = _chosenListItems.Count; for (int i = 0; i < n; i++) { // randomly choose j from [i...n) int j = Generator.Next(i, n); WriteObject(_chosenListItems[j]); // remove the output object from consideration in the next iteration. if (i != j) { _chosenListItems[j] = _chosenListItems[i]; } } } } #endregion Processing methods } /// <summary> /// Provides an adapter API for random numbers that may be either cryptographically random, or /// generated with the regular pseudo-random number generator. Re-implementations of /// methods using the NextBytes() primitive based on the CLR implementation: /// https://referencesource.microsoft.com/#mscorlib/system/random.cs. /// </summary> internal class PolymorphicRandomNumberGenerator { /// <summary> /// Initializes a new instance of the <see cref="PolymorphicRandomNumberGenerator"/> class. /// </summary> public PolymorphicRandomNumberGenerator() { _cryptographicGenerator = RandomNumberGenerator.Create(); _pseudoGenerator = null; } internal PolymorphicRandomNumberGenerator(int seed) { _cryptographicGenerator = null; _pseudoGenerator = new Random(seed); } private readonly Random _pseudoGenerator = null; private readonly RandomNumberGenerator _cryptographicGenerator = null; /// <summary> /// Generates a random floating-point number that is greater than or equal to 0.0, and less than 1.0. /// </summary> /// <returns>A random floating-point number that is greater than or equal to 0.0, and less than 1.0.</returns> internal double NextDouble() { // According to the CLR source: // "Including this division at the end gives us significantly improved random number distribution." return Next() * (1.0 / int.MaxValue); } /// <summary> /// Generates a non-negative random integer. /// </summary> /// <returns>A non-negative random integer.</returns> internal int Next() { int randomNumber; // The CLR implementation just fudges // Int32.MaxValue down to (Int32.MaxValue - 1). This implementation // errs on the side of correctness. do { randomNumber = InternalSample(); } while (randomNumber == int.MaxValue); if (randomNumber < 0) { randomNumber += int.MaxValue; } return randomNumber; } /// <summary> /// Returns a random integer that is within a specified range. /// </summary> /// <param name="maxValue">The exclusive upper bound of the random number returned.</param> /// <returns></returns> internal int Next(int maxValue) { if (maxValue < 0) { throw new ArgumentOutOfRangeException(nameof(maxValue), GetRandomCommandStrings.MaxMustBeGreaterThanZeroApi); } return Next(0, maxValue); } /// <summary> /// Returns a random integer that is within a specified range. /// </summary> /// <param name="minValue">The inclusive lower bound of the random number returned.</param> /// <param name="maxValue">The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.</param> /// <returns></returns> public int Next(int minValue, int maxValue) { if (minValue > maxValue) { throw new ArgumentOutOfRangeException(nameof(minValue), GetRandomCommandStrings.MinGreaterThanOrEqualMaxApi); } int randomNumber = 0; long range = (long)maxValue - (long)minValue; if (range <= int.MaxValue) { randomNumber = ((int)(NextDouble() * range) + minValue); } else { double largeSample = InternalSampleLargeRange() * (1.0 / (2 * ((uint)int.MaxValue))); randomNumber = (int)((long)(largeSample * range) + minValue); } return randomNumber; } /// <summary> /// Fills the elements of a specified array of bytes with random numbers. /// </summary> /// <param name="buffer">The array to be filled.</param> internal void NextBytes(byte[] buffer) { if (_cryptographicGenerator != null) { _cryptographicGenerator.GetBytes(buffer); } else { _pseudoGenerator.NextBytes(buffer); } } /// <summary> /// Samples a random integer. /// </summary> /// <returns>A random integer, using the full range of Int32.</returns> private int InternalSample() { int randomNumber; byte[] data = new byte[sizeof(int)]; NextBytes(data); randomNumber = BitConverter.ToInt32(data, 0); return randomNumber; } /// <summary> /// Samples a random int when the range is large. This does /// not need to be in the range of -Double.MaxValue .. Double.MaxValue, /// just 0.. (2 * Int32.MaxValue) - 1 . /// </summary> /// <returns></returns> private double InternalSampleLargeRange() { double randomNumber; do { randomNumber = InternalSample(); } while (randomNumber == int.MaxValue); randomNumber += int.MaxValue; return randomNumber; } } }
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC 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 the EntitySpaces, LLC 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 EntitySpaces, LLC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- */ using System; using System.Data; using Tiraggo.Interfaces; using Tiraggo.DynamicQuery; using System.ComponentModel; namespace Tiraggo.Core { /// <summary> /// Provides all of the protected methods available to you in your Custom classes that query the database. /// This class can be useful to query the database when certain calls don't seem to fit in your business /// objects. /// </summary> public class tgUtility { private esPrivateCollection coll; public tgUtility() { coll = new esPrivateCollection(this); } public IEntityCollection tg { get { return coll.tg; } } /// <summary> /// Used only to override the IConnectionNameService API when in use /// </summary> /// <param name="connectionName">The Name of the connection</param> /// <returns>The newly created tgConnection Connection</returns> [EditorBrowsable(EditorBrowsableState.Never)] public tgConnection ConnectionServiceOverride(string connectionName) { return coll.ConnectionServiceOverride(connectionName); } public string Source = "esUtility"; public string Destination = "esUtility"; #region ExecuteNonQuery public int ExecuteNonQuery(tgQueryType queryType, string query) { return coll.ExecuteNonQuery(queryType, query); } public int ExecuteNonQuery(tgQueryType queryType, string query, params object[] parameters) { return coll.ExecuteNonQuery(queryType, query, parameters); } public int ExecuteNonQuery(tgQueryType queryType, string query, tgParameters parms) { return coll.ExecuteNonQuery(queryType, query, parms); } public int ExecuteNonQuery(string schema, string storedProcedure) { return coll.ExecuteNonQuery(schema, storedProcedure); } public int ExecuteNonQuery(string schema, string storedProcedure, params object[] parameters) { return coll.ExecuteNonQuery(schema, storedProcedure, parameters); } public int ExecuteNonQuery(string schema, string storedProcedure, tgParameters parms) { return coll.ExecuteNonQuery(schema, storedProcedure, parms); } public int ExecuteNonQuery(string catalog, string schema, string storedProcedure, tgParameters parameters) { return coll.ExecuteNonQuery(catalog, schema, storedProcedure,parameters); } #endregion #region ExecuteReader public IDataReader ExecuteReader(tgQueryType queryType, string query) { return coll.ExecuteReader(queryType, query); } public IDataReader ExecuteReader(tgQueryType queryType, string query, params object[] parameters) { return coll.ExecuteReader(queryType, query, parameters); } public IDataReader ExecuteReader(tgQueryType queryType, string query, tgParameters parms) { return coll.ExecuteReader(queryType, query, parms); } public IDataReader ExecuteReader(string schema, string storedProcedure) { return coll.ExecuteReader(schema, storedProcedure); } public IDataReader ExecuteReader(string schema, string storedProcedure, params object[] parameters) { return coll.ExecuteReader(schema, storedProcedure, parameters); } public IDataReader ExecuteReader(string schema, string storedProcedure, tgParameters parms) { return coll.ExecuteReader(schema, storedProcedure, parms); } public IDataReader ExecuteReader(string catalog, string schema, string storedProcedure, tgParameters parameters) { return coll.ExecuteReader(catalog, schema, storedProcedure, parameters); } #endregion #region ExecuteScalar public object ExecuteScalar(tgQueryType queryType, string query) { return coll.ExecuteScalar(queryType, query); } public object ExecuteScalar(tgQueryType queryType, string query, params object[] parameters) { return coll.ExecuteScalar(queryType, query, parameters); } public object ExecuteScalar(tgQueryType queryType, string query, tgParameters parms) { return coll.ExecuteScalar(queryType, query, parms); } public object ExecuteScalar(string schema, string storedProcedure) { return coll.ExecuteScalar(schema, storedProcedure); } public object ExecuteScalar(string schema, string storedProcedure, params object[] parameters) { return coll.ExecuteScalar(schema, storedProcedure, parameters); } public object ExecuteScalar(string schema, string storedProcedure, tgParameters parms) { return coll.ExecuteScalar(schema, storedProcedure, parms); } public object ExecuteScalar(string catalog, string schema, string storedProcedure, tgParameters parameters) { return coll.ExecuteScalar(catalog, schema, storedProcedure, parameters); } #region Generic Versions public T ExecuteScalar<T>(tgQueryType queryType, string query) { return (T)coll.ExecuteScalar<T>(queryType, query); } public T ExecuteScalar<T>(tgQueryType queryType, string query, params object[] parameters) { return (T)coll.ExecuteScalar<T>(queryType, query, parameters); } public T ExecuteScalar<T>(tgQueryType queryType, string query, tgParameters parms) { return (T)coll.ExecuteScalar<T>(queryType, query, parms); } public T ExecuteScalar<T>(string schema, string storedProcedure) { return (T)coll.ExecuteScalar<T>(schema, storedProcedure); } public T ExecuteScalar<T>(string schema, string storedProcedure, params object[] parameters) { return (T)coll.ExecuteScalar<T>(schema, storedProcedure, parameters); } public T ExecuteScalar<T>(string schema, string storedProcedure, tgParameters parms) { return (T)coll.ExecuteScalar<T>(schema, storedProcedure, parms); } public T ExecuteScalar<T>(string catalog, string schema, string storedProcedure, tgParameters parameters) { return (T)coll.ExecuteScalar<T>(catalog, schema, storedProcedure, parameters); } #endregion #endregion #region FillDataTable public DataTable FillDataTable(tgQueryType queryType, string query) { return coll.FillDataTable(queryType, query); } public DataTable FillDataTable(tgQueryType queryType, string query, params object[] parameters) { return coll.FillDataTable(queryType, query, parameters); } public DataTable FillDataTable(tgQueryType queryType, string query, tgParameters parms) { return coll.FillDataTable(queryType, query, parms); } public DataTable FillDataTable(string schema, string storedProcedure) { return coll.FillDataTable(schema, storedProcedure); } public DataTable FillDataTable(string schema, string storedProcedure, params object[] parameters) { return coll.FillDataTable(schema, storedProcedure, parameters); } public DataTable FillDataTable(string schema, string storedProcedure, tgParameters parms) { return coll.FillDataTable(schema, storedProcedure, parms); } public DataTable FillDataTable(string catalog, string schema, string storedProcedure, tgParameters parameters) { return coll.FillDataTable(catalog, schema, storedProcedure, parameters); } #endregion #region FillDataSet public DataSet FillDataSet(tgQueryType queryType, string query) { return coll.FillDataSet(queryType, query); } public DataSet FillDataSet(tgQueryType queryType, string query, params object[] parameters) { return coll.FillDataSet(queryType, query, parameters); } public DataSet FillDataSet(tgQueryType queryType, string query, tgParameters parms) { return coll.FillDataSet(queryType, query, parms); } public DataSet FillDataSet(string schema, string storedProcedure) { return coll.FillDataSet(schema, storedProcedure); } public DataSet FillDataSet(string schema, string storedProcedure, params object[] parameters) { return coll.FillDataSet(schema, storedProcedure, parameters); } public DataSet FillDataSet(string schema, string storedProcedure, tgParameters parms) { return coll.FillDataSet(schema, storedProcedure, parms); } public DataSet FillDataSet(string catalog, string schema, string storedProcedure, tgParameters parameters) { return coll.FillDataSet(catalog, schema, storedProcedure, parameters); } #endregion #region Virtual Methods virtual public tgProviderSpecificMetadata GetProviderMetadata(string mapName) { esProv.Schema = this.tg.Connection.Schema; esProv.Catalog = this.tg.Connection.Catalog; esProv.Source = this.Source; esProv.Destination = this.Destination; return esProv; } virtual public Guid DataID { get { return dataID; } } virtual public bool MultiProviderMode { get { return false; } } virtual public tgColumnMetadataCollection Columns { get { return null; } } #endregion #region Nested 'esPrivateCollection' class private class esPrivateCollection : tgEntityCollection<tgUtilityEntity> { private esPrivateCollection() { } public esPrivateCollection(tgUtility util) { md = new MetaData(util); } protected override IMetadata Meta { get { return md; } } #region Nested 'MetaData' class protected class MetaData : IMetadata { public MetaData(tgUtility esUtil) { this.esUtil = esUtil; } public Guid DataID { get { return esUtil.DataID; } } public bool MultiProviderMode { get { return esUtil.MultiProviderMode; } } public tgColumnMetadataCollection Columns { get { return esUtil.Columns; } } public tgProviderSpecificMetadata GetProviderMetadata(string mapName) { return esUtil.GetProviderMetadata(mapName); } private tgUtility esUtil; } #endregion MetaData md; } #endregion protected Guid dataID = Guid.NewGuid(); protected tgProviderSpecificMetadata esProv = new tgProviderSpecificMetadata(); } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; #if SILVERLIGHT using System.Core; #endif #if CLR2 namespace Microsoft.Scripting.Ast { #else namespace System.Linq.Expressions { #endif /// <summary> /// Represents a try/catch/finally/fault block. /// /// The body is protected by the try block. /// The handlers consist of a set of <see cref="CatchBlock"/>s that can either be catch or filters. /// The fault runs if an exception is thrown. /// The finally runs regardless of how control exits the body. /// Only one of fault or finally can be supplied. /// The return type of the try block must match the return type of any associated catch statements. /// </summary> #if !SILVERLIGHT [DebuggerTypeProxy(typeof(Expression.TryExpressionProxy))] #endif public sealed class TryExpression : Expression { private readonly Type _type; private readonly Expression _body; private readonly ReadOnlyCollection<CatchBlock> _handlers; private readonly Expression _finally; private readonly Expression _fault; internal TryExpression(Type type, Expression body, Expression @finally, Expression fault, ReadOnlyCollection<CatchBlock> handlers) { _type = type; _body = body; _handlers = handlers; _finally = @finally; _fault = fault; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _type; } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Try; } } /// <summary> /// Gets the <see cref="Expression"/> representing the body of the try block. /// </summary> public Expression Body { get { return _body; } } /// <summary> /// Gets the collection of <see cref="CatchBlock"/>s associated with the try block. /// </summary> public ReadOnlyCollection<CatchBlock> Handlers { get { return _handlers; } } /// <summary> /// Gets the <see cref="Expression"/> representing the finally block. /// </summary> public Expression Finally { get { return _finally; } } /// <summary> /// Gets the <see cref="Expression"/> representing the fault block. /// </summary> public Expression Fault { get { return _fault; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitTry(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="body">The <see cref="Body" /> property of the result.</param> /// <param name="handlers">The <see cref="Handlers" /> property of the result.</param> /// <param name="finally">The <see cref="Finally" /> property of the result.</param> /// <param name="fault">The <see cref="Fault" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public TryExpression Update(Expression body, IEnumerable<CatchBlock> handlers, Expression @finally, Expression fault) { if (body == Body && handlers == Handlers && @finally == Finally && fault == Fault) { return this; } return Expression.MakeTry(Type, body, @finally, fault, handlers); } } public partial class Expression { /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with a fault block and no catch statements. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="fault">The body of the fault block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryFault(Expression body, Expression fault) { return MakeTry(null, body, null, fault, null); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with a finally block and no catch statements. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="finally">The body of the finally block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryFinally(Expression body, Expression @finally) { return MakeTry(null, body, @finally, null, null); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with any number of catch statements and neither a fault nor finally block. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="handlers">The array of zero or more <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryCatch(Expression body, params CatchBlock[] handlers) { return MakeTry(null, body, null, null, handlers); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with any number of catch statements and a finally block. /// </summary> /// <param name="body">The body of the try block.</param> /// <param name="finally">The body of the finally block.</param> /// <param name="handlers">The array of zero or more <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression TryCatchFinally(Expression body, Expression @finally, params CatchBlock[] handlers) { return MakeTry(null, body, @finally, null, handlers); } /// <summary> /// Creates a <see cref="TryExpression"/> representing a try block with the specified elements. /// </summary> /// <param name="type">The result type of the try expression. If null, bodh and all handlers must have identical type.</param> /// <param name="body">The body of the try block.</param> /// <param name="finally">The body of the finally block. Pass null if the try block has no finally block associated with it.</param> /// <param name="fault">The body of the t block. Pass null if the try block has no fault block associated with it.</param> /// <param name="handlers">A collection of <see cref="CatchBlock"/>s representing the catch statements to be associated with the try block.</param> /// <returns>The created <see cref="TryExpression"/>.</returns> public static TryExpression MakeTry(Type type, Expression body, Expression @finally, Expression fault, IEnumerable<CatchBlock> handlers) { RequiresCanRead(body, "body"); var @catch = handlers.ToReadOnly(); ContractUtils.RequiresNotNullItems(@catch, "handlers"); ValidateTryAndCatchHaveSameType(type, body, @catch); if (fault != null) { if (@finally != null || @catch.Count > 0) { throw Error.FaultCannotHaveCatchOrFinally(); } RequiresCanRead(fault, "fault"); } else if (@finally != null) { RequiresCanRead(@finally, "finally"); } else if (@catch.Count == 0) { throw Error.TryMustHaveCatchFinallyOrFault(); } return new TryExpression(type ?? body.Type, body, @finally, fault, @catch); } //Validate that the body of the try expression must have the same type as the body of every try block. private static void ValidateTryAndCatchHaveSameType(Type type, Expression tryBody, ReadOnlyCollection<CatchBlock> handlers) { // Type unification ... all parts must be reference assignable to "type" if (type != null) { if (type != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(type, tryBody.Type)) { throw Error.ArgumentTypesMustMatch(); } foreach (var cb in handlers) { if (!TypeUtils.AreReferenceAssignable(type, cb.Body.Type)) { throw Error.ArgumentTypesMustMatch(); } } } } else if (tryBody == null || tryBody.Type == typeof(void)) { //The body of every try block must be null or have void type. foreach (CatchBlock cb in handlers) { if (cb.Body != null && cb.Body.Type != typeof(void)) { throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry(); } } } else { //Body of every catch must have the same type of body of try. type = tryBody.Type; foreach (CatchBlock cb in handlers) { if (cb.Body == null || !TypeUtils.AreEquivalent(cb.Body.Type, type)) { throw Error.BodyOfCatchMustHaveSameTypeAsBodyOfTry(); } } } } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Web; using System.Xml; using System.Xml.Serialization; using System.Net; using System.IO; using System.Collections.Specialized; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; namespace WebsitePanel.Ecommerce.EnterpriseServer { /// <summary> /// Payment provider for the PayPal Gateway /// </summary> public class PayPalStandardProvider : SystemPluginBase, IInteractivePaymentGatewayProvider { public const string DEMO_SERVICE_URL = "https://www.sandbox.paypal.com/cgi-bin/webscr"; public const string LIVE_SERVICE_URL = "https://www.paypal.com/cgi-bin/webscr"; public const string BUSINESS_NOT_MATCH_MSG = "Business account doesn't match"; public const string INVALID_RESPONSE_MSG = "Response is reported as either invalid or corrupted"; public const string PAYMENT_REJECTED_MSG = "Payment has been rejected by payment gateway"; public const string IPN_PROCESSOR_ENDPOINT = "Services/PayPalIPN.ashx"; public const string CART_COMMAND = "_cart"; public const string ErrorPrefix = "PayPalStandard."; /// <summary> /// Gets whether plug-in running in live mode /// </summary> public bool LiveMode { get { return Convert.ToBoolean(PluginSettings[PayPalStdSettings.LIVE_MODE]); } } /// <summary> /// Gets service business account /// </summary> public string Business { get { return PluginSettings[PayPalStdSettings.BUSINESS]; } } /// <summary> /// Gets service return url /// </summary> public string ReturnUrl { get { return PluginSettings[PayPalStdSettings.RETURN_URL]; } } /// <summary> /// Gets service cancel return url /// </summary> public string CancelReturnUrl { get { return PluginSettings[PayPalStdSettings.CANCEL_RETURN_URL]; } } /// <summary> /// Gets service url /// </summary> public string ServiceUrl { get { if (LiveMode) return LIVE_SERVICE_URL; return DEMO_SERVICE_URL; } } public PayPalStandardProvider() { } #region IInteractivePaymentGatewayProvider Members public CheckoutFormParams GetCheckoutFormParams(FormParameters formParams, InvoiceItem[] invoiceLines) { // normalize target site variable string targetSite = formParams["target_site"].EndsWith("/") ? formParams["target_site"] : formParams["target_site"] + "/"; CheckoutFormParams outputParams = new CheckoutFormParams(); // setup service url outputParams.Action = ServiceUrl; outputParams.Method = CheckoutFormParams.POST_METHOD; // copy command outputParams["cmd"] = CART_COMMAND; // workaround to make IPN callbacks work outputParams["rm"] = "2"; // set upload value to indicate a third-party shopping cart outputParams["upload"] = "1"; // set business outputParams["business"] = Business; // set cancel return url outputParams["cancel_return"] = String.Concat(targetSite, "?pid=ecOnlineStore&ContractId=", formParams[FormParameters.CONTRACT]); // set return url outputParams["return"] = targetSite; // set IPN-Endpoint url outputParams["notify_url"] = String.Concat(targetSite, IPN_PROCESSOR_ENDPOINT); // set invoice number outputParams["invoice"] = formParams[FormParameters.INVOICE]; // set contract number outputParams["custom"] = formParams[FormParameters.CONTRACT]; // set invoice currency outputParams["currency_code"] = formParams[FormParameters.CURRENCY]; // set formatted invoice number outputParams["item_name_1"] = String.Format("{0} #{1}", FormParameters.INVOICE, formParams[FormParameters.INVOICE]); // set invoice amount outputParams["amount_1"] = formParams[FormParameters.AMOUNT]; // copy first name AddParameter(formParams, outputParams, FormParameters.FIRST_NAME, "first_name"); // copy last name AddParameter(formParams, outputParams, FormParameters.LAST_NAME, "last_name"); // copy address AddParameter(formParams, outputParams, FormParameters.ADDRESS, "address1"); // copy city AddParameter(formParams, outputParams, FormParameters.CITY, "city"); // copy state AddParameter(formParams, outputParams, FormParameters.STATE, "state"); // copy country AddParameter(formParams, outputParams, FormParameters.COUNTRY, "country"); // copy zip AddParameter(formParams, outputParams, FormParameters.ZIP, "zip"); // copty email AddParameter(formParams, outputParams, FormParameters.EMAIL, "email"); // copy phone number if (formParams[FormParameters.COUNTRY] != "US" && formParams[FormParameters.COUNTRY] != "CA") { // phone numbers outside U.S copy as is outputParams["night_phone_b"] = formParams[FormParameters.PHONE]; } // return whole set of params return outputParams; } #endregion #region IPaymentGatewayProvider Members public TransactionResult SubmitPaymentTransaction(CheckoutDetails details) { //init result structure TransactionResult result = new TransactionResult(); // check is request genuine depending on the provider mode Process_IPN_Request(result, details); // return result; } private void Process_PDT_Request(TransactionResult result, CheckoutDetails details) { } private void Process_IPN_Request(TransactionResult result, CheckoutDetails details) { result.RawResponse = ""; // build raw response foreach (string keyName in details.GetAllKeys()) { if (String.IsNullOrEmpty(keyName)) continue; // check for separator if (!String.IsNullOrEmpty(result.RawResponse) && !result.RawResponse.EndsWith("&")) result.RawResponse += "&"; result.RawResponse += keyName + "=" + details[keyName]; } // compare business account against email addres in response if (!String.Equals(details["receiver_email"], Business, StringComparison.InvariantCultureIgnoreCase)) throw new Exception(BUSINESS_NOT_MATCH_MSG); // validate whether response still genuine if(!IsResponseGenuine(result.RawResponse)) throw new Exception(INVALID_RESPONSE_MSG); // build tran id string transactionId = details["txn_id"]; // check payment status switch(details["payment_status"]) { case "Completed": case "Processed": result.Succeed = true; // store order details result.TransactionId = transactionId; result.TransactionStatus = TransactionStatus.Approved; break; case "Pending": result.Succeed = true; // store order details result.TransactionId = transactionId; result.TransactionStatus = TransactionStatus.Pending; break; default: result.Succeed = false; result.TransactionStatus = TransactionStatus.Declined; break; } } #endregion private void AddParameter(FormParameters inputParams, CheckoutFormParams outputParams, string inputKey, string outputKey) { string formParameter = inputParams[inputKey]; if (formParameter != null) { outputParams[outputKey] = formParameter; } } private bool IsResponseGenuine(string strFormValues) { // Create the request back HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ServiceUrl); // Set values for the request back request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; string strNewValue = strFormValues + "&cmd=_notify-validate"; request.ContentLength = strNewValue.Length; // Write the request back IPN strings StreamWriter writer = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII); writer.Write(strNewValue); writer.Close(); // Do the request to PayPal and get the response StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()); string strResponse = reader.ReadToEnd().Trim().ToUpper(); reader.Close(); return String.Equals(strResponse, "VERIFIED", StringComparison.InvariantCultureIgnoreCase); } private string HtmlEncode(string s) { return HttpContext.Current.Server.UrlEncode(s); } } }
/* * 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; using System.Collections.Generic; using System.Data; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; using MySql.Data.MySqlClient; namespace OpenSim.Data.MySQL { public class MySqlRegionData : MySqlFramework, IRegionData { private string m_Realm; private List<string> m_ColumnNames; //private string m_connectionString; public MySqlRegionData(string connectionString, string realm) : base(connectionString) { m_Realm = realm; m_connectionString = connectionString; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, GetType().Assembly, "GridStore"); m.Update(); } } public List<RegionData> Get(string regionName, UUID scopeID) { string command = "select * from `"+m_Realm+"` where regionName like ?regionName"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?regionName", regionName); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); return RunCommand(cmd); } } public RegionData Get(int posX, int posY, UUID scopeID) { string command = "select * from `"+m_Realm+"` where locX = ?posX and locY = ?posY"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?posX", posX.ToString()); cmd.Parameters.AddWithValue("?posY", posY.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); List<RegionData> ret = RunCommand(cmd); if (ret.Count == 0) return null; return ret[0]; } } public RegionData Get(UUID regionID, UUID scopeID) { string command = "select * from `"+m_Realm+"` where uuid = ?regionID"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?regionID", regionID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); List<RegionData> ret = RunCommand(cmd); if (ret.Count == 0) return null; return ret[0]; } } public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID) { string command = "select * from `"+m_Realm+"` where locX between ?startX and ?endX and locY between ?startY and ?endY"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; using (MySqlCommand cmd = new MySqlCommand(command)) { cmd.Parameters.AddWithValue("?startX", startX.ToString()); cmd.Parameters.AddWithValue("?startY", startY.ToString()); cmd.Parameters.AddWithValue("?endX", endX.ToString()); cmd.Parameters.AddWithValue("?endY", endY.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); return RunCommand(cmd); } } public List<RegionData> RunCommand(MySqlCommand cmd) { List<RegionData> retList = new List<RegionData>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); cmd.Connection = dbcon; using (IDataReader result = cmd.ExecuteReader()) { while (result.Read()) { RegionData ret = new RegionData(); ret.Data = new Dictionary<string, object>(); ret.RegionID = DBGuid.FromDB(result["uuid"]); ret.ScopeID = DBGuid.FromDB(result["ScopeID"]); ret.RegionName = result["regionName"].ToString(); ret.posX = Convert.ToInt32(result["locX"]); ret.posY = Convert.ToInt32(result["locY"]); ret.sizeX = Convert.ToInt32(result["sizeX"]); ret.sizeY = Convert.ToInt32(result["sizeY"]); if (m_ColumnNames == null) { m_ColumnNames = new List<string>(); DataTable schemaTable = result.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { if (row["ColumnName"] != null) m_ColumnNames.Add(row["ColumnName"].ToString()); } } foreach (string s in m_ColumnNames) { if (s == "uuid") continue; if (s == "ScopeID") continue; if (s == "regionName") continue; if (s == "locX") continue; if (s == "locY") continue; ret.Data[s] = result[s].ToString(); } retList.Add(ret); } } } return retList; } public bool Store(RegionData data) { if (data.Data.ContainsKey("uuid")) data.Data.Remove("uuid"); if (data.Data.ContainsKey("ScopeID")) data.Data.Remove("ScopeID"); if (data.Data.ContainsKey("regionName")) data.Data.Remove("regionName"); if (data.Data.ContainsKey("posX")) data.Data.Remove("posX"); if (data.Data.ContainsKey("posY")) data.Data.Remove("posY"); if (data.Data.ContainsKey("sizeX")) data.Data.Remove("sizeX"); if (data.Data.ContainsKey("sizeY")) data.Data.Remove("sizeY"); if (data.Data.ContainsKey("locX")) data.Data.Remove("locX"); if (data.Data.ContainsKey("locY")) data.Data.Remove("locY"); if (data.RegionName.Length > 32) data.RegionName = data.RegionName.Substring(0, 32); string[] fields = new List<string>(data.Data.Keys).ToArray(); using (MySqlCommand cmd = new MySqlCommand()) { string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY"; foreach (string field in fields) { update += ", "; update += "`" + field + "` = ?" + field; cmd.Parameters.AddWithValue("?" + field, data.Data[field]); } update += " where uuid = ?regionID"; if (data.ScopeID != UUID.Zero) update += " and ScopeID = ?scopeID"; cmd.CommandText = update; cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString()); cmd.Parameters.AddWithValue("?regionName", data.RegionName); cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString()); cmd.Parameters.AddWithValue("?posX", data.posX.ToString()); cmd.Parameters.AddWithValue("?posY", data.posY.ToString()); cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString()); cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString()); if (ExecuteNonQuery(cmd) < 1) { string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `locX`, `locY`, `sizeX`, `sizeY`, `regionName`, `" + String.Join("`, `", fields) + "`) values ( ?regionID, ?scopeID, ?posX, ?posY, ?sizeX, ?sizeY, ?regionName, ?" + String.Join(", ?", fields) + ")"; cmd.CommandText = insert; if (ExecuteNonQuery(cmd) < 1) { return false; } } } return true; } public bool SetDataItem(UUID regionID, string item, string value) { using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" + item + "` = ?" + item + " where uuid = ?UUID")) { cmd.Parameters.AddWithValue("?" + item, value); cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); if (ExecuteNonQuery(cmd) > 0) return true; } return false; } public bool Delete(UUID regionID) { using (MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + "` where uuid = ?UUID")) { cmd.Parameters.AddWithValue("?UUID", regionID.ToString()); if (ExecuteNonQuery(cmd) > 0) return true; } return false; } public List<RegionData> GetDefaultRegions(UUID scopeID) { return Get((int)RegionFlags.DefaultRegion, scopeID); } public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y) { // TODO: distance-sort results return Get((int)RegionFlags.FallbackRegion, scopeID); } public List<RegionData> GetHyperlinks(UUID scopeID) { return Get((int)RegionFlags.Hyperlink, scopeID); } private List<RegionData> Get(int regionFlags, UUID scopeID) { string command = "select * from `" + m_Realm + "` where (flags & " + regionFlags.ToString() + ") <> 0"; if (scopeID != UUID.Zero) command += " and ScopeID = ?scopeID"; MySqlCommand cmd = new MySqlCommand(command); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); return RunCommand(cmd); } } }
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="CampaignFeedServiceClient"/> instances.</summary> public sealed partial class CampaignFeedServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="CampaignFeedServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="CampaignFeedServiceSettings"/>.</returns> public static CampaignFeedServiceSettings GetDefault() => new CampaignFeedServiceSettings(); /// <summary>Constructs a new <see cref="CampaignFeedServiceSettings"/> object with default settings.</summary> public CampaignFeedServiceSettings() { } private CampaignFeedServiceSettings(CampaignFeedServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetCampaignFeedSettings = existing.GetCampaignFeedSettings; MutateCampaignFeedsSettings = existing.MutateCampaignFeedsSettings; OnCopy(existing); } partial void OnCopy(CampaignFeedServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CampaignFeedServiceClient.GetCampaignFeed</c> and <c>CampaignFeedServiceClient.GetCampaignFeedAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetCampaignFeedSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>CampaignFeedServiceClient.MutateCampaignFeeds</c> and /// <c>CampaignFeedServiceClient.MutateCampaignFeedsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateCampaignFeedsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="CampaignFeedServiceSettings"/> object.</returns> public CampaignFeedServiceSettings Clone() => new CampaignFeedServiceSettings(this); } /// <summary> /// Builder class for <see cref="CampaignFeedServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class CampaignFeedServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignFeedServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public CampaignFeedServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public CampaignFeedServiceClientBuilder() { UseJwtAccessWithScopes = CampaignFeedServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref CampaignFeedServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignFeedServiceClient> task); /// <summary>Builds the resulting client.</summary> public override CampaignFeedServiceClient Build() { CampaignFeedServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<CampaignFeedServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<CampaignFeedServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private CampaignFeedServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return CampaignFeedServiceClient.Create(callInvoker, Settings); } private async stt::Task<CampaignFeedServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return CampaignFeedServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => CampaignFeedServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => CampaignFeedServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignFeedServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>CampaignFeedService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage campaign feeds. /// </remarks> public abstract partial class CampaignFeedServiceClient { /// <summary> /// The default endpoint for the CampaignFeedService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default CampaignFeedService scopes.</summary> /// <remarks> /// The default CampaignFeedService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="CampaignFeedServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="CampaignFeedServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="CampaignFeedServiceClient"/>.</returns> public static stt::Task<CampaignFeedServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new CampaignFeedServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="CampaignFeedServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="CampaignFeedServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="CampaignFeedServiceClient"/>.</returns> public static CampaignFeedServiceClient Create() => new CampaignFeedServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="CampaignFeedServiceClient"/> 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="CampaignFeedServiceSettings"/>.</param> /// <returns>The created <see cref="CampaignFeedServiceClient"/>.</returns> internal static CampaignFeedServiceClient Create(grpccore::CallInvoker callInvoker, CampaignFeedServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } CampaignFeedService.CampaignFeedServiceClient grpcClient = new CampaignFeedService.CampaignFeedServiceClient(callInvoker); return new CampaignFeedServiceClientImpl(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 CampaignFeedService client</summary> public virtual CampaignFeedService.CampaignFeedServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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 gagvr::CampaignFeed GetCampaignFeed(GetCampaignFeedRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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<gagvr::CampaignFeed> GetCampaignFeedAsync(GetCampaignFeedRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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<gagvr::CampaignFeed> GetCampaignFeedAsync(GetCampaignFeedRequest request, st::CancellationToken cancellationToken) => GetCampaignFeedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the campaign feed to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CampaignFeed GetCampaignFeed(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCampaignFeed(new GetCampaignFeedRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the campaign feed to fetch. /// </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<gagvr::CampaignFeed> GetCampaignFeedAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetCampaignFeedAsync(new GetCampaignFeedRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the campaign feed to fetch. /// </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<gagvr::CampaignFeed> GetCampaignFeedAsync(string resourceName, st::CancellationToken cancellationToken) => GetCampaignFeedAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the campaign feed to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::CampaignFeed GetCampaignFeed(gagvr::CampaignFeedName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCampaignFeed(new GetCampaignFeedRequest { ResourceNameAsCampaignFeedName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the campaign feed to fetch. /// </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<gagvr::CampaignFeed> GetCampaignFeedAsync(gagvr::CampaignFeedName resourceName, gaxgrpc::CallSettings callSettings = null) => GetCampaignFeedAsync(new GetCampaignFeedRequest { ResourceNameAsCampaignFeedName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the campaign feed to fetch. /// </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<gagvr::CampaignFeed> GetCampaignFeedAsync(gagvr::CampaignFeedName resourceName, st::CancellationToken cancellationToken) => GetCampaignFeedAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCampaignFeedsResponse MutateCampaignFeeds(MutateCampaignFeedsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(MutateCampaignFeedsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(MutateCampaignFeedsRequest request, st::CancellationToken cancellationToken) => MutateCampaignFeedsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose campaign feeds are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual campaign feeds. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateCampaignFeedsResponse MutateCampaignFeeds(string customerId, scg::IEnumerable<CampaignFeedOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCampaignFeeds(new MutateCampaignFeedsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose campaign feeds are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual campaign feeds. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(string customerId, scg::IEnumerable<CampaignFeedOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateCampaignFeedsAsync(new MutateCampaignFeedsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose campaign feeds are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual campaign feeds. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(string customerId, scg::IEnumerable<CampaignFeedOperation> operations, st::CancellationToken cancellationToken) => MutateCampaignFeedsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>CampaignFeedService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage campaign feeds. /// </remarks> public sealed partial class CampaignFeedServiceClientImpl : CampaignFeedServiceClient { private readonly gaxgrpc::ApiCall<GetCampaignFeedRequest, gagvr::CampaignFeed> _callGetCampaignFeed; private readonly gaxgrpc::ApiCall<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse> _callMutateCampaignFeeds; /// <summary> /// Constructs a client wrapper for the CampaignFeedService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="CampaignFeedServiceSettings"/> used within this client.</param> public CampaignFeedServiceClientImpl(CampaignFeedService.CampaignFeedServiceClient grpcClient, CampaignFeedServiceSettings settings) { GrpcClient = grpcClient; CampaignFeedServiceSettings effectiveSettings = settings ?? CampaignFeedServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetCampaignFeed = clientHelper.BuildApiCall<GetCampaignFeedRequest, gagvr::CampaignFeed>(grpcClient.GetCampaignFeedAsync, grpcClient.GetCampaignFeed, effectiveSettings.GetCampaignFeedSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetCampaignFeed); Modify_GetCampaignFeedApiCall(ref _callGetCampaignFeed); _callMutateCampaignFeeds = clientHelper.BuildApiCall<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse>(grpcClient.MutateCampaignFeedsAsync, grpcClient.MutateCampaignFeeds, effectiveSettings.MutateCampaignFeedsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateCampaignFeeds); Modify_MutateCampaignFeedsApiCall(ref _callMutateCampaignFeeds); 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_GetCampaignFeedApiCall(ref gaxgrpc::ApiCall<GetCampaignFeedRequest, gagvr::CampaignFeed> call); partial void Modify_MutateCampaignFeedsApiCall(ref gaxgrpc::ApiCall<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse> call); partial void OnConstruction(CampaignFeedService.CampaignFeedServiceClient grpcClient, CampaignFeedServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC CampaignFeedService client</summary> public override CampaignFeedService.CampaignFeedServiceClient GrpcClient { get; } partial void Modify_GetCampaignFeedRequest(ref GetCampaignFeedRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateCampaignFeedsRequest(ref MutateCampaignFeedsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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 gagvr::CampaignFeed GetCampaignFeed(GetCampaignFeedRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCampaignFeedRequest(ref request, ref callSettings); return _callGetCampaignFeed.Sync(request, callSettings); } /// <summary> /// Returns the requested campaign feed in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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<gagvr::CampaignFeed> GetCampaignFeedAsync(GetCampaignFeedRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetCampaignFeedRequest(ref request, ref callSettings); return _callGetCampaignFeed.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateCampaignFeedsResponse MutateCampaignFeeds(MutateCampaignFeedsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCampaignFeedsRequest(ref request, ref callSettings); return _callMutateCampaignFeeds.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes campaign feeds. Operation statuses are /// returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CampaignFeedError]() /// [CollectionSizeError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FunctionError]() /// [FunctionParsingError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateCampaignFeedsResponse> MutateCampaignFeedsAsync(MutateCampaignFeedsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateCampaignFeedsRequest(ref request, ref callSettings); return _callMutateCampaignFeeds.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using PhilosophicalMonkey; namespace Temptress { public abstract class TemplateBase { protected const string Pattern = @"{{([^{}]+)}}"; protected const string ForeachControlSectionPattern = @"(<<foreach:([^{}]+)\b[^>]*>>(.*?)<</foreach:([^{}]+)>>)";//<<foreach:([^{}]+)\b[^>]*>>(.*?)<</foreach:([^{}]+)>> protected readonly Regex regex; protected readonly Regex controlSectionRegex; protected PropertyInfo[] properties; public string TemplateContent { get; private set; } protected TemplateBase(string template) { regex = new Regex(Pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); controlSectionRegex = new Regex(ForeachControlSectionPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); TemplateContent = template; } public IEnumerable<TemplateMergeItem> TemplateMergeItems { get { if(templateItems == null || !templateItems.IsValueCreated) GetTemplateMergeItems(); return templateItems.Value; } } public bool HasControlSections { get { return ControlSections.Any(); } } public IEnumerable<ControlSection> ControlSections { get { return GetControlSections(); } } public bool IsValid() { //Lazy<bool> isValid = new Lazy<bool>(() => //{ foreach (var mergeValue in this.TemplateMergeItems) { if (!this.MergeNames().Any(x => x.Equals(mergeValue.Value))) return false; } return true; //}); //return isValid.Value; } #region Working with Control Sections protected Lazy<IEnumerable<ControlSection>> controlSections; protected IEnumerable<ControlSection> GetControlSections() { this.controlSections = new Lazy<IEnumerable<ControlSection>>( () => { IEnumerable<Capture> captures = RegexTextReplacementValues(this.controlSectionRegex, this.TemplateContent); var captureArr = captures.ToArray(); if (captureArr.Length == 0) return new List<ControlSection>(); IEnumerable<Temptress.ControlSection> result = new List<ControlSection> { new ControlSection { Index = captureArr[0].Index, Length = captureArr[0].Length, Value = captureArr[0].Value, PropertyName = captureArr[1].Value, TemplateText = captureArr[2].Value } }; return result; }); return controlSections.Value; } #endregion #region Working with TemplateContent protected Lazy<IEnumerable<TemplateMergeItem>> templateItems; protected IEnumerable<TemplateMergeItem> GetTemplateMergeItems() { this.templateItems = new Lazy<IEnumerable<TemplateMergeItem>>(() => { IEnumerable<Capture> captures = RegexTextReplacementValues(this.regex, this.TemplateContent); return captures .Select( c => new TemplateMergeItem { Value = c.Value, Index = c.Index, Length = c.Length }); }); return templateItems.Value; } protected IEnumerable<Capture> RegexTextReplacementValues(Regex curRegex, string template) { Match m = curRegex.Match(template); int matchCount = 0; while (m.Success) { for (int i = 1; i <= 3; i++) { Group g = m.Groups[i]; CaptureCollection cc = g.Captures; for (int j = 0; j < cc.Count; j++) { Capture c = cc[j]; if (!string.IsNullOrEmpty(c.Value)) { yield return c; } } } m = m.NextMatch(); } } #endregion #region Working with T public IEnumerable<string> MergeNames() { IEnumerable<string> result = MergeOptions().Select(x => x.ReplaceableText); return result; } public IEnumerable<string> MergeValues() { return MergeOptions().Select(x => "{{" + x.ReplaceableText + "}}"); } public IEnumerable<string> FriendlyMergeLabels() { return MergeOptions().Select(x => x.DisplayName); } private IEnumerable<MergeOption> mergeOptions; public IEnumerable<MergeOption> MergeOptions() { if (mergeOptions == null) { mergeOptions = TypeOptionNamesFromProperties(this.properties); } return mergeOptions; } protected IEnumerable<MergeOption> TypeOptionNamesFromProperties(PropertyInfo[] props, string path = "") { List<MergeOption> result = new List<MergeOption>(); foreach (var prop in props) { Type type = GetUnderlyingType(prop); if (Reflect.OnTypes.IsSimple(type)) { var option = new MergeOption(); var attributes = GetPropertyAttributes(prop); object displayName = null; option.ReplaceableText = BuildPropertyName(prop, path); if (attributes.TryGetValue("DisplayName", out displayName)) { option.DisplayName = displayName.ToString(); } else { option.DisplayName = option.ReplaceableText; } result.Add(option); } else { path = BuildPath(prop.Name, path); var option = BuildComplexPropertyName(type, path); result.AddRange(option); path = ""; } } return result; } public Dictionary<string, object> GetPropertyAttributes(PropertyInfo property) { Dictionary<string, object> attribs = new Dictionary<string, object>(); // look for attributes that takes one constructor argument foreach (CustomAttributeData attribData in Reflect.OnAttributes.GetCustomAttributesData(property)) { if (attribData.ConstructorArguments.Count == 1) { //string typeName = attribData.Constructor.DeclaringType.Name; string typeName = attribData.AttributeType.Name; if (typeName.EndsWith("Attribute")) typeName = typeName.Substring(0, typeName.Length - 9); attribs[typeName] = attribData.ConstructorArguments[0].Value; } } return attribs; } protected Type GetUnderlyingType(PropertyInfo prop) { Type type = prop.PropertyType; if (Reflect.OnTypes.IsGenericType(type) && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return Nullable.GetUnderlyingType(type); } return type; } protected IEnumerable<MergeOption> BuildComplexPropertyName(Type type, string path) { var curProps = type.GetProperties(); IEnumerable<MergeOption> currentPropNames = TypeOptionNamesFromProperties(curProps, path); return currentPropNames; } protected string BuildPath(string name, string path) { string breadCrumb = name; if (string.IsNullOrEmpty(path)) path = breadCrumb; else path = string.Format("{0}.{1}", path, breadCrumb); return path; } protected string BuildPropertyName(PropertyInfo prop, string path) { string propName = prop.Name; if (!string.IsNullOrEmpty(path)) propName = string.Format("{0}.{1}", path, propName); return propName; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System.Threading { using System; using System.Security; using System.Security.Permissions; using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using Microsoft.Win32.SafeHandles; [System.Runtime.InteropServices.ComVisible(true)] public delegate void TimerCallback(Object state); // // TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer, supplied by the VM, // to schedule all managed timers in the AppDomain. // // Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire. // There are roughly two types of timer: // // - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because // the whole point is that the timer only fires if something has gone wrong. // // - scheduled background tasks. These typically do fire, but they usually have quite long durations. // So the impact of spending a few extra cycles to fire these is negligible. // // Because of this, we want to choose a data structure with very fast insert and delete times, but we can live // with linear traversal times when firing timers. // // The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion // and removal, and O(N) traversal when finding expired timers. // // Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance. // class TimerQueue { #region singleton pattern implementation // The one-and-only TimerQueue for the AppDomain. static TimerQueue s_queue = new TimerQueue(); public static TimerQueue Instance { get { return s_queue; } } private TimerQueue() { // empty private constructor to ensure we remain a singleton. } #endregion #region interface to native per-AppDomain timer // // We need to keep our notion of time synchronized with the calls to SleepEx that drive // the underlying native timer. In Win8, SleepEx does not count the time the machine spends // sleeping/hibernating. Environment.TickCount (GetTickCount) *does* count that time, // so we will get out of sync with SleepEx if we use that method. // // So, on Win8, we use QueryUnbiasedInterruptTime instead; this does not count time spent // in sleep/hibernate mode. // private static int TickCount { [SecuritySafeCritical] get { #if !FEATURE_PAL if (Environment.IsWindows8OrAbove) { ulong time100ns; bool result = Win32Native.QueryUnbiasedInterruptTime(out time100ns); if (!result) throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error()); // convert to 100ns to milliseconds, and truncate to 32 bits. return (int)(uint)(time100ns / 10000); } else #endif { return Environment.TickCount; } } } // // We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded. // [SecurityCritical] class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public AppDomainTimerSafeHandle() : base(true) { } [SecurityCritical] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { return DeleteAppDomainTimer(handle); } } [SecurityCritical] AppDomainTimerSafeHandle m_appDomainTimer; bool m_isAppDomainTimerScheduled; int m_currentAppDomainTimerStartTicks; uint m_currentAppDomainTimerDuration; [SecuritySafeCritical] private bool EnsureAppDomainTimerFiresBy(uint requestedDuration) { // // The VM's timer implementation does not work well for very long-duration timers. // See kb 950807. // So we'll limit our native timer duration to a "small" value. // This may cause us to attempt to fire timers early, but that's ok - // we'll just see that none of our timers has actually reached its due time, // and schedule the native timer again. // const uint maxPossibleDuration = 0x0fffffff; uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration); if (m_isAppDomainTimerScheduled) { uint elapsed = (uint)(TickCount - m_currentAppDomainTimerStartTicks); if (elapsed >= m_currentAppDomainTimerDuration) return true; //the timer's about to fire uint remainingDuration = m_currentAppDomainTimerDuration - elapsed; if (actualDuration >= remainingDuration) return true; //the timer will fire earlier than this request } // If Pause is underway then do not schedule the timers // A later update during resume will re-schedule if(m_pauseTicks != 0) { Contract.Assert(!m_isAppDomainTimerScheduled); Contract.Assert(m_appDomainTimer == null); return true; } if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid) { Contract.Assert(!m_isAppDomainTimerScheduled); m_appDomainTimer = CreateAppDomainTimer(actualDuration); if (!m_appDomainTimer.IsInvalid) { m_isAppDomainTimerScheduled = true; m_currentAppDomainTimerStartTicks = TickCount; m_currentAppDomainTimerDuration = actualDuration; return true; } else { return false; } } else { if (ChangeAppDomainTimer(m_appDomainTimer, actualDuration)) { m_isAppDomainTimerScheduled = true; m_currentAppDomainTimerStartTicks = TickCount; m_currentAppDomainTimerDuration = actualDuration; return true; } else { return false; } } } // // The VM calls this when the native timer fires. // [SecuritySafeCritical] internal static void AppDomainTimerCallback() { Instance.FireNextTimers(); } [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime); [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime); [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] static extern bool DeleteAppDomainTimer(IntPtr handle); #endregion #region Firing timers // // The list of timers // TimerQueueTimer m_timers; volatile int m_pauseTicks = 0; // Time when Pause was called [SecurityCritical] internal void Pause() { lock(this) { // Delete the native timer so that no timers are fired in the Pause zone if(m_appDomainTimer != null && !m_appDomainTimer.IsInvalid) { m_appDomainTimer.Dispose(); m_appDomainTimer = null; m_isAppDomainTimerScheduled = false; m_pauseTicks = TickCount; } } } [SecurityCritical] internal void Resume() { // // Update timers to adjust their due-time to accomodate Pause/Resume // lock (this) { // prevent ThreadAbort while updating state try { } finally { int pauseTicks = m_pauseTicks; m_pauseTicks = 0; // Set this to 0 so that now timers can be scheduled int resumedTicks = TickCount; int pauseDuration = resumedTicks - pauseTicks; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; TimerQueueTimer timer = m_timers; while (timer != null) { Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); Contract.Assert(resumedTicks >= timer.m_startTicks); uint elapsed; // How much of the timer dueTime has already elapsed // Timers started before the paused event has to be sufficiently delayed to accomodate // for the Pause time. However, timers started after the Paused event shouldnt be adjusted. // E.g. ones created by the app in its Activated event should fire when it was designated. // The Resumed event which is where this routine is executing is after this Activated and hence // shouldn't delay this timer if(timer.m_startTicks <= pauseTicks) elapsed = (uint)(pauseTicks - timer.m_startTicks); else elapsed = (uint)(resumedTicks - timer.m_startTicks); // Handling the corner cases where a Timer was already due by the time Resume is happening, // We shouldn't delay those timers. // Example is a timer started in App's Activated event with a very small duration timer.m_dueTime = (timer.m_dueTime > elapsed) ? timer.m_dueTime - elapsed : 0;; timer.m_startTicks = resumedTicks; // re-baseline if (timer.m_dueTime < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = timer.m_dueTime; } timer = timer.m_next; } if (haveTimerToSchedule) { EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration); } } } } // // Fire any timers that have expired, and update the native timer to schedule the rest of them. // private void FireNextTimers() { // // we fire the first timer on this thread; any other timers that might have fired are queued // to the ThreadPool. // TimerQueueTimer timerToFireOnThisThread = null; lock (this) { // prevent ThreadAbort while updating state try { } finally { // // since we got here, that means our previous timer has fired. // m_isAppDomainTimerScheduled = false; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; int nowTicks = TickCount; // // Sweep through all timers. The ones that have reached their due time // will fire. We will calculate the next native timer due time from the // other timers. // TimerQueueTimer timer = m_timers; while (timer != null) { Contract.Assert(timer.m_dueTime != Timeout.UnsignedInfinite); uint elapsed = (uint)(nowTicks - timer.m_startTicks); if (elapsed >= timer.m_dueTime) { // // Remember the next timer in case we delete this one // TimerQueueTimer nextTimer = timer.m_next; if (timer.m_period != Timeout.UnsignedInfinite) { timer.m_startTicks = nowTicks; timer.m_dueTime = timer.m_period; // // This is a repeating timer; schedule it to run again. // if (timer.m_dueTime < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = timer.m_dueTime; } } else { // // Not repeating; remove it from the queue // DeleteTimer(timer); } // // If this is the first timer, we'll fire it on this thread. Otherwise, queue it // to the ThreadPool. // if (timerToFireOnThisThread == null) timerToFireOnThisThread = timer; else QueueTimerCompletion(timer); timer = nextTimer; } else { // // This timer hasn't fired yet. Just update the next time the native timer fires. // uint remaining = timer.m_dueTime - elapsed; if (remaining < nextAppDomainTimerDuration) { haveTimerToSchedule = true; nextAppDomainTimerDuration = remaining; } timer = timer.m_next; } } if (haveTimerToSchedule) EnsureAppDomainTimerFiresBy(nextAppDomainTimerDuration); } } // // Fire the user timer outside of the lock! // if (timerToFireOnThisThread != null) timerToFireOnThisThread.Fire(); } [SecuritySafeCritical] private static void QueueTimerCompletion(TimerQueueTimer timer) { WaitCallback callback = s_fireQueuedTimerCompletion; if (callback == null) s_fireQueuedTimerCompletion = callback = new WaitCallback(FireQueuedTimerCompletion); // Can use "unsafe" variant because we take care of capturing and restoring // the ExecutionContext. ThreadPool.UnsafeQueueUserWorkItem(callback, timer); } private static WaitCallback s_fireQueuedTimerCompletion; private static void FireQueuedTimerCompletion(object state) { ((TimerQueueTimer)state).Fire(); } #endregion #region Queue implementation public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period) { if (timer.m_dueTime == Timeout.UnsignedInfinite) { // the timer is not in the list; add it (as the head of the list). timer.m_next = m_timers; timer.m_prev = null; if (timer.m_next != null) timer.m_next.m_prev = timer; m_timers = timer; } timer.m_dueTime = dueTime; timer.m_period = (period == 0) ? Timeout.UnsignedInfinite : period; timer.m_startTicks = TickCount; return EnsureAppDomainTimerFiresBy(dueTime); } public void DeleteTimer(TimerQueueTimer timer) { if (timer.m_dueTime != Timeout.UnsignedInfinite) { if (timer.m_next != null) timer.m_next.m_prev = timer.m_prev; if (timer.m_prev != null) timer.m_prev.m_next = timer.m_next; if (m_timers == timer) m_timers = timer.m_next; timer.m_dueTime = Timeout.UnsignedInfinite; timer.m_period = Timeout.UnsignedInfinite; timer.m_startTicks = 0; timer.m_prev = null; timer.m_next = null; } } #endregion } // // A timer in our TimerQueue. // sealed class TimerQueueTimer { // // All fields of this class are protected by a lock on TimerQueue.Instance. // // The first four fields are maintained by TimerQueue itself. // internal TimerQueueTimer m_next; internal TimerQueueTimer m_prev; // // The time, according to TimerQueue.TickCount, when this timer's current interval started. // internal int m_startTicks; // // Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from m_startTime when we will fire. // internal uint m_dueTime; // // Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval. // internal uint m_period; // // Info about the user's callback // readonly TimerCallback m_timerCallback; readonly Object m_state; readonly ExecutionContext m_executionContext; // // When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only // after all pending callbacks are complete. We set m_canceled to prevent any callbacks that // are already queued from running. We track the number of callbacks currently executing in // m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning // reaches zero. // int m_callbacksRunning; volatile bool m_canceled; volatile WaitHandle m_notifyWhenNoCallbacksRunning; [SecurityCritical] internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, ref StackCrawlMark stackMark) { m_timerCallback = timerCallback; m_state = state; m_dueTime = Timeout.UnsignedInfinite; m_period = Timeout.UnsignedInfinite; if (!ExecutionContext.IsFlowSuppressed()) { m_executionContext = ExecutionContext.Capture( ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx | ExecutionContext.CaptureOptions.OptimizeDefaultCase); } // // After the following statement, the timer may fire. No more manipulation of timer state outside of // the lock is permitted beyond this point! // if (dueTime != Timeout.UnsignedInfinite) Change(dueTime, period); } internal bool Change(uint dueTime, uint period) { bool success; lock (TimerQueue.Instance) { if (m_canceled) throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic")); // prevent ThreadAbort while updating state try { } finally { m_period = period; if (dueTime == Timeout.UnsignedInfinite) { TimerQueue.Instance.DeleteTimer(this); success = true; } else { if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) FrameworkEventSource.Log.ThreadTransferSendObj(this, 1, string.Empty, true); success = TimerQueue.Instance.UpdateTimer(this, dueTime, period); } } } return success; } public void Close() { lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { if (!m_canceled) { m_canceled = true; TimerQueue.Instance.DeleteTimer(this); } } } } public bool Close(WaitHandle toSignal) { bool success; bool shouldSignal = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { if (m_canceled) { success = false; } else { m_canceled = true; m_notifyWhenNoCallbacksRunning = toSignal; TimerQueue.Instance.DeleteTimer(this); if (m_callbacksRunning == 0) shouldSignal = true; success = true; } } } if (shouldSignal) SignalNoCallbacksRunning(); return success; } internal void Fire() { bool canceled = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { canceled = m_canceled; if (!canceled) m_callbacksRunning++; } } if (canceled) return; CallCallback(); bool shouldSignal = false; lock (TimerQueue.Instance) { // prevent ThreadAbort while updating state try { } finally { m_callbacksRunning--; if (m_canceled && m_callbacksRunning == 0 && m_notifyWhenNoCallbacksRunning != null) shouldSignal = true; } } if (shouldSignal) SignalNoCallbacksRunning(); } [SecuritySafeCritical] internal void SignalNoCallbacksRunning() { Win32Native.SetEvent(m_notifyWhenNoCallbacksRunning.SafeWaitHandle); } [SecuritySafeCritical] internal void CallCallback() { if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) FrameworkEventSource.Log.ThreadTransferReceiveObj(this, 1, string.Empty); // call directly if EC flow is suppressed if (m_executionContext == null) { m_timerCallback(m_state); } else { using (ExecutionContext executionContext = m_executionContext.IsPreAllocatedDefault ? m_executionContext : m_executionContext.CreateCopy()) { ContextCallback callback = s_callCallbackInContext; if (callback == null) s_callCallbackInContext = callback = new ContextCallback(CallCallbackInContext); ExecutionContext.Run( executionContext, callback, this, // state true); // ignoreSyncCtx } } } [SecurityCritical] private static ContextCallback s_callCallbackInContext; [SecurityCritical] private static void CallCallbackInContext(object state) { TimerQueueTimer t = (TimerQueueTimer)state; t.m_timerCallback(t.m_state); } } // // TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer // if the Timer is collected. // This is necessary because Timer itself cannot use its finalizer for this purpose. If it did, // then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize. // You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this // via first-class APIs), but Timer has never offered this, and adding it now would be a breaking // change, because any code that happened to be suppressing finalization of Timer objects would now // unwittingly be changing the lifetime of those timers. // sealed class TimerHolder { internal TimerQueueTimer m_timer; public TimerHolder(TimerQueueTimer timer) { m_timer = timer; } ~TimerHolder() { // // If shutdown has started, another thread may be suspended while holding the timer lock. // So we can't safely close the timer. // // Similarly, we should not close the timer during AD-unload's live-object finalization phase. // A rude abort may have prevented us from releasing the lock. // // Note that in either case, the Timer still won't fire, because ThreadPool threads won't be // allowed to run in this AppDomain. // if (Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload()) return; m_timer.Close(); } public void Close() { m_timer.Close(); GC.SuppressFinalize(this); } public bool Close(WaitHandle notifyObject) { bool result = m_timer.Close(notifyObject); GC.SuppressFinalize(this); return result; } } [HostProtection(Synchronization=true, ExternalThreading=true)] [System.Runtime.InteropServices.ComVisible(true)] #if FEATURE_REMOTING public sealed class Timer : MarshalByRefObject, IDisposable #else // FEATURE_REMOTING public sealed class Timer : IDisposable #endif // FEATURE_REMOTING { private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; private TimerHolder m_timer; [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, int dueTime, int period) { if (dueTime < -1) throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1 ) throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period,ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, TimeSpan dueTime, TimeSpan period) { long dueTm = (long)dueTime.TotalMilliseconds; if (dueTm < -1) throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("dueTm",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); long periodTm = (long)period.TotalMilliseconds; if (periodTm < -1) throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (periodTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("periodTm",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm,ref stackMark); } [CLSCompliant(false)] [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,dueTime,period,ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback, Object state, long dueTime, long period) { if (dueTime < -1) throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period,ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public Timer(TimerCallback callback) { int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call int period = -1; // Change after a timer instance is created. This is to avoid the potential // for a timer to be fired before the returned value is assigned to the variable, // potentially causing the callback to reference a bogus value (if passing the timer to the callback). StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period, ref stackMark); } [SecurityCritical] private void TimerSetup(TimerCallback callback, Object state, UInt32 dueTime, UInt32 period, ref StackCrawlMark stackMark) { if (callback == null) throw new ArgumentNullException("TimerCallback"); Contract.EndContractBlock(); m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, ref stackMark)); } [SecurityCritical] internal static void Pause() { TimerQueue.Instance.Pause(); } [SecurityCritical] internal static void Resume() { TimerQueue.Instance.Resume(); } public bool Change(int dueTime, int period) { if (dueTime < -1 ) throw new ArgumentOutOfRangeException("dueTime",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException("period",Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Change(TimeSpan dueTime, TimeSpan period) { return Change((long) dueTime.TotalMilliseconds, (long) period.TotalMilliseconds); } [CLSCompliant(false)] public bool Change(UInt32 dueTime, UInt32 period) { return m_timer.m_timer.Change(dueTime, period); } public bool Change(long dueTime, long period) { if (dueTime < -1 ) throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (period < -1) throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1")); if (dueTime > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("dueTime", Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge")); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException("period", Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge")); Contract.EndContractBlock(); return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period); } public bool Dispose(WaitHandle notifyObject) { if (notifyObject==null) throw new ArgumentNullException("notifyObject"); Contract.EndContractBlock(); return m_timer.Close(notifyObject); } public void Dispose() { m_timer.Close(); } internal void KeepRootedWhileScheduled() { GC.SuppressFinalize(m_timer); } } }
namespace RRLab.PhysiologyWorkbench.Daq { partial class OscilloscopeConfigurationControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param genotype="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.AddButton = new System.Windows.Forms.Button(); this.RemoveButton = new System.Windows.Forms.Button(); this.SampleRateTextBox = new System.Windows.Forms.TextBox(); this.UpdateTimeTextBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.ChannelNameTextBox = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.PhysicalChannelComboBox = new System.Windows.Forms.ComboBox(); this.ChannelsListBox = new System.Windows.Forms.ListBox(); this.ChannelsBindingSource = new System.Windows.Forms.BindingSource(this.components); this.UpdateButton = new System.Windows.Forms.Button(); this.ProtocolBindingSource = new System.Windows.Forms.BindingSource(this.components); this.tableLayoutPanel1.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.ChannelsBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ProtocolBindingSource)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.AutoSize = true; this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 2); this.tableLayoutPanel1.Controls.Add(this.SampleRateTextBox, 1, 4); this.tableLayoutPanel1.Controls.Add(this.UpdateTimeTextBox, 1, 3); this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.ChannelNameTextBox, 1, 0); this.tableLayoutPanel1.Controls.Add(this.label3, 0, 3); this.tableLayoutPanel1.Controls.Add(this.label4, 0, 4); this.tableLayoutPanel1.Controls.Add(this.PhysicalChannelComboBox, 1, 1); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 92); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 5; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(182, 140); this.tableLayoutPanel1.TabIndex = 0; // // flowLayoutPanel1 // this.flowLayoutPanel1.AutoSize = true; this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel1.SetColumnSpan(this.flowLayoutPanel1, 2); this.flowLayoutPanel1.Controls.Add(this.AddButton); this.flowLayoutPanel1.Controls.Add(this.RemoveButton); this.flowLayoutPanel1.Controls.Add(this.UpdateButton); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 56); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(177, 29); this.flowLayoutPanel1.TabIndex = 10; // // AddButton // this.AddButton.Anchor = System.Windows.Forms.AnchorStyles.Top; this.AddButton.AutoSize = true; this.AddButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.AddButton.Location = new System.Drawing.Point(3, 3); this.AddButton.Name = "AddButton"; this.AddButton.Size = new System.Drawing.Size(36, 23); this.AddButton.TabIndex = 6; this.AddButton.Text = "Add"; this.AddButton.UseVisualStyleBackColor = true; this.AddButton.Click += new System.EventHandler(this.OnAddChannelClicked); // // RemoveButton // this.RemoveButton.Anchor = System.Windows.Forms.AnchorStyles.Top; this.RemoveButton.AutoSize = true; this.RemoveButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.RemoveButton.Location = new System.Drawing.Point(45, 3); this.RemoveButton.Name = "RemoveButton"; this.RemoveButton.Size = new System.Drawing.Size(57, 23); this.RemoveButton.TabIndex = 7; this.RemoveButton.Text = "Remove"; this.RemoveButton.UseVisualStyleBackColor = true; this.RemoveButton.Click += new System.EventHandler(this.OnRemoveChannelClicked); // // SampleRateTextBox // this.SampleRateTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ProtocolBindingSource, "SampleRate", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged, null, "N0")); this.SampleRateTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.SampleRateTextBox.Location = new System.Drawing.Point(99, 117); this.SampleRateTextBox.Name = "SampleRateTextBox"; this.SampleRateTextBox.Size = new System.Drawing.Size(81, 20); this.SampleRateTextBox.TabIndex = 9; // // UpdateTimeTextBox // this.UpdateTimeTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.ProtocolBindingSource, "UpdateTime", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged, null, "N0")); this.UpdateTimeTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.UpdateTimeTextBox.Location = new System.Drawing.Point(99, 91); this.UpdateTimeTextBox.Name = "UpdateTimeTextBox"; this.UpdateTimeTextBox.Size = new System.Drawing.Size(81, 20); this.UpdateTimeTextBox.TabIndex = 8; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Fill; this.label2.Location = new System.Drawing.Point(3, 26); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(90, 27); this.label2.TabIndex = 1; this.label2.Text = "Channel"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(90, 26); this.label1.TabIndex = 0; this.label1.Text = "Name"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // ChannelNameTextBox // this.ChannelNameTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.ChannelNameTextBox.Location = new System.Drawing.Point(99, 3); this.ChannelNameTextBox.Name = "ChannelNameTextBox"; this.ChannelNameTextBox.Size = new System.Drawing.Size(81, 20); this.ChannelNameTextBox.TabIndex = 2; // // label3 // this.label3.AutoSize = true; this.label3.Dock = System.Windows.Forms.DockStyle.Fill; this.label3.Location = new System.Drawing.Point(3, 88); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(90, 26); this.label3.TabIndex = 6; this.label3.Text = "Update Time (ms)"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // label4 // this.label4.AutoSize = true; this.label4.Dock = System.Windows.Forms.DockStyle.Fill; this.label4.Location = new System.Drawing.Point(3, 114); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(90, 26); this.label4.TabIndex = 7; this.label4.Text = "Sample Rate (Hz)"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // PhysicalChannelComboBox // this.PhysicalChannelComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this.PhysicalChannelComboBox.FormattingEnabled = true; this.PhysicalChannelComboBox.Location = new System.Drawing.Point(99, 29); this.PhysicalChannelComboBox.Name = "PhysicalChannelComboBox"; this.PhysicalChannelComboBox.Size = new System.Drawing.Size(81, 21); this.PhysicalChannelComboBox.TabIndex = 11; // // ChannelsListBox // this.ChannelsListBox.Dock = System.Windows.Forms.DockStyle.Fill; this.ChannelsListBox.FormattingEnabled = true; this.ChannelsListBox.Location = new System.Drawing.Point(0, 0); this.ChannelsListBox.Name = "ChannelsListBox"; this.ChannelsListBox.Size = new System.Drawing.Size(182, 82); this.ChannelsListBox.TabIndex = 1; this.ChannelsListBox.SelectedIndexChanged += new System.EventHandler(this.OnSelectedChannelChanged); // // UpdateButton // this.UpdateButton.AutoSize = true; this.UpdateButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.UpdateButton.Location = new System.Drawing.Point(108, 3); this.UpdateButton.Name = "UpdateButton"; this.UpdateButton.Size = new System.Drawing.Size(52, 23); this.UpdateButton.TabIndex = 8; this.UpdateButton.Text = "Update"; this.UpdateButton.UseVisualStyleBackColor = true; this.UpdateButton.Click += new System.EventHandler(this.OnUpdateClicked); // // ProtocolBindingSource // this.ProtocolBindingSource.DataSource = typeof(RRLab.PhysiologyWorkbench.Daq.OscilloscopeProtocol); // // OscilloscopeConfigurationControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.Controls.Add(this.ChannelsListBox); this.Controls.Add(this.tableLayoutPanel1); this.Enabled = false; this.Name = "OscilloscopeConfigurationControl"; this.Size = new System.Drawing.Size(182, 232); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.ChannelsBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ProtocolBindingSource)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox ChannelNameTextBox; private System.Windows.Forms.ListBox ChannelsListBox; private System.Windows.Forms.TextBox SampleRateTextBox; private System.Windows.Forms.TextBox UpdateTimeTextBox; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button AddButton; private System.Windows.Forms.Button RemoveButton; private System.Windows.Forms.ComboBox PhysicalChannelComboBox; private System.Windows.Forms.BindingSource ProtocolBindingSource; private System.Windows.Forms.BindingSource ChannelsBindingSource; private System.Windows.Forms.Button UpdateButton; } }
namespace FakeItEasy.IntegrationTests { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Reflection.Emit; using FakeItEasy.Configuration; using FakeItEasy.Core; using FakeItEasy.Tests; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using NUnit.Framework; [TestFixture] public class GeneralTests { public interface ITypeWithFakeableProperties { IEnumerable<object> Collection { get; } IFoo Foo { get; } } [Test] public void Faked_object_with_fakeable_properties_should_have_fake_as_default_value() { // Arrange // Act var fake = A.Fake<ITypeWithFakeableProperties>(); // Assert fake.Collection.Should().NotBeNull(); fake.Foo.Should().NotBeNull(); } [Test] public void Faked_object_with_method_that_returns_fakeable_type_should_return_fake_by_default() { // Arrange var fake = A.Fake<IEnumerable<string>>(); // Act var enumerator = fake.GetEnumerator(); // Assert enumerator.Should().NotBeNull(); Fake.GetFakeManager(enumerator).Should().NotBeNull(); } [Test] public void Faked_object_with_additional_attributes_should_create_a_type_with_those_attributes() { // Arrange var types = new Type[0]; var constructor = typeof(ForTestAttribute).GetConstructor(types); var list = new object[0]; var attribute = new CustomAttributeBuilder(constructor, list); var builder = new List<CustomAttributeBuilder>(); builder.Add(attribute); // Act var fake = A.Fake<IEmpty>(a => a.WithAdditionalAttributes(builder)); // Assert fake.GetType().GetCustomAttributes(typeof(ForTestAttribute), true).Should().HaveCount(1); } [Test] public void Additional_attributes_should_not_be_added_to_the_next_fake() { // Arrange var types = new Type[0]; var constructor = typeof(ForTestAttribute).GetConstructor(types); var list = new object[0]; var attribute = new CustomAttributeBuilder(constructor, list); var builder = new List<CustomAttributeBuilder>(); builder.Add(attribute); A.Fake<IEmpty>(a => a.WithAdditionalAttributes(builder)); // Act var secondFake = A.Fake<IFormattable>(); // Assert secondFake.GetType().GetCustomAttributes(typeof(ForTestAttribute), true).Should().BeEmpty(); } [Test] public void Should_not_be_able_to_fake_Uri_when_no_container_is_used() { // Arrange // Act Exception exception; using (Fake.CreateScope(new NullFakeObjectContainer())) { exception = Record.Exception(() => A.Fake<Guid>()); } // Assert exception.Should().BeAnExceptionOfType<FakeCreationException>(); } [Test] public void ErrorMessage_when_type_cannot_be_faked_should_specify_non_resolvable_constructor_arguments() { // Arrange // Act Exception exception; using (Fake.CreateScope()) { exception = Record.Exception(() => A.Fake<NonResolvableType>()); } // Assert const string ExpectedMessage = @" The following constructors were not tried: (FakeItEasy.Tests.IFoo, *FakeItEasy.IntegrationTests.GeneralTests+NoInstanceType) (*FakeItEasy.IntegrationTests.GeneralTests+NoInstanceType) Types marked with * could not be resolved, register them in the current IFakeObjectContainer to enable these constructors. "; exception.Should() .BeAnExceptionOfType<FakeCreationException>().And .Message.Should().Contain(ExpectedMessage); } [Test] public void ErrorMessage_when_configuring_void_call_that_cannot_be_configured_should_be_correct() { // Arrange var fake = A.Fake<TypeWithNonConfigurableMethod>(); // Act var exception = Record.Exception(() => A.CallTo(() => fake.NonVirtualVoidMethod(string.Empty, 1)).DoesNothing()); // Assert exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And .Message.Should().Contain("Non virtual"); } [Test] public void ErrorMessage_when_configuring_function_call_that_cannot_be_configured_should_be_correct() { // Arrange var fake = A.Fake<TypeWithNonConfigurableMethod>(); // Act var exception = Record.Exception(() => A.CallTo(() => fake.NonVirtualFunction(string.Empty, 1)).Returns(10)); // Asssert exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And .Message.Should().Contain("Non virtual"); } [Test] public void ErrorMessage_when_configuring_generic_function_call_that_cannot_be_configured_should_be_correct() { // Arrange var fake = A.Fake<TypeWithNonConfigurableMethod>(); // Act var exception = Record.Exception(() => A.CallTo(() => fake.GenericNonVirtualFunction<int>()).Returns(10)); // Asssert exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And .Message.Should().Contain("Non virtual"); } [Test] public void Should_be_able_to_generate_class_fake_that_implements_additional_interface() { // Arrange var fake = A.Fake<FakeableClass>(x => x.Implements(typeof(IFoo)).Implements(typeof(IFormattable))); // Act // Assert fake.Should() .BeAssignableTo<IFoo>().And .BeAssignableTo<IFormattable>().And .BeAssignableTo<FakeableClass>(); } [Test] public void Should_be_able_to_generate_class_fake_that_implements_additional_interface_using_generic() { // Arrange var fake = A.Fake<FakeableClass>(x => x.Implements<IFoo>().Implements<IFormattable>()); // Act // Assert fake.Should() .BeAssignableTo<IFoo>().And .BeAssignableTo<IFormattable>().And .BeAssignableTo<FakeableClass>(); } [Test] public void Should_be_able_to_generate_interface_fake_that_implements_additional_interface() { // Arrange var fake = A.Fake<IFoo>(x => x.Implements(typeof(IFormatProvider)).Implements(typeof(IFormattable))); // Act // Assert fake.Should() .BeAssignableTo<IFoo>().And .BeAssignableTo<IFormattable>().And .BeAssignableTo<IFormatProvider>(); } [Test] public void Should_be_able_to_generate_interface_fake_that_implements_additional_interface_using_generic() { // Arrange var fake = A.Fake<IFoo>(x => x.Implements<IFormatProvider>().Implements<IFormattable>()); // Act // Assert fake.Should() .BeAssignableTo<IFoo>().And .BeAssignableTo<IFormattable>().And .BeAssignableTo<IFormatProvider>(); } [Test] public void FakeCollection_should_return_list_where_all_objects_are_fakes() { // Arrange // Act var result = A.CollectionOfFake<IFoo>(10); // Assert result.Should().BeAssignableTo<IList<IFoo>>().And .OnlyContain(foo => foo != null && Fake.GetFakeManager(foo) != null); } [Test] public void Returns_from_sequence_only_applies_the_number_as_many_times_as_the_number_of_specified_values() { // Arrange var foo = A.Fake<IFoo>(); A.CallTo(() => foo.Baz()).Throws(new InvalidOperationException()); A.CallTo(() => foo.Baz()).ReturnsNextFromSequence(1, 2); foo.Baz(); foo.Baz(); // Act var exception = Record.Exception(() => foo.Baz()); // Assert exception.Should().BeAnExceptionOfType<InvalidOperationException>(); } public class NonResolvableType { [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "foo", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "bar", Justification = "Required for testing.")] public NonResolvableType(IFoo foo, NoInstanceType bar) { } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "bar", Justification = "Required for testing.")] protected NonResolvableType(NoInstanceType bar) { } } public class NoInstanceType { private NoInstanceType() { } } public class FakeableClass { public virtual void Foo() { } } public class TypeWithNonConfigurableMethod { [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "otherArgument", Justification = "Required for testing.")] public void NonVirtualVoidMethod(string argument, int otherArgument) { } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "otherArgument", Justification = "Required for testing.")] public int NonVirtualFunction(string argument, int otherArgument) { return 1; } public T GenericNonVirtualFunction<T>() { return default(T); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Globalization; using IndexReader = Lucene.Net.Index.IndexReader; using ToStringUtils = Lucene.Net.Util.ToStringUtils; namespace Lucene.Net.Search { /// <summary> A Query that matches documents within an exclusive range of terms. /// /// <p/>This query matches the documents looking for terms that fall into the /// supplied range according to <see cref="String.CompareTo(String)" />. It is not intended /// for numerical ranges, use <see cref="NumericRangeQuery{T}" /> instead. /// /// <p/>This query uses the <see cref="MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT" /> /// /// rewrite method. /// </summary> /// <since> 2.9 /// </since> [Serializable] public class TermRangeQuery:MultiTermQuery { private System.String lowerTerm; private System.String upperTerm; private System.Globalization.CompareInfo collator; private System.String field; private bool includeLower; private bool includeUpper; /// <summary> Constructs a query selecting all terms greater/equal than <c>lowerTerm</c> /// but less/equal than <c>upperTerm</c>. /// /// <p/> /// If an endpoint is null, it is said /// to be "open". Either or both endpoints may be open. Open endpoints may not /// be exclusive (you can't select all but the first or last term without /// explicitly specifying the term to exclude.) /// /// </summary> /// <param name="field">The field that holds both lower and upper terms. /// </param> /// <param name="lowerTerm">The term text at the lower end of the range /// </param> /// <param name="upperTerm">The term text at the upper end of the range /// </param> /// <param name="includeLower">If true, the <c>lowerTerm</c> is /// included in the range. /// </param> /// <param name="includeUpper">If true, the <c>upperTerm</c> is /// included in the range. /// </param> public TermRangeQuery(System.String field, System.String lowerTerm, System.String upperTerm, bool includeLower, bool includeUpper):this(field, lowerTerm, upperTerm, includeLower, includeUpper, null) { } /// <summary>Constructs a query selecting all terms greater/equal than /// <c>lowerTerm</c> but less/equal than <c>upperTerm</c>. /// <p/> /// If an endpoint is null, it is said /// to be "open". Either or both endpoints may be open. Open endpoints may not /// be exclusive (you can't select all but the first or last term without /// explicitly specifying the term to exclude.) /// <p/> /// If <c>collator</c> is not null, it will be used to decide whether /// index terms are within the given range, rather than using the Unicode code /// point order in which index terms are stored. /// <p/> /// <strong>WARNING:</strong> Using this constructor and supplying a non-null /// value in the <c>collator</c> parameter will cause every single /// index Term in the Field referenced by lowerTerm and/or upperTerm to be /// examined. Depending on the number of index Terms in this Field, the /// operation could be very slow. /// /// </summary> /// <param name="field"></param> /// <param name="lowerTerm">The Term text at the lower end of the range /// </param> /// <param name="upperTerm">The Term text at the upper end of the range /// </param> /// <param name="includeLower">If true, the <c>lowerTerm</c> is /// included in the range. /// </param> /// <param name="includeUpper">If true, the <c>upperTerm</c> is /// included in the range. /// </param> /// <param name="collator">The collator to use to collate index Terms, to determine /// their membership in the range bounded by <c>lowerTerm</c> and /// <c>upperTerm</c>. /// </param> public TermRangeQuery(System.String field, System.String lowerTerm, System.String upperTerm, bool includeLower, bool includeUpper, System.Globalization.CompareInfo collator) { this.field = field; this.lowerTerm = lowerTerm; this.upperTerm = upperTerm; this.includeLower = includeLower; this.includeUpper = includeUpper; this.collator = collator; } /// <summary>Returns the field name for this query </summary> public virtual string Field { get { return field; } } /// <summary>Returns the lower value of this range query </summary> public virtual string LowerTerm { get { return lowerTerm; } } /// <summary>Returns the upper value of this range query </summary> public virtual string UpperTerm { get { return upperTerm; } } /// <summary>Returns <c>true</c> if the lower endpoint is inclusive </summary> public virtual bool IncludesLower { get { return includeLower; } } /// <summary>Returns <c>true</c> if the upper endpoint is inclusive </summary> public virtual bool IncludesUpper { get { return includeUpper; } } /// <summary>Returns the collator used to determine range inclusion, if any. </summary> public virtual CompareInfo Collator { get { return collator; } } protected internal override FilteredTermEnum GetEnum(IndexReader reader) { return new TermRangeTermEnum(reader, field, lowerTerm, upperTerm, includeLower, includeUpper, collator); } /// <summary>Prints a user-readable version of this query. </summary> public override System.String ToString(System.String field) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); if (!Field.Equals(field)) { buffer.Append(Field); buffer.Append(":"); } buffer.Append(includeLower?'[':'{'); buffer.Append(lowerTerm != null?lowerTerm:"*"); buffer.Append(" TO "); buffer.Append(upperTerm != null?upperTerm:"*"); buffer.Append(includeUpper?']':'}'); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } //@Override public override int GetHashCode() { int prime = 31; int result = base.GetHashCode(); result = prime * result + ((collator == null)?0:collator.GetHashCode()); result = prime * result + ((field == null)?0:field.GetHashCode()); result = prime * result + (includeLower?1231:1237); result = prime * result + (includeUpper?1231:1237); result = prime * result + ((lowerTerm == null)?0:lowerTerm.GetHashCode()); result = prime * result + ((upperTerm == null)?0:upperTerm.GetHashCode()); return result; } //@Override public override bool Equals(System.Object obj) { if (this == obj) return true; if (!base.Equals(obj)) return false; if (GetType() != obj.GetType()) return false; TermRangeQuery other = (TermRangeQuery) obj; if (collator == null) { if (other.collator != null) return false; } else if (!collator.Equals(other.collator)) return false; if (field == null) { if (other.field != null) return false; } else if (!field.Equals(other.field)) return false; if (includeLower != other.includeLower) return false; if (includeUpper != other.includeUpper) return false; if (lowerTerm == null) { if (other.lowerTerm != null) return false; } else if (!lowerTerm.Equals(other.lowerTerm)) return false; if (upperTerm == null) { if (other.upperTerm != null) return false; } else if (!upperTerm.Equals(other.upperTerm)) return false; return true; } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System; using System.Collections; using System.Collections.Generic; namespace Leap.Unity.Query { /// <summary> /// The wrapper for all leap queries. These queries are meant to mirror the queries present in the /// System.Linq.Enumerable class. These queries are meant to be functionaly identical, but allocate /// zero garbage, both during the generation of the query, as well as the execution. The speed is /// also aimed to be as fast or faster. /// /// There is one big difference between using Linq and using Leap queries.You must prefix your query /// with a call to a Query() method if you are starting with an external data structure. So for /// example if you want to query a list, your method call would look something like this: /// /// myList.Query().Where(someCondition).First(); /// </summary> public partial struct QueryWrapper<QueryType, QueryOp> where QueryOp : IQueryOp<QueryType> { private QueryOp _op; /// <summary> /// Returns the actual query operation wrapped by this wrapper. This operation always /// implements IQueryOp, which is an interface similar to IEnumerator. You usually /// do not need to access this op directly to use the query. Instead you can simply /// foreach over this wrapper, or use one of the direct query operations like First, /// ToList, Any, ect... /// </summary> public QueryOp op { get { return _op; } } /// <summary> /// Constructs a new wrapper given a specific query operation. /// </summary> public QueryWrapper(QueryOp op) { _op = op; } /// <summary> /// Returns an enumerator object that is able to enumerate through the query operation /// wrapped by this wrapper. You can call this directly and step through the result /// by using MoveNext/Current, or use it indirectly by using the foreach construct. /// </summary> public Enumerator GetEnumerator() { return new Enumerator(_op); } public struct Enumerator : IEnumerator<QueryType> { private QueryOp _op; private QueryType _current; public Enumerator(QueryOp op) { _op = op; _current = default(QueryType); } public bool MoveNext() { return _op.TryGetNext(out _current); } public void Reset() { _op.Reset(); _current = default(QueryType); } public void Dispose() { _op.Reset(); } public QueryType Current { get { return _current; } } object IEnumerator.Current { get { throw new NotImplementedException(); } } } } /// <summary> /// The interface all query operations must follow. It is a modified version of the /// IEnumerator interface, optimized for speed and conciseness. /// </summary> public interface IQueryOp<T> { /// <summary> /// Tries to get the next value in the sequence. If this method returns true, /// the next value will be placed into the out parameter t. If this method /// returns false, the sequence is at an end and t will be the default value /// of T. /// /// Once TryGetNext returns false, it can NEVER return true again until the /// Reset operator is called. /// </summary> bool TryGetNext(out T t); /// <summary> /// Resets the internal state of this query operation to the begining of /// the sequence. /// </summary> void Reset(); } /// <summary> /// Data structures require special conversion operations to turn them into /// objects that implement IQueryOp. These conversions can unfortunately not /// be done automatically, which is the reason for the call to Query(). All /// Query() calls are housed in this class for ease of use. /// </summary> public static class QueryConversionExtensions { /// <summary> /// Converts an IList object into a query operation, and returns a query wrapper /// that wraps this new operation. /// </summary> public static QueryWrapper<T, ListQueryOp<T>> Query<T>(this IList<T> list) { return new QueryWrapper<T, ListQueryOp<T>>(new ListQueryOp<T>(list)); } /// <summary> /// Converts a two dimensional array into a query operation, and returns a query /// wrapper that wraps this new operation. Elements are traversed in row-major /// (C-style) order. /// </summary> public static QueryWrapper<T, Array2DQueryOp<T>> Query<T>(this T[,] array) { return new QueryWrapper<T, Array2DQueryOp<T>>(new Array2DQueryOp<T>(array)); } /// <summary> /// Converts a ReadonlyList object into a query operation, and returns a query wrapper /// that wraps this new operation. /// </summary> public static QueryWrapper<T, ReadonlyListQueryOp<T>> Query<T>(this ReadonlyList<T> list) { return new QueryWrapper<T, ReadonlyListQueryOp<T>>(new ReadonlyListQueryOp<T>(list)); } /// <summary> /// Converts a Dictionary object into a query operation, and returns a query wrapper /// that wraps this new operation. /// </summary> public static QueryWrapper<KeyValuePair<K, V>, EnumerableQueryOp<KeyValuePair<K, V>, Dictionary<K, V>.Enumerator>> Query<T, K, V>(this Dictionary<K, V> dictionary) { return new QueryWrapper<KeyValuePair<K, V>, EnumerableQueryOp<KeyValuePair<K, V>, Dictionary<K, V>.Enumerator>>(new EnumerableQueryOp<KeyValuePair<K, V>, Dictionary<K, V>.Enumerator>(dictionary.GetEnumerator())); } /// <summary> /// Converts a HashSet object into a query operation, and returns a query wrapper /// that wraps this new operation. /// </summary> public static QueryWrapper<T, EnumerableQueryOp<T, HashSet<T>.Enumerator>> Query<T>(this HashSet<T> hashSet) { return new QueryWrapper<T, EnumerableQueryOp<T, HashSet<T>.Enumerator>>(new EnumerableQueryOp<T, HashSet<T>.Enumerator>(hashSet.GetEnumerator())); } /// <summary> /// Converts a ReadonlyHashSet object into a query operation, and returns a query /// wrapper that wraps this new operation. /// </summary> public static QueryWrapper<T, EnumerableQueryOp<T, HashSet<T>.Enumerator>> Query<T>(this ReadonlyHashSet<T> hashSet) { return new QueryWrapper<T, EnumerableQueryOp<T, HashSet<T>.Enumerator>>(new EnumerableQueryOp<T, HashSet<T>.Enumerator>(hashSet.GetEnumerator())); } /// <summary> /// Converts a Queue object into a query operation, and returns a query wrapper /// that wraps this new operation. /// </summary> public static QueryWrapper<T, EnumerableQueryOp<T, Queue<T>.Enumerator>> Query<T>(this Queue<T> queue) { return new QueryWrapper<T, EnumerableQueryOp<T, Queue<T>.Enumerator>>(new EnumerableQueryOp<T, Queue<T>.Enumerator>(queue.GetEnumerator())); } /// <summary> /// Generic fallback for calling Query on any IEnumerator. /// /// IMPORTANT! Since this uses the IEnumerator interface, it MUST create a small allocation /// during the call to GetEnumerator that cannot be avoided. /// </summary> public static QueryWrapper<T, EnumerableQueryOp<T, IEnumerator<T>>> Query<T>(this IEnumerator<T> enumerator) { return new QueryWrapper<T, EnumerableQueryOp<T, IEnumerator<T>>>(new EnumerableQueryOp<T, IEnumerator<T>>(enumerator)); } /// <summary> /// Generic fallback for calling Query on any IEnumerable. /// /// IMPORTANT! Since this uses the IEnumerable interface, it MUST create a small allocation /// during the call to GetEnumerator that cannot be avoided. /// </summary> public static QueryWrapper<T, EnumerableQueryOp<T, IEnumerator<T>>> Query<T>(this IEnumerable<T> enumerable) { return new QueryWrapper<T, EnumerableQueryOp<T, IEnumerator<T>>>(new EnumerableQueryOp<T, IEnumerator<T>>(enumerable.GetEnumerator())); } public struct ListQueryOp<T> : IQueryOp<T> { private IList<T> _list; private int _index; public ListQueryOp(IList<T> list) { _list = list; _index = 0; } public bool TryGetNext(out T t) { if (_index >= _list.Count) { t = default(T); return false; } else { t = _list[_index++]; return true; } } public void Reset() { _index = 0; } } public struct Array2DQueryOp<T> : IQueryOp<T> { private T[,] _array; private int _numCols, _numRows; private int _colIdx, _rowIdx; public Array2DQueryOp(T[,] array) { _array = array; _numRows = array.GetLength(0); _numCols = array.GetLength(1); _rowIdx = 0; _colIdx = 0; } public bool TryGetNext(out T t) { if (_rowIdx >= _numRows) { t = default(T); return false; } t = _array[_rowIdx, _colIdx]; // C-style, row-major (C# standard) _colIdx++; if (_colIdx >= _numCols) { _colIdx = 0; _rowIdx++; } return true; } public void Reset() { _rowIdx = 0; _colIdx = 0; } } public struct ReadonlyListQueryOp<T> : IQueryOp<T> { private ReadonlyList<T> _list; private int _index; public ReadonlyListQueryOp(ReadonlyList<T> list) { _list = list; _index = 0; } public bool TryGetNext(out T t) { if (_index >= _list.Count) { t = default(T); return false; } else { t = _list[_index++]; return true; } } public void Reset() { _index = 0; } } public struct EnumerableQueryOp<T, Enumerable> : IQueryOp<T> where Enumerable : IEnumerator<T> { private Enumerable _source; public EnumerableQueryOp(Enumerable source) { _source = source; } public bool TryGetNext(out T t) { if (_source.MoveNext()) { t = _source.Current; return true; } else { t = default(T); return false; } } public void Reset() { _source.Reset(); } } } }
namespace PackStream.NET.Tests { using System; using System.Collections.Generic; using FluentAssertions; using global::PackStream.NET; using global::PackStream.NET.Packers; using Xunit; using Packers = global::PackStream.NET.Packers.Packers; public class ObjectPackerTests { private class SimpleClassWithField { #pragma warning disable 414 public bool _a; #pragma warning restore 414 } private class SimpleClass { // ReSharper disable once UnusedAutoPropertyAccessor.Local public bool A { get; set; } } private class MultiPropertyClass : SimpleClass { // ReSharper disable once UnusedAutoPropertyAccessor.Local public bool B { get; set; } } private class SimpleClassWithPrivateProperty : SimpleClass { // ReSharper disable once UnusedAutoPropertyAccessor.Local private bool B { get; set; } public void SetB(bool value) { B = value; } } private class SimpleClassWithBoltIgnoredProperty : SimpleClass { [PackStreamIgnore] public bool B { get; set; } } public class PackMethod { [Fact] public void PacksPrivatePropertyCorrectly() { var toPack = new SimpleClassWithPrivateProperty {A = true}; toPack.SetB(true); var expected = new List<byte> { 0xA2, 0x81, 0x42, Markers.True, 0x81, 0x41, Markers.True }; var actual = Packers.Map.Pack(toPack); actual.Should().Equal(expected); } [Fact] public void PacksAnonymousCorrectly() { var toPack = new {A = true}; var expected = new List<byte> {0xA1, 0x81, 0x41, Markers.True}; //1 fields var actual = Packers.Map.Pack(toPack); actual.Should().Equal(expected); } [Fact] public void PacksDefinedClassCorrectly() { var toPack = new SimpleClass {A = true}; var expected = new List<byte> {0xA1, 0x81, 0x41, Markers.True}; //1 fields var actual = Packers.Map.Pack(toPack); actual.Should().Equal(expected); } [Fact] public void PacksDefinedClassWithMultiplePropertiesCorrectly() { var toPack = new MultiPropertyClass {A = true, B = false}; var expected = new List<byte> {0xA2, 0x81, 0x42, Markers.False, 0x81, 0x41, Markers.True}; var actual = Packers.Map.Pack(toPack); actual.Should().Equal(expected); } [Fact] public void PacksDefinedClassCorrectlyIgnoringBoltIgnoredProperties() { var toPack = new SimpleClassWithBoltIgnoredProperty {A = true}; var expected = new List<byte> {0xA1, 0x81, 0x41, Markers.True}; //1 fields var actual = Packers.Map.Pack(toPack); actual.Should().Equal(expected); } [Theory] [InlineData(0, new byte[] {0xA0})] [InlineData(1, new byte[] {0xA1, 0x82, 0x61, 0x30, 0x82, 0x61, 0x30})] public void PacksDictionary_StringString_Correctly(int size, byte[] expected) { var dictionary = new Dictionary<string, string>(); for (var i = 0; i < size; i++) dictionary.Add("a" + i, "a" + i); var actual = Packers.Map.Pack(dictionary); actual.Should().Equal(expected); } } public class UnpackMethod { [Theory] [InlineData(0, new byte[] {0xA0})] [InlineData(1, new byte[] {0xA1, 0x82, 0x61, 0x30, 0x82, 0x61, 0x30})] public void UnpacksDictionary_StringString_Correctly(int size, byte[] input) { var expected = new Dictionary<string, string>(); for (var i = 0; i < size; i++) expected.Add("a" + i, "a" + i); var actual = Packers.Map.Unpack<Dictionary<string, string>>(input); actual.Should().Equal(expected); } [Fact] public void UnpacksDefinedClass_WithProperty() { var expected = new SimpleClass {A = true}; var toUnpack = new List<byte> {0xA1, 0x81, 0x41, Markers.True}; //1 fields var actual = Packers.Map.Unpack<SimpleClass>(toUnpack.ToArray()); actual.ShouldBeEquivalentTo(expected); } [Fact] public void PacksPrivatePropertyCorrectly() { var expected = new SimpleClassWithPrivateProperty { A = true }; expected.SetB(true); var toUnpack = new List<byte> { 0xA2, 0x81, 0x42, Markers.True, 0x81, 0x41, Markers.True }; var actual = Packers.Map.Unpack<SimpleClassWithPrivateProperty>(toUnpack.ToArray()); actual.ShouldBeEquivalentTo(expected); } [Fact] public void UnpacksDefinedClass_WithField() { var expected = new SimpleClassWithField {_a = true}; var toUnpack = new List<byte> {0xA1, 0x82, 0x5F, 0x61, Markers.True}; //1 fields var actual = Packers.Map.Unpack<SimpleClassWithField>(toUnpack.ToArray()); actual.ShouldBeEquivalentTo(expected); } [Fact] public void UnpPacksDefinedClassCorrectlyIgnoringBoltIgnoredProperties() { var expected = new SimpleClassWithBoltIgnoredProperty {A = true}; var toUnpack = new List<byte> {0xA1, 0x81, 0x41, Markers.True}.ToArray(); //1 fields var actual = Packers.Map.Unpack<SimpleClassWithBoltIgnoredProperty>(toUnpack); actual.ShouldBeEquivalentTo(expected); } [Fact] public void UnpacksSuccessMetaDataProperly() { var bytes = new byte[] {0xA1, 0x86, 0x66, 0x69, 0x65, 0x6C, 0x64, 0x73, 0x91, 0x81, 0x78}; var expected = new Dictionary<string, dynamic> {{"fields", new List<dynamic> {"x"}}}; var actual = Packers.Map.Unpack<Dictionary<string, dynamic>>(bytes); actual.Keys.Should().BeEquivalentTo(expected.Keys); Assert.Equal(actual.Values, expected.Values); } [Fact] public void UnpacksSuccessMetaDataProperlyAsString() { var bytes = new byte[] { 0xA1, 0x86, 0x66, 0x69, 0x65, 0x6C, 0x64, 0x73, 0x91, 0x81, 0x78 }; var expected = new Dictionary<string, IEnumerable<string>> { { "fields", new List<string> { "x" } } }; var actual = Packers.Map.Unpack<Dictionary<string, IEnumerable<string>>>(bytes); foreach (var kvp in expected) { actual.Keys.Should().Contain(kvp.Key); foreach (var val in kvp.Value) actual[kvp.Key].Should().Contain(val); } } [Fact(Skip = "To come back to")] public void UnpacksAnonymousCorrectly() { throw new NotImplementedException(); } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Graph.Test.Requests.Generated { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Graph; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; [TestClass] public class CollectionWithReferencesRequestTests : RequestTestBase { /// <summary> /// Tests building a request for an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void BuildRequest() { var expectedRequestUri = new Uri(string.Format(Constants.Url.GraphBaseUrlFormatString, "v1.0") + "/groups/groupId/members"); var membersCollectionRequestBuilder = this.graphServiceClient.Groups["groupId"].Members as GroupMembersCollectionWithReferencesRequestBuilder; Assert.IsNotNull(membersCollectionRequestBuilder, "Unexpected request builder."); Assert.AreEqual(expectedRequestUri, new Uri(membersCollectionRequestBuilder.RequestUrl), "Unexpected request URL."); var membersCollectionRequest = membersCollectionRequestBuilder.Request() as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(membersCollectionRequest, "Unexpected request."); Assert.AreEqual(expectedRequestUri, new Uri(membersCollectionRequest.RequestUrl), "Unexpected request URL."); } /// <summary> /// Tests the GetAsync() method on the request for an entity collection that has a $ref navigation. /// </summary> [TestMethod] public async Task GetAsync() { using (var httpResponseMessage = new HttpResponseMessage()) using (var responseStream = new MemoryStream()) using (var streamContent = new StreamContent(responseStream)) { httpResponseMessage.Content = streamContent; var nextQueryKey = "key"; var nextQueryValue = "value"; var requestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var nextPageRequestUrl = string.Format("{0}?{1}={2}", requestUrl, nextQueryKey, nextQueryValue); this.httpProvider.Setup( provider => provider.SendAsync( It.Is<HttpRequestMessage>( request => request.RequestUri.ToString().StartsWith(requestUrl) && request.Method == HttpMethod.Get), HttpCompletionOption.ResponseContentRead, CancellationToken.None)) .Returns(Task.FromResult(httpResponseMessage)); var membersCollectionPage = new GroupMembersCollectionWithReferencesPage { new User(), }; var membersCollectionResponse = new GroupMembersCollectionWithReferencesResponse { Value = membersCollectionPage, AdditionalData = new Dictionary<string, object> { { "@odata.nextLink", nextPageRequestUrl } }, }; this.serializer.Setup( serializer => serializer.DeserializeObject<GroupMembersCollectionWithReferencesResponse>(It.IsAny<string>())) .Returns(membersCollectionResponse); var returnedCollectionPage = await this.graphServiceClient.Groups["groupId"].Members.Request().GetAsync() as GroupMembersCollectionWithReferencesPage; Assert.IsNotNull(returnedCollectionPage, "Collection page not returned."); Assert.AreEqual(membersCollectionPage, returnedCollectionPage, "Unexpected collection page returned."); Assert.AreEqual( membersCollectionResponse.AdditionalData, returnedCollectionPage.AdditionalData, "Additional data not initialized on collection page."); var nextPageRequest = returnedCollectionPage.NextPageRequest as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(nextPageRequest, "Next page request not returned."); Assert.AreEqual(new Uri(requestUrl), new Uri(nextPageRequest.RequestUrl), "Unexpected URL initialized for next page request."); Assert.AreEqual(1, nextPageRequest.QueryOptions.Count, "Unexpected query options initialized."); Assert.AreEqual(nextQueryKey, nextPageRequest.QueryOptions[0].Name, "Unexpected query option name initialized."); Assert.AreEqual(nextQueryValue, nextPageRequest.QueryOptions[0].Value, "Unexpected query option value initialized."); } } #if false // This test can no longer run at this time since the Graph does not have a $ref navigation that allows expand. /// <summary> /// Tests the Expand() method on the request for an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Expand() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Expand("value") as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$expand", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("value", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #endif #if false // This test can no longer run at this time since the Graph does not have a $ref navigation that allows select. /// <summary> /// Tests the Select() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Select() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Select("value") as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$select", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("value", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #endif /// <summary> /// Tests the Top() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Top() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Top(1) as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$top", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("1", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #if false // This test can no longer run at this time since the Graph does not have a $ref navigation that allows filter. /// <summary> /// Tests the Filter() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Filter() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Filter("value") as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$filter", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("value", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #endif #if false // This test can no longer run at this time since the Graph does not have a $ref navigation that allows skip. /// <summary> /// Tests the Skip() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void Skip() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().Skip(1) as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$skip", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("1", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } #endif /// <summary> /// Tests the OrderBy() method on an entity collection that has a $ref navigation. /// </summary> [TestMethod] public void OrderBy() { var expectedRequestUrl = string.Format("{0}/groups/groupId/members", this.graphBaseUrl); var groupMembersRequest = this.graphServiceClient.Groups["groupId"].Members.Request().OrderBy("value") as GroupMembersCollectionWithReferencesRequest; Assert.IsNotNull(groupMembersRequest, "Unexpected request."); Assert.AreEqual(new Uri(expectedRequestUrl), new Uri(groupMembersRequest.RequestUrl), "Unexpected request URL."); Assert.AreEqual(1, groupMembersRequest.QueryOptions.Count, "Unexpected number of query options."); Assert.AreEqual("$orderby", groupMembersRequest.QueryOptions[0].Name, "Unexpected query option name."); Assert.AreEqual("value", groupMembersRequest.QueryOptions[0].Value, "Unexpected query option value."); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Threading; #pragma warning disable 618 namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; using DeltaEx = Apache.Geode.Client.Tests.DeltaEx; public class CqDeltaListener<TKey, TResult> : ICqListener<TKey, TResult> { public CqDeltaListener() { m_deltaCount = 0; m_valueCount = 0; } public void OnEvent(CqEvent<TKey, TResult> aCqEvent) { byte[] deltaValue = aCqEvent.getDeltaValue(); DeltaTestImpl newValue = new DeltaTestImpl(); DataInput input = new DataInput(deltaValue); newValue.FromDelta(input); if (newValue.GetIntVar() == 5) { m_deltaCount++; } DeltaTestImpl fullObject = (DeltaTestImpl)(object)aCqEvent.getNewValue(); if (fullObject.GetIntVar() == 5) { m_valueCount++; } } public void OnError(CqEvent<TKey, TResult> aCqEvent) { } public void Close() { } public int GetDeltaCount() { return m_deltaCount; } public int GetValueCount() { return m_valueCount; } private int m_deltaCount; private int m_valueCount; } public class DeltaTestAD : IGeodeDelta, IGeodeSerializable { private int _deltaUpdate; private string _staticData; public static DeltaTestAD Create() { return new DeltaTestAD(); } public DeltaTestAD() { _deltaUpdate = 1; _staticData = "Data which don't get updated"; } #region IGeodeDelta Members public void FromDelta(DataInput input) { _deltaUpdate = input.ReadInt32(); } public bool HasDelta() { _deltaUpdate++; bool isDelta = (_deltaUpdate % 2) == 1; Util.Log("In DeltaTestAD.HasDelta _deltaUpdate:" + _deltaUpdate + " : isDelta:" + isDelta); return isDelta; } public void ToDelta(DataOutput output) { output.WriteInt32(_deltaUpdate); } #endregion #region IGeodeSerializable Members public uint ClassId { get { return 151; } } public IGeodeSerializable FromData(DataInput input) { _deltaUpdate = input.ReadInt32(); _staticData = input.ReadUTF(); return this; } public uint ObjectSize { get { return (uint)(4 + _staticData.Length); } } public void ToData(DataOutput output) { output.WriteInt32(_deltaUpdate); output.WriteUTF(_staticData); } public int DeltaUpdate { get { return _deltaUpdate; } set { _deltaUpdate = value; } } #endregion } [TestFixture] [Category("group1")] [Category("unicast_only")] [Category("generics")] public class ThinClientDeltaTest : ThinClientRegionSteps { #region Private members private UnitProcess m_client1, m_client2; private CqDeltaListener<object, DeltaTestImpl> myCqListener; #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); return new ClientBase[] { m_client1, m_client2 }; } [TestFixtureTearDown] public override void EndTests() { CacheHelper.StopJavaServers(); base.EndTests(); } [TearDown] public override void EndTest() { try { CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } finally { CacheHelper.StopJavaServers(); CacheHelper.StopJavaLocators(); } base.EndTest(); } public void createLRURegionAndAttachPool(string regionName, string poolName) { CacheHelper.CreateLRUTCRegion_Pool<object, object>(regionName, true, true, null, null, poolName, false, 3); } public void createRegionAndAttachPool(string regionName, string poolName) { createRegionAndAttachPool(regionName, poolName, false); } public void createRegionAndAttachPool(string regionName, string poolName, bool cloningEnabled) { CacheHelper.CreateTCRegion_Pool<object, object>(regionName, true, true, null, null, poolName, false, false, cloningEnabled); } //public void createPooledRegion(string regionName, string poolName, string endpoints, string locators) //{ // CacheHelper.CreateTCRegion_Pool(regionName, true, true, null, endpoints, locators, poolName, false); //} public void createPool(string name, string locators, string serverGroup, int redundancy, bool subscription) { CacheHelper.CreatePool<object, object>(name, locators, serverGroup, redundancy, subscription); } public void createExpirationRegion(string name, string poolName) { IRegion<object, object> region = CacheHelper.CreateExpirationRegion<object, object>(name, poolName, ExpirationAction.LocalInvalidate, 5); } public void createExpirationRegion(string name) { createExpirationRegion(name, null); } public void CreateRegion(string name) { CreateRegion(name, false); } public void CreateRegion(string name, bool enableNotification) { CreateRegion(name, enableNotification, false); } public void CreateRegion(string name, bool enableNotification, bool cloningEnabled) { Apache.Geode.Client.RegionAttributes<object, object> attrs; AttributesFactory<object, object> attrFac = new AttributesFactory<object, object>(); attrFac.SetCacheListener(new SimpleCacheListener<object, object>()); attrFac.SetCloningEnabled(cloningEnabled); attrs = attrFac.CreateRegionAttributes(); CacheHelper.CreateRegion<object, object>(name, attrs); } //public void CreateOverflowRegion(string name, uint entriesLimit) //{ // AttributesFactory af = new AttributesFactory(); // af.SetScope(ScopeType.DistributedAck); // af.SetCachingEnabled(true); // af.SetClientNotificationEnabled(true); // af.SetLruEntriesLimit(entriesLimit);// LRU Entry limit set to 3 // af.SetDiskPolicy(DiskPolicyType.Overflows); // Properties bdbProperties = Properties.Create(); // bdbProperties.Insert("CacheSizeGb", "0"); // bdbProperties.Insert("CacheSizeMb", "512"); // bdbProperties.Insert("PageSize", "65536"); // bdbProperties.Insert("MaxFileSize", "512000000"); // String wdPath = Directory.GetCurrentDirectory(); // String absPersistenceDir = wdPath + "/absBDB"; // String absEnvDir = wdPath + "/absBDBEnv"; // bdbProperties.Insert("PersistenceDirectory", absPersistenceDir); // bdbProperties.Insert("EnvironmentDirectory", absEnvDir); // af.SetPersistenceManager("BDBImpl", "createBDBInstance", bdbProperties); // CacheHelper.CreateRegion(name, af.CreateRegionAttributes()); //} void DoPutWithDelta() { try { Serializable.RegisterTypeGeneric(DeltaEx.create); } catch (IllegalStateException) { //do nothng } string cKey = m_keys[0]; DeltaEx val = new DeltaEx(); IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); reg[cKey] = (object)val; val.SetDelta(true); reg[cKey] = (object)val; DeltaEx val1 = new DeltaEx(0); // In this case JAVA side will throw invalid DeltaException reg[cKey] = (object)val1; val1.SetDelta(true); reg[cKey] = (object)val1; if (DeltaEx.ToDeltaCount != 2) { Util.Log("DeltaEx.ToDataCount = " + DeltaEx.ToDataCount); Assert.Fail(" Delta count should have been 2, is " + DeltaEx.ToDeltaCount); } if (DeltaEx.ToDataCount != 3) Assert.Fail("Data count should have been 3, is " + DeltaEx.ToDataCount); DeltaEx.ToDeltaCount = 0; DeltaEx.ToDataCount = 0; DeltaEx.FromDataCount = 0; DeltaEx.FromDeltaCount = 0; } void Do_Put_Contains_Remove_WithDelta() { try { Serializable.RegisterTypeGeneric(DeltaEx.create); } catch (IllegalStateException) { //do nothng } string cKey = m_keys[0]; DeltaEx val = new DeltaEx(); IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); reg[cKey] = (object)val; val.SetDelta(true); reg[cKey] = (object)val; DeltaEx val1 = new DeltaEx(0); // In this case JAVA side will throw invalid DeltaException reg[cKey] = (object)val1; val1.SetDelta(true); reg[cKey] = (object)val1; if (DeltaEx.ToDeltaCount != 2) { Util.Log("DeltaEx.ToDataCount = " + DeltaEx.ToDataCount); Assert.Fail(" Delta count should have been 2, is " + DeltaEx.ToDeltaCount); } if (DeltaEx.ToDataCount != 3) Assert.Fail("Data count should have been 3, is " + DeltaEx.ToDataCount); DeltaEx.ToDeltaCount = 0; DeltaEx.ToDataCount = 0; DeltaEx.FromDataCount = 0; DeltaEx.FromDeltaCount = 0; // Try Contains with key & value that are present. Result should be true. KeyValuePair<object, object> myentry = new KeyValuePair<object, object>(cKey, val1); bool containsOpflag = reg.Contains(myentry); Assert.IsTrue(containsOpflag, "Result should be true as key & value are present"); // Try Remove with key & value that are present. Result should be true. bool removeOpflag = reg.Remove(cKey); Assert.IsTrue(removeOpflag, "Result should be true as key & value are present"); //Check Contains with removed entry. Result should be false. bool updatedcontainsOpflag = reg.Contains(myentry); Assert.IsFalse(updatedcontainsOpflag, "Result should be false as key & value are removed"); } void DoNotificationWithDelta() { try { Serializable.RegisterTypeGeneric(DeltaEx.create); } catch (IllegalStateException) { //do nothig. } string cKey = m_keys[0]; DeltaEx val = new DeltaEx(); IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); reg[cKey] = val; val.SetDelta(true); reg[cKey] = val; string cKey1 = m_keys[1]; DeltaEx val1 = new DeltaEx(); reg[cKey1] = val1; val1.SetDelta(true); reg[cKey1] = val1; DeltaEx.ToDeltaCount = 0; DeltaEx.ToDataCount = 0; } void DoNotificationWithDefaultCloning() { string cKey = m_keys[0]; DeltaTestImpl val = new DeltaTestImpl(); IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); reg[cKey] = val; val.SetIntVar(2); val.SetDelta(true); reg[cKey] = val; javaobject.PdxDelta pd = new javaobject.PdxDelta(1001); for (int i = 0; i < 10; i++) { reg["pdxdelta"] = pd; } } void DoNotificationWithDeltaLRU() { try { Serializable.RegisterTypeGeneric(DeltaEx.create); } catch (IllegalStateException) { //do nothig. } string cKey1 = "key1"; string cKey2 = "key2"; string cKey3 = "key3"; string cKey4 = "key4"; string cKey5 = "key5"; string cKey6 = "key6"; DeltaEx val1 = new DeltaEx(); DeltaEx val2 = new DeltaEx(); IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); reg[cKey1] = val1; reg[cKey2] = val1; reg[cKey3] = val1; reg[cKey4] = val1; reg[cKey5] = val1; reg[cKey6] = val1; val2.SetDelta(true); reg[cKey1] = val2; DeltaEx.ToDeltaCount = 0; DeltaEx.ToDataCount = 0; } void DoExpirationWithDelta() { try { Serializable.RegisterTypeGeneric(DeltaEx.create); } catch (IllegalStateException) { //do nothig. } DeltaEx val1 = new DeltaEx(); IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); reg[1] = val1; // Sleep 10 seconds to allow expiration of entry in client 2 Thread.Sleep(10000); val1.SetDelta(true); reg[1] = val1; DeltaEx.ToDeltaCount = 0; DeltaEx.ToDataCount = 0; } void DoCqWithDelta() { string cKey1 = "key1"; IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); DeltaTestImpl value = new DeltaTestImpl(); reg[cKey1] = value; value.SetIntVar(5); value.SetDelta(true); reg[cKey1] = value; } void initializeDeltaClientAD() { try { Serializable.RegisterTypeGeneric(DeltaTestAD.Create); } catch (IllegalStateException) { //do nothng } } void DoDeltaAD_C1_1() { DeltaTestAD val = new DeltaTestAD(); IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); reg.GetSubscriptionService().RegisterAllKeys(); Util.Log("clientAD1 put"); reg[1] = val; Util.Log("clientAD1 put done"); } void DoDeltaAD_C2_1() { IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); Util.Log("clientAD2 get"); DeltaTestAD val = (DeltaTestAD)reg[1]; Assert.AreEqual(2, val.DeltaUpdate); Util.Log("clientAD2 get done"); reg[1] = val; Util.Log("clientAD2 put done"); javaobject.PdxDelta pd = new javaobject.PdxDelta(1001); for (int i = 0; i < 10; i++) { reg["pdxdelta"] = pd; } } void DoDeltaAD_C1_afterC2Put() { Thread.Sleep(15000); DeltaTestAD val = null; IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); Util.Log("client fetching entry from local cache"); val = (DeltaTestAD)reg.GetEntry(1).Value; Assert.IsNotNull(val); Assert.AreEqual(3, val.DeltaUpdate); Util.Log("done"); System.Threading.Thread.Sleep(5000); //Assert.Greater(javaobject.PdxDelta.GotDelta, 7, "this should have recieve delta"); javaobject.PdxDelta pd = (javaobject.PdxDelta)(reg.GetLocalView()["pdxdelta"]); Assert.Greater(pd.Delta, 7, "this should have recieve delta"); } void runDeltaWithAppdomian(bool cloningenable) { CacheHelper.SetupJavaServers(true, "cacheserver_with_deltaAD.xml"); CacheHelper.StartJavaLocator(1, "GFELOC1"); CacheHelper.StartJavaServerWithLocators(1, "GFECS5", 1); string regionName = "DistRegionAck"; // if (usePools) { //CacheHelper.CreateTCRegion_Pool_AD("DistRegionAck", false, false, null, null, CacheHelper.Locators, "__TEST_POOL1__", false, false, false); m_client1.Call(CacheHelper.CreateTCRegion_Pool_AD1, regionName, false, true, CacheHelper.Locators, (string)"__TEST_POOL1__", true, cloningenable); m_client2.Call(CacheHelper.CreateTCRegion_Pool_AD1, regionName, false, true, CacheHelper.Locators, (string)"__TEST_POOL1__", false, cloningenable); // m_client1.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, false); // m_client1.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__"); } m_client1.Call(initializeDeltaClientAD); m_client2.Call(initializeDeltaClientAD); m_client1.Call(DoDeltaAD_C1_1); m_client2.Call(DoDeltaAD_C2_1); m_client1.Call(DoDeltaAD_C1_afterC2Put); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runPutWithDelta() { CacheHelper.SetupJavaServers(true, "cacheserver_with_delta.xml"); CacheHelper.StartJavaLocator(1, "GFELOC1"); CacheHelper.StartJavaServerWithLocators(1, "GFECS5", 1); m_client1.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, false); m_client1.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__"); m_client1.Call(DoPutWithDelta); m_client1.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runPut_Contains_Remove_WithDelta() { CacheHelper.SetupJavaServers(true, "cacheserver_with_delta.xml"); CacheHelper.StartJavaLocator(1, "GFELOC1"); CacheHelper.StartJavaServerWithLocators(1, "GFECS5", 1); m_client1.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, false); m_client1.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__"); m_client1.Call(Do_Put_Contains_Remove_WithDelta); m_client1.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void registerClassCl2() { try { Serializable.RegisterTypeGeneric(DeltaEx.create); } catch (IllegalStateException) { //do nothing } IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); reg.GetSubscriptionService().RegisterRegex(".*"); AttributesMutator<object, object> attrMutator = reg.AttributesMutator; attrMutator.SetCacheListener(new SimpleCacheListener<object, object>()); } void registerClassDeltaTestImpl() { try { Serializable.RegisterTypeGeneric(DeltaTestImpl.CreateDeserializable); } catch (IllegalStateException) { // ARB: ignore exception caused by type reregistration. } DeltaTestImpl.ResetDataCount(); Thread.Sleep(2000); IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); try { reg.GetSubscriptionService().RegisterRegex(".*"); } catch (Exception) { // ARB: ignore regex exception for missing notification channel. } } void registerCq() { Pool thePool = PoolManager.Find("__TEST_POOL1__"); QueryService<object, DeltaTestImpl> cqService = null; cqService = thePool.GetQueryService<object, DeltaTestImpl>(); CqAttributesFactory<object, DeltaTestImpl> attrFac = new CqAttributesFactory<object, DeltaTestImpl>(); myCqListener = new CqDeltaListener<object, DeltaTestImpl>(); attrFac.AddCqListener(myCqListener); CqAttributes<object, DeltaTestImpl> cqAttr = attrFac.Create(); CqQuery<object, DeltaTestImpl> theQuery = cqService.NewCq("select * from /DistRegionAck d where d.intVar > 4", cqAttr, false); theQuery.Execute(); } void VerifyDeltaCount() { Thread.Sleep(1000); Util.Log("Total Data count" + DeltaEx.FromDataCount); Util.Log("Total Data count" + DeltaEx.FromDeltaCount); if (DeltaEx.FromDataCount != 3) Assert.Fail("Count of fromData called should be 3 "); if (DeltaEx.FromDeltaCount != 2) Assert.Fail("Count of fromDelta called should be 2 "); if (SimpleCacheListener<object, object>.isSuccess == false) Assert.Fail("Listener failure"); SimpleCacheListener<object, object>.isSuccess = false; if (DeltaEx.CloneCount != 2) Assert.Fail("Clone count should be 2, is " + DeltaEx.CloneCount); DeltaEx.FromDataCount = 0; DeltaEx.FromDeltaCount = 0; DeltaEx.CloneCount = 0; } void VerifyCloning() { Thread.Sleep(1000); string cKey = m_keys[0]; IRegion<object, object> reg = CacheHelper.GetRegion<object, object>("DistRegionAck"); DeltaTestImpl val = reg[cKey] as DeltaTestImpl; if (val.GetIntVar() != 2) Assert.Fail("Int value after cloning should be 2, is " + val.GetIntVar()); if (DeltaTestImpl.GetFromDataCount() != 2) Assert.Fail("After cloning, fromDataCount should have been 2, is " + DeltaTestImpl.GetFromDataCount()); if (DeltaTestImpl.GetToDataCount() != 1) Assert.Fail("After cloning, toDataCount should have been 1, is " + DeltaTestImpl.GetToDataCount()); System.Threading.Thread.Sleep(5000); //Assert.Greater(javaobject.PdxDelta.GotDelta, 7, "this should have recieve delta"); javaobject.PdxDelta pd = (javaobject.PdxDelta)(reg.GetLocalView()["pdxdelta"]); Assert.Greater(pd.Delta, 7, "this should have recieve delta"); } void VerifyDeltaCountLRU() { Thread.Sleep(1000); if (DeltaEx.FromDataCount != 8) { Util.Log("DeltaEx.FromDataCount = " + DeltaEx.FromDataCount); Util.Log("DeltaEx.FromDeltaCount = " + DeltaEx.FromDeltaCount); Assert.Fail("Count should have been 8. 6 for common put and two when pulled from database and deserialized"); } if (DeltaEx.FromDeltaCount != 1) { Util.Log("DeltaEx.FromDeltaCount = " + DeltaEx.FromDeltaCount); Assert.Fail("Count should have been 1"); } DeltaEx.FromDataCount = 0; DeltaEx.FromDeltaCount = 0; } void VerifyCqDeltaCount() { // Wait for Cq event processing in listener Thread.Sleep(1000); if (myCqListener.GetDeltaCount() != 1) { Assert.Fail("Delta from CQ event does not have expected value"); } if (myCqListener.GetValueCount() != 1) { Assert.Fail("Value from CQ event is incorrect"); } } void VerifyExpirationDeltaCount() { Thread.Sleep(1000); if (DeltaEx.FromDataCount != 2) Assert.Fail("Count should have been 2."); if (DeltaEx.FromDeltaCount != 0) Assert.Fail("Count should have been 0."); DeltaEx.FromDataCount = 0; DeltaEx.FromDeltaCount = 0; } void runNotificationWithDelta() { CacheHelper.SetupJavaServers(true, "cacheserver_with_delta.xml"); CacheHelper.StartJavaLocator(1, "GFELOC1"); CacheHelper.StartJavaServerWithLocators(1, "GFECS5", 1); m_client1.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client1.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__", true); m_client2.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client2.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__", true); m_client2.Call(registerClassCl2); m_client1.Call(DoNotificationWithDelta); m_client2.Call(VerifyDeltaCount); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runNotificationWithDefaultCloning() { CacheHelper.SetupJavaServers(true, "cacheserver_with_delta_test_impl.xml"); CacheHelper.StartJavaLocator(1, "GFELOC1"); CacheHelper.StartJavaServerWithLocators(1, "GFECS5", 1); m_client1.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client1.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__", true); m_client2.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client2.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__", true); m_client1.Call(registerClassDeltaTestImpl); m_client2.Call(registerClassDeltaTestImpl); m_client1.Call(DoNotificationWithDefaultCloning); m_client2.Call(VerifyCloning); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runNotificationWithDeltaWithOverFlow() { CacheHelper.SetupJavaServers(true, "cacheserver_with_delta.xml"); CacheHelper.StartJavaLocator(1, "GFELOC1"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); m_client1.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client1.Call(createLRURegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__"); m_client2.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client2.Call(createLRURegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__"); m_client2.Call(registerClassCl2); m_client1.Call(DoNotificationWithDeltaLRU); m_client2.Call(VerifyDeltaCountLRU); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runCqWithDelta() { CacheHelper.SetupJavaServers(true, "cacheserver_with_delta_test_impl.xml"); CacheHelper.StartJavaLocator(1, "GFELOC1"); CacheHelper.StartJavaServerWithLocators(1, "GFECS5", 1); m_client1.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client1.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__"); m_client2.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client2.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__"); m_client1.Call(registerClassDeltaTestImpl); m_client2.Call(registerClassDeltaTestImpl); m_client2.Call(registerCq); m_client1.Call(DoCqWithDelta); m_client2.Call(VerifyCqDeltaCount); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } void runExpirationWithDelta() { CacheHelper.SetupJavaServers(true, "cacheserver_with_delta.xml"); CacheHelper.StartJavaLocator(1, "GFELOC1"); CacheHelper.StartJavaServerWithLocators(1, "GFECS5", 1); m_client1.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client1.Call(createRegionAndAttachPool, "DistRegionAck", "__TEST_POOL1__"); m_client2.Call(createPool, "__TEST_POOL1__", CacheHelper.Locators, (string)null, 0, true); m_client2.Call(createExpirationRegion, "DistRegionAck", "__TEST_POOL1__"); m_client2.Call(registerClassCl2); m_client1.Call(DoExpirationWithDelta); m_client2.Call(VerifyExpirationDeltaCount); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } //#region Tests [Test] public void PutWithDeltaAD() { runDeltaWithAppdomian(false); runDeltaWithAppdomian(true);//cloning enable } [Test] public void PutWithDelta() { runPutWithDelta(); } [Test] public void Put_Contains_Remove_WithDelta() { runPut_Contains_Remove_WithDelta(); } [Test] public void NotificationWithDelta() { runNotificationWithDelta(); } [Test] public void NotificationWithDefaultCloning() { runNotificationWithDefaultCloning(); } [Test] public void NotificationWithDeltaWithOverFlow() { runNotificationWithDeltaWithOverFlow(); } [Test] public void CqWithDelta() { runCqWithDelta(); } [Test] public void ExpirationWithDelta() { runExpirationWithDelta(); } //#endregion } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using EarLab.Utilities; namespace EarLab.Dialogs { /// <summary> /// Summary description for AnalysisDialogNew. /// </summary> public class AnalysisDialogNew : System.Windows.Forms.Form { private EarLab.Viewers.Layouts.Layout2DColorFull layout2DColor; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private double[,] dataArray; private MenuStrip menuStrip1; private ToolStripMenuItem fileToolStripMenuItem; private ToolStripMenuItem saveToolStripMenuItem; private ToolStripSeparator toolStripSeparator1; private ToolStripMenuItem closeToolStripMenuItem; private ToolStripMenuItem editToolStripMenuItem; private ToolStripMenuItem copyToolStripMenuItem; private ToolStripMenuItem toolsToolStripMenuItem; private ToolStripMenuItem toolTipsToolStripMenuItem; private SaveFileDialog saveFileDialog; private bool toolTipShow = false; public AnalysisDialogNew(double[,] dataArray, double[] axisArray, string[] axisNames) { // Required for Windows Form Designer support InitializeComponent(); this.dataArray = dataArray; this.layout2DColor.View(dataArray); this.layout2DColor.Layout2DColor.ColorbarPanel.SetMinMax(axisArray[4], axisArray[5], true); this.layout2DColor.Layout2DColor.ViewerAxisPanel.TopAxisLabel = axisNames[0]; this.layout2DColor.Layout2DColor.ViewerAxisPanel.LeftAxisLabel = axisNames[1]; this.layout2DColor.Layout2DColor.ViewerAxisPanel.LeftAxisStartValue = (float)axisArray[0]; this.layout2DColor.Layout2DColor.ViewerAxisPanel.LeftAxisEndValue = (float)axisArray[1]; this.layout2DColor.Layout2DColor.ViewerAxisPanel.LeftAxisMajorTickNumbersFormat = "0"; this.layout2DColor.Layout2DColor.ViewerAxisPanel.BottomAxisLabel = axisNames[2]; this.layout2DColor.Layout2DColor.ViewerAxisPanel.BottomAxisStartValue = (float)axisArray[2]; this.layout2DColor.Layout2DColor.ViewerAxisPanel.BottomAxisEndValue = (float)axisArray[3]; this.layout2DColor.Layout2DColor.ViewerAxisPanel.BottomAxisMajorTickNumbersFormat = "0.00e00"; this.layout2DColor.Layout2DColor.ColorbarAxisPanel.RightAxisLabel = axisNames[3]; this.layout2DColor.Layout2DColor.ColorbarAxisPanel.RightAxisStartValue = (float)axisArray[4]; this.layout2DColor.Layout2DColor.ColorbarAxisPanel.RightAxisEndValue = (float)axisArray[5]; this.layout2DColor.Layout2DColor.ViewerPanel.MouseMove += new MouseEventHandler(ViewerPanel_MouseMove); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Tool Tip Code private void ViewerPanel_MouseMove(object sender, MouseEventArgs e) { ToolTip toolTip = this.layout2DColor.Layout2DColor.ViewerPanel.ToolTip; Point mousePoint = new Point(e.X, e.Y); String tipString; if (e.Button == MouseButtons.None && this.toolTipShow) { int xIndex, yIndex; double xValue, yValue, dValue; dValue = this.layout2DColor.Layout2DColor.PointData(mousePoint, out xIndex, out yIndex); yValue = this.layout2DColor.Layout2DColor.ViewerAxisPanel.LeftAxisStartValue + (this.layout2DColor.Layout2DColor.ViewerAxisPanel.LeftAxisEndValue - this.layout2DColor.Layout2DColor.ViewerAxisPanel.LeftAxisStartValue) * ((float)yIndex / (dataArray.GetLength(1) - 1)); xValue = this.layout2DColor.Layout2DColor.ViewerAxisPanel.BottomAxisStartValue + (this.layout2DColor.Layout2DColor.ViewerAxisPanel.BottomAxisEndValue - this.layout2DColor.Layout2DColor.ViewerAxisPanel.BottomAxisStartValue) * ((float)xIndex / (dataArray.GetLength(0) - 1)); tipString = " Location: " + xValue.ToString(this.layout2DColor.Layout2DColor.ViewerAxisPanel.BottomAxisMajorTickNumbersFormat) + ", "; tipString += yValue.ToString(this.layout2DColor.Layout2DColor.ViewerAxisPanel.LeftAxisMajorTickNumbersFormat); tipString += "\nData Value: " + dValue.ToString("0.00e00"); toolTip.SetToolTip((Control)this.layout2DColor.Layout2DColor.ViewerPanel, tipString); toolTip.Active = true; } else { // hide the tool tip (it might have been showing toolTip.Active = false; } } private void tipMenuItem_Click(object sender, System.EventArgs e) { //if (this.tipMenuItem.Checked) // this.tipMenuItem.Checked = this.toolTipShow = false; //else // this.tipMenuItem.Checked = this.toolTipShow = true; } private Bitmap GetBitmap() { Application.DoEvents(); Graphics layoutGraphics = this.layout2DColor.CreateGraphics(); Bitmap layoutBitmap = new Bitmap(this.layout2DColor.ClientSize.Width, this.layout2DColor.ClientSize.Height, layoutGraphics); Graphics bitmapGraphics = Graphics.FromImage(layoutBitmap); IntPtr layoutDeviceContext = layoutGraphics.GetHdc(); IntPtr bitmapDeviceContext = bitmapGraphics.GetHdc(); NativeMethods.BitBlt(bitmapDeviceContext, 0, 0, this.layout2DColor.ClientSize.Width, this.layout2DColor.ClientSize.Height, layoutDeviceContext, 0, 0, 13369376); layoutGraphics.ReleaseHdc(layoutDeviceContext); bitmapGraphics.ReleaseHdc(bitmapDeviceContext); layoutGraphics.Dispose(); bitmapGraphics.Dispose(); return layoutBitmap; } #endregion #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(AnalysisDialogNew)); this.layout2DColor = new EarLab.Viewers.Layouts.Layout2DColorFull(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolTipsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // layout2DColor // this.layout2DColor.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.layout2DColor.Location = new System.Drawing.Point(0, 27); this.layout2DColor.Name = "layout2DColor"; this.layout2DColor.Size = new System.Drawing.Size(648, 315); this.layout2DColor.TabIndex = 0; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.toolsToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(648, 24); this.menuStrip1.TabIndex = 1; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.saveToolStripMenuItem, this.toolStripSeparator1, this.closeToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // saveToolStripMenuItem // this.saveToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripMenuItem.Image"))); this.saveToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveToolStripMenuItem.Size = new System.Drawing.Size(147, 22); this.saveToolStripMenuItem.Text = "&Save"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(144, 6); // // closeToolStripMenuItem // this.closeToolStripMenuItem.Name = "closeToolStripMenuItem"; this.closeToolStripMenuItem.Size = new System.Drawing.Size(147, 22); this.closeToolStripMenuItem.Text = "Close"; this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.copyToolStripMenuItem}); this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.editToolStripMenuItem.Text = "&Edit"; // // copyToolStripMenuItem // this.copyToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripMenuItem.Image"))); this.copyToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Magenta; this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C))); this.copyToolStripMenuItem.Size = new System.Drawing.Size(149, 22); this.copyToolStripMenuItem.Text = "&Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click); // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolTipsToolStripMenuItem}); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.toolsToolStripMenuItem.Text = "&Tools"; // // toolTipsToolStripMenuItem // this.toolTipsToolStripMenuItem.CheckOnClick = true; this.toolTipsToolStripMenuItem.Name = "toolTipsToolStripMenuItem"; this.toolTipsToolStripMenuItem.Size = new System.Drawing.Size(124, 22); this.toolTipsToolStripMenuItem.Text = "ToolTips"; this.toolTipsToolStripMenuItem.Click += new System.EventHandler(this.toolTipsToolStripMenuItem_Click); // // saveFileDialog // this.saveFileDialog.Filter = resources.GetString("saveFileDialog.Filter"); this.saveFileDialog.Title = "Save File..."; // // AnalysisDialogNew // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(648, 342); this.Controls.Add(this.layout2DColor); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.MinimumSize = new System.Drawing.Size(650, 360); this.Name = "AnalysisDialogNew"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Data Analysis"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void toolTipsToolStripMenuItem_Click(object sender, EventArgs e) { this.toolTipShow = this.toolTipsToolStripMenuItem.Checked; } private void closeToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { if (this.saveFileDialog.ShowDialog() == DialogResult.OK) { System.Drawing.Imaging.ImageFormat imageFormat; switch (saveFileDialog.FilterIndex) { case 2: imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; break; case 3: imageFormat = System.Drawing.Imaging.ImageFormat.Gif; break; case 4: imageFormat = System.Drawing.Imaging.ImageFormat.Png; break; case 5: imageFormat = System.Drawing.Imaging.ImageFormat.Tiff; break; default: imageFormat = System.Drawing.Imaging.ImageFormat.Bmp; break; } Bitmap saveBitmap = this.GetBitmap(); saveBitmap.Save(saveFileDialog.FileName, imageFormat); } } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { Bitmap copyBitmap = this.GetBitmap(); Clipboard.SetImage(copyBitmap); } } }
// 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 gcnv = Google.Cloud.Notebooks.V1; using sys = System; namespace Google.Cloud.Notebooks.V1 { /// <summary>Resource name for the <c>Environment</c> resource.</summary> public sealed partial class EnvironmentName : gax::IResourceName, sys::IEquatable<EnvironmentName> { /// <summary>The possible contents of <see cref="EnvironmentName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/environments/{environment}</c>.</summary> ProjectEnvironment = 1, } private static gax::PathTemplate s_projectEnvironment = new gax::PathTemplate("projects/{project}/environments/{environment}"); /// <summary>Creates a <see cref="EnvironmentName"/> 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="EnvironmentName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static EnvironmentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new EnvironmentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="EnvironmentName"/> with the pattern <c>projects/{project}/environments/{environment}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="EnvironmentName"/> constructed from the provided ids.</returns> public static EnvironmentName FromProjectEnvironment(string projectId, string environmentId) => new EnvironmentName(ResourceNameType.ProjectEnvironment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="EnvironmentName"/> with pattern /// <c>projects/{project}/environments/{environment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EnvironmentName"/> with pattern /// <c>projects/{project}/environments/{environment}</c>. /// </returns> public static string Format(string projectId, string environmentId) => FormatProjectEnvironment(projectId, environmentId); /// <summary> /// Formats the IDs into the string representation of this <see cref="EnvironmentName"/> with pattern /// <c>projects/{project}/environments/{environment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EnvironmentName"/> with pattern /// <c>projects/{project}/environments/{environment}</c>. /// </returns> public static string FormatProjectEnvironment(string projectId, string environmentId) => s_projectEnvironment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId))); /// <summary>Parses the given resource name string into a new <see cref="EnvironmentName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/environments/{environment}</c></description></item> /// </list> /// </remarks> /// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="EnvironmentName"/> if successful.</returns> public static EnvironmentName Parse(string environmentName) => Parse(environmentName, false); /// <summary> /// Parses the given resource name string into a new <see cref="EnvironmentName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/environments/{environment}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="environmentName">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="EnvironmentName"/> if successful.</returns> public static EnvironmentName Parse(string environmentName, bool allowUnparsed) => TryParse(environmentName, allowUnparsed, out EnvironmentName 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="EnvironmentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/environments/{environment}</c></description></item> /// </list> /// </remarks> /// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="EnvironmentName"/>, 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 environmentName, out EnvironmentName result) => TryParse(environmentName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EnvironmentName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/environments/{environment}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="environmentName">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="EnvironmentName"/>, 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 environmentName, bool allowUnparsed, out EnvironmentName result) { gax::GaxPreconditions.CheckNotNull(environmentName, nameof(environmentName)); gax::TemplatedResourceName resourceName; if (s_projectEnvironment.TryParseName(environmentName, out resourceName)) { result = FromProjectEnvironment(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(environmentName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private EnvironmentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string environmentId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; EnvironmentId = environmentId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="EnvironmentName"/> class from the component parts of pattern /// <c>projects/{project}/environments/{environment}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> public EnvironmentName(string projectId, string environmentId) : this(ResourceNameType.ProjectEnvironment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId))) { } /// <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>Environment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EnvironmentId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectEnvironment: return s_projectEnvironment.Expand(ProjectId, EnvironmentId); 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 EnvironmentName); /// <inheritdoc/> public bool Equals(EnvironmentName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(EnvironmentName a, EnvironmentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(EnvironmentName a, EnvironmentName b) => !(a == b); } public partial class Environment { /// <summary> /// <see cref="gcnv::EnvironmentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcnv::EnvironmentName EnvironmentName { get => string.IsNullOrEmpty(Name) ? null : gcnv::EnvironmentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // //#define COMPUTECALLSCLOSURE_FORCE_SINGLE_THREADED namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public interface ICallClosureComputationTarget { void ExpandClosure( ComputeCallsClosure.Context host ); } public sealed class ComputeCallsClosure { public delegate void Notification( Context host, Operator op ); public class Context { // // State // private readonly ComputeCallsClosure m_owner; private readonly TypeSystem.Reachability m_reachabilitySet; // // Constructor Methods // internal Context( ComputeCallsClosure owner , TypeSystem.Reachability reachabilitySet ) { m_owner = owner; m_reachabilitySet = reachabilitySet; } // // Helper Methods // internal void ProcessMethod( MethodRepresentation md ) { CoverObject( md ); ControlFlowGraphStateForCodeTransformation cfg = TypeSystemForCodeTransformation.GetCodeForMethod( md ); if(cfg != null) { Transformations.ScanCodeWithCallback.Execute( m_owner.m_typeSystem, this, cfg, delegate( Operator op, object target ) { if(target != null) { MethodRepresentation mdTarget = target as MethodRepresentation; if(mdTarget != null) { m_owner.QueueMethodForProcessing( mdTarget ); } CoverObject( target ); if(target is Operator) { Operator opTarget = (Operator)target; Type type = opTarget.GetType(); while(type != null) { List< Notification > lst; if(m_owner.m_delegation.TryGetValue( type, out lst )) { foreach(Notification dlg in lst) { dlg( this, opTarget ); } } type = type.BaseType; } CallOperator call = opTarget as CallOperator; if(call != null) { m_owner.m_callsDatabase.RegisterCallSite( call ); } var tdCodePointer = m_owner.m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_CodePointer; foreach(var ex in opTarget.Arguments) { var exConst = ex as ConstantExpression; if(exConst != null && exConst.Type == tdCodePointer) { var od = (DataManager.ObjectDescriptor)exConst.Value; if(od != null) { var cp = (CodePointer)od.Source; var mdDelegate = m_owner.m_typeSystem.DataManagerInstance.GetCodePointerFromUniqueID( cp.Target ); CoverObject( mdDelegate ); } } } } } return Transformations.ScanCodeWithCallback.CallbackResult.Proceed; } ); } } public void CoverObject( object obj ) { if(obj == null) return; if(obj is MethodRepresentation) { CoverMethod( (MethodRepresentation)obj ); } else if(obj is FieldRepresentation) { CoverField( (FieldRepresentation)obj ); } else if(obj is TypeRepresentation) { CoverType( (TypeRepresentation)obj ); } else if(obj is AssemblyRepresentation) { CoverAssembly( (AssemblyRepresentation)obj ); } else if(obj is CustomAttributeRepresentation) { CoverCustomAttribute( (CustomAttributeRepresentation)obj ); } else if(obj is CustomAttributeAssociationRepresentation) { CoverCustomAttributeAssociation( (CustomAttributeAssociationRepresentation)obj ); } else if(obj is ICallClosureComputationTarget) { ICallClosureComputationTarget itf = (ICallClosureComputationTarget)obj; itf.ExpandClosure( this ); } else { m_reachabilitySet.ExpandPending( obj ); } } private void CoverReflectionType( object obj ) { TypeRepresentation td = m_owner.m_typeSystem.TryGetTypeRepresentationFromType( obj.GetType() ); if(td != null) { CoverType( td ); } } private void CoverAssembly( AssemblyRepresentation asml ) { m_reachabilitySet.ExpandPending( asml ); } private void CoverType( TypeRepresentation td ) { while(td != null) { if(m_reachabilitySet.ExpandPending( td )) { break; } CoverReflectionType( td ); CoverAssembly( td.Owner ); CoverType( td.Extends ); CoverType( td.EnclosingClass ); // // If a generic type, include the context. // TypeRepresentation.GenericContext gc = td.Generic; if(gc != null) { CoverType( gc.Template ); foreach(TypeRepresentation td2 in gc.Parameters) { CoverType( td2 ); } GenericParameterDefinition[] parametersDefinition = gc.ParametersDefinition; if(parametersDefinition != null) { for(int i = 0; i < parametersDefinition.Length; i++) { foreach(TypeRepresentation constraint in parametersDefinition[i].Constraints) { CoverType( constraint ); } } } } // // These are weird objects, because they actually contain a use of themselves in their definition. // We want to keep the fields alive, so that the size computation doesn't generate the wrong values. // if(td is ScalarTypeRepresentation) { foreach(FieldRepresentation fd in td.Fields) { if(fd is InstanceFieldRepresentation) { CoverField( fd ); } } } if(td is ArrayReferenceTypeRepresentation) { // // Keep alive also the managed pointer to the elements of the array, it will be used later. // CoverType( m_owner.m_typeSystem.GetManagedPointerToType( td.ContainedType ) ); } // // For a non-pointer type, keep alive any associated pointer type. // if(!(td is PointerTypeRepresentation)) { foreach(TypeRepresentation td2 in m_owner.m_typeSystem.Types) { PointerTypeRepresentation ptr = td2 as PointerTypeRepresentation; if(ptr != null && ptr.ContainedType == td) { CoverType( ptr ); } } } // // Look for all the fields, if they have an "AssumeReferenced" attribute, force them to be included. // { TypeRepresentation tdAttrib = m_owner.m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_TypeSystem_AssumeReferencedAttribute; foreach(FieldRepresentation fd in td.Fields) { if(fd.HasCustomAttribute( tdAttrib )) { CoverField( fd ); } } } // // Look for all the methods that are marked as exception handlers and include them. // { var heh = m_owner.m_typeSystem.HardwareExceptionHandlers; foreach(MethodRepresentation md in td.Methods) { CustomAttributeRepresentation ca; if(heh.TryGetValue( md, out ca )) { CoverMethod ( md ); CoverCustomAttribute( ca ); } } } // // Look for all the methods that are marked as debugger handlers and include them. // { var dhh = m_owner.m_typeSystem.DebuggerHookHandlers; foreach(MethodRepresentation md in td.Methods) { CustomAttributeRepresentation ca; if(dhh.TryGetValue( md, out ca )) { CoverMethod ( md ); CoverCustomAttribute( ca ); } } } td = td.ContainedType; } } private void CoverField( FieldRepresentation fd ) { if(fd == null) return; if(m_reachabilitySet.ExpandPending( fd )) { return; } CoverReflectionType( fd ); CoverType( fd.OwnerType ); CoverType( fd.FieldType ); if(fd is StaticFieldRepresentation) { StaticFieldRepresentation fdS = (StaticFieldRepresentation)fd; CoverField( fdS.ImplementedBy ); CoverStaticConstructor( fdS ); } if(fd is InstanceFieldRepresentation) { InstanceFieldRepresentation fdI = (InstanceFieldRepresentation)fd; CoverField( fdI.ImplementationOf ); CoverStaticConstructor( fdI.ImplementationOf ); } } private void CoverStaticConstructor( StaticFieldRepresentation fd ) { if(fd == null) return; StaticConstructorMethodRepresentation md = fd.OwnerType.FindDefaultStaticConstructor(); if(md != null) { CoverMethod( md ); CoverMethod( m_owner.m_typeSystem.WellKnownMethods.TypeSystemManager_InvokeStaticConstructors ); } } private void CoverMethod( MethodRepresentation md ) { if(md == null) return; if(m_reachabilitySet.ExpandPending( md )) { return; } CoverReflectionType( md ); m_owner.QueueMethodForProcessing( md ); // // If a generic method, include the context. // MethodRepresentation.GenericContext gc = md.Generic; if(gc != null) { CoverMethod( gc.Template ); foreach(TypeRepresentation td in gc.Parameters) { CoverType( td ); } GenericParameterDefinition[] parametersDefinition = gc.ParametersDefinition; if(parametersDefinition != null) { for(int i = 0; i < parametersDefinition.Length; i++) { foreach(TypeRepresentation constraint in parametersDefinition[i].Constraints) { CoverType( constraint ); } } } } CoverType( md.OwnerType ); CoverType( md.ReturnType ); foreach(TypeRepresentation td in md.ThisPlusArguments) { CoverType( td ); } /// /// For imported methods we need to make sure that any passed structures are preserved. /// The type system reduction phase will attempt to remove member fields if they are /// not used or covered here which will leave them with a different signature/size than /// the native imported method is expecting. /// if(0 != ( md.BuildTimeFlags & MethodRepresentation.BuildTimeAttributes.Imported )) { foreach(CustomAttributeAssociationRepresentation caa in md.CustomAttributes) { CoverCustomAttributeAssociation( caa ); } HashSet<TypeRepresentation> importTypes = new HashSet<TypeRepresentation>(); foreach(TypeRepresentation tr in md.ThisPlusArguments) { // Make imported structures do not lose members during type system reduction if( tr.BuiltInType == TypeRepresentation.BuiltInTypes.BYREF && tr.UnderlyingType.BuiltInType == TypeRepresentation.BuiltInTypes.VALUETYPE ) { CoverImportedDataType( tr.UnderlyingType, importTypes ); } // also check for arrays of structs else if( tr.BuiltInType == TypeRepresentation.BuiltInTypes.ARRAY && tr.ContainedType.BuiltInType == TypeRepresentation.BuiltInTypes.VALUETYPE ) { CoverImportedDataType( tr.ContainedType, importTypes ); } } } } /// <summary> /// Cover all fields from an imported structure so that its size/signature remains consistent. /// </summary> /// <param name="tr"></param> /// <param name="coveredTypes"></param> private void CoverImportedDataType( TypeRepresentation tr, HashSet<TypeRepresentation> coveredTypes ) { if(coveredTypes.Contains( tr )) return; coveredTypes.Add( tr ); CoverType( tr ); foreach(FieldRepresentation fr in tr.Fields) { CoverField( fr ); CoverImportedDataType( fr.FieldType, coveredTypes ); } } private void CoverCustomAttribute( CustomAttributeRepresentation ca ) { if(ca == null) return; if(m_reachabilitySet.ExpandPending( ca )) { return; } CoverReflectionType( ca ); CoverMethod( ca.Constructor ); } private void CoverCustomAttributeAssociation( CustomAttributeAssociationRepresentation caa ) { if(caa == null) return; if(m_reachabilitySet.ExpandPending( caa )) { return; } CoverReflectionType( caa ); CoverObject( caa.Target ); CoverObject( caa.CustomAttribute ); } //--// internal void IncludeGeneric( object obj ) { CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( obj ) == false, "Found use of '{0}' after the entity was marked illegal to use", obj ); if(obj is TypeRepresentation) { Include( (TypeRepresentation)obj ); } else if(obj is TypeRepresentation.GenericContext) { Include( (TypeRepresentation.GenericContext)obj ); } else if(obj is FieldRepresentation) { Include( (FieldRepresentation)obj ); } else if(obj is MethodRepresentation) { Include( (MethodRepresentation)obj ); } else if(obj is MethodRepresentation.GenericContext) { Include( (MethodRepresentation.GenericContext)obj ); } else if(obj is CustomAttributeRepresentation) { Include( (CustomAttributeRepresentation)obj ); } else if(obj is VTable) { Include( (VTable)obj ); } else if(obj is DataManager.DataDescriptor) { Include( (DataManager.DataDescriptor)obj ); } } private void Include( TypeRepresentation td ) { CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( td ) == false, "Found use of '{0}' after the entity was marked illegal to use", td ); CoverType( td ); //--// TypeRepresentation tdSystem_Attribute = m_owner.m_typeSystem.WellKnownTypes.System_Attribute; if(tdSystem_Attribute != null && tdSystem_Attribute.IsSuperClassOf( td, null )) { // // If we touch an attribute, make sure all the constructor methods used by actual instances are touched. // m_owner.m_typeSystem.EnumerateCustomAttributes( delegate( CustomAttributeAssociationRepresentation caa ) { CustomAttributeRepresentation ca = caa.CustomAttribute; MethodRepresentation mdCa = ca .Constructor; if(mdCa.OwnerType == td) { // // BUGBUG: The named arguments are not included! // if(m_reachabilitySet.Contains( mdCa ) == false) { CoverMethod( mdCa ); } } } ); } //--// // // Include all the concrete subclasses, because we need at least one implementation. // if(td.HasBuildTimeFlag( TypeRepresentation.BuildTimeAttributes.ForceDevirtualization )) { var list = m_owner.m_typeSystem.CollectConcreteImplementations(td); foreach (var td2 in list) { CoverType(td2); } } //--// // // Since call closure has reached a new type, make sure that all the overrides to already touched virtual methods are included. // foreach(MethodRepresentation md in td.Methods) { if(md is VirtualMethodRepresentation && md.IsOpenMethod == false && td.IsOpenType == false && m_reachabilitySet.Contains( md ) == false) { int index = md.FindVirtualTableIndex(); if(index == -1) { continue; } MethodRepresentation mdRoot = md; TypeRepresentation tdRoot = td; while((mdRoot.Flags & MethodRepresentation.Attributes.NewSlot) == 0) { tdRoot = tdRoot.Extends; if(tdRoot == null) break; mdRoot = tdRoot.MethodTable[index]; if(m_reachabilitySet.Contains( mdRoot )) { CoverMethod( md ); break; } } } } // // Also, include the methods associated with already touched interfaces. // foreach(TypeRepresentation.InterfaceMap map in td.InterfaceMaps) { if(m_reachabilitySet.Contains( map.Interface )) { MethodRepresentation[] mdOverride = map.Methods; MethodRepresentation[] mdDeclaration = map.Interface.FindInterfaceTable( map.Interface ); for(int i = 0; i < mdDeclaration.Length; i++) { if(m_reachabilitySet.Contains( mdDeclaration[i] )) { if(m_reachabilitySet.Contains( mdOverride[i] ) == false) { CoverMethod( mdOverride[i] ); } } } } } } private void Include( TypeRepresentation.GenericContext ctx ) { if(ctx.Template != null) { Include( ctx.Template ); } foreach(TypeRepresentation td in ctx.Parameters) { Include( td ); } if(ctx.ParametersDefinition != null) { foreach(GenericParameterDefinition def in ctx.ParametersDefinition) { foreach(TypeRepresentation td in def.Constraints) { Include( td ); } } } } private void Include( FieldRepresentation fd ) { CHECKS.ASSERT( m_reachabilitySet.Contains( fd.OwnerType ), "ComputeCallsClosure.GlobalReachabilitySet does not contain '{0}', although it should", fd.OwnerType ); CoverField( fd ); } private void Include( MethodRepresentation md ) { CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( md ) == false, "Found use of '{0}' after the entity was marked illegal to use", md ); CHECKS.ASSERT( m_owner.m_pendingHistory.Contains( md ), "ComputeCallsClosure.EntitiesReferencedByMethod does not contain '{0}', although it should", md ); CHECKS.ASSERT( m_reachabilitySet.Contains( md.OwnerType ), "ComputeCallsClosure.GlobalReachabilitySet does not contain '{0}', although it should", md.OwnerType ); CoverMethod( md ); if(md is VirtualMethodRepresentation && !(md is FinalMethodRepresentation)) { // // Include all the overrides for this method in all the subclasses already reached by the closure computation. // int index = md.FindVirtualTableIndex(); TypeRepresentation td = md.OwnerType; List< TypeRepresentation > lst; if(m_owner.m_typeSystem.DirectDescendant.TryGetValue( td, out lst )) { foreach(TypeRepresentation td2 in lst) { MethodRepresentation md2 = td2.MethodTable[index]; if(m_reachabilitySet.Contains( md2.OwnerType )) { CoverMethod( md2 ); } } } // // A virtual method defines a slot when it's first introduced. // Make sure all the methods from this one up to the root of the override tree are included. // MethodRepresentation mdRoot = md; while((mdRoot.Flags & MethodRepresentation.Attributes.NewSlot) == 0) { td = td.Extends; if(td == null) break; mdRoot = td.MethodTable[index]; if(m_reachabilitySet.Contains( mdRoot ) == false) { CoverMethod( mdRoot ); } } //--// // // The method belongs to an interface, we have to include all the implementations in all the touched types. // if(td is InterfaceTypeRepresentation) { InterfaceTypeRepresentation itf = (InterfaceTypeRepresentation)td; int itfIndex = md.FindInterfaceTableIndex(); foreach(TypeRepresentation td2 in m_owner.m_typeSystem.InterfaceImplementors[itf]) { if(m_reachabilitySet.Contains( td2 )) { MethodRepresentation mdOverride = td2.FindInterfaceTable( itf )[itfIndex]; if(m_reachabilitySet.Contains( mdOverride ) == false) { CoverMethod( mdOverride ); } } } } } } private void Include( MethodRepresentation.GenericContext ctx ) { Include( ctx.Template ); foreach(TypeRepresentation td in ctx.Parameters) { Include( td ); } if(ctx.ParametersDefinition != null) { foreach(GenericParameterDefinition def in ctx.ParametersDefinition) { foreach(TypeRepresentation td in def.Constraints) { Include( td ); } } } } private void Include( CustomAttributeRepresentation ca ) { CHECKS.ASSERT( m_owner.m_typeSystem.IsUseProhibited( ca ) == false, "Found use of '{0}' after the entity was marked illegal to use", ca ); CoverCustomAttribute( ca ); } private void Include( VTable vTable ) { Include( vTable.TypeInfo ); } private void Include( DataManager.DataDescriptor dd ) { lock(m_owner.m_delayedExpansion) { m_owner.m_delayedExpansion.Insert( dd ); } } internal bool Contains( object obj ) { return m_reachabilitySet.Contains( obj ); } //--// // // Access Methods // public TypeSystemForCodeTransformation TypeSystem { get { return m_owner.m_typeSystem; } } internal TypeSystem.Reachability ReachabilitySet { get { return m_reachabilitySet; } } } // // State // private readonly TypeSystemForCodeTransformation m_typeSystem; private readonly CallsDataBase m_callsDatabase; private readonly PhaseDriver m_phase; private readonly GrowOnlyHashTable< Type, List< Notification > > m_delegation; private readonly GrowOnlySet < DataManager.DataDescriptor > m_delayedExpansion; private readonly GrowOnlySet < MethodRepresentation > m_pendingHistory; private readonly Queue < MethodRepresentation > m_pending; private readonly Context m_globalContext; private readonly GrowOnlyHashTable< MethodRepresentation, GrowOnlySet< object > > m_entitiesReferencedByMethods; // // Constructor Methods // public ComputeCallsClosure( TypeSystemForCodeTransformation typeSystem , DelegationCache cache , CallsDataBase callsDatabase , PhaseDriver phase , bool fCollectPerMethodInfo ) { m_typeSystem = typeSystem; m_callsDatabase = callsDatabase; m_phase = phase; m_delegation = HashTableFactory.New < Type, List< Notification > >(); m_delayedExpansion = SetFactory .NewWithReferenceEquality< DataManager.DataDescriptor >(); m_pendingHistory = SetFactory .NewWithReferenceEquality< MethodRepresentation >(); m_pending = new Queue < MethodRepresentation >(); m_globalContext = new Context( this, typeSystem.ReachabilitySet ); if(fCollectPerMethodInfo) { m_entitiesReferencedByMethods = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, GrowOnlySet< object > >(); } typeSystem.ReachabilitySet.RestartComputation(); cache.HookNotifications( typeSystem, this, phase ); } // // Helper Methods // public void Execute( MethodRepresentation mdStart ) { if(m_globalContext.Contains( mdStart ) == false) { QueueMethodForProcessing( mdStart ); ProcessInner(); } } public void Expand( object val ) { m_globalContext.CoverObject( val ); ProcessInner(); } public void ExpandContents< TKey, TValue >( GrowOnlyHashTable< TKey, TValue > ht ) { foreach(TKey key in ht.Keys) { Expand( key ); Expand( ht[key] ); } } public void ExpandValueIfKeyIsReachable< TKey, TValue >( GrowOnlyHashTable< TKey, TValue > ht ) { foreach(TKey key in ht.Keys) { if(m_globalContext.Contains( key )) { Expand( ht[key] ); } } } //--// private void QueueMethodForProcessing( MethodRepresentation md ) { lock(m_pendingHistory) { if(m_pendingHistory.Insert( md ) == true) { return; } } lock(m_pending) { m_pending.Enqueue( md ); } } private void ProcessInner() { while(IsThereWorkToDo()) { ProcessMethods(); ProcessDataDescriptors(); } } private bool IsThereWorkToDo() { if(m_pending.Count > 0) { return true; } if(m_globalContext.ReachabilitySet.HasPendingItems()) { return true; } return false; } private void Analyze( MethodRepresentation md ) { m_globalContext.ProcessMethod( md ); if(m_entitiesReferencedByMethods != null) { GrowOnlySet< object > entitiesReferencedByMethod; lock(m_entitiesReferencedByMethods) { if(m_entitiesReferencedByMethods.ContainsKey( md )) return; entitiesReferencedByMethod = SetFactory.NewWithWeakEquality< object >(); m_entitiesReferencedByMethods[md] = entitiesReferencedByMethod; } var currentMethodReachabilitySet = TypeSystemForCodeTransformation.Reachability.CreateForUpdate( entitiesReferencedByMethod ); Context ctx = new Context( this, currentMethodReachabilitySet ); ctx.ProcessMethod( md ); } } private void ProcessMethods() { using(ParallelTransformationsHandler handler = new ParallelTransformationsHandler( Analyze )) { while(true) { DrainIncrementalSet(); if(m_pending.Count == 0) { break; } var methods = m_pending.ToArray(); m_pending.Clear(); #if COMPUTECALLSCLOSURE_FORCE_SINGLE_THREADED foreach(var md in methods) { Analyze( md ); } #else foreach(var md in methods) { handler.Queue( md ); } handler.Synchronize(); #endif } } } private void DrainIncrementalSet() { while(true) { object[] set = m_globalContext.ReachabilitySet.ApplyPendingSet( true ); if(set == null) { break; } foreach(object obj in set) { m_globalContext.IncludeGeneric( obj ); } } } private void ProcessDataDescriptors() { TypeSystem.Reachability reachability = m_globalContext.ReachabilitySet.CloneForIncrementalUpdate(); foreach(DataManager.DataDescriptor dd in m_delayedExpansion) { if(reachability.Contains( dd )) { dd.IncludeExtraTypes( reachability, m_phase ); } } object[] set = reachability.ApplyPendingSet( false ); if(set != null) { foreach(object obj in set) { m_globalContext.CoverObject( obj ); } } } //--// public void RegisterForNotification( Type type , Notification notification ) { HashTableWithListFactory.AddUnique( m_delegation, type, notification ); } //--// // // Access Methods // public TypeSystemForCodeTransformation TypeSystem { get { return m_typeSystem; } } public GrowOnlyHashTable< MethodRepresentation, GrowOnlySet< object > > EntitiesReferencedByMethods { get { return m_entitiesReferencedByMethods; } } } }
using MasterLogFile; //Todo: Add last rendered timestamps? namespace MasterChaosDisplay { //This will be the base for Mandlebrot, Julia, Sierpenski, Buddhabrot, etc. class ChaosEngine : PassThroughLoggedClass { //The total number of rendered points private long _TotalPointsRendered; //This is TRUE when Rendering. Stops a lot of things from working when set. private bool _Rendering; //This is a list of parameters for this engine. protected ChaosEngineParameterList _EngineParameters; //The default parameters using Param_PARAMETERNAME as the nomenclature private double _Param_XMin; private double _Param_YMin; private double _Param_XMax; private double _Param_YMax; private int _Param_ScreenColorCount; //The color count for the current Render. //This stuff is used in the dynamically recompiling rendering logic private double _RenderingRatio; //Screen to chaos space ratio private double _RenderingQuality; //The "quality" of the render. 1 is lowest, or in general a 1 to 1 mapping of points public ChaosEngine() { //Make sure the rendering subsystem is explicitly off this._Rendering = false; //Reset the count of rendered points. this._TotalPointsRendered = 0; this._EngineParameters = new ChaosEngineParameterList(); //There are a few parameters that ALWAYS are required in a paramlist this._EngineParameters.AddParameter ( "XMin", "X Minimum", "The left edge X Value in Chaos space, which is translated to the origin of the screen render device.", "Chaos Space X Minimum", "Float", "-400" ); this._EngineParameters.AddParameter ( "XMax", "X Maximum", "The right edge X Value in Chaos space, which is translated to the right edge screen render device..", "Chaos Space X Maximum", "Float", "400" ); this._EngineParameters.AddParameter ( "YMin", "Y Minimum", "The top edge Y Value in Chaos space, which is translated to the origin of the screen render device.", "Chaos Space Y Minimum", "Float", "-300" ); this._EngineParameters.AddParameter ( "YMax", "Y Maximum", "The bottom edge Y Value in Chaos space, which is translated to the bottom edge screen render device.", "Chaos Space Y Maximum", "Float", "300" ); this._EngineParameters.AddParameter ( "Screen_Color_Count", "Screen Color Count", "The number of colors to use in the onscreen image palette.", "Screen Color Count", "Integer", "255" ); this.SyncInternalParameters(); this.InitializeEngineParameters (); this._RenderingQuality = 1; } public string GetParameter ( string pParameterKey ) { return this._EngineParameters.GetParameter( pParameterKey ); } public bool SetParameter ( string pParameterKey, string pParameterValue ) { return this._EngineParameters.SetParameter( pParameterKey, pParameterValue ); } public string ParameterSerialization { get {return this._EngineParameters.Serialize_Parameters; } } protected void SetDefaultLimits ( double pXMin, double pXMax, double pYMin, double pYMax ) { this._EngineParameters.SetParameter( "XMin", pXMin.ToString() ); this._EngineParameters.SetParameter( "XMax", pXMax.ToString() ); this._EngineParameters.SetParameter( "YMin", pYMin.ToString() ); this._EngineParameters.SetParameter( "YMax", pYMax.ToString() ); } //Add any engine-specific parameters public virtual void InitializeEngineParameters () { //This will hold any engine parameters that are necessary } //This is the overridden rendering system initialization public virtual void InitializeRenderSubsystem () { //This would initialize any variables that are used. } //The overridden render value (without changing this we have no engine) public virtual int EngineRenderValue ( double pChaosSpaceX, double pChaosSpaceY ) { //Default to always returning infinity. return -1; } #region Render Subsystem (Untouchable) //Begin the render public bool RenderBegin() { if ( !this._Rendering ) { //Set the built-in parameters in the cache this.SyncInternalParameters(); //Set all user parameters. Use overloadable functions JUST LIKE IN THE MOOBIES this.InitializeRenderSubsystem(); this._Rendering = true; return true; } else { return false; } } private void SyncInternalParameters() { //Set the default parameters from the list this._Param_XMin = double.Parse( this._EngineParameters.GetParameter( "XMin" ) ); this._Param_YMin = double.Parse( this._EngineParameters.GetParameter( "XMax" ) ); this._Param_XMax = double.Parse( this._EngineParameters.GetParameter( "YMin" ) ); this._Param_YMax = double.Parse( this._EngineParameters.GetParameter( "YMax" ) ); this._Param_ScreenColorCount = int.Parse( this._EngineParameters.GetParameter( "Screen_Color_Count" ) ); } //Get a pixel rendering value. -1 will be Infinite, otherwise it will ALWAYS have to fall inside the range of 0 to color_count - 1 //TODO: We will have to test after we put the REAL code in here whether this function // should be virtualized or it should wrap one for nicer outside calls. public int RenderPixel( double pChaosSpaceX, double pChaosSpaceY ) { if (this._Rendering) { this._TotalPointsRendered++; return this.EngineRenderQualityValue (pChaosSpaceX, pChaosSpaceY); } else { return -2; } } private int EngineRenderQualityValue ( double pChaosSpaceX, double pChaosSpaceY ) { if ( this.CurrentRenderQuality <= 1 ) { return this.EngineRenderValue ( pChaosSpaceX, pChaosSpaceY ); } else { //Do a subgrid-based averaging system. We could also Weight them by distance from pixel but I think that will be freaky. int tmpRenderAverager = 0; int tmpSubpixelValue; bool tmpInfinitePoint = true; //This is the spacing gap that we walk between pixels double tmpCurrentRatioSubpixelGap = (this.CurrentRenderRatio / this.CurrentRenderQuality); //This is the distance from the "center" we go for the origin and boundaries of the subpixel grouping double tmpCurrentRatioSubpixelHalf = ((this.CurrentRenderQuality-1)/2)*tmpCurrentRatioSubpixelGap; for ( double tmpChaosSpaceX = pChaosSpaceX - tmpCurrentRatioSubpixelHalf; tmpChaosSpaceX <= pChaosSpaceX + tmpCurrentRatioSubpixelHalf; tmpChaosSpaceX = tmpChaosSpaceX + tmpCurrentRatioSubpixelGap ) { for ( double tmpChaosSpaceY = pChaosSpaceY - tmpCurrentRatioSubpixelHalf; tmpChaosSpaceY <= pChaosSpaceY + tmpCurrentRatioSubpixelHalf; tmpChaosSpaceY = tmpChaosSpaceY + tmpCurrentRatioSubpixelGap ) { tmpSubpixelValue = this.EngineRenderValue ( tmpChaosSpaceX, tmpChaosSpaceY ); if ( tmpSubpixelValue >= 0 ) tmpInfinitePoint = false; else tmpSubpixelValue = this.ColorCount - 1; tmpRenderAverager += tmpSubpixelValue; } } if ( tmpInfinitePoint ) //Return the infinity return -1; else return tmpRenderAverager / (int)(this.CurrentRenderQuality*this.CurrentRenderQuality); } } //End the render public bool Render_End() { this._Rendering = false; return true; } #endregion #region Data Access public double CurrentRenderQuality { set { this._RenderingQuality = value; //This will require only odd numbers for render values. if ( this.CurrentRenderQuality % 2 == 0 ) this.CurrentRenderQuality -= 1; } get {return this._RenderingQuality; } } public double CurrentRenderRatio { set {this._RenderingRatio = value; } get {return this._RenderingRatio; } } public int ColorCount { get {return this._Param_ScreenColorCount; } } public double ChaosMinX { get {return this._Param_XMin; } } public double ChaosMaxX { get {return this._Param_YMin; } } public double ChaosMinY { get {return this._Param_XMax; } } public double ChaosMaxY { get {return this._Param_YMax; } } public double ChaosWidth { get {return this._Param_YMin - this._Param_XMin; } } public double ChaosHeight { get {return this._Param_YMax - this._Param_XMax; } } public long TotalPointsRendered { get {return this._TotalPointsRendered; } } public virtual string Name { get {return "None"; } } #endregion } }
namespace UltraSFV { partial class ManualCheck { /// <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(ManualCheck)); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.labelChecksumStatus = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBoxChecksum = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.buttonBrowse = new System.Windows.Forms.Button(); this.textBoxFileName = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.buttonCheck = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.labelChecksumStatus); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.textBoxChecksum); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Location = new System.Drawing.Point(12, 6); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(268, 78); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; // // labelChecksumStatus // this.labelChecksumStatus.AutoSize = true; this.labelChecksumStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelChecksumStatus.ForeColor = System.Drawing.Color.Firebrick; this.labelChecksumStatus.Location = new System.Drawing.Point(70, 55); this.labelChecksumStatus.Name = "labelChecksumStatus"; this.labelChecksumStatus.Size = new System.Drawing.Size(133, 13); this.labelChecksumStatus.TabIndex = 3; this.labelChecksumStatus.Text = "No Checksum Entered"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 55); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(67, 13); this.label2.TabIndex = 2; this.label2.Text = "Hash format:"; // // textBoxChecksum // this.textBoxChecksum.Location = new System.Drawing.Point(9, 32); this.textBoxChecksum.Name = "textBoxChecksum"; this.textBoxChecksum.Size = new System.Drawing.Size(248, 20); this.textBoxChecksum.TabIndex = 1; this.textBoxChecksum.TextChanged += new System.EventHandler(this.textBoxChecksum_TextChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(188, 13); this.label1.TabIndex = 0; this.label1.Text = "Paste CRC32 or MD5 checksum here:"; // // groupBox2 // this.groupBox2.Controls.Add(this.buttonBrowse); this.groupBox2.Controls.Add(this.textBoxFileName); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Location = new System.Drawing.Point(12, 90); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(268, 65); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; // // buttonBrowse // this.buttonBrowse.Location = new System.Drawing.Point(182, 30); this.buttonBrowse.Name = "buttonBrowse"; this.buttonBrowse.Size = new System.Drawing.Size(75, 23); this.buttonBrowse.TabIndex = 2; this.buttonBrowse.Text = "Browse"; this.buttonBrowse.UseVisualStyleBackColor = true; this.buttonBrowse.Click += new System.EventHandler(this.buttonBrowse_Click); // // textBoxFileName // this.textBoxFileName.Location = new System.Drawing.Point(9, 32); this.textBoxFileName.Name = "textBoxFileName"; this.textBoxFileName.ReadOnly = true; this.textBoxFileName.Size = new System.Drawing.Size(167, 20); this.textBoxFileName.TabIndex = 1; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 16); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(59, 13); this.label4.TabIndex = 0; this.label4.Text = "Select File:"; // // buttonCheck // this.buttonCheck.Enabled = false; this.buttonCheck.Location = new System.Drawing.Point(124, 162); this.buttonCheck.Name = "buttonCheck"; this.buttonCheck.Size = new System.Drawing.Size(75, 23); this.buttonCheck.TabIndex = 2; this.buttonCheck.Text = "Check File"; this.buttonCheck.UseVisualStyleBackColor = true; this.buttonCheck.Click += new System.EventHandler(this.buttonCheck_Click); // // buttonCancel // this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(205, 162); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(75, 23); this.buttonCancel.TabIndex = 3; this.buttonCancel.Text = "Cancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // openFileDialog1 // this.openFileDialog1.Filter = "All Files (*.*)|*.*"; this.openFileDialog1.Title = "Select the file to check"; // // ManualCheck // this.AcceptButton = this.buttonCheck; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(292, 193); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonCheck); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ManualCheck"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Manual Check"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label labelChecksumStatus; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBoxChecksum; private System.Windows.Forms.Button buttonBrowse; private System.Windows.Forms.TextBox textBoxFileName; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button buttonCheck; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.OpenFileDialog openFileDialog1; } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace MyCSOMAppWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted add-in. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Text; using System.Web.Http; using AutoMapper; using Umbraco.Core; using Umbraco.Core.Models.Membership; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Mvc; using System.Linq; using Umbraco.Core.Models; using Constants = Umbraco.Core.Constants; using Examine; using Umbraco.Web.Dynamics; using System.Text.RegularExpressions; using Umbraco.Core.Xml; namespace Umbraco.Web.Editors { /// <summary> /// The API controller used for getting entity objects, basic name, icon, id representation of umbraco objects that are based on CMSNode /// </summary> /// <remarks> /// Some objects such as macros are not based on CMSNode /// </remarks> [EntityControllerConfiguration] [PluginController("UmbracoApi")] public class EntityController : UmbracoAuthorizedJsonController { /// <summary> /// Returns an Umbraco alias given a string /// </summary> /// <param name="value"></param> /// <param name="camelCase"></param> /// <returns></returns> public dynamic GetSafeAlias(string value, bool camelCase = true) { var returnValue = (string.IsNullOrWhiteSpace(value)) ? string.Empty : value.ToSafeAlias(camelCase); dynamic returnObj = new System.Dynamic.ExpandoObject(); returnObj.alias = returnValue; returnObj.original = value; returnObj.camelCase = camelCase; return returnObj; } /// <summary> /// Searches for results based on the entity type /// </summary> /// <param name="query"></param> /// <param name="type"></param> /// <param name="searchFrom"> /// A starting point for the search, generally a node id, but for members this is a member type alias /// </param> /// <returns></returns> [HttpGet] public IEnumerable<EntityBasic> Search(string query, UmbracoEntityTypes type, string searchFrom = null) { //TODO: Should we restrict search results based on what app the user has access to? // - Theoretically you shouldn't be able to see member data if you don't have access to members right? if (string.IsNullOrEmpty(query)) return Enumerable.Empty<EntityBasic>(); return ExamineSearch(query, type, searchFrom); } /// <summary> /// Searches for all content that the user is allowed to see (based on their allowed sections) /// </summary> /// <param name="query"></param> /// <returns></returns> /// <remarks> /// Even though a normal entity search will allow any user to search on a entity type that they may not have access to edit, we need /// to filter these results to the sections they are allowed to edit since this search function is explicitly for the global search /// so if we showed entities that they weren't allowed to edit they would get errors when clicking on the result. /// /// The reason a user is allowed to search individual entity types that they are not allowed to edit is because those search /// methods might be used in things like pickers in the content editor. /// </remarks> [HttpGet] public IEnumerable<EntityTypeSearchResult> SearchAll(string query) { if (string.IsNullOrEmpty(query)) return Enumerable.Empty<EntityTypeSearchResult>(); var allowedSections = Security.CurrentUser.AllowedSections.ToArray(); var result = new List<EntityTypeSearchResult>(); if (allowedSections.InvariantContains(Constants.Applications.Content)) { result.Add(new EntityTypeSearchResult { Results = ExamineSearch(query, UmbracoEntityTypes.Document), EntityType = UmbracoEntityTypes.Document.ToString() }); } if (allowedSections.InvariantContains(Constants.Applications.Media)) { result.Add(new EntityTypeSearchResult { Results = ExamineSearch(query, UmbracoEntityTypes.Media), EntityType = UmbracoEntityTypes.Media.ToString() }); } if (allowedSections.InvariantContains(Constants.Applications.Members)) { result.Add(new EntityTypeSearchResult { Results = ExamineSearch(query, UmbracoEntityTypes.Member), EntityType = UmbracoEntityTypes.Member.ToString() }); } return result; } /// <summary> /// Gets the path for a given node ID /// </summary> /// <param name="id"></param> /// <param name="type"></param> /// <returns></returns> public IEnumerable<int> GetPath(int id, UmbracoEntityTypes type) { var foundContent = GetResultForId(id, type); return foundContent.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse); } /// <summary> /// Gets an entity by it's unique id if the entity supports that /// </summary> /// <param name="id"></param> /// <param name="type"></param> /// <returns></returns> public EntityBasic GetByKey(Guid id, UmbracoEntityTypes type) { return GetResultForKey(id, type); } /// <summary> /// Gets an entity by a xpath query /// </summary> /// <param name="query"></param> /// <param name="nodeContextId"></param> /// <param name="type"></param> /// <returns></returns> public EntityBasic GetByQuery(string query, int nodeContextId, UmbracoEntityTypes type) { //TODO: Rename this!!! It's a bit misleading, it should be GetByXPath if (type != UmbracoEntityTypes.Document) throw new ArgumentException("Get by query is only compatible with enitities of type Document"); var q = ParseXPathQuery(query, nodeContextId); var node = Umbraco.TypedContentSingleAtXPath(q); if (node == null) return null; return GetById(node.Id, type); } //PP: wip in progress on the query parser private string ParseXPathQuery(string query, int id) { return UmbracoXPathPathSyntaxParser.ParseXPathQuery( xpathExpression: query, nodeContextId: id, getPath: nodeid => { var ent = Services.EntityService.Get(nodeid); return ent.Path.Split(',').Reverse(); }, publishedContentExists: i => Umbraco.TypedContent(i) != null); } public EntityBasic GetById(int id, UmbracoEntityTypes type) { return GetResultForId(id, type); } public IEnumerable<EntityBasic> GetByIds([FromUri]int[] ids, UmbracoEntityTypes type) { if (ids == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return GetResultForIds(ids, type); } public IEnumerable<EntityBasic> GetByKeys([FromUri]Guid[] ids, UmbracoEntityTypes type) { if (ids == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return GetResultForKeys(ids, type); } public IEnumerable<EntityBasic> GetChildren(int id, UmbracoEntityTypes type) { return GetResultForChildren(id, type); } /// <summary> /// Get paged descendant entities by id /// </summary> /// <param name="id"></param> /// <param name="type"></param> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> /// <param name="orderBy"></param> /// <param name="orderDirection"></param> /// <param name="filter"></param> /// <returns></returns> public IEnumerable<EntityBasic> GetAncestors(int id, UmbracoEntityTypes type) { return GetResultForAncestors(id, type); } public IEnumerable<EntityBasic> GetAll(UmbracoEntityTypes type, string postFilter, [FromUri]IDictionary<string, object> postFilterParams) { return GetResultForAll(type, postFilter, postFilterParams); } /// <summary> /// Searches for results based on the entity type /// </summary> /// <param name="query"></param> /// <param name="entityType"></param> /// <param name="searchFrom"> /// A starting point for the search, generally a node id, but for members this is a member type alias /// </param> /// <returns></returns> private IEnumerable<EntityBasic> ExamineSearch(string query, UmbracoEntityTypes entityType, string searchFrom = null) { var sb = new StringBuilder(); string type; var searcher = Constants.Examine.InternalSearcher; var fields = new[] { "id", "__NodeId" }; //TODO: WE should really just allow passing in a lucene raw query switch (entityType) { case UmbracoEntityTypes.Member: searcher = Constants.Examine.InternalMemberSearcher; type = "member"; fields = new[] { "id", "__NodeId", "email", "loginName"}; if (searchFrom != null && searchFrom != Constants.Conventions.MemberTypes.AllMembersListId && searchFrom.Trim() != "-1") { sb.Append("+__NodeTypeAlias:"); sb.Append(searchFrom); sb.Append(" "); } break; case UmbracoEntityTypes.Media: type = "media"; var mediaSearchFrom = int.MinValue; if (Security.CurrentUser.StartMediaId > 0 || //if searchFrom is specified and it is greater than 0 (searchFrom != null && int.TryParse(searchFrom, out mediaSearchFrom) && mediaSearchFrom > 0)) { sb.Append("+__Path: \\-1*\\,"); sb.Append(mediaSearchFrom > 0 ? mediaSearchFrom.ToString(CultureInfo.InvariantCulture) : Security.CurrentUser.StartMediaId.ToString(CultureInfo.InvariantCulture)); sb.Append("\\,* "); } break; case UmbracoEntityTypes.Document: type = "content"; var contentSearchFrom = int.MinValue; if (Security.CurrentUser.StartContentId > 0 || //if searchFrom is specified and it is greater than 0 (searchFrom != null && int.TryParse(searchFrom, out contentSearchFrom) && contentSearchFrom > 0)) { sb.Append("+__Path: \\-1*\\,"); sb.Append(contentSearchFrom > 0 ? contentSearchFrom.ToString(CultureInfo.InvariantCulture) : Security.CurrentUser.StartContentId.ToString(CultureInfo.InvariantCulture)); sb.Append("\\,* "); } break; default: throw new NotSupportedException("The " + typeof(EntityController) + " currently does not support searching against object type " + entityType); } var internalSearcher = ExamineManager.Instance.SearchProviderCollection[searcher]; //build a lucene query: // the __nodeName will be boosted 10x without wildcards // then __nodeName will be matched normally with wildcards // the rest will be normal without wildcards //check if text is surrounded by single or double quotes, if so, then exact match var surroundedByQuotes = Regex.IsMatch(query, "^\".*?\"$") || Regex.IsMatch(query, "^\'.*?\'$"); if (surroundedByQuotes) { //strip quotes, escape string, the replace again query = query.Trim(new[] { '\"', '\'' }); query = Lucene.Net.QueryParsers.QueryParser.Escape(query); if (query.IsNullOrWhiteSpace()) { return new List<EntityBasic>(); } //add back the surrounding quotes query = string.Format("{0}{1}{0}", "\"", query); //node name exactly boost x 10 sb.Append("+(__nodeName: ("); sb.Append(query.ToLower()); sb.Append(")^10.0 "); foreach (var f in fields) { //additional fields normally sb.Append(f); sb.Append(": ("); sb.Append(query); sb.Append(") "); } } else { if (query.Trim(new[] { '\"', '\'' }).IsNullOrWhiteSpace()) { return new List<EntityBasic>(); } query = Lucene.Net.QueryParsers.QueryParser.Escape(query); var querywords = query.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); //node name exactly boost x 10 sb.Append("+(__nodeName:"); sb.Append("\""); sb.Append(query.ToLower()); sb.Append("\""); sb.Append("^10.0 "); //node name normally with wildcards sb.Append(" __nodeName:"); sb.Append("("); foreach (var w in querywords) { sb.Append(w.ToLower()); sb.Append("* "); } sb.Append(") "); foreach (var f in fields) { //additional fields normally sb.Append(f); sb.Append(":"); sb.Append("("); foreach (var w in querywords) { sb.Append(w.ToLower()); sb.Append("* "); } sb.Append(")"); sb.Append(" "); } } //must match index type sb.Append(") +__IndexType:"); sb.Append(type); var raw = internalSearcher.CreateSearchCriteria().RawQuery(sb.ToString()); //limit results to 200 to avoid huge over processing (CPU) var result = internalSearcher.Search(raw, 200); switch (entityType) { case UmbracoEntityTypes.Member: return MemberFromSearchResults(result); case UmbracoEntityTypes.Media: return MediaFromSearchResults(result); case UmbracoEntityTypes.Document: return ContentFromSearchResults(result); default: throw new NotSupportedException("The " + typeof(EntityController) + " currently does not support searching against object type " + entityType); } } /// <summary> /// Returns a collection of entities for media based on search results /// </summary> /// <param name="results"></param> /// <returns></returns> private IEnumerable<EntityBasic> MemberFromSearchResults(ISearchResults results) { var mapped = Mapper.Map<IEnumerable<EntityBasic>>(results).ToArray(); //add additional data foreach (var m in mapped) { //if no icon could be mapped, it will be set to document, so change it to picture if (m.Icon == "icon-document") { m.Icon = "icon-user"; } var searchResult = results.First(x => x.Id.ToInvariantString() == m.Id.ToString()); if (searchResult.Fields.ContainsKey("email") && searchResult.Fields["email"] != null) { m.AdditionalData["Email"] = results.First(x => x.Id.ToInvariantString() == m.Id.ToString()).Fields["email"]; } if (searchResult.Fields.ContainsKey("__key") && searchResult.Fields["__key"] != null) { Guid key; if (Guid.TryParse(searchResult.Fields["__key"], out key)) { m.Key = key; } } } return mapped; } /// <summary> /// Returns a collection of entities for media based on search results /// </summary> /// <param name="results"></param> /// <returns></returns> private IEnumerable<EntityBasic> MediaFromSearchResults(ISearchResults results) { var mapped = Mapper.Map<IEnumerable<EntityBasic>>(results).ToArray(); //add additional data foreach (var m in mapped) { //if no icon could be mapped, it will be set to document, so change it to picture if (m.Icon == "icon-document") { m.Icon = "icon-picture"; } } return mapped; } /// <summary> /// Returns a collection of entities for content based on search results /// </summary> /// <param name="results"></param> /// <returns></returns> private IEnumerable<EntityBasic> ContentFromSearchResults(ISearchResults results) { var mapped = Mapper.Map<ISearchResults, IEnumerable<EntityBasic>>(results).ToArray(); //add additional data foreach (var m in mapped) { var intId = m.Id.TryConvertTo<int>(); if (intId.Success) { m.AdditionalData["Url"] = Umbraco.NiceUrl(intId.Result); } } return mapped; } private IEnumerable<EntityBasic> GetResultForChildren(int id, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { //TODO: Need to check for Object types that support hierarchic here, some might not. return Services.EntityService.GetChildren(id, objectType.Value) .WhereNotNull() .Select(Mapper.Map<EntityBasic>); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private IEnumerable<EntityBasic> GetResultForAncestors(int id, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { //TODO: Need to check for Object types that support hierarchic here, some might not. var ids = Services.EntityService.Get(id).Path.Split(',').Select(int.Parse).Distinct().ToArray(); return Services.EntityService.GetAll(objectType.Value, ids) .WhereNotNull() .OrderBy(x => x.Level) .Select(Mapper.Map<EntityBasic>); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } /// <summary> /// Gets the result for the entity list based on the type /// </summary> /// <param name="entityType"></param> /// <param name="postFilter">A string where filter that will filter the results dynamically with linq - optional</param> /// <param name="postFilterParams">the parameters to fill in the string where filter - optional</param> /// <returns></returns> private IEnumerable<EntityBasic> GetResultForAll(UmbracoEntityTypes entityType, string postFilter = null, IDictionary<string, object> postFilterParams = null) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { //TODO: Should we order this by something ? var entities = Services.EntityService.GetAll(objectType.Value).WhereNotNull().Select(Mapper.Map<EntityBasic>); return ExecutePostFilter(entities, postFilter, postFilterParams); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.Template: var templates = Services.FileService.GetTemplates(); var filteredTemplates = ExecutePostFilter(templates, postFilter, postFilterParams); return filteredTemplates.Select(Mapper.Map<EntityBasic>); case UmbracoEntityTypes.Macro: //Get all macros from the macro service var macros = Services.MacroService.GetAll().WhereNotNull().OrderBy(x => x.Name); var filteredMacros = ExecutePostFilter(macros, postFilter, postFilterParams); return filteredMacros.Select(Mapper.Map<EntityBasic>); case UmbracoEntityTypes.PropertyType: //get all document types, then combine all property types into one list var propertyTypes = Services.ContentTypeService.GetAllContentTypes().Cast<IContentTypeComposition>() .Concat(Services.ContentTypeService.GetAllMediaTypes()) .ToArray() .SelectMany(x => x.PropertyTypes) .DistinctBy(composition => composition.Alias); var filteredPropertyTypes = ExecutePostFilter(propertyTypes, postFilter, postFilterParams); return Mapper.Map<IEnumerable<PropertyType>, IEnumerable<EntityBasic>>(filteredPropertyTypes); case UmbracoEntityTypes.PropertyGroup: //get all document types, then combine all property types into one list var propertyGroups = Services.ContentTypeService.GetAllContentTypes().Cast<IContentTypeComposition>() .Concat(Services.ContentTypeService.GetAllMediaTypes()) .ToArray() .SelectMany(x => x.PropertyGroups) .DistinctBy(composition => composition.Name); var filteredpropertyGroups = ExecutePostFilter(propertyGroups, postFilter, postFilterParams); return Mapper.Map<IEnumerable<PropertyGroup>, IEnumerable<EntityBasic>>(filteredpropertyGroups); case UmbracoEntityTypes.User: int total; var users = Services.UserService.GetAll(0, int.MaxValue, out total); var filteredUsers = ExecutePostFilter(users, postFilter, postFilterParams); return Mapper.Map<IEnumerable<IUser>, IEnumerable<EntityBasic>>(filteredUsers); case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private IEnumerable<EntityBasic> GetResultForKeys(IEnumerable<Guid> keys, UmbracoEntityTypes entityType) { var keysArray = keys.ToArray(); if (keysArray.Any() == false) return Enumerable.Empty<EntityBasic>(); var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { var entities = Services.EntityService.GetAll(objectType.Value, keysArray) .WhereNotNull() .Select(Mapper.Map<EntityBasic>); // entities are in "some" order, put them back in order var xref = entities.ToDictionary(x => x.Key); var result = keysArray.Select(x => xref.ContainsKey(x) ? xref[x] : null).Where(x => x != null); return result; } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private IEnumerable<EntityBasic> GetResultForIds(IEnumerable<int> ids, UmbracoEntityTypes entityType) { var idsArray = ids.ToArray(); if (idsArray.Any() == false) return Enumerable.Empty<EntityBasic>(); var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { var entities = Services.EntityService.GetAll(objectType.Value, idsArray) .WhereNotNull() .Select(Mapper.Map<EntityBasic>); // entities are in "some" order, put them back in order var xref = entities.ToDictionary(x => x.Id); var result = idsArray.Select(x => xref.ContainsKey(x) ? xref[x] : null).Where(x => x != null); return result; } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private EntityBasic GetResultForKey(Guid key, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { var found = Services.EntityService.GetByKey(key, objectType.Value); if (found == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return Mapper.Map<EntityBasic>(found); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private EntityBasic GetResultForId(int id, UmbracoEntityTypes entityType) { var objectType = ConvertToObjectType(entityType); if (objectType.HasValue) { var found = Services.EntityService.Get(id, objectType.Value); if (found == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return Mapper.Map<EntityBasic>(found); } //now we need to convert the unknown ones switch (entityType) { case UmbracoEntityTypes.PropertyType: case UmbracoEntityTypes.PropertyGroup: case UmbracoEntityTypes.Domain: case UmbracoEntityTypes.Language: case UmbracoEntityTypes.User: case UmbracoEntityTypes.Macro: default: throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType); } } private static UmbracoObjectTypes? ConvertToObjectType(UmbracoEntityTypes entityType) { switch (entityType) { case UmbracoEntityTypes.Document: return UmbracoObjectTypes.Document; case UmbracoEntityTypes.Media: return UmbracoObjectTypes.Media; case UmbracoEntityTypes.MemberType: return UmbracoObjectTypes.MediaType; case UmbracoEntityTypes.MemberGroup: return UmbracoObjectTypes.MemberGroup; case UmbracoEntityTypes.ContentItem: return UmbracoObjectTypes.ContentItem; case UmbracoEntityTypes.MediaType: return UmbracoObjectTypes.MediaType; case UmbracoEntityTypes.DocumentType: return UmbracoObjectTypes.DocumentType; case UmbracoEntityTypes.Stylesheet: return UmbracoObjectTypes.Stylesheet; case UmbracoEntityTypes.Member: return UmbracoObjectTypes.Member; case UmbracoEntityTypes.DataType: return UmbracoObjectTypes.DataType; default: //There is no UmbracoEntity conversion (things like Macros, Users, etc...) return null; } } /// <summary> /// Executes the post filter against a collection of objects /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entities"></param> /// <param name="postFilter"></param> /// <param name="postFilterParams"></param> /// <returns></returns> private IEnumerable<T> ExecutePostFilter<T>(IEnumerable<T> entities, string postFilter, IDictionary<string, object> postFilterParams) { //if a post filter is assigned then try to execute it if (postFilter.IsNullOrWhiteSpace() == false) { return postFilterParams == null ? entities.AsQueryable().Where(postFilter).ToArray() : entities.AsQueryable().Where(postFilter, postFilterParams).ToArray(); } return entities; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Orleans.Transactions.Abstractions; namespace Orleans.Transactions.TestKit.Correctnesss { [Serializable] public class BitArrayState { protected bool Equals(BitArrayState other) { if (ReferenceEquals(null, this.value)) return false; if (ReferenceEquals(null, other.value)) return false; if (this.value.Length != other.value.Length) return false; for (var i = 0; i < this.value.Length; i++) { if (this.value[i] != other.value[i]) { return false; } } return true; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((BitArrayState) obj); } public override int GetHashCode() { return (value != null ? value.GetHashCode() : 0); } private static readonly int BitsInInt = sizeof(int) * 8; [JsonProperty("v")] private int[] value = { 0 }; [JsonIgnore] public int[] Value => value; [JsonIgnore] public int Length => this.value.Length; public BitArrayState() { } public BitArrayState(BitArrayState other) { this.value = new int[other.value.Length]; for (var i = 0; i < other.value.Length; i++) { this.value[i] = other.value[i]; } } public void Set(int index, bool value) { int idx = index / BitsInInt; if (idx >= this.value.Length) { Array.Resize(ref this.value, idx+1); } int shift = 1 << (index % BitsInInt); if (value) { this.value[idx] |= shift; } else this.value[idx] &= ~shift; } public IEnumerator<int> GetEnumerator() { foreach (var v in this.value) yield return v; } public override string ToString() { // Write the values from least significant bit to most significant bit var builder = new StringBuilder(); foreach (var v in this.value) { builder.Append(Reverse(Convert.ToString(v, 2)).PadRight(BitsInInt, '0')); string Reverse(string s) { char[] charArray = s.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } } return builder.ToString(); } public int this[int index] { get => this.value[index]; set => this.value[index] = value; } public static bool operator ==(BitArrayState left, BitArrayState right) { if (ReferenceEquals(left, right)) return true; if (ReferenceEquals(left, null)) return false; if (ReferenceEquals(right, null)) return false; return left.Equals(right); } public static bool operator !=(BitArrayState left, BitArrayState right) { return !(left == right); } public static BitArrayState operator ^(BitArrayState left, BitArrayState right) { return Apply(left, right, (l, r) => l ^ r); } public static BitArrayState operator |(BitArrayState left, BitArrayState right) { return Apply(left, right, (l, r) => l | r); } public static BitArrayState operator &(BitArrayState left, BitArrayState right) { return Apply(left, right, (l, r) => l & r); } public static BitArrayState Apply(BitArrayState left, BitArrayState right, Func<int, int, int> op) { var result = new BitArrayState(left.value.Length > right.value.Length ? left : right); var overlappingLength = Math.Min(left.value.Length, right.value.Length); var i = 0; for (; i < overlappingLength; i++) { result.value[i] = op(left.value[i], right.value[i]); } // Continue with the non-overlapping portion. for (; i < result.value.Length; i++) { var leftVal = left.value.Length > i ? left.value[i] : 0; var rightVal = right.value.Length > i ? right.value[i] : 0; result.value[i] = op(leftVal, rightVal); } return result; } } public class MaxStateTransactionalGrain : MultiStateTransactionalBitArrayGrain { public MaxStateTransactionalGrain(ITransactionalStateFactory stateFactory, ILoggerFactory loggerFactory) : base(Enumerable.Range(0, TransactionTestConstants.MaxCoordinatedTransactions) .Select(i => stateFactory.Create<BitArrayState>(new TransactionalStateConfiguration(new TransactionalStateAttribute($"data{i}", TransactionTestConstants.TransactionStore)))) .ToArray(), loggerFactory) { } } public class DoubleStateTransactionalGrain : MultiStateTransactionalBitArrayGrain { public DoubleStateTransactionalGrain( [TransactionalState("data1", TransactionTestConstants.TransactionStore)] ITransactionalState<BitArrayState> data1, [TransactionalState("data2", TransactionTestConstants.TransactionStore)] ITransactionalState<BitArrayState> data2, ILoggerFactory loggerFactory) : base(new ITransactionalState<BitArrayState>[2] { data1, data2 }, loggerFactory) { } } public class SingleStateTransactionalGrain : MultiStateTransactionalBitArrayGrain { public SingleStateTransactionalGrain( [TransactionalState("data", TransactionTestConstants.TransactionStore)] ITransactionalState<BitArrayState> data, ILoggerFactory loggerFactory) : base(new ITransactionalState<BitArrayState>[1] { data }, loggerFactory) { } } public class MultiStateTransactionalBitArrayGrain : Grain, ITransactionalBitArrayGrain { protected ITransactionalState<BitArrayState>[] dataArray; private readonly ILoggerFactory loggerFactory; protected ILogger logger; public MultiStateTransactionalBitArrayGrain( ITransactionalState<BitArrayState>[] dataArray, ILoggerFactory loggerFactory) { this.dataArray = dataArray; this.loggerFactory = loggerFactory; } public override Task OnActivateAsync() { this.logger = this.loggerFactory.CreateLogger(this.GetGrainId().ToString()); this.logger.LogTrace($"GrainId : {this.GetPrimaryKey()}."); return base.OnActivateAsync(); } public Task Ping() { return Task.CompletedTask; } public Task SetBit(int index) { return Task.WhenAll(this.dataArray .Select(data => data.PerformUpdate(state => { this.logger.LogTrace($"Setting bit {index} in state {state}. Transaction {TransactionContext.CurrentTransactionId}"); state.Set(index, true); this.logger.LogTrace($"Set bit {index} in state {state}."); }))); } public async Task<List<BitArrayState>> Get() { return (await Task.WhenAll(this.dataArray .Select(state => state.PerformRead(s => { this.logger.LogTrace($"Get state {s}."); return s; })))).ToList(); } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace Revit.SDK.Samples.RotateFramingObjects.CS { /// <summary> /// Summary description for PutDialog. /// </summary> public class RotateFramingObjectsForm : System.Windows.Forms.Form { private RotateFramingObjects m_instance; private System.ComponentModel.Container m_components = null; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; public System.Windows.Forms.RadioButton absoluteRadio; private System.Windows.Forms.RadioButton relativeRadio; private System.Windows.Forms.Label rotationLabel; public System.Windows.Forms.TextBox rotationTextBox; private bool m_isReset; /// <summary> /// /// </summary> public bool IsReset { get { return m_isReset; } set { m_isReset = value; } } /// <summary> /// new form, retrieve relevant data from instance /// </summary> /// <param name="Inst">RotateFramingObjects instance</param> public RotateFramingObjectsForm(RotateFramingObjects Inst) { m_isReset = false; m_instance = Inst; if (null == m_instance) { MessageBox.Show("Load Application Failed"); } InitializeComponent(); //this.rotationTextBox.Text = "Value"; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(m_components != null) { m_components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.absoluteRadio = new System.Windows.Forms.RadioButton(); this.relativeRadio = new System.Windows.Forms.RadioButton(); this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.rotationLabel = new System.Windows.Forms.Label(); this.rotationTextBox = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // absoluteRadio // this.absoluteRadio.Location = new System.Drawing.Point(85, 35); this.absoluteRadio.Name = "absoluteRadio"; this.absoluteRadio.Size = new System.Drawing.Size(72, 24); this.absoluteRadio.TabIndex = 0; this.absoluteRadio.Text = "Absolute"; this.absoluteRadio.CheckedChanged += new System.EventHandler(this.allRadio_CheckedChanged); // // relativeRadio // this.relativeRadio.Checked = true; this.relativeRadio.Location = new System.Drawing.Point(15, 35); this.relativeRadio.Name = "relativeRadio"; this.relativeRadio.Size = new System.Drawing.Size(64, 24); this.relativeRadio.TabIndex = 1; this.relativeRadio.TabStop = true; this.relativeRadio.Text = "Relative"; this.relativeRadio.CheckedChanged += new System.EventHandler(this.singleRadio_CheckedChanged); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(93, 65); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 6; this.cancelButton.Text = "&Cancel"; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // okButton // this.okButton.Location = new System.Drawing.Point(15, 65); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 8; this.okButton.Text = "&OK"; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // rotationLabel // this.rotationLabel.Location = new System.Drawing.Point(12, 12); this.rotationLabel.Name = "rotationLabel"; this.rotationLabel.Size = new System.Drawing.Size(50, 16); this.rotationLabel.TabIndex = 10; this.rotationLabel.Text = "Rotation"; // // rotationTextBox // this.rotationTextBox.Location = new System.Drawing.Point(68, 9); this.rotationTextBox.Name = "rotationTextBox"; this.rotationTextBox.Size = new System.Drawing.Size(100, 20); this.rotationTextBox.TabIndex = 1; this.rotationTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.rotationTextBox_KeyPress); this.rotationTextBox.TextChanged += new System.EventHandler(this.rotationTextBox_TextChanged); // // RotateFramingObjectsForm // this.AcceptButton = this.okButton; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(185, 101); this.Controls.Add(this.rotationTextBox); this.Controls.Add(this.relativeRadio); this.Controls.Add(this.rotationLabel); this.Controls.Add(this.okButton); this.Controls.Add(this.cancelButton); this.Controls.Add(this.absoluteRadio); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "RotateFramingObjectsForm"; this.ShowInTaskbar = false; this.Text = "Rotate Framing Objects"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private void okButton_Click(object sender, System.EventArgs e) { if(IsReset) { m_instance.RotateElement(); } this.DialogResult=DialogResult.OK; this.Close(); } private void cancelButton_Click(object sender, System.EventArgs e) { this.DialogResult=DialogResult.Cancel; this.Close(); } private void singleRadio_CheckedChanged(object sender, System.EventArgs e) { m_isReset = true; m_instance.IsAbsoluteChecked = false; } private void allRadio_CheckedChanged(object sender, System.EventArgs e) { m_isReset = true; m_instance.IsAbsoluteChecked = true; } private void rotationTextBox_TextChanged(object sender, System.EventArgs e) { if("" != this.rotationTextBox.Text) { try { m_instance.ReceiveRotationTextBox = Convert.ToDouble(this.rotationTextBox.Text); } catch (Exception) { //this.DialogResult=DialogResult.Cancel; MessageBox.Show("Please input number."); this.rotationTextBox.Clear(); } } else { m_instance.ReceiveRotationTextBox = 0; } m_isReset = true; } private void rotationTextBox_KeyPress(object sender, KeyPressEventArgs e) { if (13 == e.KeyChar) { okButton_Click(sender,e); } else rotationTextBox_TextChanged(sender,e); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the email-2010-12-01.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.SimpleEmail.Model; namespace Amazon.SimpleEmail { /// <summary> /// Interface for accessing SimpleEmailService /// /// Amazon Simple Email Service /// <para> /// This is the API Reference for Amazon Simple Email Service (Amazon SES). /// This documentation is intended to be used in conjunction with the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html">Amazon /// SES Developer Guide</a>. /// </para> /// <note>For a list of Amazon SES endpoints to use in service requests, see <a /// href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html">Regions and /// Amazon SES</a> in the Amazon SES Developer Guide. </note> /// </summary> public partial interface IAmazonSimpleEmailService : IDisposable { #region DeleteIdentity /// <summary> /// Initiates the asynchronous execution of the DeleteIdentity operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteIdentity operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteIdentityResponse> DeleteIdentityAsync(DeleteIdentityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteVerifiedEmailAddress /// <summary> /// Initiates the asynchronous execution of the DeleteVerifiedEmailAddress operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteVerifiedEmailAddress operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteVerifiedEmailAddressResponse> DeleteVerifiedEmailAddressAsync(DeleteVerifiedEmailAddressRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetIdentityDkimAttributes /// <summary> /// Initiates the asynchronous execution of the GetIdentityDkimAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIdentityDkimAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetIdentityDkimAttributesResponse> GetIdentityDkimAttributesAsync(GetIdentityDkimAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetIdentityNotificationAttributes /// <summary> /// Initiates the asynchronous execution of the GetIdentityNotificationAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIdentityNotificationAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetIdentityNotificationAttributesResponse> GetIdentityNotificationAttributesAsync(GetIdentityNotificationAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetIdentityVerificationAttributes /// <summary> /// Initiates the asynchronous execution of the GetIdentityVerificationAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIdentityVerificationAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetIdentityVerificationAttributesResponse> GetIdentityVerificationAttributesAsync(GetIdentityVerificationAttributesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetSendQuota /// <summary> /// Initiates the asynchronous execution of the GetSendQuota operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSendQuota operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetSendQuotaResponse> GetSendQuotaAsync(GetSendQuotaRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetSendStatistics /// <summary> /// Initiates the asynchronous execution of the GetSendStatistics operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSendStatistics operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetSendStatisticsResponse> GetSendStatisticsAsync(GetSendStatisticsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListIdentities /// <summary> /// Initiates the asynchronous execution of the ListIdentities operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListIdentities operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListIdentitiesResponse> ListIdentitiesAsync(ListIdentitiesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListVerifiedEmailAddresses /// <summary> /// Initiates the asynchronous execution of the ListVerifiedEmailAddresses operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListVerifiedEmailAddresses operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListVerifiedEmailAddressesResponse> ListVerifiedEmailAddressesAsync(ListVerifiedEmailAddressesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SendEmail /// <summary> /// Initiates the asynchronous execution of the SendEmail operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SendEmail operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SendEmailResponse> SendEmailAsync(SendEmailRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SendRawEmail /// <summary> /// Initiates the asynchronous execution of the SendRawEmail operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SendRawEmail operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SendRawEmailResponse> SendRawEmailAsync(SendRawEmailRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetIdentityDkimEnabled /// <summary> /// Initiates the asynchronous execution of the SetIdentityDkimEnabled operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetIdentityDkimEnabled operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetIdentityDkimEnabledResponse> SetIdentityDkimEnabledAsync(SetIdentityDkimEnabledRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetIdentityFeedbackForwardingEnabled /// <summary> /// Initiates the asynchronous execution of the SetIdentityFeedbackForwardingEnabled operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetIdentityFeedbackForwardingEnabled operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetIdentityFeedbackForwardingEnabledResponse> SetIdentityFeedbackForwardingEnabledAsync(SetIdentityFeedbackForwardingEnabledRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetIdentityNotificationTopic /// <summary> /// Initiates the asynchronous execution of the SetIdentityNotificationTopic operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetIdentityNotificationTopic operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetIdentityNotificationTopicResponse> SetIdentityNotificationTopicAsync(SetIdentityNotificationTopicRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region VerifyDomainDkim /// <summary> /// Initiates the asynchronous execution of the VerifyDomainDkim operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifyDomainDkim operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<VerifyDomainDkimResponse> VerifyDomainDkimAsync(VerifyDomainDkimRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region VerifyDomainIdentity /// <summary> /// Initiates the asynchronous execution of the VerifyDomainIdentity operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifyDomainIdentity operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<VerifyDomainIdentityResponse> VerifyDomainIdentityAsync(VerifyDomainIdentityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region VerifyEmailAddress /// <summary> /// Initiates the asynchronous execution of the VerifyEmailAddress operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifyEmailAddress operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<VerifyEmailAddressResponse> VerifyEmailAddressAsync(VerifyEmailAddressRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region VerifyEmailIdentity /// <summary> /// Initiates the asynchronous execution of the VerifyEmailIdentity operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifyEmailIdentity operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<VerifyEmailIdentityResponse> VerifyEmailIdentityAsync(VerifyEmailIdentityRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
/* transpiled with BefunCompile v1.3.0 (c) 2017 */ public static class Program { private static readonly string _g = "Ah+LCAAAAAAABACT7+ZgAAEWhrfX7+Y1GUgc+xi9UnPelsRLfDL7FM/qLbl4eF7REUHx/YtuLuuOvuN+6ENlHTsXC+/J+/seLOBaytmfVOHDw++VWhzPfLZBW07kcPOj"+ "FexHPyyQADGTKgJ4+LseOhraaLTRSnCK1JWzfM1xnvs9t/aHlW6v7/s3/4LG/W+XrwVnlz3bOCXz9vXjzrevzSmbfa/j/jetHUGrNPb5va6yv+96+T1v/Lo7B3dttl33"+ "0Tqo9vGdjT5T0//+FpgjKjhZfef7UNHl0v8EvJfverB6H9enDL/mu27xq7d4Gp2rPfpFvWv72oNmvSWKuzYYB7rtrPpVHCjC//JLRfj6z7Mjvv8SncN6WuRa4Je6K7P/"+ "MHe4pq+fY7jXR/nAPv/GP8onjA9vXxlTKKYTpDGlz/G56vqpGdU/3iy0lRCs36P8RZz7vvu6H6o368881+PfMePT3f9/AnxEl//69PfPfYvH+re49af/CM8qYmAAAFun"+ "LAS3AQAA"; private static readonly long[] g = System.Array.ConvertAll(zd(System.Convert.FromBase64String(_g)),b=>(long)b); private static byte[]zd(byte[]o){byte[]d=System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Skip(o, 1));for(int i=0;i<o[0];i++)d=zs(d);return d;} private static byte[]zs(byte[]o){using(var c=new System.IO.MemoryStream(o)) using(var z=new System.IO.Compression.GZipStream(c,System.IO.Compression.CompressionMode.Decompress)) using(var r=new System.IO.MemoryStream()){z.CopyTo(r);return r.ToArray();}} private static long gr(long x,long y){return(x>=0&&y>=0&&x<505&&y<58)?g[y*505+x]:0;} private static void gw(long x,long y,long v){if(x>=0&&y>=0&&x<505&&y<58)g[y*505+x]=v;} private static long td(long a,long b){ return (b==0)?0:(a/b); } private static long tm(long a,long b){ return (b==0)?0:(a%b); } private static System.Collections.Generic.Stack<long> s=new System.Collections.Generic.Stack<long>(); private static long sp(){ return (s.Count==0)?0:s.Pop(); } private static void sa(long v){ s.Push(v); } private static long sr(){ return (s.Count==0)?0:s.Peek(); } static void Main(string[]args) { long t0; gw(2,8,5); gw(2,4,501); gw(2,5,48); gw(2,6,24048); gw((tm(24047,gr(2,4)))+4,td(24047,gr(2,4)),0); sa(24047); sa(24047); _1: if(sp()!=0)goto _20;else goto _2; _2: gw(2,2,1); sa(1); sa(0); sa(1); sa(1); sa(1); _3: if(sp()!=0)goto _4;else goto _8; _4: {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(9); _5: {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sr()); if(sp()!=0)goto _7;else goto _6; _6: sp(); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()/10L); sa(sr()%10); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sr()); goto _3; _7: sa(sp()-1L); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()*9L); goto _5; _8: {long v0=sp();long v1=sp();sa(v0);sa(v1);} sp(); sp(); _9: {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sr()); if(sp()!=0)goto _10;else goto _11; _10: sa(sp()+sp()); goto _9; _11: sa(sp()+sp()); sa(sr()); gw(2,0,sp()); sa(0); sa(gr(4,0)); sa(gr(4,0)); _12: if(sp()!=0)goto _13;else goto _19; _13: sa(sp()-gr(2,0)); if(sp()!=0)goto _18;else goto _14; _14: sa(sp()*3L); sa(sr()+2); sa((tm(sr(),gr(2,4)))+4); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(2,4))); {long v0=sp();sa(gr(sp(),v0));} sa(sp()+1L); if((sr()-gr(2,8))!=0)goto _16;else goto _15; _15: sp(); sa(sp()+1L); sa((tm(sr(),gr(2,4)))+4); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(2,4))); {long v0=sp();t0=gr(sp(),v0);} System.Console.Out.Write(t0+" "); sp(); sp(); sp(); return; _16: {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+2L); sa((tm(sr(),gr(2,4)))+4); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(2,4))); {long v0=sp();long v1=sp();gw(v1,v0,sp());} _17: sp(); sa(sp()+1L); sa(sr()); sa(sr()); sa(sr()); sa(sp()*sp()); t0=sp(); sa(sp()*t0); sa(sr()); gw(2,2,sp()); sa(0); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sr()%10); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sr()); goto _3; _18: sa(sp()+1L); sa(sr()*3); sa((tm(sr(),gr(2,4)))+4); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(2,4))); {long v0=sp();sa(gr(sp(),v0));} sa(sr()); goto _12; _19: sp(); sa(sp()*3L); sa(sr()); sa(sr()); sa(gr(2,0)); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa((tm(sr(),gr(2,4)))+4); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(2,4))); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(gr(2,2)); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+1L); sa((tm(sr(),gr(2,4)))+4); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(2,4))); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(1); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(sp()+2L); sa((tm(sr(),gr(2,4)))+4); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(2,4))); {long v0=sp();long v1=sp();gw(v1,v0,sp());} goto _17; _20: sa(sp()-1L); sa(sr()); sa(0); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa((tm(sr(),gr(2,4)))+4); {long v0=sp();long v1=sp();sa(v0);sa(v1);} sa(td(sp(),gr(2,4))); {long v0=sp();long v1=sp();gw(v1,v0,sp());} sa(sr()); goto _1; } }
using Kitware.VTK; using System; // input file is C:\VTK\Graphics\Testing\Tcl\officeStreamPoints.tcl // output file is AVofficeStreamPoints.cs /// <summary> /// The testing class derived from AVofficeStreamPoints /// </summary> public class AVofficeStreamPointsClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVofficeStreamPoints(String [] argv) { //Prefix Content is: "" ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); // read data[] //[] reader = new vtkStructuredGridReader(); reader.SetFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/office.binary.vtk"); reader.Update(); //force a read to occur[] // to add coverage for vtkOnePieceExtentTranslator[] translator = new vtkOnePieceExtentTranslator(); vtkStreamingDemandDrivenPipeline.SetExtentTranslator(reader.GetOutputInformation(0), (vtkExtentTranslator)translator); length = reader.GetOutput().GetLength(); maxVelocity = reader.GetOutput().GetPointData().GetVectors().GetMaxNorm(); maxTime = 35.0*length/maxVelocity; table1 = new vtkStructuredGridGeometryFilter(); table1.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); table1.SetExtent((int)11,(int)15,(int)7,(int)9,(int)8,(int)8); mapTable1 = vtkPolyDataMapper.New(); mapTable1.SetInputConnection((vtkAlgorithmOutput)table1.GetOutputPort()); mapTable1.ScalarVisibilityOff(); table1Actor = new vtkActor(); table1Actor.SetMapper((vtkMapper)mapTable1); table1Actor.GetProperty().SetColor((double).59,(double).427,(double).392); table2 = new vtkStructuredGridGeometryFilter(); table2.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); table2.SetExtent((int)11,(int)15,(int)10,(int)12,(int)8,(int)8); mapTable2 = vtkPolyDataMapper.New(); mapTable2.SetInputConnection((vtkAlgorithmOutput)table2.GetOutputPort()); mapTable2.ScalarVisibilityOff(); table2Actor = new vtkActor(); table2Actor.SetMapper((vtkMapper)mapTable2); table2Actor.GetProperty().SetColor((double).59,(double).427,(double).392); FilingCabinet1 = new vtkStructuredGridGeometryFilter(); FilingCabinet1.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); FilingCabinet1.SetExtent((int)15,(int)15,(int)7,(int)9,(int)0,(int)8); mapFilingCabinet1 = vtkPolyDataMapper.New(); mapFilingCabinet1.SetInputConnection((vtkAlgorithmOutput)FilingCabinet1.GetOutputPort()); mapFilingCabinet1.ScalarVisibilityOff(); FilingCabinet1Actor = new vtkActor(); FilingCabinet1Actor.SetMapper((vtkMapper)mapFilingCabinet1); FilingCabinet1Actor.GetProperty().SetColor((double).8,(double).8,(double).6); FilingCabinet2 = new vtkStructuredGridGeometryFilter(); FilingCabinet2.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); FilingCabinet2.SetExtent((int)15,(int)15,(int)10,(int)12,(int)0,(int)8); mapFilingCabinet2 = vtkPolyDataMapper.New(); mapFilingCabinet2.SetInputConnection((vtkAlgorithmOutput)FilingCabinet2.GetOutputPort()); mapFilingCabinet2.ScalarVisibilityOff(); FilingCabinet2Actor = new vtkActor(); FilingCabinet2Actor.SetMapper((vtkMapper)mapFilingCabinet2); FilingCabinet2Actor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf1Top = new vtkStructuredGridGeometryFilter(); bookshelf1Top.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf1Top.SetExtent((int)13,(int)13,(int)0,(int)4,(int)0,(int)11); mapBookshelf1Top = vtkPolyDataMapper.New(); mapBookshelf1Top.SetInputConnection((vtkAlgorithmOutput)bookshelf1Top.GetOutputPort()); mapBookshelf1Top.ScalarVisibilityOff(); bookshelf1TopActor = new vtkActor(); bookshelf1TopActor.SetMapper((vtkMapper)mapBookshelf1Top); bookshelf1TopActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf1Bottom = new vtkStructuredGridGeometryFilter(); bookshelf1Bottom.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf1Bottom.SetExtent((int)20,(int)20,(int)0,(int)4,(int)0,(int)11); mapBookshelf1Bottom = vtkPolyDataMapper.New(); mapBookshelf1Bottom.SetInputConnection((vtkAlgorithmOutput)bookshelf1Bottom.GetOutputPort()); mapBookshelf1Bottom.ScalarVisibilityOff(); bookshelf1BottomActor = new vtkActor(); bookshelf1BottomActor.SetMapper((vtkMapper)mapBookshelf1Bottom); bookshelf1BottomActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf1Front = new vtkStructuredGridGeometryFilter(); bookshelf1Front.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf1Front.SetExtent((int)13,(int)20,(int)0,(int)0,(int)0,(int)11); mapBookshelf1Front = vtkPolyDataMapper.New(); mapBookshelf1Front.SetInputConnection((vtkAlgorithmOutput)bookshelf1Front.GetOutputPort()); mapBookshelf1Front.ScalarVisibilityOff(); bookshelf1FrontActor = new vtkActor(); bookshelf1FrontActor.SetMapper((vtkMapper)mapBookshelf1Front); bookshelf1FrontActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf1Back = new vtkStructuredGridGeometryFilter(); bookshelf1Back.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf1Back.SetExtent((int)13,(int)20,(int)4,(int)4,(int)0,(int)11); mapBookshelf1Back = vtkPolyDataMapper.New(); mapBookshelf1Back.SetInputConnection((vtkAlgorithmOutput)bookshelf1Back.GetOutputPort()); mapBookshelf1Back.ScalarVisibilityOff(); bookshelf1BackActor = new vtkActor(); bookshelf1BackActor.SetMapper((vtkMapper)mapBookshelf1Back); bookshelf1BackActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf1LHS = new vtkStructuredGridGeometryFilter(); bookshelf1LHS.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf1LHS.SetExtent((int)13,(int)20,(int)0,(int)4,(int)0,(int)0); mapBookshelf1LHS = vtkPolyDataMapper.New(); mapBookshelf1LHS.SetInputConnection((vtkAlgorithmOutput)bookshelf1LHS.GetOutputPort()); mapBookshelf1LHS.ScalarVisibilityOff(); bookshelf1LHSActor = new vtkActor(); bookshelf1LHSActor.SetMapper((vtkMapper)mapBookshelf1LHS); bookshelf1LHSActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf1RHS = new vtkStructuredGridGeometryFilter(); bookshelf1RHS.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf1RHS.SetExtent((int)13,(int)20,(int)0,(int)4,(int)11,(int)11); mapBookshelf1RHS = vtkPolyDataMapper.New(); mapBookshelf1RHS.SetInputConnection((vtkAlgorithmOutput)bookshelf1RHS.GetOutputPort()); mapBookshelf1RHS.ScalarVisibilityOff(); bookshelf1RHSActor = new vtkActor(); bookshelf1RHSActor.SetMapper((vtkMapper)mapBookshelf1RHS); bookshelf1RHSActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf2Top = new vtkStructuredGridGeometryFilter(); bookshelf2Top.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf2Top.SetExtent((int)13,(int)13,(int)15,(int)19,(int)0,(int)11); mapBookshelf2Top = vtkPolyDataMapper.New(); mapBookshelf2Top.SetInputConnection((vtkAlgorithmOutput)bookshelf2Top.GetOutputPort()); mapBookshelf2Top.ScalarVisibilityOff(); bookshelf2TopActor = new vtkActor(); bookshelf2TopActor.SetMapper((vtkMapper)mapBookshelf2Top); bookshelf2TopActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf2Bottom = new vtkStructuredGridGeometryFilter(); bookshelf2Bottom.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf2Bottom.SetExtent((int)20,(int)20,(int)15,(int)19,(int)0,(int)11); mapBookshelf2Bottom = vtkPolyDataMapper.New(); mapBookshelf2Bottom.SetInputConnection((vtkAlgorithmOutput)bookshelf2Bottom.GetOutputPort()); mapBookshelf2Bottom.ScalarVisibilityOff(); bookshelf2BottomActor = new vtkActor(); bookshelf2BottomActor.SetMapper((vtkMapper)mapBookshelf2Bottom); bookshelf2BottomActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf2Front = new vtkStructuredGridGeometryFilter(); bookshelf2Front.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf2Front.SetExtent((int)13,(int)20,(int)15,(int)15,(int)0,(int)11); mapBookshelf2Front = vtkPolyDataMapper.New(); mapBookshelf2Front.SetInputConnection((vtkAlgorithmOutput)bookshelf2Front.GetOutputPort()); mapBookshelf2Front.ScalarVisibilityOff(); bookshelf2FrontActor = new vtkActor(); bookshelf2FrontActor.SetMapper((vtkMapper)mapBookshelf2Front); bookshelf2FrontActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf2Back = new vtkStructuredGridGeometryFilter(); bookshelf2Back.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf2Back.SetExtent((int)13,(int)20,(int)19,(int)19,(int)0,(int)11); mapBookshelf2Back = vtkPolyDataMapper.New(); mapBookshelf2Back.SetInputConnection((vtkAlgorithmOutput)bookshelf2Back.GetOutputPort()); mapBookshelf2Back.ScalarVisibilityOff(); bookshelf2BackActor = new vtkActor(); bookshelf2BackActor.SetMapper((vtkMapper)mapBookshelf2Back); bookshelf2BackActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf2LHS = new vtkStructuredGridGeometryFilter(); bookshelf2LHS.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf2LHS.SetExtent((int)13,(int)20,(int)15,(int)19,(int)0,(int)0); mapBookshelf2LHS = vtkPolyDataMapper.New(); mapBookshelf2LHS.SetInputConnection((vtkAlgorithmOutput)bookshelf2LHS.GetOutputPort()); mapBookshelf2LHS.ScalarVisibilityOff(); bookshelf2LHSActor = new vtkActor(); bookshelf2LHSActor.SetMapper((vtkMapper)mapBookshelf2LHS); bookshelf2LHSActor.GetProperty().SetColor((double).8,(double).8,(double).6); bookshelf2RHS = new vtkStructuredGridGeometryFilter(); bookshelf2RHS.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); bookshelf2RHS.SetExtent((int)13,(int)20,(int)15,(int)19,(int)11,(int)11); mapBookshelf2RHS = vtkPolyDataMapper.New(); mapBookshelf2RHS.SetInputConnection((vtkAlgorithmOutput)bookshelf2RHS.GetOutputPort()); mapBookshelf2RHS.ScalarVisibilityOff(); bookshelf2RHSActor = new vtkActor(); bookshelf2RHSActor.SetMapper((vtkMapper)mapBookshelf2RHS); bookshelf2RHSActor.GetProperty().SetColor((double).8,(double).8,(double).6); window = new vtkStructuredGridGeometryFilter(); window.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); window.SetExtent((int)20,(int)20,(int)6,(int)13,(int)10,(int)13); mapWindow = vtkPolyDataMapper.New(); mapWindow.SetInputConnection((vtkAlgorithmOutput)window.GetOutputPort()); mapWindow.ScalarVisibilityOff(); windowActor = new vtkActor(); windowActor.SetMapper((vtkMapper)mapWindow); windowActor.GetProperty().SetColor((double).3,(double).3,(double).5); outlet = new vtkStructuredGridGeometryFilter(); outlet.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); outlet.SetExtent((int)0,(int)0,(int)9,(int)10,(int)14,(int)16); mapOutlet = vtkPolyDataMapper.New(); mapOutlet.SetInputConnection((vtkAlgorithmOutput)outlet.GetOutputPort()); mapOutlet.ScalarVisibilityOff(); outletActor = new vtkActor(); outletActor.SetMapper((vtkMapper)mapOutlet); outletActor.GetProperty().SetColor((double)0,(double)0,(double)0); inlet = new vtkStructuredGridGeometryFilter(); inlet.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); inlet.SetExtent((int)0,(int)0,(int)9,(int)10,(int)0,(int)6); mapInlet = vtkPolyDataMapper.New(); mapInlet.SetInputConnection((vtkAlgorithmOutput)inlet.GetOutputPort()); mapInlet.ScalarVisibilityOff(); inletActor = new vtkActor(); inletActor.SetMapper((vtkMapper)mapInlet); inletActor.GetProperty().SetColor((double)0,(double)0,(double)0); outline = new vtkStructuredGridOutlineFilter(); outline.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); mapOutline = vtkPolyDataMapper.New(); mapOutline.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort()); outlineActor = new vtkActor(); outlineActor.SetMapper((vtkMapper)mapOutline); outlineActor.GetProperty().SetColor((double)0,(double)0,(double)0); // Create source for streamtubes[] streamer = new vtkStreamPoints(); streamer.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); streamer.SetStartPosition((double)0.1,(double)2.1,(double)0.5); streamer.SetMaximumPropagationTime((double)500); streamer.SetTimeIncrement((double)0.5); streamer.SetIntegrationDirectionToForward(); cone = new vtkConeSource(); cone.SetResolution((int)8); cones = new vtkGlyph3D(); cones.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort()); cones.SetSourceConnection(cone.GetOutputPort()); cones.SetScaleFactor((double)0.5); cones.SetScaleModeToScaleByVector(); mapCones = vtkPolyDataMapper.New(); mapCones.SetInputConnection((vtkAlgorithmOutput)cones.GetOutputPort()); mapCones.SetScalarRange((double)((vtkDataSet)reader.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)reader.GetOutput()).GetScalarRange()[1]); conesActor = new vtkActor(); conesActor.SetMapper((vtkMapper)mapCones); ren1.AddActor((vtkProp)table1Actor); ren1.AddActor((vtkProp)table2Actor); ren1.AddActor((vtkProp)FilingCabinet1Actor); ren1.AddActor((vtkProp)FilingCabinet2Actor); ren1.AddActor((vtkProp)bookshelf1TopActor); ren1.AddActor((vtkProp)bookshelf1BottomActor); ren1.AddActor((vtkProp)bookshelf1FrontActor); ren1.AddActor((vtkProp)bookshelf1BackActor); ren1.AddActor((vtkProp)bookshelf1LHSActor); ren1.AddActor((vtkProp)bookshelf1RHSActor); ren1.AddActor((vtkProp)bookshelf2TopActor); ren1.AddActor((vtkProp)bookshelf2BottomActor); ren1.AddActor((vtkProp)bookshelf2FrontActor); ren1.AddActor((vtkProp)bookshelf2BackActor); ren1.AddActor((vtkProp)bookshelf2LHSActor); ren1.AddActor((vtkProp)bookshelf2RHSActor); ren1.AddActor((vtkProp)windowActor); ren1.AddActor((vtkProp)outletActor); ren1.AddActor((vtkProp)inletActor); ren1.AddActor((vtkProp)outlineActor); ren1.AddActor((vtkProp)conesActor); ren1.SetBackground((double)0.4,(double)0.4,(double)0.5); aCamera = new vtkCamera(); aCamera.SetClippingRange((double)0.7724,(double)39); aCamera.SetFocalPoint((double)1.14798,(double)3.08416,(double)2.47187); aCamera.SetPosition((double)-2.64683,(double)-3.55525,(double)3.55848); aCamera.SetViewUp((double)0.0511273,(double)0.132773,(double)0.989827); aCamera.SetViewAngle((double)15.5033); ren1.SetActiveCamera((vtkCamera)aCamera); renWin.SetSize((int)500,(int)300); iren.Initialize(); // interact with data[] //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkStructuredGridReader reader; static vtkOnePieceExtentTranslator translator; static double length; static double maxVelocity; static double maxTime; static vtkStructuredGridGeometryFilter table1; static vtkPolyDataMapper mapTable1; static vtkActor table1Actor; static vtkStructuredGridGeometryFilter table2; static vtkPolyDataMapper mapTable2; static vtkActor table2Actor; static vtkStructuredGridGeometryFilter FilingCabinet1; static vtkPolyDataMapper mapFilingCabinet1; static vtkActor FilingCabinet1Actor; static vtkStructuredGridGeometryFilter FilingCabinet2; static vtkPolyDataMapper mapFilingCabinet2; static vtkActor FilingCabinet2Actor; static vtkStructuredGridGeometryFilter bookshelf1Top; static vtkPolyDataMapper mapBookshelf1Top; static vtkActor bookshelf1TopActor; static vtkStructuredGridGeometryFilter bookshelf1Bottom; static vtkPolyDataMapper mapBookshelf1Bottom; static vtkActor bookshelf1BottomActor; static vtkStructuredGridGeometryFilter bookshelf1Front; static vtkPolyDataMapper mapBookshelf1Front; static vtkActor bookshelf1FrontActor; static vtkStructuredGridGeometryFilter bookshelf1Back; static vtkPolyDataMapper mapBookshelf1Back; static vtkActor bookshelf1BackActor; static vtkStructuredGridGeometryFilter bookshelf1LHS; static vtkPolyDataMapper mapBookshelf1LHS; static vtkActor bookshelf1LHSActor; static vtkStructuredGridGeometryFilter bookshelf1RHS; static vtkPolyDataMapper mapBookshelf1RHS; static vtkActor bookshelf1RHSActor; static vtkStructuredGridGeometryFilter bookshelf2Top; static vtkPolyDataMapper mapBookshelf2Top; static vtkActor bookshelf2TopActor; static vtkStructuredGridGeometryFilter bookshelf2Bottom; static vtkPolyDataMapper mapBookshelf2Bottom; static vtkActor bookshelf2BottomActor; static vtkStructuredGridGeometryFilter bookshelf2Front; static vtkPolyDataMapper mapBookshelf2Front; static vtkActor bookshelf2FrontActor; static vtkStructuredGridGeometryFilter bookshelf2Back; static vtkPolyDataMapper mapBookshelf2Back; static vtkActor bookshelf2BackActor; static vtkStructuredGridGeometryFilter bookshelf2LHS; static vtkPolyDataMapper mapBookshelf2LHS; static vtkActor bookshelf2LHSActor; static vtkStructuredGridGeometryFilter bookshelf2RHS; static vtkPolyDataMapper mapBookshelf2RHS; static vtkActor bookshelf2RHSActor; static vtkStructuredGridGeometryFilter window; static vtkPolyDataMapper mapWindow; static vtkActor windowActor; static vtkStructuredGridGeometryFilter outlet; static vtkPolyDataMapper mapOutlet; static vtkActor outletActor; static vtkStructuredGridGeometryFilter inlet; static vtkPolyDataMapper mapInlet; static vtkActor inletActor; static vtkStructuredGridOutlineFilter outline; static vtkPolyDataMapper mapOutline; static vtkActor outlineActor; static vtkStreamPoints streamer; static vtkConeSource cone; static vtkGlyph3D cones; static vtkPolyDataMapper mapCones; static vtkActor conesActor; static vtkCamera aCamera; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridReader Getreader() { return reader; } ///<summary> A Set Method for Static Variables </summary> public static void Setreader(vtkStructuredGridReader toSet) { reader = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkOnePieceExtentTranslator Gettranslator() { return translator; } ///<summary> A Set Method for Static Variables </summary> public static void Settranslator(vtkOnePieceExtentTranslator toSet) { translator = toSet; } ///<summary> A Get Method for Static Variables </summary> public static double Getlength() { return length; } ///<summary> A Set Method for Static Variables </summary> public static void Setlength(double toSet) { length = toSet; } ///<summary> A Get Method for Static Variables </summary> public static double GetmaxVelocity() { return maxVelocity; } ///<summary> A Set Method for Static Variables </summary> public static void SetmaxVelocity(double toSet) { maxVelocity = toSet; } ///<summary> A Get Method for Static Variables </summary> public static double GetmaxTime() { return maxTime; } ///<summary> A Set Method for Static Variables </summary> public static void SetmaxTime(double toSet) { maxTime = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Gettable1() { return table1; } ///<summary> A Set Method for Static Variables </summary> public static void Settable1(vtkStructuredGridGeometryFilter toSet) { table1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapTable1() { return mapTable1; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapTable1(vtkPolyDataMapper toSet) { mapTable1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Gettable1Actor() { return table1Actor; } ///<summary> A Set Method for Static Variables </summary> public static void Settable1Actor(vtkActor toSet) { table1Actor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Gettable2() { return table2; } ///<summary> A Set Method for Static Variables </summary> public static void Settable2(vtkStructuredGridGeometryFilter toSet) { table2 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapTable2() { return mapTable2; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapTable2(vtkPolyDataMapper toSet) { mapTable2 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Gettable2Actor() { return table2Actor; } ///<summary> A Set Method for Static Variables </summary> public static void Settable2Actor(vtkActor toSet) { table2Actor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter GetFilingCabinet1() { return FilingCabinet1; } ///<summary> A Set Method for Static Variables </summary> public static void SetFilingCabinet1(vtkStructuredGridGeometryFilter toSet) { FilingCabinet1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapFilingCabinet1() { return mapFilingCabinet1; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapFilingCabinet1(vtkPolyDataMapper toSet) { mapFilingCabinet1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetFilingCabinet1Actor() { return FilingCabinet1Actor; } ///<summary> A Set Method for Static Variables </summary> public static void SetFilingCabinet1Actor(vtkActor toSet) { FilingCabinet1Actor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter GetFilingCabinet2() { return FilingCabinet2; } ///<summary> A Set Method for Static Variables </summary> public static void SetFilingCabinet2(vtkStructuredGridGeometryFilter toSet) { FilingCabinet2 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapFilingCabinet2() { return mapFilingCabinet2; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapFilingCabinet2(vtkPolyDataMapper toSet) { mapFilingCabinet2 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetFilingCabinet2Actor() { return FilingCabinet2Actor; } ///<summary> A Set Method for Static Variables </summary> public static void SetFilingCabinet2Actor(vtkActor toSet) { FilingCabinet2Actor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf1Top() { return bookshelf1Top; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1Top(vtkStructuredGridGeometryFilter toSet) { bookshelf1Top = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf1Top() { return mapBookshelf1Top; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf1Top(vtkPolyDataMapper toSet) { mapBookshelf1Top = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf1TopActor() { return bookshelf1TopActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1TopActor(vtkActor toSet) { bookshelf1TopActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf1Bottom() { return bookshelf1Bottom; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1Bottom(vtkStructuredGridGeometryFilter toSet) { bookshelf1Bottom = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf1Bottom() { return mapBookshelf1Bottom; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf1Bottom(vtkPolyDataMapper toSet) { mapBookshelf1Bottom = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf1BottomActor() { return bookshelf1BottomActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1BottomActor(vtkActor toSet) { bookshelf1BottomActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf1Front() { return bookshelf1Front; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1Front(vtkStructuredGridGeometryFilter toSet) { bookshelf1Front = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf1Front() { return mapBookshelf1Front; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf1Front(vtkPolyDataMapper toSet) { mapBookshelf1Front = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf1FrontActor() { return bookshelf1FrontActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1FrontActor(vtkActor toSet) { bookshelf1FrontActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf1Back() { return bookshelf1Back; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1Back(vtkStructuredGridGeometryFilter toSet) { bookshelf1Back = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf1Back() { return mapBookshelf1Back; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf1Back(vtkPolyDataMapper toSet) { mapBookshelf1Back = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf1BackActor() { return bookshelf1BackActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1BackActor(vtkActor toSet) { bookshelf1BackActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf1LHS() { return bookshelf1LHS; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1LHS(vtkStructuredGridGeometryFilter toSet) { bookshelf1LHS = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf1LHS() { return mapBookshelf1LHS; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf1LHS(vtkPolyDataMapper toSet) { mapBookshelf1LHS = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf1LHSActor() { return bookshelf1LHSActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1LHSActor(vtkActor toSet) { bookshelf1LHSActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf1RHS() { return bookshelf1RHS; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1RHS(vtkStructuredGridGeometryFilter toSet) { bookshelf1RHS = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf1RHS() { return mapBookshelf1RHS; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf1RHS(vtkPolyDataMapper toSet) { mapBookshelf1RHS = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf1RHSActor() { return bookshelf1RHSActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf1RHSActor(vtkActor toSet) { bookshelf1RHSActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf2Top() { return bookshelf2Top; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2Top(vtkStructuredGridGeometryFilter toSet) { bookshelf2Top = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf2Top() { return mapBookshelf2Top; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf2Top(vtkPolyDataMapper toSet) { mapBookshelf2Top = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf2TopActor() { return bookshelf2TopActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2TopActor(vtkActor toSet) { bookshelf2TopActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf2Bottom() { return bookshelf2Bottom; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2Bottom(vtkStructuredGridGeometryFilter toSet) { bookshelf2Bottom = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf2Bottom() { return mapBookshelf2Bottom; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf2Bottom(vtkPolyDataMapper toSet) { mapBookshelf2Bottom = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf2BottomActor() { return bookshelf2BottomActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2BottomActor(vtkActor toSet) { bookshelf2BottomActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf2Front() { return bookshelf2Front; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2Front(vtkStructuredGridGeometryFilter toSet) { bookshelf2Front = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf2Front() { return mapBookshelf2Front; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf2Front(vtkPolyDataMapper toSet) { mapBookshelf2Front = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf2FrontActor() { return bookshelf2FrontActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2FrontActor(vtkActor toSet) { bookshelf2FrontActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf2Back() { return bookshelf2Back; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2Back(vtkStructuredGridGeometryFilter toSet) { bookshelf2Back = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf2Back() { return mapBookshelf2Back; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf2Back(vtkPolyDataMapper toSet) { mapBookshelf2Back = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf2BackActor() { return bookshelf2BackActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2BackActor(vtkActor toSet) { bookshelf2BackActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf2LHS() { return bookshelf2LHS; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2LHS(vtkStructuredGridGeometryFilter toSet) { bookshelf2LHS = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf2LHS() { return mapBookshelf2LHS; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf2LHS(vtkPolyDataMapper toSet) { mapBookshelf2LHS = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf2LHSActor() { return bookshelf2LHSActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2LHSActor(vtkActor toSet) { bookshelf2LHSActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getbookshelf2RHS() { return bookshelf2RHS; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2RHS(vtkStructuredGridGeometryFilter toSet) { bookshelf2RHS = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapBookshelf2RHS() { return mapBookshelf2RHS; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapBookshelf2RHS(vtkPolyDataMapper toSet) { mapBookshelf2RHS = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor Getbookshelf2RHSActor() { return bookshelf2RHSActor; } ///<summary> A Set Method for Static Variables </summary> public static void Setbookshelf2RHSActor(vtkActor toSet) { bookshelf2RHSActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getwindow() { return window; } ///<summary> A Set Method for Static Variables </summary> public static void Setwindow(vtkStructuredGridGeometryFilter toSet) { window = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapWindow() { return mapWindow; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapWindow(vtkPolyDataMapper toSet) { mapWindow = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetwindowActor() { return windowActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetwindowActor(vtkActor toSet) { windowActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getoutlet() { return outlet; } ///<summary> A Set Method for Static Variables </summary> public static void Setoutlet(vtkStructuredGridGeometryFilter toSet) { outlet = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapOutlet() { return mapOutlet; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapOutlet(vtkPolyDataMapper toSet) { mapOutlet = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetoutletActor() { return outletActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutletActor(vtkActor toSet) { outletActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridGeometryFilter Getinlet() { return inlet; } ///<summary> A Set Method for Static Variables </summary> public static void Setinlet(vtkStructuredGridGeometryFilter toSet) { inlet = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapInlet() { return mapInlet; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapInlet(vtkPolyDataMapper toSet) { mapInlet = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetinletActor() { return inletActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetinletActor(vtkActor toSet) { inletActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStructuredGridOutlineFilter Getoutline() { return outline; } ///<summary> A Set Method for Static Variables </summary> public static void Setoutline(vtkStructuredGridOutlineFilter toSet) { outline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapOutline() { return mapOutline; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapOutline(vtkPolyDataMapper toSet) { mapOutline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetoutlineActor() { return outlineActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineActor(vtkActor toSet) { outlineActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStreamPoints Getstreamer() { return streamer; } ///<summary> A Set Method for Static Variables </summary> public static void Setstreamer(vtkStreamPoints toSet) { streamer = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkConeSource Getcone() { return cone; } ///<summary> A Set Method for Static Variables </summary> public static void Setcone(vtkConeSource toSet) { cone = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkGlyph3D Getcones() { return cones; } ///<summary> A Set Method for Static Variables </summary> public static void Setcones(vtkGlyph3D toSet) { cones = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapCones() { return mapCones; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapCones(vtkPolyDataMapper toSet) { mapCones = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetconesActor() { return conesActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetconesActor(vtkActor toSet) { conesActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCamera GetaCamera() { return aCamera; } ///<summary> A Set Method for Static Variables </summary> public static void SetaCamera(vtkCamera toSet) { aCamera = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} if(reader!= null){reader.Dispose();} if(translator!= null){translator.Dispose();} if(table1!= null){table1.Dispose();} if(mapTable1!= null){mapTable1.Dispose();} if(table1Actor!= null){table1Actor.Dispose();} if(table2!= null){table2.Dispose();} if(mapTable2!= null){mapTable2.Dispose();} if(table2Actor!= null){table2Actor.Dispose();} if(FilingCabinet1!= null){FilingCabinet1.Dispose();} if(mapFilingCabinet1!= null){mapFilingCabinet1.Dispose();} if(FilingCabinet1Actor!= null){FilingCabinet1Actor.Dispose();} if(FilingCabinet2!= null){FilingCabinet2.Dispose();} if(mapFilingCabinet2!= null){mapFilingCabinet2.Dispose();} if(FilingCabinet2Actor!= null){FilingCabinet2Actor.Dispose();} if(bookshelf1Top!= null){bookshelf1Top.Dispose();} if(mapBookshelf1Top!= null){mapBookshelf1Top.Dispose();} if(bookshelf1TopActor!= null){bookshelf1TopActor.Dispose();} if(bookshelf1Bottom!= null){bookshelf1Bottom.Dispose();} if(mapBookshelf1Bottom!= null){mapBookshelf1Bottom.Dispose();} if(bookshelf1BottomActor!= null){bookshelf1BottomActor.Dispose();} if(bookshelf1Front!= null){bookshelf1Front.Dispose();} if(mapBookshelf1Front!= null){mapBookshelf1Front.Dispose();} if(bookshelf1FrontActor!= null){bookshelf1FrontActor.Dispose();} if(bookshelf1Back!= null){bookshelf1Back.Dispose();} if(mapBookshelf1Back!= null){mapBookshelf1Back.Dispose();} if(bookshelf1BackActor!= null){bookshelf1BackActor.Dispose();} if(bookshelf1LHS!= null){bookshelf1LHS.Dispose();} if(mapBookshelf1LHS!= null){mapBookshelf1LHS.Dispose();} if(bookshelf1LHSActor!= null){bookshelf1LHSActor.Dispose();} if(bookshelf1RHS!= null){bookshelf1RHS.Dispose();} if(mapBookshelf1RHS!= null){mapBookshelf1RHS.Dispose();} if(bookshelf1RHSActor!= null){bookshelf1RHSActor.Dispose();} if(bookshelf2Top!= null){bookshelf2Top.Dispose();} if(mapBookshelf2Top!= null){mapBookshelf2Top.Dispose();} if(bookshelf2TopActor!= null){bookshelf2TopActor.Dispose();} if(bookshelf2Bottom!= null){bookshelf2Bottom.Dispose();} if(mapBookshelf2Bottom!= null){mapBookshelf2Bottom.Dispose();} if(bookshelf2BottomActor!= null){bookshelf2BottomActor.Dispose();} if(bookshelf2Front!= null){bookshelf2Front.Dispose();} if(mapBookshelf2Front!= null){mapBookshelf2Front.Dispose();} if(bookshelf2FrontActor!= null){bookshelf2FrontActor.Dispose();} if(bookshelf2Back!= null){bookshelf2Back.Dispose();} if(mapBookshelf2Back!= null){mapBookshelf2Back.Dispose();} if(bookshelf2BackActor!= null){bookshelf2BackActor.Dispose();} if(bookshelf2LHS!= null){bookshelf2LHS.Dispose();} if(mapBookshelf2LHS!= null){mapBookshelf2LHS.Dispose();} if(bookshelf2LHSActor!= null){bookshelf2LHSActor.Dispose();} if(bookshelf2RHS!= null){bookshelf2RHS.Dispose();} if(mapBookshelf2RHS!= null){mapBookshelf2RHS.Dispose();} if(bookshelf2RHSActor!= null){bookshelf2RHSActor.Dispose();} if(window!= null){window.Dispose();} if(mapWindow!= null){mapWindow.Dispose();} if(windowActor!= null){windowActor.Dispose();} if(outlet!= null){outlet.Dispose();} if(mapOutlet!= null){mapOutlet.Dispose();} if(outletActor!= null){outletActor.Dispose();} if(inlet!= null){inlet.Dispose();} if(mapInlet!= null){mapInlet.Dispose();} if(inletActor!= null){inletActor.Dispose();} if(outline!= null){outline.Dispose();} if(mapOutline!= null){mapOutline.Dispose();} if(outlineActor!= null){outlineActor.Dispose();} if(streamer!= null){streamer.Dispose();} if(cone!= null){cone.Dispose();} if(cones!= null){cones.Dispose();} if(mapCones!= null){mapCones.Dispose();} if(conesActor!= null){conesActor.Dispose();} if(aCamera!= null){aCamera.Dispose();} } } //--- end of script --//
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Utils; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osuTK; #nullable enable namespace osu.Game.Rulesets.Catch.Objects { /// <summary> /// Represents the path of a juice stream. /// <para> /// A <see cref="JuiceStream"/> holds a legacy <see cref="SliderPath"/> as the representation of the path. /// However, the <see cref="SliderPath"/> representation is difficult to work with. /// This <see cref="JuiceStreamPath"/> represents the path in a more convenient way, a polyline connecting list of <see cref="JuiceStreamPathVertex"/>s. /// </para> /// <para> /// The path can be regarded as a function from the closed interval <c>[Vertices[0].Distance, Vertices[^1].Distance]</c> to the x position, given by <see cref="PositionAtDistance"/>. /// To ensure the path is convertible to a <see cref="SliderPath"/>, the slope of the function must not be more than <c>1</c> everywhere, /// and this slope condition is always maintained as an invariant. /// </para> /// </summary> public class JuiceStreamPath { /// <summary> /// The height of legacy osu!standard playfield. /// The sliders converted by <see cref="ConvertToSliderPath"/> are vertically contained in this height. /// </summary> internal const float OSU_PLAYFIELD_HEIGHT = 384; /// <summary> /// The list of vertices of the path, which is represented as a polyline connecting the vertices. /// </summary> public IReadOnlyList<JuiceStreamPathVertex> Vertices => vertices; /// <summary> /// The current version number. /// This starts from <c>1</c> and incremented whenever this <see cref="JuiceStreamPath"/> is modified. /// </summary> public int InvalidationID { get; private set; } = 1; /// <summary> /// The difference between first vertex's <see cref="JuiceStreamPathVertex.Distance"/> and last vertex's <see cref="JuiceStreamPathVertex.Distance"/>. /// </summary> public double Distance => vertices[^1].Distance - vertices[0].Distance; /// <remarks> /// This list should always be non-empty. /// </remarks> private readonly List<JuiceStreamPathVertex> vertices = new List<JuiceStreamPathVertex> { new JuiceStreamPathVertex() }; /// <summary> /// Compute the x-position of the path at the given <paramref name="distance"/>. /// </summary> /// <remarks> /// When the given distance is outside of the path, the x position at the corresponding endpoint is returned, /// </remarks> public float PositionAtDistance(double distance) { int index = vertexIndexAtDistance(distance); return positionAtDistance(distance, index); } /// <summary> /// Remove all vertices of this path, then add a new vertex <c>(0, 0)</c>. /// </summary> public void Clear() { vertices.Clear(); vertices.Add(new JuiceStreamPathVertex()); invalidate(); } /// <summary> /// Insert a vertex at given <paramref name="distance"/>. /// The <see cref="PositionAtDistance"/> is used as the position of the new vertex. /// Thus, the set of points of the path is not changed (up to floating-point precision). /// </summary> /// <returns>The index of the new vertex.</returns> public int InsertVertex(double distance) { if (!double.IsFinite(distance)) throw new ArgumentOutOfRangeException(nameof(distance)); int index = vertexIndexAtDistance(distance); float x = positionAtDistance(distance, index); vertices.Insert(index, new JuiceStreamPathVertex(distance, x)); invalidate(); return index; } /// <summary> /// Move the vertex of given <paramref name="index"/> to the given position <paramref name="newX"/>. /// When the distances between vertices are too small for the new vertex positions, the adjacent vertices are moved towards <paramref name="newX"/>. /// </summary> public void SetVertexPosition(int index, float newX) { if (index < 0 || index >= vertices.Count) throw new ArgumentOutOfRangeException(nameof(index)); if (!float.IsFinite(newX)) throw new ArgumentOutOfRangeException(nameof(newX)); var newVertex = new JuiceStreamPathVertex(vertices[index].Distance, newX); for (int i = index - 1; i >= 0 && !canConnect(vertices[i], newVertex); i--) { float clampedX = clampToConnectablePosition(newVertex, vertices[i]); vertices[i] = new JuiceStreamPathVertex(vertices[i].Distance, clampedX); } for (int i = index + 1; i < vertices.Count; i++) { float clampedX = clampToConnectablePosition(newVertex, vertices[i]); vertices[i] = new JuiceStreamPathVertex(vertices[i].Distance, clampedX); } vertices[index] = newVertex; invalidate(); } /// <summary> /// Add a new vertex at given <paramref name="distance"/> and position. /// Adjacent vertices are moved when necessary in the same way as <see cref="SetVertexPosition"/>. /// </summary> public void Add(double distance, float x) { int index = InsertVertex(distance); SetVertexPosition(index, x); } /// <summary> /// Remove all vertices that satisfy the given <paramref name="predicate"/>. /// </summary> /// <remarks> /// If all vertices are removed, a new vertex <c>(0, 0)</c> is added. /// </remarks> /// <param name="predicate">The predicate to determine whether a vertex should be removed given the vertex and its index in the path.</param> /// <returns>The number of removed vertices.</returns> public int RemoveVertices(Func<JuiceStreamPathVertex, int, bool> predicate) { int index = 0; int removeCount = vertices.RemoveAll(vertex => predicate(vertex, index++)); if (vertices.Count == 0) vertices.Add(new JuiceStreamPathVertex()); if (removeCount != 0) invalidate(); return removeCount; } /// <summary> /// Recreate this path by using difference set of vertices at given distances. /// In addition to the given <paramref name="sampleDistances"/>, the first vertex and the last vertex are always added to the new path. /// New vertices use the positions on the original path. Thus, <see cref="PositionAtDistance"/>s at <paramref name="sampleDistances"/> are preserved. /// </summary> public void ResampleVertices(IEnumerable<double> sampleDistances) { var sampledVertices = new List<JuiceStreamPathVertex>(); foreach (double distance in sampleDistances) { if (!double.IsFinite(distance)) throw new ArgumentOutOfRangeException(nameof(sampleDistances)); double clampedDistance = Math.Clamp(distance, vertices[0].Distance, vertices[^1].Distance); float x = PositionAtDistance(clampedDistance); sampledVertices.Add(new JuiceStreamPathVertex(clampedDistance, x)); } sampledVertices.Sort(); // The first vertex and the last vertex are always used in the result. vertices.RemoveRange(1, vertices.Count - (vertices.Count == 1 ? 1 : 2)); vertices.InsertRange(1, sampledVertices); invalidate(); } /// <summary> /// Convert a <see cref="SliderPath"/> to list of vertices and write the result to this <see cref="JuiceStreamPath"/>. /// </summary> /// <remarks> /// Duplicated vertices are automatically removed. /// </remarks> public void ConvertFromSliderPath(SliderPath sliderPath) { var sliderPathVertices = new List<Vector2>(); sliderPath.GetPathToProgress(sliderPathVertices, 0, 1); double distance = 0; vertices.Clear(); vertices.Add(new JuiceStreamPathVertex(0, sliderPathVertices.FirstOrDefault().X)); for (int i = 1; i < sliderPathVertices.Count; i++) { distance += Vector2.Distance(sliderPathVertices[i - 1], sliderPathVertices[i]); if (!Precision.AlmostEquals(vertices[^1].Distance, distance)) vertices.Add(new JuiceStreamPathVertex(distance, sliderPathVertices[i].X)); } invalidate(); } /// <summary> /// Convert the path of this <see cref="JuiceStreamPath"/> to a <see cref="SliderPath"/> and write the result to <paramref name="sliderPath"/>. /// The resulting slider is "folded" to make it vertically contained in the playfield `(0..<see cref="OSU_PLAYFIELD_HEIGHT"/>)` assuming the slider start position is <paramref name="sliderStartY"/>. /// </summary> public void ConvertToSliderPath(SliderPath sliderPath, float sliderStartY) { const float margin = 1; // Note: these two variables and `sliderPath` are modified by the local functions. double currentDistance = 0; Vector2 lastPosition = new Vector2(vertices[0].X, 0); sliderPath.ControlPoints.Clear(); sliderPath.ControlPoints.Add(new PathControlPoint(lastPosition)); for (int i = 1; i < vertices.Count; i++) { sliderPath.ControlPoints[^1].Type.Value = PathType.Linear; float deltaX = vertices[i].X - lastPosition.X; double length = vertices[i].Distance - currentDistance; // Should satisfy `deltaX^2 + deltaY^2 = length^2`. // By invariants, the expression inside the `sqrt` is (almost) non-negative. double deltaY = Math.Sqrt(Math.Max(0, length * length - (double)deltaX * deltaX)); // When `deltaY` is small, one segment is always enough. // This case is handled separately to prevent divide-by-zero. if (deltaY <= OSU_PLAYFIELD_HEIGHT / 2 - margin) { float nextX = vertices[i].X; float nextY = (float)(lastPosition.Y + getYDirection() * deltaY); addControlPoint(nextX, nextY); continue; } // When `deltaY` is large or when the slider velocity is fast, the segment must be partitioned to subsegments to stay in bounds. for (double currentProgress = 0; currentProgress < deltaY;) { double nextProgress = Math.Min(currentProgress + getMaxDeltaY(), deltaY); float nextX = (float)(vertices[i - 1].X + nextProgress / deltaY * deltaX); float nextY = (float)(lastPosition.Y + getYDirection() * (nextProgress - currentProgress)); addControlPoint(nextX, nextY); currentProgress = nextProgress; } } int getYDirection() { float lastSliderY = sliderStartY + lastPosition.Y; return lastSliderY < OSU_PLAYFIELD_HEIGHT / 2 ? 1 : -1; } float getMaxDeltaY() { float lastSliderY = sliderStartY + lastPosition.Y; return Math.Max(lastSliderY, OSU_PLAYFIELD_HEIGHT - lastSliderY) - margin; } void addControlPoint(float nextX, float nextY) { Vector2 nextPosition = new Vector2(nextX, nextY); sliderPath.ControlPoints.Add(new PathControlPoint(nextPosition)); currentDistance += Vector2.Distance(lastPosition, nextPosition); lastPosition = nextPosition; } } /// <summary> /// Find the index at which a new vertex with <paramref name="distance"/> can be inserted. /// </summary> private int vertexIndexAtDistance(double distance) { // The position of `(distance, Infinity)` is uniquely determined because infinite positions are not allowed. int i = vertices.BinarySearch(new JuiceStreamPathVertex(distance, float.PositiveInfinity)); return i < 0 ? ~i : i; } /// <summary> /// Compute the position at the given <paramref name="distance"/>, assuming <paramref name="index"/> is the vertex index returned by <see cref="vertexIndexAtDistance"/>. /// </summary> private float positionAtDistance(double distance, int index) { if (index <= 0) return vertices[0].X; if (index >= vertices.Count) return vertices[^1].X; double length = vertices[index].Distance - vertices[index - 1].Distance; if (Precision.AlmostEquals(length, 0)) return vertices[index].X; float deltaX = vertices[index].X - vertices[index - 1].X; return (float)(vertices[index - 1].X + deltaX * ((distance - vertices[index - 1].Distance) / length)); } /// <summary> /// Check the two vertices can connected directly while satisfying the slope condition. /// </summary> private bool canConnect(JuiceStreamPathVertex vertex1, JuiceStreamPathVertex vertex2, float allowance = 0) { double xDistance = Math.Abs((double)vertex2.X - vertex1.X); float length = (float)Math.Abs(vertex2.Distance - vertex1.Distance); return xDistance <= length + allowance; } /// <summary> /// Move the position of <paramref name="movableVertex"/> towards the position of <paramref name="fixedVertex"/> /// until the vertex pair satisfies the condition <see cref="canConnect"/>. /// </summary> /// <returns>The resulting position of <paramref name="movableVertex"/>.</returns> private float clampToConnectablePosition(JuiceStreamPathVertex fixedVertex, JuiceStreamPathVertex movableVertex) { float length = (float)Math.Abs(movableVertex.Distance - fixedVertex.Distance); return Math.Clamp(movableVertex.X, fixedVertex.X - length, fixedVertex.X + length); } private void invalidate() => InvalidationID++; } }