context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Monitor.Management
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Monitor Management Client
/// </summary>
public partial class MonitorManagementClient : ServiceClient<MonitorManagementClient>, IMonitorManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The Azure subscription Id.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IAutoscaleSettingsOperations.
/// </summary>
public virtual IAutoscaleSettingsOperations AutoscaleSettings { get; private set; }
/// <summary>
/// Gets the IAlertRuleIncidentsOperations.
/// </summary>
public virtual IAlertRuleIncidentsOperations AlertRuleIncidents { get; private set; }
/// <summary>
/// Gets the IAlertRulesOperations.
/// </summary>
public virtual IAlertRulesOperations AlertRules { get; private set; }
/// <summary>
/// Gets the ILogProfilesOperations.
/// </summary>
public virtual ILogProfilesOperations LogProfiles { get; private set; }
/// <summary>
/// Gets the IServiceDiagnosticSettingsOperations.
/// </summary>
public virtual IServiceDiagnosticSettingsOperations ServiceDiagnosticSettings { get; private set; }
/// <summary>
/// Gets the IActionGroupsOperations.
/// </summary>
public virtual IActionGroupsOperations ActionGroups { get; private set; }
/// <summary>
/// Gets the IActivityLogAlertsOperations.
/// </summary>
public virtual IActivityLogAlertsOperations ActivityLogAlerts { get; private set; }
/// <summary>
/// Initializes a new instance of the MonitorManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected MonitorManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the MonitorManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected MonitorManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the MonitorManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected MonitorManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the MonitorManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected MonitorManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the MonitorManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MonitorManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MonitorManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MonitorManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MonitorManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MonitorManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the MonitorManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public MonitorManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
AutoscaleSettings = new AutoscaleSettingsOperations(this);
AlertRuleIncidents = new AlertRuleIncidentsOperations(this);
AlertRules = new AlertRulesOperations(this);
LogProfiles = new LogProfilesOperations(this);
ServiceDiagnosticSettings = new ServiceDiagnosticSettingsOperations(this);
ActionGroups = new ActionGroupsOperations(this);
ActivityLogAlerts = new ActivityLogAlertsOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RuleDataSource>("odata.type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RuleDataSource>("odata.type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RuleCondition>("odata.type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RuleCondition>("odata.type"));
SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<RuleAction>("odata.type"));
DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<RuleAction>("odata.type"));
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// 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="FeedItemSetServiceClient"/> instances.</summary>
public sealed partial class FeedItemSetServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="FeedItemSetServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="FeedItemSetServiceSettings"/>.</returns>
public static FeedItemSetServiceSettings GetDefault() => new FeedItemSetServiceSettings();
/// <summary>Constructs a new <see cref="FeedItemSetServiceSettings"/> object with default settings.</summary>
public FeedItemSetServiceSettings()
{
}
private FeedItemSetServiceSettings(FeedItemSetServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetFeedItemSetSettings = existing.GetFeedItemSetSettings;
MutateFeedItemSetsSettings = existing.MutateFeedItemSetsSettings;
OnCopy(existing);
}
partial void OnCopy(FeedItemSetServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FeedItemSetServiceClient.GetFeedItemSet</c> and <c>FeedItemSetServiceClient.GetFeedItemSetAsync</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 GetFeedItemSetSettings { 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>FeedItemSetServiceClient.MutateFeedItemSets</c> and <c>FeedItemSetServiceClient.MutateFeedItemSetsAsync</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 MutateFeedItemSetsSettings { 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="FeedItemSetServiceSettings"/> object.</returns>
public FeedItemSetServiceSettings Clone() => new FeedItemSetServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="FeedItemSetServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class FeedItemSetServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeedItemSetServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public FeedItemSetServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public FeedItemSetServiceClientBuilder()
{
UseJwtAccessWithScopes = FeedItemSetServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref FeedItemSetServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeedItemSetServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override FeedItemSetServiceClient Build()
{
FeedItemSetServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<FeedItemSetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<FeedItemSetServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private FeedItemSetServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return FeedItemSetServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<FeedItemSetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return FeedItemSetServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => FeedItemSetServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeedItemSetServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => FeedItemSetServiceClient.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>FeedItemSetService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage feed Item Set
/// </remarks>
public abstract partial class FeedItemSetServiceClient
{
/// <summary>
/// The default endpoint for the FeedItemSetService 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 FeedItemSetService scopes.</summary>
/// <remarks>
/// The default FeedItemSetService 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="FeedItemSetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="FeedItemSetServiceClientBuilder"/>
/// .
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="FeedItemSetServiceClient"/>.</returns>
public static stt::Task<FeedItemSetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new FeedItemSetServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="FeedItemSetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="FeedItemSetServiceClientBuilder"/>
/// .
/// </summary>
/// <returns>The created <see cref="FeedItemSetServiceClient"/>.</returns>
public static FeedItemSetServiceClient Create() => new FeedItemSetServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="FeedItemSetServiceClient"/> 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="FeedItemSetServiceSettings"/>.</param>
/// <returns>The created <see cref="FeedItemSetServiceClient"/>.</returns>
internal static FeedItemSetServiceClient Create(grpccore::CallInvoker callInvoker, FeedItemSetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
FeedItemSetService.FeedItemSetServiceClient grpcClient = new FeedItemSetService.FeedItemSetServiceClient(callInvoker);
return new FeedItemSetServiceClientImpl(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 FeedItemSetService client</summary>
public virtual FeedItemSetService.FeedItemSetServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested feed item set 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::FeedItemSet GetFeedItemSet(GetFeedItemSetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested feed item set 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::FeedItemSet> GetFeedItemSetAsync(GetFeedItemSetRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested feed item set 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::FeedItemSet> GetFeedItemSetAsync(GetFeedItemSetRequest request, st::CancellationToken cancellationToken) =>
GetFeedItemSetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested feed item set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item 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::FeedItemSet GetFeedItemSet(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetFeedItemSet(new GetFeedItemSetRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested feed item set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item 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::FeedItemSet> GetFeedItemSetAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetFeedItemSetAsync(new GetFeedItemSetRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested feed item set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item 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::FeedItemSet> GetFeedItemSetAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetFeedItemSetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested feed item set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item 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::FeedItemSet GetFeedItemSet(gagvr::FeedItemSetName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetFeedItemSet(new GetFeedItemSetRequest
{
ResourceNameAsFeedItemSetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested feed item set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item 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::FeedItemSet> GetFeedItemSetAsync(gagvr::FeedItemSetName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetFeedItemSetAsync(new GetFeedItemSetRequest
{
ResourceNameAsFeedItemSetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested feed item set in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the feed item 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::FeedItemSet> GetFeedItemSetAsync(gagvr::FeedItemSetName resourceName, st::CancellationToken cancellationToken) =>
GetFeedItemSetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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 MutateFeedItemSetsResponse MutateFeedItemSets(MutateFeedItemSetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(MutateFeedItemSetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(MutateFeedItemSetsRequest request, st::CancellationToken cancellationToken) =>
MutateFeedItemSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose feed item sets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual feed item sets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateFeedItemSetsResponse MutateFeedItemSets(string customerId, scg::IEnumerable<FeedItemSetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateFeedItemSets(new MutateFeedItemSetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose feed item sets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual feed item 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<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(string customerId, scg::IEnumerable<FeedItemSetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateFeedItemSetsAsync(new MutateFeedItemSetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose feed item sets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual feed item 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<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(string customerId, scg::IEnumerable<FeedItemSetOperation> operations, st::CancellationToken cancellationToken) =>
MutateFeedItemSetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>FeedItemSetService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage feed Item Set
/// </remarks>
public sealed partial class FeedItemSetServiceClientImpl : FeedItemSetServiceClient
{
private readonly gaxgrpc::ApiCall<GetFeedItemSetRequest, gagvr::FeedItemSet> _callGetFeedItemSet;
private readonly gaxgrpc::ApiCall<MutateFeedItemSetsRequest, MutateFeedItemSetsResponse> _callMutateFeedItemSets;
/// <summary>
/// Constructs a client wrapper for the FeedItemSetService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="FeedItemSetServiceSettings"/> used within this client.</param>
public FeedItemSetServiceClientImpl(FeedItemSetService.FeedItemSetServiceClient grpcClient, FeedItemSetServiceSettings settings)
{
GrpcClient = grpcClient;
FeedItemSetServiceSettings effectiveSettings = settings ?? FeedItemSetServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetFeedItemSet = clientHelper.BuildApiCall<GetFeedItemSetRequest, gagvr::FeedItemSet>(grpcClient.GetFeedItemSetAsync, grpcClient.GetFeedItemSet, effectiveSettings.GetFeedItemSetSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetFeedItemSet);
Modify_GetFeedItemSetApiCall(ref _callGetFeedItemSet);
_callMutateFeedItemSets = clientHelper.BuildApiCall<MutateFeedItemSetsRequest, MutateFeedItemSetsResponse>(grpcClient.MutateFeedItemSetsAsync, grpcClient.MutateFeedItemSets, effectiveSettings.MutateFeedItemSetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateFeedItemSets);
Modify_MutateFeedItemSetsApiCall(ref _callMutateFeedItemSets);
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_GetFeedItemSetApiCall(ref gaxgrpc::ApiCall<GetFeedItemSetRequest, gagvr::FeedItemSet> call);
partial void Modify_MutateFeedItemSetsApiCall(ref gaxgrpc::ApiCall<MutateFeedItemSetsRequest, MutateFeedItemSetsResponse> call);
partial void OnConstruction(FeedItemSetService.FeedItemSetServiceClient grpcClient, FeedItemSetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC FeedItemSetService client</summary>
public override FeedItemSetService.FeedItemSetServiceClient GrpcClient { get; }
partial void Modify_GetFeedItemSetRequest(ref GetFeedItemSetRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateFeedItemSetsRequest(ref MutateFeedItemSetsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested feed item set 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::FeedItemSet GetFeedItemSet(GetFeedItemSetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetFeedItemSetRequest(ref request, ref callSettings);
return _callGetFeedItemSet.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested feed item set 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::FeedItemSet> GetFeedItemSetAsync(GetFeedItemSetRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetFeedItemSetRequest(ref request, ref callSettings);
return _callGetFeedItemSet.Async(request, callSettings);
}
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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 MutateFeedItemSetsResponse MutateFeedItemSets(MutateFeedItemSetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateFeedItemSetsRequest(ref request, ref callSettings);
return _callMutateFeedItemSets.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [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<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(MutateFeedItemSetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateFeedItemSetsRequest(ref request, ref callSettings);
return _callMutateFeedItemSets.Async(request, callSettings);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using System.Runtime.Serialization;
using Newtonsoft.Json.Utilities.LinqBridge;
namespace Newtonsoft.Json.Serialization
{
internal class JsonSerializerInternalWriter : JsonSerializerInternalBase
{
private JsonContract _rootContract;
private int _rootLevel;
private readonly List<object> _serializeStack = new List<object>();
private JsonSerializerProxy _internalSerializer;
public JsonSerializerInternalWriter(JsonSerializer serializer)
: base(serializer)
{
}
public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
{
if (jsonWriter == null)
throw new ArgumentNullException("jsonWriter");
_rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
_rootLevel = _serializeStack.Count + 1;
JsonContract contract = GetContractSafe(value);
try
{
SerializeValue(jsonWriter, value, contract, null, null, null);
}
catch (Exception ex)
{
if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
{
HandleError(jsonWriter, 0);
}
else
{
// clear context in case serializer is being used inside a converter
// if the converter wraps the error then not clearing the context will cause this error:
// "Current error context error is different to requested error."
ClearErrorContext();
throw;
}
}
finally
{
// clear root contract to ensure that if level was > 1 then it won't
// accidently be used for non root values
_rootContract = null;
}
}
private JsonSerializerProxy GetInternalSerializer()
{
if (_internalSerializer == null)
_internalSerializer = new JsonSerializerProxy(this);
return _internalSerializer;
}
private JsonContract GetContractSafe(object value)
{
if (value == null)
return null;
return Serializer._contractResolver.ResolveContract(value.GetType());
}
private void SerializePrimitive(JsonWriter writer, object value, JsonPrimitiveContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (contract.TypeCode == PrimitiveTypeCode.Bytes)
{
// if type name handling is enabled then wrap the base64 byte string in an object with the type name
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Objects, contract, member, containerContract, containerProperty);
if (includeTypeDetails)
{
writer.WriteStartObject();
WriteTypeProperty(writer, contract.CreatedType);
writer.WritePropertyName(JsonTypeReflector.ValuePropertyName, false);
JsonWriter.WriteValue(writer, contract.TypeCode, value);
writer.WriteEndObject();
return;
}
}
JsonWriter.WriteValue(writer, contract.TypeCode, value);
}
private void SerializeValue(JsonWriter writer, object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null)
{
writer.WriteNull();
return;
}
JsonConverter converter =
((member != null) ? member.Converter : null) ??
((containerProperty != null) ? containerProperty.ItemConverter : null) ??
((containerContract != null) ? containerContract.ItemConverter : null) ??
valueContract.Converter ??
Serializer.GetMatchingConverter(valueContract.UnderlyingType) ??
valueContract.InternalConverter;
if (converter != null && converter.CanWrite)
{
SerializeConvertable(writer, converter, value, valueContract, containerContract, containerProperty);
return;
}
switch (valueContract.ContractType)
{
case JsonContractType.Object:
SerializeObject(writer, value, (JsonObjectContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Array:
JsonArrayContract arrayContract = (JsonArrayContract)valueContract;
if (!arrayContract.IsMultidimensionalArray)
SerializeList(writer, (IEnumerable)value, arrayContract, member, containerContract, containerProperty);
else
SerializeMultidimensionalArray(writer, (Array)value, arrayContract, member, containerContract, containerProperty);
break;
case JsonContractType.Primitive:
SerializePrimitive(writer, value, (JsonPrimitiveContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.String:
SerializeString(writer, value, (JsonStringContract)valueContract);
break;
case JsonContractType.Dictionary:
JsonDictionaryContract dictionaryContract = (JsonDictionaryContract)valueContract;
SerializeDictionary(writer, (value is IDictionary) ? (IDictionary)value : dictionaryContract.CreateWrapper(value), dictionaryContract, member, containerContract, containerProperty);
break;
case JsonContractType.Serializable:
SerializeISerializable(writer, (ISerializable)value, (JsonISerializableContract)valueContract, member, containerContract, containerProperty);
break;
case JsonContractType.Linq:
((JToken)value).WriteTo(writer, Serializer.Converters.ToArray());
break;
}
}
private bool? ResolveIsReference(JsonContract contract, JsonProperty property, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
bool? isReference = null;
// value could be coming from a dictionary or array and not have a property
if (property != null)
isReference = property.IsReference;
if (isReference == null && containerProperty != null)
isReference = containerProperty.ItemIsReference;
if (isReference == null && collectionContract != null)
isReference = collectionContract.ItemIsReference;
if (isReference == null)
isReference = contract.IsReference;
return isReference;
}
private bool ShouldWriteReference(object value, JsonProperty property, JsonContract valueContract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (value == null)
return false;
if (valueContract.ContractType == JsonContractType.Primitive || valueContract.ContractType == JsonContractType.String)
return false;
bool? isReference = ResolveIsReference(valueContract, property, collectionContract, containerProperty);
if (isReference == null)
{
if (valueContract.ContractType == JsonContractType.Array)
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
else
isReference = HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
}
if (!isReference.Value)
return false;
return Serializer.GetReferenceResolver().IsReferenced(this, value);
}
private bool ShouldWriteProperty(object memberValue, JsonProperty property)
{
if (property.NullValueHandling.GetValueOrDefault(Serializer._nullValueHandling) == NullValueHandling.Ignore &&
memberValue == null)
return false;
if (HasFlag(property.DefaultValueHandling.GetValueOrDefault(Serializer._defaultValueHandling), DefaultValueHandling.Ignore)
&& MiscellaneousUtils.ValueEquals(memberValue, property.GetResolvedDefaultValue()))
return false;
return true;
}
private bool CheckForCircularReference(JsonWriter writer, object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
{
if (value == null || contract.ContractType == JsonContractType.Primitive || contract.ContractType == JsonContractType.String)
return true;
ReferenceLoopHandling? referenceLoopHandling = null;
if (property != null)
referenceLoopHandling = property.ReferenceLoopHandling;
if (referenceLoopHandling == null && containerProperty != null)
referenceLoopHandling = containerProperty.ItemReferenceLoopHandling;
if (referenceLoopHandling == null && containerContract != null)
referenceLoopHandling = containerContract.ItemReferenceLoopHandling;
if (_serializeStack.IndexOf(value) != -1)
{
string message = "Self referencing loop detected";
if (property != null)
message += " for property '{0}'".FormatWith(CultureInfo.InvariantCulture, property.PropertyName);
message += " with type '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType());
switch (referenceLoopHandling.GetValueOrDefault(Serializer._referenceLoopHandling))
{
case ReferenceLoopHandling.Error:
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
case ReferenceLoopHandling.Ignore:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Skipping serializing self referenced value."), null);
return false;
case ReferenceLoopHandling.Serialize:
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, message + ". Serializing self referenced value."), null);
return true;
}
}
return true;
}
private void WriteReference(JsonWriter writer, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference to Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, value.GetType())), null);
writer.WriteStartObject();
writer.WritePropertyName(JsonTypeReflector.RefPropertyName, false);
writer.WriteValue(reference);
writer.WriteEndObject();
}
private string GetReference(JsonWriter writer, object value)
{
try
{
string reference = Serializer.GetReferenceResolver().GetReference(this, value);
return reference;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Error writing object reference for '{0}'.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), ex);
}
}
internal static bool TryConvertToString(object value, Type type, out string s)
{
TypeConverter converter = ConvertUtils.GetConverter(type);
// use the objectType's TypeConverter if it has one and can convert to a string
if (converter != null
&& !(converter is ComponentConverter)
&& converter.GetType() != typeof(TypeConverter))
{
if (converter.CanConvertTo(typeof(string)))
{
s = converter.ConvertToInvariantString(value);
return true;
}
}
if (value is Type)
{
s = ((Type)value).AssemblyQualifiedName;
return true;
}
s = null;
return false;
}
private void SerializeString(JsonWriter writer, object value, JsonStringContract contract)
{
OnSerializing(writer, contract, value);
string s;
TryConvertToString(value, contract.UnderlyingType, out s);
writer.WriteValue(s);
OnSerialized(writer, contract, value);
}
private void OnSerializing(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerializing(value, Serializer._context);
}
private void OnSerialized(JsonWriter writer, JsonContract contract, object value)
{
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0}".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)), null);
contract.InvokeOnSerialized(value, Serializer._context);
}
private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
int initialDepth = writer.Top;
for (int index = 0; index < contract.Properties.Count; index++)
{
JsonProperty property = contract.Properties[index];
try
{
//UnityEngine.Debug.Log("Serializing "+property.PropertyName);
object memberValue;
JsonContract memberContract;
if (!CalculatePropertyValues(writer, value, contract, member, property, out memberContract, out memberValue))
continue;
property.WritePropertyName(writer);
SerializeValue(writer, memberValue, memberContract, property, contract, member);
}
catch (Exception ex)
{
if (IsErrorHandled(value, contract, property.PropertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
if (contract.ExtensionDataGetter != null)
{
IEnumerable<KeyValuePair<object, object>> extensionData = contract.ExtensionDataGetter(value);
if (extensionData != null)
{
foreach (KeyValuePair<object, object> e in extensionData)
{
JsonContract keyContract = GetContractSafe(e.Key);
JsonContract valueContract = GetContractSafe(e.Value);
bool escape;
string propertyName = GetPropertyName(writer, e.Key, keyContract, out escape);
if (ShouldWriteReference(e.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName);
WriteReference(writer, e.Value);
}
else
{
if (!CheckForCircularReference(writer, e.Value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName);
SerializeValue(writer, e.Value, valueContract, null, contract, member);
}
}
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool CalculatePropertyValues(JsonWriter writer, object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, out JsonContract memberContract, out object memberValue)
{
if (!property.Ignored && property.Readable && ShouldSerialize(writer, property, value) && IsSpecified(writer, property, value))
{
if (property.PropertyContract == null)
property.PropertyContract = Serializer._contractResolver.ResolveContract(property.PropertyType);
memberValue = property.ValueProvider.GetValue(value);
memberContract = (property.PropertyContract.IsSealed) ? property.PropertyContract : GetContractSafe(memberValue);
if (ShouldWriteProperty(memberValue, property))
{
if (ShouldWriteReference(memberValue, property, memberContract, contract, member))
{
property.WritePropertyName(writer);
WriteReference(writer, memberValue);
return false;
}
if (!CheckForCircularReference(writer, memberValue, property, memberContract, contract, member))
return false;
if (memberValue == null)
{
JsonObjectContract objectContract = contract as JsonObjectContract;
Required resolvedRequired = property._required ?? ((objectContract != null) ? objectContract.ItemRequired : null) ?? Required.Default;
if (resolvedRequired == Required.Always)
throw JsonSerializationException.Create(null, writer.ContainerPath, "Cannot write a null value for property '{0}'. Property requires a value.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName), null);
}
return true;
}
}
memberContract = null;
memberValue = null;
return false;
}
private void WriteObjectStart(JsonWriter writer, object value, JsonContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
writer.WriteStartObject();
bool isReference = ResolveIsReference(contract, member, collectionContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Objects);
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, value);
}
if (ShouldWriteType(TypeNameHandling.Objects, contract, member, collectionContract, containerProperty))
{
WriteTypeProperty(writer, contract.UnderlyingType);
}
}
private void WriteReferenceIdProperty(JsonWriter writer, Type type, object value)
{
string reference = GetReference(writer, value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing object reference Id '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, reference, type)), null);
writer.WritePropertyName(JsonTypeReflector.IdPropertyName, false);
writer.WriteValue(reference);
}
private void WriteTypeProperty(JsonWriter writer, Type type)
{
string typeName = ReflectionUtils.GetTypeName(type, Serializer._typeNameAssemblyFormat, Serializer._binder);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "Writing type name '{0}' for {1}.".FormatWith(CultureInfo.InvariantCulture, typeName, type)), null);
writer.WritePropertyName(JsonTypeReflector.TypePropertyName, false);
writer.WriteValue(typeName);
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(PreserveReferencesHandling value, PreserveReferencesHandling flag)
{
return ((value & flag) == flag);
}
private bool HasFlag(TypeNameHandling value, TypeNameHandling flag)
{
return ((value & flag) == flag);
}
private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty))
{
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, contract, collectionContract, containerProperty))
return;
_serializeStack.Add(value);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Started serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
converter.WriteJson(writer, value, GetInternalSerializer());
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info)
TraceWriter.Trace(TraceLevel.Info, JsonPosition.FormatMessage(null, writer.Path, "Finished serializing {0} with converter {1}.".FormatWith(CultureInfo.InvariantCulture, value.GetType(), converter.GetType())), null);
_serializeStack.RemoveAt(_serializeStack.Count - 1);
}
}
private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedCollection wrappedCollection = values as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : values;
OnSerializing(writer, contract, underlyingList);
_serializeStack.Add(underlyingList);
bool hasWrittenMetadataObject = WriteStartArray(writer, underlyingList, contract, member, collectionContract, containerProperty);
writer.WriteStartArray();
int initialDepth = writer.Top;
int index = 0;
// note that an error in the IEnumerable won't be caught
foreach (object value in values)
{
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingList, contract, index, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
finally
{
index++;
}
}
writer.WriteEndArray();
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingList);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
OnSerializing(writer, contract, values);
_serializeStack.Add(values);
bool hasWrittenMetadataObject = WriteStartArray(writer, values, contract, member, collectionContract, containerProperty);
SerializeMultidimensionalArray(writer, values, contract, member, writer.Top, new int[0]);
if (hasWrittenMetadataObject)
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, values);
}
private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty member, int initialDepth, int[] indices)
{
int dimension = indices.Length;
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
writer.WriteStartArray();
for (int i = 0; i < values.GetLength(dimension); i++)
{
newIndices[dimension] = i;
bool isTopLevel = (newIndices.Length == values.Rank);
if (isTopLevel)
{
object value = values.GetValue(newIndices);
try
{
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
WriteReference(writer, value);
}
else
{
if (CheckForCircularReference(writer, value, null, valueContract, contract, member))
{
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
}
catch (Exception ex)
{
if (IsErrorHandled(values, contract, i, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth + 1);
else
throw;
}
}
else
{
SerializeMultidimensionalArray(writer, values, contract, member, initialDepth + 1, newIndices);
}
}
writer.WriteEndArray();
}
private bool WriteStartArray(JsonWriter writer, object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
bool isReference = ResolveIsReference(contract, member, containerContract, containerProperty) ?? HasFlag(Serializer._preserveReferencesHandling, PreserveReferencesHandling.Arrays);
bool includeTypeDetails = ShouldWriteType(TypeNameHandling.Arrays, contract, member, containerContract, containerProperty);
bool writeMetadataObject = isReference || includeTypeDetails;
if (writeMetadataObject)
{
writer.WriteStartObject();
if (isReference)
{
WriteReferenceIdProperty(writer, contract.UnderlyingType, values);
}
if (includeTypeDetails)
{
WriteTypeProperty(writer, values.GetType());
}
writer.WritePropertyName(JsonTypeReflector.ArrayValuesPropertyName, false);
}
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.CollectionItemType ?? typeof(object));
return writeMetadataObject;
}
private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
if (!JsonTypeReflector.FullyTrusted)
{
string message = @"Type '{0}' implements ISerializable but cannot be serialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data." + Environment.NewLine +
@"To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true." + Environment.NewLine;
message = message.FormatWith(CultureInfo.InvariantCulture, value.GetType());
throw JsonSerializationException.Create(null, writer.ContainerPath, message, null);
}
OnSerializing(writer, contract, value);
_serializeStack.Add(value);
WriteObjectStart(writer, value, contract, member, collectionContract, containerProperty);
SerializationInfo serializationInfo = new SerializationInfo(contract.UnderlyingType, new FormatterConverter());
value.GetObjectData(serializationInfo, Serializer._context);
foreach (SerializationEntry serializationEntry in serializationInfo)
{
JsonContract valueContract = GetContractSafe(serializationEntry.Value);
if (ShouldWriteReference(serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
WriteReference(writer, serializationEntry.Value);
}
else if (CheckForCircularReference(writer, serializationEntry.Value, null, valueContract, contract, member))
{
writer.WritePropertyName(serializationEntry.Name);
SerializeValue(writer, serializationEntry.Value, valueContract, null, contract, member);
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, value);
}
private bool ShouldWriteDynamicProperty(object memberValue)
{
if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null)
return false;
if (HasFlag(Serializer._defaultValueHandling, DefaultValueHandling.Ignore) &&
(memberValue == null || MiscellaneousUtils.ValueEquals(memberValue, ReflectionUtils.GetDefaultValue(memberValue.GetType()))))
return false;
return true;
}
private bool ShouldWriteType(TypeNameHandling typeNameHandlingFlag, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
{
TypeNameHandling resolvedTypeNameHandling =
((member != null) ? member.TypeNameHandling : null)
?? ((containerProperty != null) ? containerProperty.ItemTypeNameHandling : null)
?? ((containerContract != null) ? containerContract.ItemTypeNameHandling : null)
?? Serializer._typeNameHandling;
if (HasFlag(resolvedTypeNameHandling, typeNameHandlingFlag))
return true;
// instance type and the property's type's contract default type are different (no need to put the type in JSON because the type will be created by default)
if (HasFlag(resolvedTypeNameHandling, TypeNameHandling.Auto))
{
if (member != null)
{
if (contract.UnderlyingType != member.PropertyContract.CreatedType)
return true;
}
else if (containerContract != null)
{
if (containerContract.ItemContract == null || contract.UnderlyingType != containerContract.ItemContract.CreatedType)
return true;
}
else if (_rootContract != null && _serializeStack.Count == _rootLevel)
{
if (contract.UnderlyingType != _rootContract.CreatedType)
return true;
}
}
return false;
}
private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
{
IWrappedDictionary wrappedDictionary = values as IWrappedDictionary;
object underlyingDictionary = wrappedDictionary != null ? wrappedDictionary.UnderlyingDictionary : values;
OnSerializing(writer, contract, underlyingDictionary);
_serializeStack.Add(underlyingDictionary);
WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);
if (contract.ItemContract == null)
contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
if (contract.KeyContract == null)
contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
int initialDepth = writer.Top;
foreach (DictionaryEntry entry in values)
{
bool escape;
string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out escape);
propertyName = (contract.PropertyNameResolver != null)
? contract.PropertyNameResolver(propertyName)
: propertyName;
try
{
object value = entry.Value;
JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);
if (ShouldWriteReference(value, null, valueContract, contract, member))
{
writer.WritePropertyName(propertyName, escape);
WriteReference(writer, value);
}
else
{
if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
continue;
writer.WritePropertyName(propertyName, escape);
SerializeValue(writer, value, valueContract, null, contract, member);
}
}
catch (Exception ex)
{
if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
HandleError(writer, initialDepth);
else
throw;
}
}
writer.WriteEndObject();
_serializeStack.RemoveAt(_serializeStack.Count - 1);
OnSerialized(writer, contract, underlyingDictionary);
}
private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape)
{
string propertyName;
if (contract.ContractType == JsonContractType.Primitive)
{
JsonPrimitiveContract primitiveContract = (JsonPrimitiveContract)contract;
if (primitiveContract.TypeCode == PrimitiveTypeCode.DateTime || primitiveContract.TypeCode == PrimitiveTypeCode.DateTimeNullable)
{
escape = false;
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
DateTimeUtils.WriteDateTimeString(sw, (DateTime)name, writer.DateFormatHandling, writer.DateFormatString, writer.Culture);
return sw.ToString();
}
else
{
escape = true;
return Convert.ToString(name, CultureInfo.InvariantCulture);
}
}
else if (TryConvertToString(name, name.GetType(), out propertyName))
{
escape = true;
return propertyName;
}
else
{
escape = true;
return name.ToString();
}
}
private void HandleError(JsonWriter writer, int initialDepth)
{
ClearErrorContext();
if (writer.WriteState == WriteState.Property)
writer.WriteNull();
while (writer.Top > initialDepth)
{
writer.WriteEnd();
}
}
private bool ShouldSerialize(JsonWriter writer, JsonProperty property, object target)
{
if (property.ShouldSerialize == null)
return true;
bool shouldSerialize = property.ShouldSerialize(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "ShouldSerialize result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, shouldSerialize)), null);
return shouldSerialize;
}
private bool IsSpecified(JsonWriter writer, JsonProperty property, object target)
{
if (property.GetIsSpecified == null)
return true;
bool isSpecified = property.GetIsSpecified(target);
if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose)
TraceWriter.Trace(TraceLevel.Verbose, JsonPosition.FormatMessage(null, writer.Path, "IsSpecified result for property '{0}' on {1}: {2}".FormatWith(CultureInfo.InvariantCulture, property.PropertyName, property.DeclaringType, isSpecified)), null);
return isSpecified;
}
}
}
| |
/*
* Copyright (c) 2015, Wisconsin Robotics
* 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 Wisconsin Robotics 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 WISCONSIN ROBOTICS 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.Linq;
using BadgerJaus.Messages;
using BadgerJaus.Messages.LocalWaypointDriver;
namespace BadgerJaus.Util
{
public class JausElement
{
public const int MIN_DATA_SIZE_BYTES = 9;
//Message Fields
private JausUnsignedShort elementUID;
private JausUnsignedShort previousUID;
private JausUnsignedShort nextUID;
private JausUnsignedShort dataSize;
private JausByte formatField;
private byte[] elementData;
public JausElement()
{
this.configure();
}
public JausElement(byte[] byteArray)
: this(byteArray, 0)
{
}
public JausElement(byte[] byteArray, int index)
{
int indexOffset;
this.configure();
this.Deserialize(byteArray, index, out indexOffset);
}
public JausElement(JausElement e)
{
this.configure();
elementUID.Value = e.getElementUID();
previousUID.Value = e.getPreviousUID();
nextUID.Value = e.getNextUID();
elementData = e.getElementData();
dataSize.Value = elementData.Length;
}
//Getters and Setters
public bool setElementUID(int value)
{
if (value >= 65535)
{
Console.Error.WriteLine("Invalid UID value");
return false;
}
elementUID.Value = value;
return true;
}
public int getElementUID()
{
return (int)elementUID.Value;
}
public void setPreviousUID(int value)
{
previousUID.Value = value;
}
public int getPreviousUID()
{
return (int)previousUID.Value;
}
public void setNextUID(int value)
{
nextUID.Value = value;
}
public int getNextUID()
{
return (int)nextUID.Value;
}
public void setElementData(byte[] data)
{
elementData = new byte[data.Length];
Array.Copy(data, 0, elementData, 0, data.Length);
dataSize.Value = data.Length;
}
public byte[] getElementData()
{
byte[] temp = new byte[dataSize.Value];
Array.Copy(elementData, 0, temp, 0, dataSize.Value);
return temp;
}
public bool Deserialize(byte[] byteArray, out int indexOffset)
{
Deserialize(byteArray, 0, out indexOffset);
return false;
}
public bool Deserialize(byte[] byteArray, int index, out int indexOffset)
{
indexOffset = index;
if (indexOffset + MIN_DATA_SIZE_BYTES > byteArray.Length)
{
Console.Error.WriteLine("Not enough size for Jaus Element");
return false;
}
if (!elementUID.Deserialize(byteArray, indexOffset, out indexOffset)) return false;
if (!previousUID.Deserialize(byteArray, indexOffset, out indexOffset)) return false;
if (!nextUID.Deserialize(byteArray, indexOffset, out indexOffset)) return false;
if (!formatField.Deserialize(byteArray, indexOffset, out indexOffset)) return false;
//Byte for variable-format field
dataSize.Deserialize(byteArray, indexOffset, out indexOffset);
elementData = new byte[dataSize.Value];
Array.Copy(byteArray, indexOffset, elementData, 0, dataSize.Value);
indexOffset += (int)dataSize.Value;
return true;
}
public int size()
{
return MIN_DATA_SIZE_BYTES + (int)dataSize.Value;
}
public String toString()
{
SetLocalWaypoint temp = new SetLocalWaypoint();
//temp.setPayloadFromJausBuffer(elementData, Message.COMMAND_CODE_SIZE_BYTES);
return "\nElement UID: " + elementUID + "\n" +
"Previous UID: " + previousUID + "\n" +
"Next UID: " + nextUID + "\n" +
"Data Size: " + dataSize + "\n" +
temp + "\n";
}
public String toHexString()
{
String hex = elementUID.toHexString() + previousUID.toHexString()
+ nextUID.toHexString() + dataSize.toHexString();
String temp = "";
for (int i = 0; i < elementData.Length; i++)
{
temp += String.Format("{0:X}", elementData[i]).ToUpper();
}
return hex + temp;
}
public bool Serialize(byte[] byteArray, int index, out int indexOffset)
{
indexOffset = index;
if (!elementUID.Serialize(byteArray, indexOffset, out indexOffset)) return false;
if (!previousUID.Serialize(byteArray, indexOffset, out indexOffset)) return false;
if (!nextUID.Serialize(byteArray, indexOffset, out indexOffset)) return false;
index++; //Byte for variable-format field
if (!dataSize.Serialize(byteArray, indexOffset, out indexOffset)) return false;
Array.Copy(elementData, 0, byteArray, index, dataSize.Value);
return true;
}
public bool Serialize(byte[] byteArray, out int indexOffset)
{
Serialize(byteArray, 0, out indexOffset);
return false;
}
public void configure()
{
elementUID = new JausUnsignedShort();
previousUID = new JausUnsignedShort();
nextUID = new JausUnsignedShort();
formatField = new JausByte();
dataSize = new JausUnsignedShort();
elementData = new byte[0];
}
public bool equals(JausElement other)
{
return this.getElementUID() == other.getElementUID() &&
this.getPreviousUID() == other.getPreviousUID() &&
this.getNextUID() == other.getNextUID() &&
//Arrays.equals(this.getElementData(), other.getElementData());
Enumerable.SequenceEqual(this.getElementData(), other.getElementData());
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2017 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Execution
{
using Commands;
/// <summary>
/// A WorkItem may be an individual test case, a fixture or
/// a higher level grouping of tests. All WorkItems inherit
/// from the abstract WorkItem class, which uses the template
/// pattern to allow derived classes to perform work in
/// whatever way is needed.
///
/// A WorkItem is created with a particular TestExecutionContext
/// and is responsible for re-establishing that context in the
/// current thread before it begins or resumes execution.
/// </summary>
public abstract class WorkItem : IDisposable
{
static Logger log = InternalTrace.GetLogger("WorkItem");
#region Construction and Initialization
/// <summary>
/// Construct a WorkItem for a particular test.
/// </summary>
/// <param name="test">The test that the WorkItem will run</param>
/// <param name="filter">Filter used to include or exclude child items</param>
public WorkItem(Test test, ITestFilter filter)
{
Test = test;
Filter = filter;
Result = test.MakeTestResult();
State = WorkItemState.Ready;
ParallelScope = Test.Properties.ContainsKey(PropertyNames.ParallelScope)
? (ParallelScope)Test.Properties.Get(PropertyNames.ParallelScope)
: ParallelScope.Default;
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
TargetApartment = Test.Properties.ContainsKey(PropertyNames.ApartmentState)
? (ApartmentState)Test.Properties.Get(PropertyNames.ApartmentState)
: ApartmentState.Unknown;
#endif
State = WorkItemState.Ready;
}
/// <summary>
/// Construct a work Item that wraps another work Item.
/// Wrapper items are used to represent independently
/// dispatched tasks, which form part of the execution
/// of a single test, such as OneTimeTearDown.
/// </summary>
/// <param name="wrappedItem">The WorkItem being wrapped</param>
public WorkItem(WorkItem wrappedItem)
{
// Use the same Test, Result, Actions, Context, ParallelScope
// and TargetApartment as the item being wrapped.
Test = wrappedItem.Test;
Result = wrappedItem.Result;
Context = wrappedItem.Context;
ParallelScope = wrappedItem.ParallelScope;
#if PARALLEL
TestWorker = wrappedItem.TestWorker;
#endif
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
TargetApartment = wrappedItem.TargetApartment;
#endif
// State is independent of the wrapped item
State = WorkItemState.Ready;
}
/// <summary>
/// Initialize the TestExecutionContext. This must be done
/// before executing the WorkItem.
/// </summary>
/// <remarks>
/// Originally, the context was provided in the constructor
/// but delaying initialization of the context until the item
/// is about to be dispatched allows changes in the parent
/// context during OneTimeSetUp to be reflected in the child.
/// </remarks>
/// <param name="context">The TestExecutionContext to use</param>
public void InitializeContext(TestExecutionContext context)
{
Guard.OperationValid(Context == null, "The context has already been initialized");
Context = context;
}
#endregion
#region Properties and Events
/// <summary>
/// Event triggered when the item is complete
/// </summary>
public event EventHandler Completed;
/// <summary>
/// Gets the current state of the WorkItem
/// </summary>
public WorkItemState State { get; private set; }
/// <summary>
/// The test being executed by the work item
/// </summary>
public Test Test { get; private set; }
/// <summary>
/// The name of the work item - defaults to the Test name.
/// </summary>
public virtual string Name
{
get { return Test.Name; }
}
/// <summary>
/// Filter used to include or exclude child tests
/// </summary>
public ITestFilter Filter { get; private set; }
/// <summary>
/// The execution context
/// </summary>
public TestExecutionContext Context { get; private set; }
#if PARALLEL
/// <summary>
/// The worker executing this item.
/// </summary>
public TestWorker TestWorker { get; internal set; }
private ParallelExecutionStrategy? _executionStrategy;
/// <summary>
/// The ParallelExecutionStrategy to use for this work item
/// </summary>
public virtual ParallelExecutionStrategy ExecutionStrategy
{
get
{
if (!_executionStrategy.HasValue)
_executionStrategy = GetExecutionStrategy();
return _executionStrategy.Value;
}
}
/// <summary>
/// Indicates whether this work item should use a separate dispatcher.
/// </summary>
public virtual bool IsolateChildTests { get; } = false;
#endif
/// <summary>
/// The test result
/// </summary>
public TestResult Result { get; protected set; }
/// <summary>
/// Gets the ParallelScope associated with the test, if any,
/// otherwise returning ParallelScope.Default;
/// </summary>
public ParallelScope ParallelScope { get; private set; }
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
internal ApartmentState TargetApartment { get; set; }
private ApartmentState CurrentApartment { get; set; }
#endif
#endregion
#region Public Methods
/// <summary>
/// Execute the current work item, including any
/// child work items.
/// </summary>
public virtual void Execute()
{
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
// A supplementary thread is required in two conditions...
//
// 1. If the test used the RequiresThreadAttribute. This
// is at the discretion of the user.
//
// 2. If the test needs to run in a different apartment.
// This should not normally occur when using the parallel
// dispatcher because tests are dispatches to a queue that
// matches the requested apartment. Under the SimpleDispatcher
// (--workers=0 option) it occurs routinely whenever a
// different apartment is requested.
CurrentApartment = Thread.CurrentThread.GetApartmentState();
var targetApartment = TargetApartment == ApartmentState.Unknown ? CurrentApartment : TargetApartment;
if (Test.RequiresThread || targetApartment != CurrentApartment)
{
// Handle error conditions in a single threaded fixture
if (Context.IsSingleThreaded)
{
string msg = Test.RequiresThread
? "RequiresThreadAttribute may not be specified on a test within a single-SingleThreadedAttribute fixture."
: "Tests in a single-threaded fixture may not specify a different apartment";
log.Error(msg);
Result.SetResult(ResultState.NotRunnable, msg);
WorkItemComplete();
return;
}
log.Debug("Running on separate thread because {0} is specified.",
Test.RequiresThread ? "RequiresThread" : "different Apartment");
RunOnSeparateThread(targetApartment);
}
else
RunOnCurrentThread();
#else
RunOnCurrentThread();
#endif
}
private readonly ManualResetEvent _completionEvent = new ManualResetEvent(false);
/// <summary>
/// Wait until the execution of this item is complete
/// </summary>
public void WaitForCompletion()
{
_completionEvent.WaitOne();
}
/// <summary>
/// Marks the WorkItem as NotRunnable.
/// </summary>
/// <param name="reason">Reason for test being NotRunnable.</param>
public void MarkNotRunnable(string reason)
{
Result.SetResult(ResultState.NotRunnable, reason);
WorkItemComplete();
}
private object threadLock = new object();
/// <summary>
/// Cancel (abort or stop) a WorkItem
/// </summary>
/// <param name="force">true if the WorkItem should be aborted, false if it should run to completion</param>
public virtual void Cancel(bool force)
{
if (Context != null)
Context.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested;
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
if (force)
{
Thread tThread;
int tNativeThreadId;
lock (threadLock)
{
if (thread == null)
return;
tThread = thread;
tNativeThreadId = nativeThreadId;
thread = null;
}
if (!tThread.Join(0))
{
log.Debug("Killing thread {0} for cancel", tThread.ManagedThreadId);
ThreadUtility.Kill(tThread, tNativeThreadId);
tThread.Join();
ChangeResult(ResultState.Cancelled, "Cancelled by user");
WorkItemComplete();
}
}
#endif
}
#endregion
#region IDisposable Implementation
/// <summary>
/// Standard Dispose
/// </summary>
public void Dispose()
{
if (_completionEvent != null)
#if NET_2_0 || NET_3_5
_completionEvent.Close();
#else
_completionEvent.Dispose();
#endif
}
#endregion
#region Protected Methods
/// <summary>
/// Method that performs actually performs the work. It should
/// set the State to WorkItemState.Complete when done.
/// </summary>
protected abstract void PerformWork();
/// <summary>
/// Method called by the derived class when all work is complete
/// </summary>
protected void WorkItemComplete()
{
State = WorkItemState.Complete;
Result.StartTime = Context.StartTime;
Result.EndTime = DateTime.UtcNow;
long tickCount = Stopwatch.GetTimestamp() - Context.StartTicks;
double seconds = (double)tickCount / Stopwatch.Frequency;
Result.Duration = seconds;
// We add in the assert count from the context. If
// this item is for a test case, we are adding the
// test assert count to zero. If it's a fixture, we
// are adding in any asserts that were run in the
// fixture setup or teardown. Each context only
// counts the asserts taking place in that context.
// Each result accumulates the count from child
// results along with it's own asserts.
Result.AssertCount += Context.AssertCount;
Context.Listener.TestFinished(Result);
Completed?.Invoke(this, EventArgs.Empty);
_completionEvent.Set();
//Clear references to test objects to reduce memory usage
Context.TestObject = null;
Test.Fixture = null;
}
/// <summary>
/// Builds the set up tear down list.
/// </summary>
/// <param name="setUpMethods">Unsorted array of setup MethodInfos.</param>
/// <param name="tearDownMethods">Unsorted array of teardown MethodInfos.</param>
/// <returns>A list of SetUpTearDownItems</returns>
protected List<SetUpTearDownItem> BuildSetUpTearDownList(MethodInfo[] setUpMethods, MethodInfo[] tearDownMethods)
{
Guard.ArgumentNotNull(setUpMethods, nameof(setUpMethods));
Guard.ArgumentNotNull(tearDownMethods, nameof(tearDownMethods));
var list = new List<SetUpTearDownItem>();
Type fixtureType = Test.TypeInfo?.Type;
if (fixtureType == null)
return list;
while (fixtureType != null && !fixtureType.Equals(typeof(object)))
{
var node = BuildNode(fixtureType, setUpMethods, tearDownMethods);
if (node.HasMethods)
list.Add(node);
fixtureType = fixtureType.GetTypeInfo().BaseType;
}
return list;
}
// This method builds a list of nodes that can be used to
// run setup and teardown according to the NUnit specs.
// We need to execute setup and teardown methods one level
// at a time. However, we can't discover them by reflection
// one level at a time, because that would cause overridden
// methods to be called twice, once on the base class and
// once on the derived class.
//
// For that reason, we start with a list of all setup and
// teardown methods, found using a single reflection call,
// and then descend through the inheritance hierarchy,
// adding each method to the appropriate level as we go.
private static SetUpTearDownItem BuildNode(Type fixtureType, IList<MethodInfo> setUpMethods, IList<MethodInfo> tearDownMethods)
{
// Create lists of methods for this level only.
// Note that FindAll can't be used because it's not
// available on all the platforms we support.
var mySetUpMethods = SelectMethodsByDeclaringType(fixtureType, setUpMethods);
var myTearDownMethods = SelectMethodsByDeclaringType(fixtureType, tearDownMethods);
return new SetUpTearDownItem(mySetUpMethods, myTearDownMethods);
}
private static List<MethodInfo> SelectMethodsByDeclaringType(Type type, IList<MethodInfo> methods)
{
var list = new List<MethodInfo>();
foreach (var method in methods)
if (method.DeclaringType == type)
list.Add(method);
return list;
}
/// <summary>
/// Changes the result of the test, logging the old and new states
/// </summary>
/// <param name="resultState">The new ResultState</param>
/// <param name="message">The new message</param>
protected void ChangeResult(ResultState resultState, string message)
{
log.Debug("Changing result from {0} to {1}", Result.ResultState, resultState);
Result.SetResult(resultState, message);
}
#endregion
#region Private Methods
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
private Thread thread;
private int nativeThreadId;
private void RunOnSeparateThread(ApartmentState apartment)
{
thread = new Thread(() =>
{
lock (threadLock)
nativeThreadId = ThreadUtility.GetCurrentThreadNativeId();
RunOnCurrentThread();
});
thread.SetApartmentState(apartment);
thread.CurrentCulture = Context.CurrentCulture;
thread.CurrentUICulture = Context.CurrentUICulture;
thread.Start();
thread.Join();
}
#endif
private void RunOnCurrentThread()
{
Context.CurrentTest = this.Test;
Context.CurrentResult = this.Result;
Context.Listener.TestStarted(this.Test);
Context.StartTime = DateTime.UtcNow;
Context.StartTicks = Stopwatch.GetTimestamp();
#if PARALLEL
Context.TestWorker = this.TestWorker;
#endif
Context.EstablishExecutionEnvironment();
State = WorkItemState.Running;
PerformWork();
}
#if PARALLEL
private ParallelExecutionStrategy GetExecutionStrategy()
{
// If there is no fixture and so nothing to do but dispatch
// grandchildren we run directly. This saves time that would
// otherwise be spent enqueuing and dequeing items.
if (Test.TypeInfo == null)
return ParallelExecutionStrategy.Direct;
// If the context is single-threaded we are required to run
// the tests one by one on the same thread as the fixture.
if (Context.IsSingleThreaded)
return ParallelExecutionStrategy.Direct;
// Check if item is explicitly marked as non-parallel
if (ParallelScope.HasFlag(ParallelScope.None))
return ParallelExecutionStrategy.NonParallel;
// Check if item is explicitly marked as parallel
if (ParallelScope.HasFlag(ParallelScope.Self))
return ParallelExecutionStrategy.Parallel;
// Item is not explicitly marked, so check the inherited context
if (Context.ParallelScope.HasFlag(ParallelScope.Children) ||
Test is TestFixture && Context.ParallelScope.HasFlag(ParallelScope.Fixtures))
return ParallelExecutionStrategy.Parallel;
// There is no scope specified either on the item itself or in the context.
// In that case, simple work items are test cases and just run on the same
// thread, while composite work items and teardowns are non-parallel.
return this is SimpleWorkItem
? ParallelExecutionStrategy.Direct
: ParallelExecutionStrategy.NonParallel;
}
#endif
#endregion
}
#if NET_2_0 || NET_3_5
static class ActionTargetsExtensions
{
public static bool HasFlag(this ActionTargets targets, ActionTargets value)
{
return (targets & value) != 0;
}
}
#endif
}
| |
using System;
using System.IO;
namespace liquicode.AppTools
{
public class LocalFileSystem : FileSystemProvider
{
//---------------------------------------------------------------------
private string _Root = "";
public string Root
{
get { return this._Root; }
set { this._Root = value; }
}
//---------------------------------------------------------------------
public LocalFileSystem()
{
return;
}
//---------------------------------------------------------------------
public LocalFileSystem( string ThisRoot )
{
this._Root = ThisRoot;
return;
}
//---------------------------------------------------------------------
private FileSystemItem ItemFromPathname( string Pathname )
{
FileSystemItem item = new FileSystemItem();
item.Pathname = Pathname.Substring( this._Root.Length );
if( Directory.Exists( Pathname ) )
{
item.Exists = true;
item.IsFolder = true;
item.DateCreated = Directory.GetCreationTimeUtc( Pathname );
item.DateLastWrite = Directory.GetLastWriteTimeUtc( Pathname );
item.DateLastRead = Directory.GetLastAccessTimeUtc( Pathname );
}
else if( File.Exists( Pathname ) )
{
item.Exists = true;
item.DateCreated = File.GetCreationTimeUtc( Pathname );
item.DateLastWrite = File.GetLastWriteTimeUtc( Pathname );
item.DateLastRead = File.GetLastAccessTimeUtc( Pathname );
FileInfo fi = new FileInfo( Pathname );
item.Size = fi.Length;
}
return item;
}
//---------------------------------------------------------------------
public override void Settings( Commands.SettingsCommand Command )
{
Command.out_Settings.Add( "TypeName", "LocalFileSystem" );
Command.out_Settings.Add( "ProtocolName", "file" );
Command.out_Settings.Add( "Host", "localhost" );
Command.out_Settings.Add( "User", "" );
Command.out_Settings.Add( "Port", "" );
Command.out_Settings.Add( "Root", this._Root );
return;
}
//---------------------------------------------------------------------
public override void List( Commands.ListEntriesCommand Command )
{
if( this._Root.Length == 0 ) { throw new Exceptions.InvalidOperationException( "List", "FileSystem root is undefined" ); }
string search_path = Pathname.Append( this._Root, Command.in_Pathname );
if( Directory.Exists( search_path ) )
{
SearchOption search_option = SearchOption.TopDirectoryOnly;
Command.out_ItemList = new FileSystemItemList();
if( Command.in_IncludeFolders )
{
FileSystemItemList items = new FileSystemItemList();
foreach( string localpath in Directory.GetDirectories( search_path, "*", search_option ) )
{
string itemname = localpath.Substring( search_path.Length );
FileSystemItem item = new FileSystemItem( Command.in_Pathname, itemname, true, true );
item.DateCreated = Directory.GetCreationTimeUtc( localpath );
item.DateLastRead = Directory.GetLastAccessTimeUtc( localpath );
item.DateLastWrite = Directory.GetLastWriteTimeUtc( localpath );
items.AddSorted( item );
}
Command.out_ItemList.AddRange( items.ToArray() );
}
if( Command.in_IncludeFiles )
{
FileSystemItemList items = new FileSystemItemList();
foreach( string localpath in Directory.GetFiles( search_path, "*", search_option ) )
{
string itemname = localpath.Substring( search_path.Length );
FileSystemItem item = new FileSystemItem( Command.in_Pathname, itemname, false, true );
item.DateCreated = File.GetCreationTimeUtc( localpath );
item.DateLastRead = File.GetLastAccessTimeUtc( localpath );
item.DateLastWrite = File.GetLastWriteTimeUtc( localpath );
item.Size = (new FileInfo( localpath )).Length;
items.AddSorted( item );
}
Command.out_ItemList.AddRange( items.ToArray() );
}
}
else
{
throw new Exceptions.InvalidOperationException( "List", "Path does not exist." );
}
return;
}
//---------------------------------------------------------------------
public override void Create( Commands.CreateItemCommand Command )
{
if( this._Root.Length == 0 ) { throw new Exceptions.InvalidOperationException( "Create", "FileSystem root is undefined" ); }
Pathname ItemPathname = Pathname.Append( this._Root, Command.in_Pathname );
if( Directory.Exists( ItemPathname.Path ) == false ) { throw new InvalidOperationException(); }
if( Command.in_IsFolder )
{
Directory.CreateDirectory( ItemPathname );
}
else
{
FileStream stream = File.Create( ItemPathname );
stream.Close();
}
Command.out_Item = this.ItemFromPathname( ItemPathname );
return;
}
//---------------------------------------------------------------------
public override void Read( Commands.ReadItemCommand Command )
{
if( this._Root.Length == 0 ) { throw new Exceptions.InvalidOperationException( "Read", "FileSystem root is undefined" ); }
Pathname ItemPathname = Pathname.Append( this._Root, Command.in_Pathname );
FileSystemItem item = this.ItemFromPathname( ItemPathname );
if( item.Exists )
{
Command.out_Item = item;
}
return;
}
//---------------------------------------------------------------------
public override void Update( Commands.UpdateItemCommand Command )
{
if( this._Root.Length == 0 ) { throw new Exceptions.InvalidOperationException( "Update", "FileSystem root is undefined" ); }
Pathname ItemPathname = Pathname.Append( this._Root, Command.in_Pathname );
Pathname DestItemPathname = Pathname.Append( this._Root, Command.in_Item.Pathname );
bool needs_move = !ItemPathname.Equals( DestItemPathname );
//bool needs_move = !ItemPathname.Path.Equals( DestItemPathname.Path, StringComparison.InvariantCultureIgnoreCase );
FileSystemItem item = this.ItemFromPathname( ItemPathname );
if( item.Exists )
{
if( item.IsFolder )
{
if( needs_move )
{ Directory.Move( ItemPathname, DestItemPathname ); }
if( Command.in_Item.DateCreated.HasValue )
{ Directory.SetCreationTimeUtc( DestItemPathname, (DateTime)Command.in_Item.DateCreated ); }
else
{ Directory.SetCreationTimeUtc( DestItemPathname, (DateTime)item.DateCreated ); }
if( Command.in_Item.DateLastWrite.HasValue )
{ Directory.SetLastWriteTimeUtc( DestItemPathname, (DateTime)Command.in_Item.DateLastWrite ); }
else
{ Directory.SetLastWriteTimeUtc( DestItemPathname, (DateTime)item.DateLastWrite ); }
if( Command.in_Item.DateLastRead.HasValue )
{ Directory.SetLastAccessTimeUtc( DestItemPathname, (DateTime)Command.in_Item.DateLastRead ); }
else
{ Directory.SetLastAccessTimeUtc( DestItemPathname, (DateTime)item.DateLastRead ); }
}
else
{
if( needs_move )
{ File.Move( ItemPathname, DestItemPathname ); }
if( Command.in_Item.DateCreated.HasValue )
{ File.SetCreationTimeUtc( DestItemPathname, (DateTime)Command.in_Item.DateCreated ); }
else
{ File.SetCreationTimeUtc( DestItemPathname, (DateTime)item.DateCreated ); }
if( Command.in_Item.DateLastWrite.HasValue )
{ File.SetLastWriteTimeUtc( DestItemPathname, (DateTime)Command.in_Item.DateLastWrite ); }
else
{ File.SetLastWriteTimeUtc( DestItemPathname, (DateTime)item.DateLastWrite ); }
if( Command.in_Item.DateLastRead.HasValue )
{ File.SetLastAccessTimeUtc( DestItemPathname, (DateTime)Command.in_Item.DateLastRead ); }
else
{ File.SetLastAccessTimeUtc( DestItemPathname, (DateTime)item.DateLastRead ); }
}
Command.out_Item = this.ItemFromPathname( DestItemPathname );
}
else
{
throw new Exceptions.InvalidOperationException( "Update", "Item does not exist." );
}
return;
}
//---------------------------------------------------------------------
public override void Delete( Commands.DeleteItemCommand Command )
{
if( this._Root.Length == 0 ) { throw new Exceptions.InvalidOperationException( "Delete", "FileSystem root is undefined" ); }
Pathname ItemPathname = Pathname.Append( this._Root, Command.in_Pathname );
if( Command.in_IsFolder )
{
Directory.Delete( ItemPathname, true );
}
else
{
File.Delete( ItemPathname );
}
//FileSystemItem item = this.ItemFromPathname( item_path_name );
//if( item.Exists )
//{
// if( item.IsFolder )
// {
// Directory.Delete( item_path_name, true );
// }
// else
// {
// File.Delete( item_path_name );
// }
//}
//else
//{
// throw new Exceptions.InvalidOperationException( "Delete", "Item does not exist." );
//}
return;
}
//---------------------------------------------------------------------
public override void ReadFileContent( Commands.ReadFileContentCommand Command )
{
if( this._Root.Length == 0 ) { throw new Exceptions.InvalidOperationException( "ReadContent", "FileSystem root is undefined" ); }
Pathname ItemPathname = Pathname.Append( this._Root, Command.in_Pathname );
using( FileStream stream = File.OpenRead( ItemPathname ) )
{
if( (Command.in_Offset < 0) || (Command.in_Offset >= stream.Length) )
{ throw new Exceptions.InvalidOperationException( "ReadContent", "Offset is outside of expected range." ); }
long nLength = Command.in_Length;
if( nLength < 0 )
{ nLength = (stream.Length - Command.in_Offset); }
if( (Command.in_Offset + nLength) > stream.Length )
{ nLength = (stream.Length - Command.in_Offset); }
byte[] bytes = new byte[nLength];
stream.Position = Command.in_Offset;
int cb = stream.Read( bytes, 0, bytes.Length );
if( cb != nLength )
{ throw new Exceptions.InvalidOperationException( "ReadContent", "Read error." ); }
Command.out_Content = bytes;
}
return;
}
//---------------------------------------------------------------------
public override void WriteFileContent( Commands.WriteFileContentCommand Command )
{
if( this._Root.Length == 0 ) { throw new Exceptions.InvalidOperationException( "WriteContent", "FileSystem root is undefined" ); }
Pathname ItemPathname = Pathname.Append( this._Root, Command.in_Pathname );
using( FileStream stream = File.OpenWrite( ItemPathname ) )
{
if( (Command.in_Offset < 0) || (Command.in_Offset >= stream.Length) )
{ throw new Exceptions.InvalidOperationException( "WriteContent", "Offset is outside of expected range." ); }
stream.Position = Command.in_Offset;
stream.Write( Command.in_Content, 0, Command.in_Content.Length );
if( Command.in_Truncate )
{ stream.SetLength( stream.Position ); }
}
Command.out_Item = this.ItemFromPathname( ItemPathname );
return;
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Bigtable.Admin.V2.Tests
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Api.Gax.ResourceNames;
using apis = Google.Cloud.Bigtable.Admin.V2;
using Google.Cloud.Iam.V1;
using Google.LongRunning;
using Google.Protobuf;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Moq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
/// <summary>Generated unit tests</summary>
public class GeneratedBigtableInstanceAdminClientTest
{
[Fact]
public void GetInstance()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetInstanceRequest expectedRequest = new GetInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
DisplayName = "displayName1615086568",
};
mockGrpcClient.Setup(x => x.GetInstance(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceName name = new InstanceName("[PROJECT]", "[INSTANCE]");
Instance response = client.GetInstance(name);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetInstanceAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetInstanceRequest expectedRequest = new GetInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
DisplayName = "displayName1615086568",
};
mockGrpcClient.Setup(x => x.GetInstanceAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Instance>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceName name = new InstanceName("[PROJECT]", "[INSTANCE]");
Instance response = await client.GetInstanceAsync(name);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetInstance2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
DisplayName = "displayName1615086568",
};
mockGrpcClient.Setup(x => x.GetInstance(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
Instance response = client.GetInstance(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetInstanceAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetInstanceRequest request = new GetInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
Instance expectedResponse = new Instance
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
DisplayName = "displayName1615086568",
};
mockGrpcClient.Setup(x => x.GetInstanceAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Instance>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
Instance response = await client.GetInstanceAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void ListInstances()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
ListInstancesRequest expectedRequest = new ListInstancesRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
ListInstancesResponse expectedResponse = new ListInstancesResponse
{
NextPageToken = "nextPageToken-1530815211",
};
mockGrpcClient.Setup(x => x.ListInstances(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ProjectName parent = new ProjectName("[PROJECT]");
ListInstancesResponse response = client.ListInstances(parent);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task ListInstancesAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
ListInstancesRequest expectedRequest = new ListInstancesRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
ListInstancesResponse expectedResponse = new ListInstancesResponse
{
NextPageToken = "nextPageToken-1530815211",
};
mockGrpcClient.Setup(x => x.ListInstancesAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<ListInstancesResponse>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ProjectName parent = new ProjectName("[PROJECT]");
ListInstancesResponse response = await client.ListInstancesAsync(parent);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void ListInstances2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
ListInstancesRequest request = new ListInstancesRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
ListInstancesResponse expectedResponse = new ListInstancesResponse
{
NextPageToken = "nextPageToken-1530815211",
};
mockGrpcClient.Setup(x => x.ListInstances(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ListInstancesResponse response = client.ListInstances(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task ListInstancesAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
ListInstancesRequest request = new ListInstancesRequest
{
ParentAsProjectName = new ProjectName("[PROJECT]"),
};
ListInstancesResponse expectedResponse = new ListInstancesResponse
{
NextPageToken = "nextPageToken-1530815211",
};
mockGrpcClient.Setup(x => x.ListInstancesAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<ListInstancesResponse>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ListInstancesResponse response = await client.ListInstancesAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteInstance()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteInstanceRequest expectedRequest = new DeleteInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteInstance(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceName name = new InstanceName("[PROJECT]", "[INSTANCE]");
client.DeleteInstance(name);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteInstanceAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteInstanceRequest expectedRequest = new DeleteInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteInstanceAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceName name = new InstanceName("[PROJECT]", "[INSTANCE]");
await client.DeleteInstanceAsync(name);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteInstance2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteInstance(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
client.DeleteInstance(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteInstanceAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteInstanceRequest request = new DeleteInstanceRequest
{
InstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteInstanceAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
await client.DeleteInstanceAsync(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetCluster()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetClusterRequest expectedRequest = new GetClusterRequest
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
};
Cluster expectedResponse = new Cluster
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
LocationAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
ServeNodes = 1288838783,
};
mockGrpcClient.Setup(x => x.GetCluster(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ClusterName name = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]");
Cluster response = client.GetCluster(name);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetClusterAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetClusterRequest expectedRequest = new GetClusterRequest
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
};
Cluster expectedResponse = new Cluster
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
LocationAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
ServeNodes = 1288838783,
};
mockGrpcClient.Setup(x => x.GetClusterAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Cluster>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ClusterName name = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]");
Cluster response = await client.GetClusterAsync(name);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetCluster2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetClusterRequest request = new GetClusterRequest
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
};
Cluster expectedResponse = new Cluster
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
LocationAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
ServeNodes = 1288838783,
};
mockGrpcClient.Setup(x => x.GetCluster(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
Cluster response = client.GetCluster(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetClusterAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetClusterRequest request = new GetClusterRequest
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
};
Cluster expectedResponse = new Cluster
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
LocationAsLocationName = new LocationName("[PROJECT]", "[LOCATION]"),
ServeNodes = 1288838783,
};
mockGrpcClient.Setup(x => x.GetClusterAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Cluster>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
Cluster response = await client.GetClusterAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void ListClusters()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
ListClustersRequest expectedRequest = new ListClustersRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
ListClustersResponse expectedResponse = new ListClustersResponse
{
NextPageToken = "nextPageToken-1530815211",
};
mockGrpcClient.Setup(x => x.ListClusters(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceName parent = new InstanceName("[PROJECT]", "[INSTANCE]");
ListClustersResponse response = client.ListClusters(parent);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task ListClustersAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
ListClustersRequest expectedRequest = new ListClustersRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
ListClustersResponse expectedResponse = new ListClustersResponse
{
NextPageToken = "nextPageToken-1530815211",
};
mockGrpcClient.Setup(x => x.ListClustersAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<ListClustersResponse>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceName parent = new InstanceName("[PROJECT]", "[INSTANCE]");
ListClustersResponse response = await client.ListClustersAsync(parent);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void ListClusters2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
ListClustersRequest request = new ListClustersRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
ListClustersResponse expectedResponse = new ListClustersResponse
{
NextPageToken = "nextPageToken-1530815211",
};
mockGrpcClient.Setup(x => x.ListClusters(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ListClustersResponse response = client.ListClusters(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task ListClustersAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
ListClustersRequest request = new ListClustersRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
};
ListClustersResponse expectedResponse = new ListClustersResponse
{
NextPageToken = "nextPageToken-1530815211",
};
mockGrpcClient.Setup(x => x.ListClustersAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<ListClustersResponse>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ListClustersResponse response = await client.ListClustersAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteCluster()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteClusterRequest expectedRequest = new DeleteClusterRequest
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteCluster(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ClusterName name = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]");
client.DeleteCluster(name);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteClusterAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteClusterRequest expectedRequest = new DeleteClusterRequest
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteClusterAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
ClusterName name = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]");
await client.DeleteClusterAsync(name);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteCluster2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteClusterRequest request = new DeleteClusterRequest
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteCluster(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
client.DeleteCluster(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteClusterAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteClusterRequest request = new DeleteClusterRequest
{
ClusterName = new ClusterName("[PROJECT]", "[INSTANCE]", "[CLUSTER]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteClusterAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
await client.DeleteClusterAsync(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateAppProfile()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateAppProfileRequest expectedRequest = new CreateAppProfileRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
AppProfileId = "appProfileId1262094415",
AppProfile = new AppProfile(),
};
AppProfile expectedResponse = new AppProfile
{
Name = "name3373707",
Etag = "etag3123477",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateAppProfile(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceName parent = new InstanceName("[PROJECT]", "[INSTANCE]");
string appProfileId = "appProfileId1262094415";
AppProfile appProfile = new AppProfile();
AppProfile response = client.CreateAppProfile(parent, appProfileId, appProfile);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateAppProfileAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateAppProfileRequest expectedRequest = new CreateAppProfileRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
AppProfileId = "appProfileId1262094415",
AppProfile = new AppProfile(),
};
AppProfile expectedResponse = new AppProfile
{
Name = "name3373707",
Etag = "etag3123477",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateAppProfileAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<AppProfile>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
InstanceName parent = new InstanceName("[PROJECT]", "[INSTANCE]");
string appProfileId = "appProfileId1262094415";
AppProfile appProfile = new AppProfile();
AppProfile response = await client.CreateAppProfileAsync(parent, appProfileId, appProfile);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void CreateAppProfile2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateAppProfileRequest request = new CreateAppProfileRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
AppProfileId = "appProfileId1262094415",
AppProfile = new AppProfile(),
};
AppProfile expectedResponse = new AppProfile
{
Name = "name3373707",
Etag = "etag3123477",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateAppProfile(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
AppProfile response = client.CreateAppProfile(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task CreateAppProfileAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
CreateAppProfileRequest request = new CreateAppProfileRequest
{
ParentAsInstanceName = new InstanceName("[PROJECT]", "[INSTANCE]"),
AppProfileId = "appProfileId1262094415",
AppProfile = new AppProfile(),
};
AppProfile expectedResponse = new AppProfile
{
Name = "name3373707",
Etag = "etag3123477",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.CreateAppProfileAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<AppProfile>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
AppProfile response = await client.CreateAppProfileAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetAppProfile()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetAppProfileRequest expectedRequest = new GetAppProfileRequest
{
AppProfileName = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]"),
};
AppProfile expectedResponse = new AppProfile
{
Name = "name2-1052831874",
Etag = "etag3123477",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetAppProfile(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
AppProfileName name = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]");
AppProfile response = client.GetAppProfile(name);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetAppProfileAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetAppProfileRequest expectedRequest = new GetAppProfileRequest
{
AppProfileName = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]"),
};
AppProfile expectedResponse = new AppProfile
{
Name = "name2-1052831874",
Etag = "etag3123477",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetAppProfileAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<AppProfile>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
AppProfileName name = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]");
AppProfile response = await client.GetAppProfileAsync(name);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetAppProfile2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetAppProfileRequest request = new GetAppProfileRequest
{
AppProfileName = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]"),
};
AppProfile expectedResponse = new AppProfile
{
Name = "name2-1052831874",
Etag = "etag3123477",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetAppProfile(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
AppProfile response = client.GetAppProfile(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetAppProfileAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetAppProfileRequest request = new GetAppProfileRequest
{
AppProfileName = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]"),
};
AppProfile expectedResponse = new AppProfile
{
Name = "name2-1052831874",
Etag = "etag3123477",
Description = "description-1724546052",
};
mockGrpcClient.Setup(x => x.GetAppProfileAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<AppProfile>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
AppProfile response = await client.GetAppProfileAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteAppProfile()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteAppProfileRequest expectedRequest = new DeleteAppProfileRequest
{
AppProfileName = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteAppProfile(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
AppProfileName name = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]");
client.DeleteAppProfile(name);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteAppProfileAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteAppProfileRequest expectedRequest = new DeleteAppProfileRequest
{
AppProfileName = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]"),
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteAppProfileAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
AppProfileName name = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]");
await client.DeleteAppProfileAsync(name);
mockGrpcClient.VerifyAll();
}
[Fact]
public void DeleteAppProfile2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteAppProfileRequest request = new DeleteAppProfileRequest
{
AppProfileName = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]"),
IgnoreWarnings = true,
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteAppProfile(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
client.DeleteAppProfile(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task DeleteAppProfileAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
DeleteAppProfileRequest request = new DeleteAppProfileRequest
{
AppProfileName = new AppProfileName("[PROJECT]", "[INSTANCE]", "[APP_PROFILE]"),
IgnoreWarnings = true,
};
Empty expectedResponse = new Empty();
mockGrpcClient.Setup(x => x.DeleteAppProfileAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
await client.DeleteAppProfileAsync(request);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetIamPolicy()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIamPolicyRequest expectedRequest = new GetIamPolicyRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
};
Policy expectedResponse = new Policy
{
Version = 351608024,
Etag = ByteString.CopyFromUtf8("etag3123477"),
};
mockGrpcClient.Setup(x => x.GetIamPolicy(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString();
Policy response = client.GetIamPolicy(formattedResource);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetIamPolicyAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIamPolicyRequest expectedRequest = new GetIamPolicyRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
};
Policy expectedResponse = new Policy
{
Version = 351608024,
Etag = ByteString.CopyFromUtf8("etag3123477"),
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Policy>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString();
Policy response = await client.GetIamPolicyAsync(formattedResource);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void GetIamPolicy2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIamPolicyRequest request = new GetIamPolicyRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
};
Policy expectedResponse = new Policy
{
Version = 351608024,
Etag = ByteString.CopyFromUtf8("etag3123477"),
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetIamPolicy(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task GetIamPolicyAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
GetIamPolicyRequest request = new GetIamPolicyRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
};
Policy expectedResponse = new Policy
{
Version = 351608024,
Etag = ByteString.CopyFromUtf8("etag3123477"),
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Policy>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
Policy response = await client.GetIamPolicyAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void SetIamPolicy()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
SetIamPolicyRequest expectedRequest = new SetIamPolicyRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
Policy = new Policy(),
};
Policy expectedResponse = new Policy
{
Version = 351608024,
Etag = ByteString.CopyFromUtf8("etag3123477"),
};
mockGrpcClient.Setup(x => x.SetIamPolicy(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString();
Policy policy = new Policy();
Policy response = client.SetIamPolicy(formattedResource, policy);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task SetIamPolicyAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
SetIamPolicyRequest expectedRequest = new SetIamPolicyRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
Policy = new Policy(),
};
Policy expectedResponse = new Policy
{
Version = 351608024,
Etag = ByteString.CopyFromUtf8("etag3123477"),
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Policy>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString();
Policy policy = new Policy();
Policy response = await client.SetIamPolicyAsync(formattedResource, policy);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void SetIamPolicy2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
SetIamPolicyRequest request = new SetIamPolicyRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
Policy = new Policy(),
};
Policy expectedResponse = new Policy
{
Version = 351608024,
Etag = ByteString.CopyFromUtf8("etag3123477"),
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
Policy response = client.SetIamPolicy(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task SetIamPolicyAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
SetIamPolicyRequest request = new SetIamPolicyRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
Policy = new Policy(),
};
Policy expectedResponse = new Policy
{
Version = 351608024,
Etag = ByteString.CopyFromUtf8("etag3123477"),
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<Policy>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
Policy response = await client.SetIamPolicyAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void TestIamPermissions()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
TestIamPermissionsRequest expectedRequest = new TestIamPermissionsRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
Permissions = { },
};
TestIamPermissionsResponse expectedResponse = new TestIamPermissionsResponse();
mockGrpcClient.Setup(x => x.TestIamPermissions(expectedRequest, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString();
IEnumerable<string> permissions = new List<string>();
TestIamPermissionsResponse response = client.TestIamPermissions(formattedResource, permissions);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task TestIamPermissionsAsync()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
TestIamPermissionsRequest expectedRequest = new TestIamPermissionsRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
Permissions = { },
};
TestIamPermissionsResponse expectedResponse = new TestIamPermissionsResponse();
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(expectedRequest, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<TestIamPermissionsResponse>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
string formattedResource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString();
IEnumerable<string> permissions = new List<string>();
TestIamPermissionsResponse response = await client.TestIamPermissionsAsync(formattedResource, permissions);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public void TestIamPermissions2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
Permissions = { },
};
TestIamPermissionsResponse expectedResponse = new TestIamPermissionsResponse();
mockGrpcClient.Setup(x => x.TestIamPermissions(request, It.IsAny<CallOptions>()))
.Returns(expectedResponse);
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
TestIamPermissionsResponse response = client.TestIamPermissions(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Fact]
public async Task TestIamPermissionsAsync2()
{
Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient> mockGrpcClient = new Mock<BigtableInstanceAdmin.BigtableInstanceAdminClient>(MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient())
.Returns(new Mock<Operations.OperationsClient>().Object);
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
Resource = new InstanceName("[PROJECT]", "[INSTANCE]").ToString(),
Permissions = { },
};
TestIamPermissionsResponse expectedResponse = new TestIamPermissionsResponse();
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, It.IsAny<CallOptions>()))
.Returns(new Grpc.Core.AsyncUnaryCall<TestIamPermissionsResponse>(Task.FromResult(expectedResponse), null, null, null, null));
BigtableInstanceAdminClient client = new BigtableInstanceAdminClientImpl(mockGrpcClient.Object, null);
TestIamPermissionsResponse response = await client.TestIamPermissionsAsync(request);
Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
}
}
| |
namespace SampleApp
{
partial class FolderBrowser
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cboxGrid = new System.Windows.Forms.ComboBox();
this.cbLines = new System.Windows.Forms.CheckBox();
this.label1 = new System.Windows.Forms.Label();
this._treeView = new Aga.Controls.Tree.TreeViewAdv();
this.treeColumn1 = new Aga.Controls.Tree.TreeColumn();
this.treeColumn2 = new Aga.Controls.Tree.TreeColumn();
this.treeColumn3 = new Aga.Controls.Tree.TreeColumn();
this.nodeCheckBox1 = new Aga.Controls.Tree.NodeControls.NodeCheckBox();
this._icon = new Aga.Controls.Tree.NodeControls.NodeStateIcon();
this._name = new Aga.Controls.Tree.NodeControls.NodeTextBox();
this._size = new Aga.Controls.Tree.NodeControls.NodeTextBox();
this._date = new Aga.Controls.Tree.NodeControls.NodeTextBox();
this.SuspendLayout();
//
// cboxGrid
//
this.cboxGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cboxGrid.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cboxGrid.FormattingEnabled = true;
this.cboxGrid.Location = new System.Drawing.Point(338, 303);
this.cboxGrid.Name = "cboxGrid";
this.cboxGrid.Size = new System.Drawing.Size(192, 21);
this.cboxGrid.TabIndex = 1;
this.cboxGrid.SelectedIndexChanged += new System.EventHandler(this.cboxGrid_SelectedIndexChanged);
//
// cbLines
//
this.cbLines.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.cbLines.AutoSize = true;
this.cbLines.Location = new System.Drawing.Point(3, 305);
this.cbLines.Name = "cbLines";
this.cbLines.Size = new System.Drawing.Size(81, 17);
this.cbLines.TabIndex = 3;
this.cbLines.Text = "Show Lines";
this.cbLines.UseVisualStyleBackColor = true;
this.cbLines.CheckedChanged += new System.EventHandler(this.cbLines_CheckedChanged);
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(257, 306);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(75, 13);
this.label1.TabIndex = 4;
this.label1.Text = "Grid Line Style";
//
// _treeView
//
this._treeView.AllowColumnReorder = true;
this._treeView.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._treeView.AutoRowHeight = true;
this._treeView.BackColor = System.Drawing.SystemColors.Window;
this._treeView.Columns.Add(this.treeColumn1);
this._treeView.Columns.Add(this.treeColumn2);
this._treeView.Columns.Add(this.treeColumn3);
this._treeView.Cursor = System.Windows.Forms.Cursors.Default;
this._treeView.DefaultToolTipProvider = null;
this._treeView.DragDropMarkColor = System.Drawing.Color.Black;
this._treeView.FullRowSelect = true;
this._treeView.GridLineStyle = ((Aga.Controls.Tree.GridLineStyle)((Aga.Controls.Tree.GridLineStyle.Horizontal | Aga.Controls.Tree.GridLineStyle.Vertical)));
this._treeView.LineColor = System.Drawing.SystemColors.ControlDark;
this._treeView.LoadOnDemand = true;
this._treeView.Location = new System.Drawing.Point(0, 0);
this._treeView.Model = null;
this._treeView.Name = "_treeView";
this._treeView.NodeControls.Add(this.nodeCheckBox1);
this._treeView.NodeControls.Add(this._icon);
this._treeView.NodeControls.Add(this._name);
this._treeView.NodeControls.Add(this._size);
this._treeView.NodeControls.Add(this._date);
this._treeView.SelectedNode = null;
this._treeView.ShowNodeToolTips = true;
this._treeView.Size = new System.Drawing.Size(533, 298);
this._treeView.TabIndex = 0;
this._treeView.UseColumns = true;
this._treeView.NodeMouseDoubleClick += new System.EventHandler<Aga.Controls.Tree.TreeNodeAdvMouseEventArgs>(this._treeView_NodeMouseDoubleClick);
this._treeView.ColumnClicked += new System.EventHandler<Aga.Controls.Tree.TreeColumnEventArgs>(this._treeView_ColumnClicked);
this._treeView.MouseClick += new System.Windows.Forms.MouseEventHandler(this._treeView_MouseClick);
//
// treeColumn1
//
this.treeColumn1.Header = "Name";
this.treeColumn1.SortOrder = System.Windows.Forms.SortOrder.None;
this.treeColumn1.TooltipText = "File name";
this.treeColumn1.Width = 250;
//
// treeColumn2
//
this.treeColumn2.Header = "Size";
this.treeColumn2.SortOrder = System.Windows.Forms.SortOrder.None;
this.treeColumn2.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.treeColumn2.TooltipText = "File size";
this.treeColumn2.Width = 100;
//
// treeColumn3
//
this.treeColumn3.Header = "Date";
this.treeColumn3.SortOrder = System.Windows.Forms.SortOrder.None;
this.treeColumn3.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.treeColumn3.TooltipText = "File date";
this.treeColumn3.Width = 150;
//
// nodeCheckBox1
//
this.nodeCheckBox1.DataPropertyName = "IsChecked";
this.nodeCheckBox1.LeftMargin = 0;
this.nodeCheckBox1.ParentColumn = this.treeColumn1;
//
// _icon
//
this._icon.DataPropertyName = "Icon";
this._icon.LeftMargin = 1;
this._icon.ParentColumn = this.treeColumn1;
//
// _name
//
this._name.DataPropertyName = "Name";
this._name.IncrementalSearchEnabled = true;
this._name.LeftMargin = 3;
this._name.ParentColumn = this.treeColumn1;
this._name.Trimming = System.Drawing.StringTrimming.EllipsisCharacter;
this._name.UseCompatibleTextRendering = true;
//
// _size
//
this._size.DataPropertyName = "Size";
this._size.IncrementalSearchEnabled = true;
this._size.LeftMargin = 3;
this._size.ParentColumn = this.treeColumn2;
this._size.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// _date
//
this._date.DataPropertyName = "Date";
this._date.IncrementalSearchEnabled = true;
this._date.LeftMargin = 3;
this._date.ParentColumn = this.treeColumn3;
this._date.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// FolderBrowser
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.label1);
this.Controls.Add(this.cbLines);
this.Controls.Add(this.cboxGrid);
this.Controls.Add(this._treeView);
this.Name = "FolderBrowser";
this.Size = new System.Drawing.Size(533, 327);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Aga.Controls.Tree.TreeViewAdv _treeView;
private Aga.Controls.Tree.NodeControls.NodeStateIcon _icon;
private Aga.Controls.Tree.NodeControls.NodeTextBox _name;
private Aga.Controls.Tree.NodeControls.NodeTextBox _size;
private Aga.Controls.Tree.NodeControls.NodeTextBox _date;
private Aga.Controls.Tree.NodeControls.NodeCheckBox nodeCheckBox1;
private Aga.Controls.Tree.TreeColumn treeColumn1;
private Aga.Controls.Tree.TreeColumn treeColumn2;
private Aga.Controls.Tree.TreeColumn treeColumn3;
private System.Windows.Forms.ComboBox cboxGrid;
private System.Windows.Forms.CheckBox cbLines;
private System.Windows.Forms.Label label1;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using Cairo;
using Gdk;
using Gtk;
using Exameer;
public partial class MainWindow: Gtk.Window
{
Gtk.NodeStore storePdf;
Gtk.NodeStore StorePDF {
get {
if (storePdf == null) {
storePdf = new Gtk.NodeStore (typeof(PdfNode));
}
return storePdf;
}
}
Gtk.NodeStore storePng;
Gtk.NodeStore StorePNG {
get {
if (storePng == null) {
storePng = new Gtk.NodeStore (typeof(PngNode));
}
return storePng;
}
}
public PngViewer PNGViewer { get; set; }
public MainWindow (): base (Gtk.WindowType.Toplevel)
{
Build ();
this.nodeViewPDF.NodeStore = StorePDF;
this.nodeViewPDF.AppendColumn ("Pdf", new Gtk.CellRendererText (), "text", 0);
this.nodeViewPDF.ShowAll ();
this.nodeViewPDF.NodeSelection.Changed += new System.EventHandler (OnPdfSelectionChanged);
this.nodeViewPNG.NodeStore = StorePNG;
this.nodeViewPNG.AppendColumn ("Png", new Gtk.CellRendererText (), "text", 0);
this.nodeViewPNG.ShowAll ();
this.nodeViewPNG.NodeSelection.Changed += new System.EventHandler (OnPngSelectionChanged);
this.PNGViewer = new PngViewer ();
this.PNGViewer.Resize (900, 1020);
PNGViewer.ShowAll ();
}
void OnPdfSelectionChanged (object sender, EventArgs e)
{
NodeSelection es = (NodeSelection)sender;
PdfNode node = (PdfNode)es.SelectedNode;
if (node.Images.Count == 0) {
ProcessStartInfo psi = new ProcessStartInfo ("convert", "-density 300 \"" +
node.FileName + "\" " +
node.Name.Replace (".pdf", ".png")
);
using (Process p = new Process()) {
p.StartInfo = psi;
p.Start ();
Console.Write (".");
if (false == p.WaitForExit ((int)TimeSpan.FromHours (1).TotalMilliseconds))
throw new ArgumentException ("The program did not finish in time, aborting.");
Console.WriteLine (".");
var images = Directory.GetFiles (".", node.Name.Replace (".pdf", "*.png")).ToList ()
.Where (x => x.Contains (node.Name.Replace (".pdf", "")))
.OrderBy(x => x)
.Select (x => new PngNode (x));
node.Images.AddRange (images);
foreach (var image in images) {
Console.WriteLine (image.Name);
}
PNGViewer.SetNodes (node.Images);
//node.Images.ForEach(x => this.StorePNG.AddNode(new PngNode(x)));
this.lblStatus.Text = String.Format ("converted {0}", node.Name);
}
} else {
PNGViewer.SetNodes (node.Images);
}
}
void OnPngSelectionChanged (object sender, EventArgs e)
{
NodeSelection es = (NodeSelection)sender;
PngNode pn = (PngNode)es.SelectedNode;
Console.WriteLine (pn.FileName);
PNGViewer.SetNode (pn);
}
protected void OnDeleteEvent (object sender, DeleteEventArgs a)
{
Application.Quit ();
a.RetVal = true;
}
protected void OnBtnOpenFileDialogClicked (object sender, EventArgs e)
{
using (Gtk.FileChooserDialog fc =
new FileChooserDialog ("Open PDFs", this,
FileChooserAction.Open,
"Cancel", ResponseType.Cancel,
"Open", ResponseType.Accept)) {
fc.SetCurrentFolder ("/home/zol/Downloads/exams/endima1/");
fc.SelectMultiple = true;
if (fc.Run () == (int)ResponseType.Accept) {
foreach (var name in fc.Filenames) {
this.StorePDF.AddNode (new PdfNode (name));
}
}
fc.Destroy ();
}
}
protected void OnBtnConvertClicked (object sender, EventArgs e)
{
var pdfRectangles = new Dictionary<string, Dictionary<int, List<Tuple<Exameer.Rectangle, string>>> > ();
// Merge rectangles
foreach (PdfNode pdf in StorePDF) {
foreach (var png in pdf.Images) {
foreach (var rectangle in png.Rectangles) {
if (pdfRectangles.ContainsKey (pdf.Name)) {
if (pdfRectangles [pdf.Name].ContainsKey (rectangle.ID)) {
pdfRectangles [pdf.Name] [rectangle.ID].Add (new Tuple<Exameer.Rectangle, string> (rectangle, png.FileName));
} else {
pdfRectangles [pdf.Name].Add (rectangle.ID,
new List<Tuple<Exameer.Rectangle, string>> () {
new Tuple<Exameer.Rectangle, string>(rectangle, png.FileName)
}
);
}
} else {
pdfRectangles.Add (pdf.Name,
new Dictionary<int, List<Tuple<Exameer.Rectangle, string>>> () {{
rectangle.ID, new List<Tuple<Exameer.Rectangle, string>>() {
new Tuple<Exameer.Rectangle, string>(rectangle, png.FileName)
}}}
);
}
}
}
}
int problemNbr = 0;
foreach (var pdf in pdfRectangles) {
var createdDestinationDir = Directory.CreateDirectory ("./" + pdf.Key.Replace (".pdf", "") + "/");
foreach (var pngrects in pdf.Value) {
var surfaces = new List<Tuple<ImageSurface, Exameer.Rectangle>> ();
foreach (var rectangle in pngrects.Value) {
surfaces.Add (new Tuple<ImageSurface, Exameer.Rectangle> (new ImageSurface (rectangle.Item2), rectangle.Item1));
}
var png = new ImageSurface (pngrects.Value [0].Item2);
var rectsMaxWidth = pngrects.Value.Max (x => x.Item1.Width);
var rectsMaxHeight = pngrects.Value.Select (x => x.Item1.Height).Sum ();
var newRectWidth = (int)((rectsMaxWidth / (float)pngrects.Value [0].Item1.Parent.Width) * png.Width);
var newRectHeight = (int)((rectsMaxHeight / (float)pngrects.Value [0].Item1.Parent.Height) * png.Height); //pngrects.Value.Aggregate(0, (sum, next) => sum + next.Item1.Height);
ImageSurface newImg = new ImageSurface (Format.Argb32, newRectWidth, newRectHeight);
Context cr = new Context (newImg);
//cr.SetSourceRGBA (1, 1, 1, 1);
//cr.Paint ();
// Assume they are sorted by their appearance in PNGs.
int lastY = 0;
foreach (var surface in surfaces) {
var dstx = 0;
var dsty = lastY;
var r = surface.Item2;
var srcx = (int)((r.x1 / (float)r.Parent.Width) * png.Width);
var srcy = ((int)((r.y1 / (float)r.Parent.Height) * png.Height));
var w = (int)((r.Width / (float)r.Parent.Width) * png.Width);
var h = (int)((r.Height / (float)r.Parent.Height) * png.Height);
cr.SetSourceSurface (surface.Item1, dstx - srcx, dsty - srcy);
cr.Rectangle (dstx, dsty, w, h);
cr.Fill ();
//lastY = (int)((r.Height / (float)r.Parent.Height) * png.Height);
lastY = dsty + h;
}
newImg.Flush ();
newImg.WriteToPng ("./" + pdf.Key.Replace (".pdf", "") + "/" +
(problemNbr++) + ".png");
newImg.Dispose ();
//newImg.Dispose ();
//surfaces.ForEach (x => x.Item1.Destroy ());
surfaces.ForEach (x => x.Item1.Dispose ());
png.Dispose ();
//png.Destroy ();
}
problemNbr = 0;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public sealed class ConstantExpression : Expression
{
public abstract class DelayedValue
{
//
// Access Methods
//
public abstract bool CanEvaluate
{
get;
}
public abstract object Value
{
get;
}
}
//--//
public static new readonly ConstantExpression[] SharedEmptyArray = new ConstantExpression[0];
//
// State
//
private object m_value;
//
// Constructor Methods
//
public ConstantExpression( TypeRepresentation type ,
object value ) : base( type )
{
m_value = value;
//
// Coming from byte code, we might see loads for long/ulong that take a 32 bit value as input.
//
if(this.IsValueInteger)
{
ulong val; this.GetAsRawUlong( out val );
m_value = ConvertToType( type, val );
}
}
//--//
//
// Helper Methods
//
public override Expression Clone( CloningContext context )
{
TypeRepresentation td = context.ConvertType( m_type );
if(Object.ReferenceEquals( td, m_type ))
{
return this; // Constants don't need to be cloned.
}
else
{
return new ConstantExpression( td, m_value );
}
}
//--//
public override void ApplyTransformation( TransformationContextForIR context )
{
context.Push( this );
base.ApplyTransformation( context );
context.Transform( ref m_value );
context.Pop();
}
//--//
public override Operator.OperatorLevel GetLevel( Operator.IOperatorLevelHelper helper )
{
if(m_type.ValidLayout == false)
{
return Operator.OperatorLevel.ConcreteTypes;
}
if(helper.FitsInPhysicalRegister( m_type ))
{
//
// If they can fit in a register, we consider it good enough to be at the lowest level.
//
return Operator.OperatorLevel.Lowest;
}
return Operator.OperatorLevel.ConcreteTypes_NoExceptions;
}
//--//
public bool GetAsRawUlong( out ulong value )
{
return DataConversion.GetAsRawUlong( this.Value, out value );
}
public bool GetAsUnsignedInteger( out ulong value )
{
return DataConversion.GetAsUnsignedInteger( this.Value, out value );
}
public bool GetAsSignedInteger( out long value )
{
return DataConversion.GetAsSignedInteger( this.Value, out value );
}
public bool GetFloatingPoint( out double value )
{
return DataConversion.GetFloatingPoint( this.Value, out value );
}
//--//
public static object ConvertToType( TypeRepresentation type ,
ulong value )
{
//
// Special case for memory-mapped peripherals.
//
if(type is ReferenceTypeRepresentation)
{
return new UIntPtr( (uint)value );
}
//
// Special case for pointers.
//
if(type is PointerTypeRepresentation)
{
return new UIntPtr( (uint)value );
}
if(type is EnumerationTypeRepresentation)
{
type = type.UnderlyingType;
}
if(type is ScalarTypeRepresentation)
{
switch(type.BuiltInType)
{
case TypeRepresentation.BuiltInTypes.BOOLEAN: return value != 0;
case TypeRepresentation.BuiltInTypes.CHAR : return (char )value;
case TypeRepresentation.BuiltInTypes.I1 : return (sbyte )value;
case TypeRepresentation.BuiltInTypes.U1 : return (byte )value;
case TypeRepresentation.BuiltInTypes.I2 : return (short )value;
case TypeRepresentation.BuiltInTypes.U2 : return (ushort)value;
case TypeRepresentation.BuiltInTypes.I4 : return (int )value;
case TypeRepresentation.BuiltInTypes.U4 : return (uint )value;
case TypeRepresentation.BuiltInTypes.I8 : return (long )value;
case TypeRepresentation.BuiltInTypes.U8 : return (ulong )value;
case TypeRepresentation.BuiltInTypes.I : return new IntPtr ( (int )value );
case TypeRepresentation.BuiltInTypes.U : return new UIntPtr ( (uint )value );
case TypeRepresentation.BuiltInTypes.R4 : return DataConversion.GetFloatFromBytes ( (uint )value );
case TypeRepresentation.BuiltInTypes.R8 : return DataConversion.GetDoubleFromBytes( value );
}
}
throw TypeConsistencyErrorException.Create( "Cannot convert {0} to {1}", value, type );
}
//--//
//
// Access Methods
//
public object Value
{
get
{
DelayedValue delayedValue = m_value as DelayedValue;
if(delayedValue != null && delayedValue.CanEvaluate)
{
return delayedValue.Value;
}
return m_value;
}
}
public override CanBeNull CanBeNull
{
get
{
object val = this.Value;
return (val == null) ? CanBeNull.Yes : CanBeNull.No;
}
}
public override bool CanTakeAddress
{
get
{
return false;
}
}
public int SizeOfValue
{
get
{
switch(this.TypeCode)
{
case TypeCode.Boolean: return 1;
case TypeCode.Char : return 2;
case TypeCode.SByte : return 1;
case TypeCode.Byte : return 1;
case TypeCode.Int16 : return 2;
case TypeCode.UInt16 : return 2;
case TypeCode.Int32 : return 4;
case TypeCode.UInt32 : return 4;
case TypeCode.Int64 : return 8;
case TypeCode.UInt64 : return 8;
case TypeCode.Single : return 4;
case TypeCode.Double : return 8;
//// case TypeCode.Decimal:
}
return 0;
}
}
public bool IsValueSigned
{
get
{
switch(this.TypeCode)
{
case TypeCode.SByte : return true;
case TypeCode.Int16 : return true;
case TypeCode.Int32 : return true;
case TypeCode.Int64 : return true;
case TypeCode.Single : return true;
case TypeCode.Double : return true;
//// case TypeCode.Decimal:
}
return false;
}
}
public bool IsValueInteger
{
get
{
switch(this.TypeCode)
{
case TypeCode.Boolean:
case TypeCode.Char :
case TypeCode.SByte :
case TypeCode.Byte :
case TypeCode.Int16 :
case TypeCode.UInt16 :
case TypeCode.Int32 :
case TypeCode.UInt32 :
case TypeCode.Int64 :
case TypeCode.UInt64 :
return true;
}
return false;
}
}
public TypeCode TypeCode
{
get
{
return DataConversion.GetTypeCode( this.Value );
}
}
public bool IsValueFloatingPoint
{
get
{
object val = this.Value;
if(val is float ) return true;
if(val is double) return true;
return false;
}
}
//--//
//
// Debug Methods
//
public override void InnerToString( System.Text.StringBuilder sb )
{
object val = this.Value;
if(val != null)
{
sb.AppendFormat( "$Const({0} {1})", m_type.FullNameWithAbbreviation, val );
}
else
{
sb.Append( "<null value>" );
}
}
}
}
| |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Windows.Forms;
namespace FIX_AutoFlatten
{
/// <summary>
/// program start class
/// </summary>
public partial class mainForm : Form
{
/// <summary>
/// starting point of application
/// </summary>
public mainForm()
{
InitializeComponent();
}
private static LOG.LogFiles log = new LOG.LogFiles();
private QuickFix.QFApplication _qf;
private DateTime current = DateTime.Now;
private ArrayList stoppedTraders = new ArrayList();
private bool previousPositionsLoaded = false;
private bool TimeChanged = false;
private bool TimerUpdated = false;
DataSet setINI = new DataSet("INI");
private string baseCurrency = null;
private bool isAccountFilterEnabled = false;
private bool isDebug = false;
//email variables setup
private DataTable tblParameters = null;
private bool isEmailEnabled = false;
private Decimal[] EmailLimits;
private String[] to;
private String[] cc;
private String[] bcc;
private String[] msg;
private String[] subject;
private MailPriority[] priority;
private void mainForm_Load(object sender, EventArgs e)
{
try
{
TT.SendMsg.initializeLog();
log.CreateLog("AUTOFLAT", this.listBox1);
this.Text += " v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
//log.WriteLog(this.Text);
_qf = new QuickFix.QFApplication();
_LoadINI();
_LoadMGT();
_LoadCurrency();
#region Register Delegates for passing data between threads
//these calls are registering local methods for updating the gui
//the _qf. methods are delegates that pass the data from the QuickFix thread
//to the Gui thread.
_qf.registerLogUpdater(log.WriteList);
_qf.registerGatewayUpdater(UpdateGateway);
_qf.registerPositionUpdater(UpdatePosition);
_qf.registerSecurityUpdater(UpdateSecurity);
_qf.registerPriceUpdater(UpdatePrices);
_qf.registerOrderCanceler(orderCancel);
_qf.registerOnOff(activateOnOff);
_qf.registerOrderMgmt(updateOrderMgmt);
_qf.registerClearPOS(ClearPositions);
#endregion
_qf.initiate("ini.cfg", "12345678", true, this);
}
catch (Exception ex)
{ log.WriteList(ex.ToString()); }
}
private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
dsRisk.tblCurrency.WriteXml("CURRENCY.XML");
if (TimeChanged)
{
setINI.Tables["resetTime"].Rows[0]["time"] = dateTimePicker2.Value.TimeOfDay;
setINI.WriteXml("INI.XML");
}
}
/// <summary>
/// Notify application that all positions are loaded
/// </summary>
private void activateOnOff()
{ previousPositionsLoaded = true; }
/// <summary>
/// Load Trader limits by MGT
/// </summary>
private void _LoadMGT()
{
try
{
if (File.Exists("MGT.XML"))
{
dsRisk.tblTrader.ReadXml("MGT.XML");
log.WriteList("MGT.XML: Data Loaded");
}
else
{
log.WriteList("MGT.XML: No Trader Limits File loaded!");
MessageBox.Show("Application will terminate! Can not run without trader limits file", "FATAL ERROR");
Application.Exit();
}
}
catch (Exception ex)
{ log.WriteList(ex.ToString()); }
}
/// <summary>
/// Load Currency Conversions
/// </summary>
private void _LoadCurrency()
{
try
{
if (File.Exists("CURRENCY.XML"))
{
dsRisk.tblCurrency.ReadXml("CURRENCY.XML");
log.WriteList("CURRENCY.XML: Data Loaded");
}
else
{
log.WriteList("CURRENCY.XML: No conversion will be done!");
}
}
catch (Exception ex)
{ log.WriteList(ex.ToString()); }
}
/// <summary>
/// Load email settings
/// </summary>
private void _LoadINI()
{
log.WriteLog("Load INI Parameters");
try
{
if (File.Exists("INI.XML"))
{
setINI.ReadXml("INI.XML");
log.WriteList("INI.XML: File Loaded");
if (setINI.Tables.Contains("settings"))
{
TimeSpan ts;
bool worked = TimeSpan.TryParse(setINI.Tables["settings"].Rows[0]["resetTime"].ToString(), out ts);
if (worked)
{
this.dateTimePicker2.Value = DateTime.Today + ts;
TimeChanged = false;
log.WriteList("Reset Time Set to: " + this.dateTimePicker2.Value.ToShortTimeString());
}
else
{ log.WriteList("Reset Time not Set!"); }
if (setINI.Tables["settings"].Columns.Contains("baseCurrency"))
{
baseCurrency = setINI.Tables["settings"].Rows[0]["baseCurrency"].ToString();
}
else
{
baseCurrency = "USD";
}
log.WriteList("Base Currency Set to " + baseCurrency);
bool filter = Boolean.TryParse(setINI.Tables["settings"].Rows[0]["AccountFilter"].ToString(), out isAccountFilterEnabled);
log.WriteList("Account Filtering Set to "+isAccountFilterEnabled.ToString());
bool testing = Boolean.TryParse(setINI.Tables["settings"].Rows[0]["DEBUG"].ToString(), out isDebug);
log.WriteList("DEBUG MODE: " + isDebug.ToString());
}
//setup email
if (setINI.Tables.Contains("parameters"))
{
tblParameters = setINI.Tables["parameters"];
bool[] verifyColumns = new bool[6];
DataRow r = tblParameters.Rows[0];
if (tblParameters.Columns.Contains("FROM")) { verifyColumns[0] = true; }
if (tblParameters.Columns.Contains("SERVER")) { verifyColumns[1] = true; }
if (tblParameters.Columns.Contains("PORT")) { verifyColumns[2] = true; }
if (tblParameters.Columns.Contains("SSL")) { verifyColumns[3] = true; }
if (tblParameters.Columns.Contains("LOGIN")) { verifyColumns[4] = true; }
if (tblParameters.Columns.Contains("PWORD")) { verifyColumns[5] = true; }
bool IsEmailSetup = true;
int i = 0;
foreach (bool item in verifyColumns)
{
if (!item)
{
log.WriteList("MISSING EMAIL PARAMETER: " + tblParameters.Columns[i].ColumnName);
IsEmailSetup = false;
}
i++;
}
//this needs to be done on a separate thread to prevent holding up application loading
//string test = tblParameters.Rows[0]["SERVER"].ToString();
//if (_PingTest(test))
//{ log.WriteList("Email Server exists!"); }
//else
//{
// IsEmailSetup = false;
// log.WriteList("Email server not found! Alerts Disabled");
//}
if (IsEmailSetup)
{
isEmailEnabled = true;
log.WriteList("Email Alerts Enabled");
chkBxEmail.Checked = true;
}
else
{ chkBxEmail.Checked = false; }
}
else
{
log.WriteList("EMAIL Server parameters not found in INI.XML");
chkBxEmail.Checked = false;
}
DataTable tblAddress = null;
//Set up email address table
if (setINI.Tables.Contains("address"))
{
tblAddress = setINI.Tables["address"];
int ctr = 0;
to = new String[tblAddress.Rows.Count];
cc = new String[tblAddress.Rows.Count];
bcc = new String[tblAddress.Rows.Count];
EmailLimits = new Decimal[tblAddress.Rows.Count];
subject = new String[tblAddress.Rows.Count];
msg = new String[tblAddress.Rows.Count];
priority = new MailPriority[tblAddress.Rows.Count];
foreach (DataRow row in tblAddress.Rows)
{
to.SetValue(row[tblAddress.Columns["to"]].ToString(), ctr);
cc.SetValue(row[tblAddress.Columns["cc"]].ToString(), ctr);
bcc.SetValue(row[tblAddress.Columns["bcc"]].ToString(), ctr);
EmailLimits[ctr] = Math.Abs(
Convert.ToDecimal(
row[tblAddress.Columns["limit"]])) * -1;
subject.SetValue(row[tblAddress.Columns["subject"]].ToString(), ctr);
msg.SetValue(row[tblAddress.Columns["body"]].ToString(), ctr);
if (row[tblAddress.Columns["priority"]].ToString().ToUpperInvariant() == "HIGH")
{
priority[ctr] = MailPriority.High;
}
else if (row[tblAddress.Columns["priority"]].ToString().ToUpperInvariant() == "NORMAL")
{
priority[ctr] = MailPriority.Normal;
}
else if (row[tblAddress.Columns["priority"]].ToString().ToUpperInvariant() == "LOW")
{
priority[ctr] = MailPriority.Low;
}
else
{ priority[ctr] = MailPriority.Normal; }
ctr++;
}
log.WriteList("Email addresses found!");
}
else
{
log.WriteList("No Email addresses found in INI.XML");
chkBxEmail.Checked = false;
}
}
else
{ log.WriteList("INI.XML file does not exist"); }
}
catch (Exception ex)
{ log.WriteList(ex.ToString()); }
}
//Ping test code must be Set up to run on separate thread to prevent application from hanging
//private bool _PingTest(string serverAddress)
//{
// try
// {
// Ping pingSender = new Ping();
// PingReply reply = pingSender.Send(serverAddress);
// if (reply.Status == IPStatus.Success)
// {
// log.WriteList(string.Format("{1} RoundTrip time: {0}", reply.RoundtripTime, DateTime.Now.ToString("hh:mm:ss")));
// return true;
// }
// else if (reply.Status == IPStatus.TimedOut)
// {
// log.WriteList(reply.Status.ToString());
// return false;
// }
// else
// {
// log.WriteList("Ping Failed!");
// log.WriteList(reply.Status.ToString());
// return false;
// }
// }
// catch (Exception ex)
// {
// log.WriteList("Ping Failed!");
// log.WriteLog(ex.ToString());
// return false;
// }
//}
/// <summary>
/// calculate PNL;
/// </summary>
/// <param name="SecEx">GATEWAY</param>
/// <param name="product">PRODUCT TICKER</param>
/// <param name="secID">SECURITY_ID</param>
/// <param name="bid">Market Bid Price</param>
/// <param name="ask">Market Ask Price</param>
private void CalcPnL(string SecEx, string product, string secID, decimal bid, decimal ask)
{
current = DateTime.Now;
//log.WriteList("CalcPnL");
try{
SortedDictionary<string, decimal > totalPnL = new SortedDictionary<string, decimal >();
foreach (DataRow dr in dsRisk.tblPositions)
{
if (dr[dsRisk.tblPositions.SecurityExchangeColumn].Equals(SecEx) &&
dr[dsRisk.tblPositions.SymbolColumn].Equals(product) &&
dr[dsRisk.tblPositions.SecurityIDColumn].Equals(secID) &&
dsRisk.tblSecurity.Rows.Find(new object[] { SecEx, product, secID }) != null)
{
DataRow securityInfo = dsRisk.tblSecurity.Rows.Find(new object[] { SecEx, product, secID });
DataRow conversion = dsRisk.tblCurrency.Rows.Find(baseCurrency);
int buypos = 0;
if (dr[dsRisk.tblPositions.BuyPosColumn]!=null)
buypos = (int)dr[dsRisk.tblPositions.BuyPosColumn];
int sellpos = 0;
if (dr[dsRisk.tblPositions.SellPosColumn]!=null)
sellpos = (int)dr[dsRisk.tblPositions.SellPosColumn];
int matchQty = Math.Min(buypos, sellpos);
int remainQty = buypos - sellpos;
decimal avgbuy = 0.00M;
//TODO verify that this works
if ( ((decimal)dr[dsRisk.tblPositions.AvgBuyColumn]).GetType().IsValueType )
avgbuy = (decimal )dr[dsRisk.tblPositions.AvgBuyColumn];
decimal avgsell = 0.00M;
if ( dr[dsRisk.tblPositions.AvgSellColumn] != null)
avgsell = (decimal )dr[dsRisk.tblPositions.AvgSellColumn];
decimal prcdiff = avgsell- avgbuy;
decimal exPtVal = (decimal )securityInfo[dsRisk.tblSecurity.ExchangePointValueColumn];
string contractCurrency = securityInfo[dsRisk.tblSecurity.CurrencyColumn].ToString();
decimal currencyConversionrate = 1.00M;
if (conversion[contractCurrency] != null)
{
currencyConversionrate = (decimal )conversion[contractCurrency];
}
if (matchQty != 0)
{
dr[dsRisk.tblPositions.RealizedPLColumn] = Math.Round(matchQty * prcdiff * exPtVal * currencyConversionrate, 2);
}
else
{ dr[dsRisk.tblPositions.RealizedPLColumn] = 0.00; }
if (remainQty < 0)
{
prcdiff = avgsell - ask;
}
else if (remainQty > 0)
{
prcdiff = bid - avgbuy;
}
else
{ prcdiff = 0; }
dr[dsRisk.tblPositions.UnrealizedPLColumn] = Math.Round(Math.Abs(remainQty) * prcdiff * exPtVal * currencyConversionrate, 2);
dr.AcceptChanges();
}
if (totalPnL.ContainsKey(dr[0].ToString()))
{ totalPnL[dr[0].ToString()] += ((decimal )dr[dsRisk.tblPositions.RealizedPLColumn] + (decimal )dr[dsRisk.tblPositions.UnrealizedPLColumn]); }
else
{ totalPnL[dr[0].ToString()] = ((decimal )dr[dsRisk.tblPositions.RealizedPLColumn] + (decimal )dr[dsRisk.tblPositions.UnrealizedPLColumn]); }
}
foreach (KeyValuePair<string,decimal > kvp in totalPnL)
{
DataRow dr = dsRisk.tblTrader.Rows.Find(kvp.Key);
if (dr != null)
{
dr[dsRisk.tblTrader.TotalPLColumn] = kvp.Value;
dr.AcceptChanges();
}
else
{ log.WriteList("TRADER NOT FOUND IN MGT.XML"); }
}
if (previousPositionsLoaded)
{
checkPnLAction();
}
}
catch (Exception ex)
{ log.WriteList(ex.ToString()); }
}
// check what actions must be taken based on limits and P&L
private void checkPnLAction()
{
try
{
log.WriteLog("mainForm::checkPnLAction: ");
foreach (DataRow dr in dsRisk.tblTrader)
{
//log.WriteList(string.Format("{0} < {1}", dr[dsRisk.tblTrader.TotalPLColumn], dr[dsRisk.tblTrader.LimitColumn]));
decimal total;
bool isValid = decimal .TryParse(dr[dsRisk.tblTrader.TotalPLColumn].ToString(), out total);
if (isValid && (decimal )dr[dsRisk.tblTrader.TotalPLColumn] <= (decimal )dr[dsRisk.tblTrader.LimitColumn])
{
string MGT = dr[dsRisk.tblTrader.MGTColumn].ToString();
stoppedTraders.Add(MGT);
if (chkBxAUTO.Checked)
{
TT.SendMsg send = new TT.SendMsg();
send.ttOrderStatusRequest();
}
else
{ log.WriteList("AUTO MODE DISABLED! Orders not canceled"); }
FlattenTrader(MGT);
}
if (isEmailEnabled)
{
int ActiveAlert = (int)dr[dsRisk.tblTrader.EmailAlertColumn];
if (isValid &&
ActiveAlert <= EmailLimits.GetUpperBound(0) &&
(decimal )dr[dsRisk.tblTrader.TotalPLColumn] < EmailLimits[ActiveAlert])
{
SendEmail(
to[ActiveAlert],
cc[ActiveAlert],
bcc[ActiveAlert],
msg[ActiveAlert],
subject[ActiveAlert] + Environment.NewLine + dr[dsRisk.tblTrader.MGTColumn].ToString(),
priority[ActiveAlert]);
ActiveAlert++;
dr[dsRisk.tblTrader.EmailAlertColumn] = ActiveAlert;
dr.AcceptChanges();
}
}
}
}
catch (Exception ex)
{ log.WriteList(ex.ToString()); }
}
/// <summary>
/// Flatten all positions for a trader.
/// </summary>
/// <param name="MGT"></param>
private void FlattenTrader(string MGT)
{
try
{
foreach (DataRow dr in dsRisk.tblPositions)
{
if (dr[dsRisk.tblPositions.MGTColumn].Equals(MGT) &&
!dr[dsRisk.tblPositions.BuyPosColumn].Equals(dr[dsRisk.tblPositions.SellPosColumn]))
{
string account = dr[dsRisk.tblPositions.AccountColumn].ToString();
if (String.IsNullOrEmpty(account))
{ account = dsRisk.tblTrader.Rows.Find(MGT).Field<string>(dsRisk.tblTrader.AccountColumn); }
int buys = (int)dr[dsRisk.tblPositions.BuyPosColumn];
int sells = (int)dr[dsRisk.tblPositions.SellPosColumn];
char bs = char.MinValue;
if (buys < sells)
{ bs = QuickFix.Fields.Side.BUY; }
else
{ bs = QuickFix.Fields.Side.SELL; }
decimal qty = Convert.ToDecimal(Math.Abs(buys - sells));
string SecEx = dr[dsRisk.tblPositions.SecurityExchangeColumn].ToString();
string symbol = dr[dsRisk.tblPositions.SymbolColumn].ToString();
string secID = dr[dsRisk.tblPositions.SecurityIDColumn].ToString();
string gateway = dr[dsRisk.tblPositions.ExchangeGatewayColumn].ToString();
if (TT.SendMsg.inflightOrders.Count == 0 && chkBxAUTO.Checked)
{
TT.SendMsg send = new TT.SendMsg();
send.ttNewOrderSingle(account, SecEx,symbol, secID, qty, bs, gateway );
}
else if (!chkBxAUTO.Checked)
{ log.WriteList("AUTO MODE DISABLED! No orders sent"); }
}
}
}
catch (Exception ex)
{ log.WriteList(ex.ToString()); }
}
#region Receive Data or Instructions from QuickFix (running on another thread)
/// <summary>
/// clear all position information
/// </summary>
private void ClearPositions()
{
dsRisk.tblPositions.Clear();
log.WriteList("Positions Cleared");
}
/// <summary>
/// Update contract prices
/// </summary>
/// <param name="SecEx"></param>
/// <param name="product"></param>
/// <param name="secID"></param>
/// <param name="bid"></param>
/// <param name="ask"></param>
private void UpdatePrices(string SecEx, string product, string secID, decimal bid, decimal ask)
{
try
{
DataRow dr = dsRisk.tblSecurity.Rows.Find(new object[] { SecEx, product, secID });
if (dr != null)
{
if (bid != (decimal )dr[dsRisk.tblSecurity.BidPriceColumn] ||
ask != (decimal )dr[dsRisk.tblSecurity.AskPriceColumn])
{
dr[dsRisk.tblSecurity.BidPriceColumn] = bid;
dr[dsRisk.tblSecurity.AskPriceColumn] = ask;
dr.AcceptChanges();
CalcPnL(SecEx, product, secID, bid, ask);
}
}
}
catch (Exception ex)
{ log.WriteList(ex.ToString()); }
}
/// <summary>
/// update gateway status
/// </summary>
/// <param name="exch"></param>
/// <param name="sub"></param>
/// <param name="stat"></param>
/// <param name="t"></param>
private void UpdateGateway(string exch, string sub, string stat, string t)
{
try
{
if (dsRisk.tblGateways.Rows.Find(exch) == null)
{
switch (sub)
{
case "PRICE":
dsRisk.tblGateways.AddtblGatewaysRow(exch, stat, null, null, null);
break;
case "ORDER":
dsRisk.tblGateways.AddtblGatewaysRow(exch, null, stat, null, null);
break;
case "FILL":
dsRisk.tblGateways.AddtblGatewaysRow(exch, null, null, stat, null);
break;
default:
dsRisk.tblGateways.AddtblGatewaysRow(exch, null, null, null, t);
break;
}
}
else
{
DataRow dr = dsRisk.tblGateways.Rows.Find(exch);
dr[sub] = stat;
if (t != null)
dr[dsRisk.tblGateways.TEXTColumn] = t;
dr.AcceptChanges();
}
}
catch (Exception ex)
{
log.WriteList(ex.ToString());
}
}
/// <summary>
/// Update contract information
/// </summary>
/// <param name="SecEx"></param>
/// <param name="product"></param>
/// <param name="secID"></param>
/// <param name="CUR"></param>
/// <param name="exPointValue"></param>
private void UpdateSecurity(string SecEx, string product, string secID, string CUR, decimal exPointValue)
{
try
{
if (dsRisk.tblSecurity.Rows.Find(new object[] { SecEx, product, secID }) == null)
{
dsRisk.tblSecurity.AddtblSecurityRow(SecEx, product, secID,
CUR, exPointValue, 0.00M, 0.00M);
}
else
{
DataRow dr = dsRisk.tblSecurity.Rows.Find(new object[] { SecEx, product, secID });
if (CUR != null) { dr[dsRisk.tblSecurity.CurrencyColumn] = CUR; }
//if (exPointValue != decimal .NaN) {
dr[dsRisk.tblSecurity.ExchangePointValueColumn] = exPointValue;
//save changes
dr.AcceptChanges();
}
}
catch (Exception ex)
{
log.WriteList(ex.ToString());
}
}
/// <summary>
///
/// </summary>
/// <param name="MGT"></param>
/// <param name="acct"></param>
/// <param name="SecEx"></param>
/// <param name="product"></param>
/// <param name="secID"></param>
/// <param name="tradesize"></param>
/// <param name="side"></param>
/// <param name="price"></param>
/// <param name="gateway"></param>
private void UpdatePosition(
string MGT,
string acct,
string SecEx,
string product,
string secID,
int tradesize,
char side,
decimal price,
string gateway)
{
log.WriteLog("mainForm::UpdatePosition");
//added to filter by account
if (isAccountFilterEnabled)
{
string watchedAccount = dsRisk.tblTrader.Rows.Find(MGT).Field<string>(dsRisk.tblTrader.AccountColumn);
if (watchedAccount == null || watchedAccount != acct)
{
log.WriteList("Execution disregarded because account does not match");
return;
}
}
//end account filter code
int currentBuyPos = 0;
int currentSellPos = 0;
decimal currentBuyPrc = 0.00M;
decimal currentSellPrc = 0.00M;
int previousBuyPos = 0;
int previousSellPos = 0;
if (side == QuickFix.Fields.Side.SELL )
{
currentSellPos = tradesize;
currentSellPrc = price;
}
else if (side == QuickFix.Fields.Side.BUY)
{
currentBuyPos = tradesize;
currentBuyPrc = price;
}
else
{
log.WriteList("NO BuySell info");
return;
}
try
{
if (dsRisk.tblPositions.Rows.Find(new object[] { MGT, SecEx, product, secID }) == null)
{
//TODO why cast to double??
dsRisk.tblPositions.AddtblPositionsRow(MGT, SecEx, product, secID,
currentBuyPos, currentSellPos, (double)currentBuyPrc, (double)currentSellPrc, 0.00, 0.00, gateway, acct );
TT.SendMsg send = new TT.SendMsg();
send.ttSecurityDefinitionRequest(SecEx, product, secID);
send.ttMarketDataRequest(SecEx, product, secID);
}
else
{
DataRow dr = dsRisk.tblPositions.Rows.Find(new object[] { MGT, SecEx, product, secID });
dr[dsRisk.tblPositions.AccountColumn] = acct;
//existing buy/sell positions
previousBuyPos = (int)dr[dsRisk.tblPositions.BuyPosColumn];
previousSellPos = (int)dr[dsRisk.tblPositions.SellPosColumn];
dr[dsRisk.tblPositions.BuyPosColumn] = previousBuyPos + currentBuyPos;
dr[dsRisk.tblPositions.SellPosColumn] = previousSellPos + currentSellPos;
decimal previousAvgBuyPrc = 0.00M;
if ( dr[dsRisk.tblPositions.AvgBuyColumn] != null)
previousAvgBuyPrc = (decimal )dr[dsRisk.tblPositions.AvgBuyColumn];
decimal previousAvgSellPrc = 0.00M;
if ( dr[dsRisk.tblPositions.AvgSellColumn] != null)
previousAvgSellPrc = (decimal )dr[dsRisk.tblPositions.AvgSellColumn];
dr[dsRisk.tblPositions.AvgBuyColumn] = ((previousBuyPos * previousAvgBuyPrc) +
(currentBuyPos * currentBuyPrc)) / (previousBuyPos + currentBuyPos);
dr[dsRisk.tblPositions.AvgSellColumn] = ((previousSellPos * previousAvgSellPrc) +
(currentSellPos * currentSellPrc)) / (previousSellPos + currentSellPos);
// using decimals negates the need to check for NaN?
// if (dr[dsRisk.tblPositions.AvgBuyColumn].Equals(decimal. .NaN)) { dr[dsRisk.tblPositions.AvgBuyColumn] = 0.00; }
// if (dr[dsRisk.tblPositions.AvgSellColumn].Equals(decimal .NaN)) { dr[dsRisk.tblPositions.AvgSellColumn] = 0.00; }
dr.AcceptChanges();
}
DataRow drPrc = dsRisk.tblSecurity.Rows.Find(new object[] { SecEx, product, secID });
if (drPrc != null)
{
decimal bid = (decimal )drPrc[dsRisk.tblSecurity.BidPriceColumn];
decimal ask = (decimal )drPrc[dsRisk.tblSecurity.AskPriceColumn];
CalcPnL(SecEx, product, secID, bid, ask);
}
}
catch (Exception ex)
{
log.WriteList("Exception occured mainForm::UpdatePosition");
log.WriteLog(ex.ToString());
}
}
/// <summary>
/// Application is designed to only submit one order at a time, when this order is filled
/// the application is enabled to send another if needed. If order is rejected the application will also be
/// enabled to resubmit.
/// </summary>
/// <param name="ordID"></param>
private void updateOrderMgmt(string ordID)
{
if (TT.SendMsg.inflightOrders.Contains(ordID))
TT.SendMsg.inflightOrders.Remove(ordID);
}
/// <summary>
/// Receive data from QuickFix to cancel all orders for a shutdown trader
/// </summary>
/// <param name="MGT"></param>
/// <param name="key"></param>
private void orderCancel(string MGT, string key)
{
if (stoppedTraders.Contains(MGT))
{
TT.SendMsg send = new TT.SendMsg();
send.ttOrderCancelRequest(key);
}
}
#endregion
/// <summary>
/// send an email
/// </summary>
/// <param name="to">comma separated list of addresses</param>
/// <param name="cc">comma separated list of addresses</param>
/// <param name="bcc">comma separated list of addresses</param>
/// <param name="msgSubject">subject text</param>
/// <param name="msgBody">body text</param>
/// <param name="mp">.NET MailPriotity enumeration</param>
public void SendEmail(
string to,
string cc,
string bcc,
string msgSubject,
string msgBody,
MailPriority mp
)
{
//create the mail message
System.Net.Mail.MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.CC.Add(cc);
mail.Bcc.Add(bcc);
mail.Subject = msgSubject;
log.WriteLog(mail.Subject);
mail.Body = msgBody;
log.WriteLog(msgBody);
mail.Priority = mp;
try
{
DataRow email = tblParameters.Rows[0];
mail.From = new MailAddress(email["FROM"].ToString());
System.Net.Mail.SmtpClient smtp = new SmtpClient(email["SERVER"].ToString(), Convert.ToInt32(email["PORT"]));
smtp.Credentials = new NetworkCredential(email["LOGIN"].ToString(), email["PWORD"].ToString());
smtp.EnableSsl = Convert.ToBoolean(email["SSL"]);
smtp.Send(mail);
log.WriteList("Email Sent!");
}
catch (Exception ex)
{ log.WriteList(ex.ToString()); }
mail.Dispose();
}
/// <summary>
/// This event starts off ticking every second when application starts and at the end of first minute
/// slows to checking time once per minute.
/// If current time = the time Set on the application for reset all PNL and positions are cleared off
/// and email alerts are reset to start at first alert.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
if (!TimerUpdated &&
DateTime.Now.TimeOfDay.Seconds == 0)
{
timer1.Interval = 60000;
TimerUpdated = true;
}
if (dateTimePicker2.Value.TimeOfDay.Hours == DateTime.Now.TimeOfDay.Hours &&
dateTimePicker2.Value.TimeOfDay.Minutes == DateTime.Now.TimeOfDay.Minutes &&
checkBox1.Checked)
{
dsRisk.tblPositions.Clear();
foreach (DataRow dr in dsRisk.tblTrader)
{
dr[dsRisk.tblTrader.TotalPLColumn] = 0;
dr[dsRisk.tblTrader.EmailAlertColumn] = 0;
dr.AcceptChanges();
}
log.WriteList("Position data cleared: P&L reset to zero.");
}
if (TimerUpdated)
{
if (current < DateTime.Now.Subtract(TimeSpan.FromSeconds(30)))
{ checkPnLAction(); }
}
}
/// <summary>
/// just a variable to know if we need to save a new time setting for the reset time.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
TimeChanged = true;
}
/// <summary>
/// Disable/enable email alerts
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void chkBxEmail_CheckedChanged(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
if (c.Checked)
{ isEmailEnabled = true; }
else
{ isEmailEnabled = false; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Sanford.Multimedia.Midi
{
public class Sequencer : IComponent
{
private Sequence sequence = null;
private List<IEnumerator<int>> enumerators = new List<IEnumerator<int>>();
private MessageDispatcher dispatcher = new MessageDispatcher();
private ChannelChaser chaser = new ChannelChaser();
private ChannelStopper stopper = new ChannelStopper();
private MidiInternalClock clock = new MidiInternalClock();
private int tracksPlayingCount;
private readonly object lockObject = new object();
private bool playing = false;
private bool disposed = false;
private ISite site = null;
#region Events
public event EventHandler PlayingCompleted;
public event EventHandler<ChannelMessageEventArgs> ChannelMessagePlayed
{
add
{
dispatcher.ChannelMessageDispatched += value;
}
remove
{
dispatcher.ChannelMessageDispatched -= value;
}
}
public event EventHandler<SysExMessageEventArgs> SysExMessagePlayed
{
add
{
dispatcher.SysExMessageDispatched += value;
}
remove
{
dispatcher.SysExMessageDispatched -= value;
}
}
public event EventHandler<MetaMessageEventArgs> MetaMessagePlayed
{
add
{
dispatcher.MetaMessageDispatched += value;
}
remove
{
dispatcher.MetaMessageDispatched -= value;
}
}
public event EventHandler<ChasedEventArgs> Chased
{
add
{
chaser.Chased += value;
}
remove
{
chaser.Chased -= value;
}
}
public event EventHandler<StoppedEventArgs> Stopped
{
add
{
stopper.Stopped += value;
}
remove
{
stopper.Stopped -= value;
}
}
#endregion
public Sequencer()
{
dispatcher.MetaMessageDispatched += delegate(object sender, MetaMessageEventArgs e)
{
if(e.Message.MetaType == MetaType.EndOfTrack)
{
tracksPlayingCount--;
if(tracksPlayingCount == 0)
{
Stop();
OnPlayingCompleted(EventArgs.Empty);
}
}
else
{
clock.Process(e.Message);
}
};
dispatcher.ChannelMessageDispatched += delegate(object sender, ChannelMessageEventArgs e)
{
stopper.Process(e.Message);
};
clock.Tick += delegate(object sender, EventArgs e)
{
lock(lockObject)
{
if(!playing)
{
return;
}
foreach(IEnumerator<int> enumerator in enumerators)
{
enumerator.MoveNext();
}
}
};
}
~Sequencer()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if(disposing)
{
lock(lockObject)
{
Stop();
clock.Dispose();
disposed = true;
GC.SuppressFinalize(this);
}
}
}
public void Start()
{
#region Require
if(disposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
lock(lockObject)
{
Stop();
Position = 0;
Continue();
}
}
public void Continue()
{
#region Require
if(disposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
#region Guard
if(Sequence == null)
{
return;
}
#endregion
lock(lockObject)
{
Stop();
enumerators.Clear();
foreach(Track t in Sequence)
{
enumerators.Add(t.TickIterator(Position, chaser, dispatcher).GetEnumerator());
}
tracksPlayingCount = Sequence.Count;
playing = true;
clock.Ppqn = sequence.Division;
clock.Continue();
}
}
public void Stop()
{
#region Require
if(disposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
lock(lockObject)
{
#region Guard
if(!playing)
{
return;
}
#endregion
playing = false;
clock.Stop();
stopper.AllSoundOff();
}
}
protected virtual void OnPlayingCompleted(EventArgs e)
{
PlayingCompleted?.Invoke(this, e);
}
protected virtual void OnDisposed(EventArgs e)
{
Disposed?.Invoke(this, e);
}
public int Position
{
get
{
#region Require
if(disposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
#endregion
return clock.Ticks;
}
set
{
#region Require
if(disposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}
else if(value < 0)
{
throw new ArgumentOutOfRangeException();
}
#endregion
bool wasPlaying;
lock(lockObject)
{
wasPlaying = playing;
Stop();
clock.SetTicks(value);
}
lock(lockObject)
{
if(wasPlaying)
{
Continue();
}
}
}
}
public Sequence Sequence
{
get
{
return sequence;
}
set
{
#region Require
if(value == null)
{
throw new ArgumentNullException();
}
else if(value.SequenceType == SequenceType.Smpte)
{
throw new NotSupportedException();
}
#endregion
lock(lockObject)
{
Stop();
sequence = value;
}
}
}
#region IComponent Members
public event EventHandler Disposed;
public ISite Site
{
get
{
return site;
}
set
{
site = value;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
#region Guard
if(disposed)
{
return;
}
#endregion
Dispose(true);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.Versioning;
using System.Text;
using System.Globalization;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.Contracts;
using StackCrawlMark = System.Threading.StackCrawlMark;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe struct RuntimeTypeHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeTypeHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, Environment.GetResourceString("Arg_InvalidHandle"));
return new RuntimeTypeHandle(type);
}
// Returns type for interop with EE. The type is guaranteed to be non-null.
internal RuntimeType GetTypeChecked()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, Environment.GetResourceString("Arg_InvalidHandle"));
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInstanceOfType(RuntimeType type, Object o);
internal unsafe static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers)
{
Type type = typeStart;
if (genericArgs != null)
{
type = type.MakeGenericType(genericArgs);
}
if (cModifiers > 0)
{
int* arModifiers = (int*)pModifiers.ToPointer();
for(int i = 0; i < cModifiers; i++)
{
if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.Ptr)
type = type.MakePointerType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ByRef)
type = type.MakeByRefType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.SzArray)
type = type.MakeArrayType();
else
type = type.MakeArrayType(Marshal.ReadInt32((IntPtr)arModifiers, ++i * sizeof(int)));
}
}
return type;
}
public static bool operator ==(RuntimeTypeHandle left, object right) { return left.Equals(right); }
public static bool operator ==(object left, RuntimeTypeHandle right) { return right.Equals(left); }
public static bool operator !=(RuntimeTypeHandle left, object right) { return !left.Equals(right); }
public static bool operator !=(object left, RuntimeTypeHandle right) { return !right.Equals(left); }
internal static RuntimeTypeHandle EmptyHandle
{
get
{
return new RuntimeTypeHandle(null);
}
}
// This is the RuntimeType for the type
private RuntimeType m_type;
public override int GetHashCode()
{
return m_type != null ? m_type.GetHashCode() : 0;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public override bool Equals(object obj)
{
if(!(obj is RuntimeTypeHandle))
return false;
RuntimeTypeHandle handle =(RuntimeTypeHandle)obj;
return handle.m_type == m_type;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public bool Equals(RuntimeTypeHandle handle)
{
return handle.m_type == m_type;
}
public IntPtr Value
{
get
{
return m_type != null ? m_type.m_handle : IntPtr.Zero;
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetValueInternal(RuntimeTypeHandle handle);
internal RuntimeTypeHandle(RuntimeType type)
{
m_type = type;
}
internal bool IsNullHandle()
{
return m_type == null;
}
internal static bool IsPrimitive(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType >= CorElementType.Boolean && corElemType <= CorElementType.R8) ||
corElemType == CorElementType.I ||
corElemType == CorElementType.U;
}
internal static bool IsByRef(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.ByRef);
}
internal static bool IsPointer(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.Ptr);
}
internal static bool IsArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.Array || corElemType == CorElementType.SzArray);
}
internal static bool IsSzArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.SzArray);
}
internal static bool HasElementType(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return ((corElemType == CorElementType.Array || corElemType == CorElementType.SzArray) // IsArray
|| (corElemType == CorElementType.Ptr) // IsPointer
|| (corElemType == CorElementType.ByRef)); // IsByRef
}
internal static IntPtr[] CopyRuntimeTypeHandles(RuntimeTypeHandle[] inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].Value;
}
length = outHandles.Length;
return outHandles;
}
internal static IntPtr[] CopyRuntimeTypeHandles(Type[] inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].GetTypeHandleInternal().Value;
}
length = outHandles.Length;
return outHandles;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, bool noCheck, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor, ref bool bNeedSecurityCheck);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object Allocate(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateInstanceForAnotherGenericParameter(RuntimeType type, RuntimeType genericParameter);
internal RuntimeType GetRuntimeType()
{
return m_type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static CorElementType GetCorElementType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeAssembly GetAssembly(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal extern static RuntimeModule GetModule(RuntimeType type);
[CLSCompliant(false)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public ModuleHandle GetModuleHandle()
{
return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetBaseType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static TypeAttributes GetAttributes(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetElementType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CompareCanonicalHandles(RuntimeType left, RuntimeType right);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetArrayRank(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetToken(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot);
// This is managed wrapper for MethodTable::IntroducedMethodIterator
internal struct IntroducedMethodEnumerator
{
bool _firstCall;
RuntimeMethodHandleInternal _handle;
internal IntroducedMethodEnumerator(RuntimeType type)
{
_handle = RuntimeTypeHandle.GetFirstIntroducedMethod(type);
_firstCall = true;
}
public bool MoveNext()
{
if (_firstCall)
{
_firstCall = false;
}
else if (_handle.Value != IntPtr.Zero)
{
RuntimeTypeHandle.GetNextIntroducedMethod(ref _handle);
}
return !(_handle.Value == IntPtr.Zero);
}
public RuntimeMethodHandleInternal Current
{
get {
return _handle;
}
}
// Glue to make this work nicely with C# foreach statement
public IntroducedMethodEnumerator GetEnumerator()
{
return this;
}
}
internal static IntroducedMethodEnumerator GetIntroducedMethods(RuntimeType type)
{
return new IntroducedMethodEnumerator(type);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern RuntimeMethodHandleInternal GetFirstIntroducedMethod(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool GetFields(RuntimeType type, IntPtr* result, int* count);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Type[] GetInterfaces(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetConstraints(RuntimeTypeHandle handle, ObjectHandleOnStack types);
internal Type[] GetConstraints()
{
Type[] types = null;
GetConstraints(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types));
return types;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static IntPtr GetGCHandle(RuntimeTypeHandle handle, GCHandleType type);
internal IntPtr GetGCHandle(GCHandleType type)
{
return GetGCHandle(GetNativeHandle(), type);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetNumVirtuals(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void VerifyInterfaceIsImplemented(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle);
internal void VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
{
VerifyInterfaceIsImplemented(GetNativeHandle(), interfaceHandle.GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle);
internal int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle)
{
return GetInterfaceMethodImplementationSlot(GetNativeHandle(), interfaceHandle.GetNativeHandle(), interfaceMethodHandle);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsComObject(RuntimeType type, bool isGenericCOM);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsContextful(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInterface(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool _IsVisible(RuntimeTypeHandle typeHandle);
internal static bool IsVisible(RuntimeType type)
{
return _IsVisible(new RuntimeTypeHandle(type));
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecurityCritical(RuntimeTypeHandle typeHandle);
internal bool IsSecurityCritical()
{
return IsSecurityCritical(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecuritySafeCritical(RuntimeTypeHandle typeHandle);
internal bool IsSecuritySafeCritical()
{
return IsSecuritySafeCritical(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecurityTransparent(RuntimeTypeHandle typeHandle);
internal bool IsSecurityTransparent()
{
return IsSecurityTransparent(GetNativeHandle());
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasProxyAttribute(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsValueType(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ConstructName(RuntimeTypeHandle handle, TypeNameFormatFlags formatFlags, StringHandleOnStack retString);
internal string ConstructName(TypeNameFormatFlags formatFlags)
{
string name = null;
ConstructName(GetNativeHandle(), formatFlags, JitHelpers.GetStringHandleOnStack(ref name));
return name;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static void* _GetUtf8Name(RuntimeType type);
internal static Utf8String GetUtf8Name(RuntimeType type)
{
return new Utf8String(_GetUtf8Name(type));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CanCastTo(RuntimeType type, RuntimeType target);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetDeclaringType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetDefaultConstructor(RuntimeTypeHandle handle, ObjectHandleOnStack method);
internal IRuntimeMethodInfo GetDefaultConstructor()
{
IRuntimeMethodInfo ctor = null;
GetDefaultConstructor(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref ctor));
return ctor;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, StackCrawlMarkHandle stackMark,
IntPtr pPrivHostBinder,
bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive);
// Wrapper function to reduce the need for ifdefs.
internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark, bool loadTypeFromPartialName)
{
return GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly, ref stackMark, IntPtr.Zero, loadTypeFromPartialName);
}
internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark,
IntPtr pPrivHostBinder,
bool loadTypeFromPartialName)
{
if (name == null || name.Length == 0)
{
if (throwOnError)
throw new TypeLoadException(Environment.GetResourceString("Arg_TypeLoadNullStr"));
return null;
}
RuntimeType type = null;
Object keepAlive = null;
GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly,
JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
pPrivHostBinder,
loadTypeFromPartialName, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
return type;
}
internal static Type GetTypeByName(string name, ref StackCrawlMark stackMark)
{
return GetTypeByName(name, false, false, false, ref stackMark, false);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypeByNameUsingCARules(string name, RuntimeModule scope, ObjectHandleOnStack type);
internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope)
{
if (name == null || name.Length == 0)
throw new ArgumentException(null, nameof(name));
Contract.EndContractBlock();
RuntimeType type = null;
GetTypeByNameUsingCARules(name, scope.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void GetInstantiation(RuntimeTypeHandle type, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
internal RuntimeType[] GetInstantiationInternal()
{
RuntimeType[] types = null;
GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), true);
return types;
}
internal Type[] GetInstantiationPublic()
{
Type[] types = null;
GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), false);
return types;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type);
internal RuntimeType Instantiate(Type[] inst)
{
// defensive copy to be sure array is not mutated from the outside during processing
int instCount;
IntPtr []instHandles = CopyRuntimeTypeHandles(inst, out instCount);
fixed (IntPtr* pInst = instHandles)
{
RuntimeType type = null;
Instantiate(GetNativeHandle(), pInst, instCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(inst);
return type;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeArray(RuntimeTypeHandle handle, int rank, ObjectHandleOnStack type);
internal RuntimeType MakeArray(int rank)
{
RuntimeType type = null;
MakeArray(GetNativeHandle(), rank, JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeSZArray(RuntimeTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeSZArray()
{
RuntimeType type = null;
MakeSZArray(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeByRef(RuntimeTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeByRef()
{
RuntimeType type = null;
MakeByRef(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakePointer(RuntimeTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakePointer()
{
RuntimeType type = null;
MakePointer(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static bool IsCollectible(RuntimeTypeHandle handle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasInstantiation(RuntimeType type);
internal bool HasInstantiation()
{
return HasInstantiation(GetTypeChecked());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetGenericTypeDefinition(RuntimeTypeHandle type, ObjectHandleOnStack retType);
internal static RuntimeType GetGenericTypeDefinition(RuntimeType type)
{
RuntimeType retType = type;
if (HasInstantiation(retType) && !IsGenericTypeDefinition(retType))
GetGenericTypeDefinition(retType.GetTypeHandleInternal(), JitHelpers.GetObjectHandleOnStack(ref retType));
return retType;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericTypeDefinition(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericVariable(RuntimeType type);
internal bool IsGenericVariable()
{
return IsGenericVariable(GetTypeChecked());
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetGenericVariableIndex(RuntimeType type);
internal int GetGenericVariableIndex()
{
RuntimeType type = GetTypeChecked();
if (!IsGenericVariable(type))
throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter"));
return GetGenericVariableIndex(type);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool ContainsGenericVariables(RuntimeType handle);
internal bool ContainsGenericVariables()
{
return ContainsGenericVariables(GetTypeChecked());
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool SatisfiesConstraints(RuntimeType paramType, IntPtr *pTypeContext, int typeContextLength, IntPtr *pMethodContext, int methodContextLength, RuntimeType toType);
internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType)
{
int typeContextLength;
int methodContextLength;
IntPtr[] typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength);
IntPtr[] methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength);
fixed (IntPtr *pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles)
{
bool result = SatisfiesConstraints(paramType, pTypeContextHandles, typeContextLength, pMethodContextHandles, methodContextLength, toType);
GC.KeepAlive(typeContext);
GC.KeepAlive(methodContext);
return result;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr _GetMetadataImport(RuntimeType type);
internal static MetadataImport GetMetadataImport(RuntimeType type)
{
return new MetadataImport(_GetMetadataImport(type), type);
}
private RuntimeTypeHandle(SerializationInfo info, StreamingContext context)
{
if(info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
RuntimeType m = (RuntimeType)info.GetValue("TypeObj", typeof(RuntimeType));
m_type = m;
if (m_type == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if(info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_type == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidFieldState"));
info.AddValue("TypeObj", m_type, typeof(RuntimeType));
}
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an IRuntimeMethodInfo, and ensure that the IRuntimeMethodInfo is preserved
// across the lifetime of the RuntimeMethodHandleInternal instance
// 3. When another object is used to keep the RuntimeMethodHandleInternal alive. See delegates, CreateInstance cache, Signature structure
// When in doubt, do not use.
internal struct RuntimeMethodHandleInternal
{
internal static RuntimeMethodHandleInternal EmptyHandle
{
get
{
return new RuntimeMethodHandleInternal();
}
}
internal bool IsNullHandle()
{
return m_handle.IsNull();
}
internal IntPtr Value
{
get
{
return m_handle;
}
}
internal RuntimeMethodHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal class RuntimeMethodInfoStub : IRuntimeMethodInfo
{
public RuntimeMethodInfoStub(RuntimeMethodHandleInternal methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = methodHandleValue;
}
public RuntimeMethodInfoStub(IntPtr methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = new RuntimeMethodHandleInternal(methodHandleValue);
}
object m_keepalive;
// These unused variables are used to ensure that this class has the same layout as RuntimeMethodInfo
#pragma warning disable 169
object m_a;
object m_b;
object m_c;
object m_d;
object m_e;
object m_f;
object m_g;
#pragma warning restore 169
public RuntimeMethodHandleInternal m_value;
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
get
{
return m_value;
}
}
}
internal interface IRuntimeMethodInfo
{
RuntimeMethodHandleInternal Value
{
get;
}
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe struct RuntimeMethodHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal static IRuntimeMethodInfo EnsureNonNullMethodInfo(IRuntimeMethodInfo method)
{
if (method == null)
throw new ArgumentNullException(null, Environment.GetResourceString("Arg_InvalidHandle"));
return method;
}
internal static RuntimeMethodHandle EmptyHandle
{
get { return new RuntimeMethodHandle(); }
}
private IRuntimeMethodInfo m_value;
internal RuntimeMethodHandle(IRuntimeMethodInfo method)
{
m_value = method;
}
internal IRuntimeMethodInfo GetMethodInfo()
{
return m_value;
}
// Used by EE
private static IntPtr GetValueInternal(RuntimeMethodHandle rmh)
{
return rmh.Value;
}
// ISerializable interface
private RuntimeMethodHandle(SerializationInfo info, StreamingContext context)
{
if(info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MethodBase m =(MethodBase)info.GetValue("MethodObj", typeof(MethodBase));
m_value = m.MethodHandle.m_value;
if (m_value == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_value == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidFieldState"));
// This is either a RuntimeMethodInfo or a RuntimeConstructorInfo
MethodBase methodInfo = RuntimeType.GetMethodBase(m_value);
info.AddValue("MethodObj", methodInfo, typeof(MethodBase));
}
public IntPtr Value
{
get
{
return m_value != null ? m_value.Value.Value : IntPtr.Zero;
}
}
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public override bool Equals(object obj)
{
if (!(obj is RuntimeMethodHandle))
return false;
RuntimeMethodHandle handle = (RuntimeMethodHandle)obj;
return handle.Value == Value;
}
public static bool operator ==(RuntimeMethodHandle left, RuntimeMethodHandle right)
{
return left.Equals(right);
}
public static bool operator !=(RuntimeMethodHandle left, RuntimeMethodHandle right)
{
return !left.Equals(right);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public bool Equals(RuntimeMethodHandle handle)
{
return handle.Value == Value;
}
[Pure]
internal bool IsNullHandle()
{
return m_value == null;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static IntPtr GetFunctionPointer(RuntimeMethodHandleInternal handle);
public IntPtr GetFunctionPointer()
{
IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value).Value);
GC.KeepAlive(m_value);
return ptr;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal unsafe extern static void CheckLinktimeDemands(IRuntimeMethodInfo method, RuntimeModule module, bool isDecoratedTargetSecurityTransparent);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static bool IsCAVisibleFromDecoratedType(
RuntimeTypeHandle attrTypeHandle,
IRuntimeMethodInfo attrCtor,
RuntimeTypeHandle sourceTypeHandle,
RuntimeModule sourceModule);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IRuntimeMethodInfo _GetCurrentMethod(ref StackCrawlMark stackMark);
internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark)
{
return _GetCurrentMethod(ref stackMark);
}
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method);
internal static MethodAttributes GetAttributes(IRuntimeMethodInfo method)
{
MethodAttributes retVal = RuntimeMethodHandle.GetAttributes(method.Value);
GC.KeepAlive(method);
return retVal;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format, StringHandleOnStack retString);
internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format)
{
string name = null;
ConstructInstantiation(EnsureNonNullMethodInfo(method), format, JitHelpers.GetStringHandleOnStack(ref name));
return name;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetDeclaringType(RuntimeMethodHandleInternal method);
internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method)
{
RuntimeType type = RuntimeMethodHandle.GetDeclaringType(method.Value);
GC.KeepAlive(method);
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetSlot(RuntimeMethodHandleInternal method);
internal static int GetSlot(IRuntimeMethodInfo method)
{
Contract.Requires(method != null);
int slot = RuntimeMethodHandle.GetSlot(method.Value);
GC.KeepAlive(method);
return slot;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMethodDef(IRuntimeMethodInfo method);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static string GetName(RuntimeMethodHandleInternal method);
internal static string GetName(IRuntimeMethodInfo method)
{
string name = RuntimeMethodHandle.GetName(method.Value);
GC.KeepAlive(method);
return name;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static void* _GetUtf8Name(RuntimeMethodHandleInternal method);
internal static Utf8String GetUtf8Name(RuntimeMethodHandleInternal method)
{
return new Utf8String(_GetUtf8Name(method));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeMethodHandleInternal method, uint hash);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor);
#region Private Invocation Helpers
internal static INVOCATION_FLAGS GetSecurityFlags(IRuntimeMethodInfo handle)
{
return (INVOCATION_FLAGS)RuntimeMethodHandle.GetSpecialSecurityFlags(handle);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern internal uint GetSpecialSecurityFlags(IRuntimeMethodInfo method);
#endregion
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static void SerializationInvoke(IRuntimeMethodInfo method,
Object target, SerializationInfo info, ref StreamingContext context);
// This returns true if the token is SecurityTransparent:
// just the token - does not consider including module/type etc.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool _IsTokenSecurityTransparent(RuntimeModule module, int metaDataToken);
internal static bool IsTokenSecurityTransparent(Module module, int metaDataToken)
{
return _IsTokenSecurityTransparent(module.ModuleHandle.GetRuntimeModule(), metaDataToken);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool _IsSecurityCritical(IRuntimeMethodInfo method);
internal static bool IsSecurityCritical(IRuntimeMethodInfo method)
{
return _IsSecurityCritical(method);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool _IsSecuritySafeCritical(IRuntimeMethodInfo method);
internal static bool IsSecuritySafeCritical(IRuntimeMethodInfo method)
{
return _IsSecuritySafeCritical(method);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool _IsSecurityTransparent(IRuntimeMethodInfo method);
internal static bool IsSecurityTransparent(IRuntimeMethodInfo method)
{
return _IsSecurityTransparent(method);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method)
{
RuntimeType[] types = null;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), true);
GC.KeepAlive(method);
return types;
}
internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method)
{
RuntimeType[] types = null;
GetMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref types), true);
return types;
}
internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method)
{
RuntimeType[] types = null;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), false);
GC.KeepAlive(method);
return types;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasMethodInstantiation(RuntimeMethodHandleInternal method);
internal static bool HasMethodInstantiation(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.HasMethodInstantiation(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method);
internal static bool IsGenericMethodDefinition(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.IsGenericMethodDefinition(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsTypicalMethodDefinition(IRuntimeMethodInfo method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypicalMethodDefinition(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method)
{
if (!IsTypicalMethodDefinition(method))
GetTypicalMethodDefinition(method, JitHelpers.GetObjectHandleOnStack(ref method));
return method;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void StripMethodInstantiation(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method)
{
IRuntimeMethodInfo strippedMethod = method;
StripMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref strippedMethod));
return strippedMethod;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsDynamicMethod(RuntimeMethodHandleInternal method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void Destroy(RuntimeMethodHandleInternal method);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Resolver GetResolver(RuntimeMethodHandleInternal method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetCallerType(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retType);
internal static RuntimeType GetCallerType(ref StackCrawlMark stackMark)
{
RuntimeType type = null;
GetCallerType(JitHelpers.GetStackCrawlMarkHandle(ref stackMark), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static MethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static bool IsConstructor(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static LoaderAllocator GetLoaderAllocator(RuntimeMethodHandleInternal method);
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an RtFieldInfo, and ensure that the RtFieldInfo is preserved
// across the lifetime of the RuntimeFieldHandleInternal instance
// 3. When another object is used to keep the RuntimeFieldHandleInternal alive.
// When in doubt, do not use.
internal struct RuntimeFieldHandleInternal
{
internal static RuntimeFieldHandleInternal EmptyHandle
{
get
{
return new RuntimeFieldHandleInternal();
}
}
internal bool IsNullHandle()
{
return m_handle.IsNull();
}
internal IntPtr Value
{
get
{
return m_handle;
}
}
internal RuntimeFieldHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal interface IRuntimeFieldInfo
{
RuntimeFieldHandleInternal Value
{
get;
}
}
[StructLayout(LayoutKind.Sequential)]
internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
{
public RuntimeFieldInfoStub(IntPtr methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_fieldHandle = new RuntimeFieldHandleInternal(methodHandleValue);
}
// These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo
#pragma warning disable 169
object m_keepalive;
object m_c;
object m_d;
int m_b;
object m_e;
RuntimeFieldHandleInternal m_fieldHandle;
#pragma warning restore 169
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
get
{
return m_fieldHandle;
}
}
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe struct RuntimeFieldHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeFieldHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
IRuntimeFieldInfo field = m_ptr;
if (field == null)
throw new ArgumentNullException(null, Environment.GetResourceString("Arg_InvalidHandle"));
return new RuntimeFieldHandle(field);
}
private IRuntimeFieldInfo m_ptr;
internal RuntimeFieldHandle(IRuntimeFieldInfo fieldInfo)
{
m_ptr = fieldInfo;
}
internal IRuntimeFieldInfo GetRuntimeFieldInfo()
{
return m_ptr;
}
public IntPtr Value
{
get
{
return m_ptr != null ? m_ptr.Value.Value : IntPtr.Zero;
}
}
internal bool IsNullHandle()
{
return m_ptr == null;
}
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public override bool Equals(object obj)
{
if (!(obj is RuntimeFieldHandle))
return false;
RuntimeFieldHandle handle = (RuntimeFieldHandle)obj;
return handle.Value == Value;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public unsafe bool Equals(RuntimeFieldHandle handle)
{
return handle.Value == Value;
}
public static bool operator ==(RuntimeFieldHandle left, RuntimeFieldHandle right)
{
return left.Equals(right);
}
public static bool operator !=(RuntimeFieldHandle left, RuntimeFieldHandle right)
{
return !left.Equals(right);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetName(RtFieldInfo field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern unsafe void* _GetUtf8Name(RuntimeFieldHandleInternal field);
internal static unsafe Utf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new Utf8String(_GetUtf8Name(field)); }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field);
internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field)
{
RuntimeType type = GetApproxDeclaringType(field.Value);
GC.KeepAlive(field);
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RtFieldInfo field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void *pTypedRef, RuntimeType contextType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetValue(RtFieldInfo field, Object obj, Object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, Object value, RuntimeType contextType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool AcquiresContextFromThis(RuntimeFieldHandleInternal field);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecurityCritical(RuntimeFieldHandle fieldHandle);
internal bool IsSecurityCritical()
{
return IsSecurityCritical(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecuritySafeCritical(RuntimeFieldHandle fieldHandle);
internal bool IsSecuritySafeCritical()
{
return IsSecuritySafeCritical(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsSecurityTransparent(RuntimeFieldHandle fieldHandle);
internal bool IsSecurityTransparent()
{
return IsSecurityTransparent(GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void CheckAttributeAccess(RuntimeFieldHandle fieldHandle, RuntimeModule decoratedTarget);
// ISerializable interface
private RuntimeFieldHandle(SerializationInfo info, StreamingContext context)
{
if(info==null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
FieldInfo f =(RuntimeFieldInfo) info.GetValue("FieldObj", typeof(RuntimeFieldInfo));
if( f == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
m_ptr = f.FieldHandle.m_ptr;
if (m_ptr == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_ptr == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidFieldState"));
RuntimeFieldInfo fldInfo = (RuntimeFieldInfo)RuntimeType.GetFieldInfo(this.GetRuntimeFieldInfo());
info.AddValue("FieldObj",fldInfo, typeof(RuntimeFieldInfo));
}
}
[System.Runtime.InteropServices.ComVisible(true)]
public unsafe struct ModuleHandle
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
#region Public Static Members
public static readonly ModuleHandle EmptyHandle = GetEmptyMH();
#endregion
unsafe static private ModuleHandle GetEmptyMH()
{
return new ModuleHandle();
}
#region Private Data Members
private RuntimeModule m_ptr;
#endregion
#region Constructor
internal ModuleHandle(RuntimeModule module)
{
m_ptr = module;
}
#endregion
#region Internal FCalls
internal RuntimeModule GetRuntimeModule()
{
return m_ptr;
}
internal bool IsNullHandle()
{
return m_ptr == null;
}
public override int GetHashCode()
{
return m_ptr != null ? m_ptr.GetHashCode() : 0;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public override bool Equals(object obj)
{
if (!(obj is ModuleHandle))
return false;
ModuleHandle handle = (ModuleHandle)obj;
return handle.m_ptr == m_ptr;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public unsafe bool Equals(ModuleHandle handle)
{
return handle.m_ptr == m_ptr;
}
public static bool operator ==(ModuleHandle left, ModuleHandle right)
{
return left.Equals(right);
}
public static bool operator !=(ModuleHandle left, ModuleHandle right)
{
return !left.Equals(right);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IRuntimeMethodInfo GetDynamicMethod(DynamicMethod method, RuntimeModule module, string name, byte[] sig, Resolver resolver);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeModule module);
private static void ValidateModulePointer(RuntimeModule module)
{
// Make sure we have a valid Module to resolve against.
if (module == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullModuleHandle"));
}
// SQL-CLR LKG9 Compiler dependency
public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) { return ResolveTypeHandle(typeToken); }
public RuntimeTypeHandle ResolveTypeHandle(int typeToken)
{
return new RuntimeTypeHandle(ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, null, null));
}
public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext));
}
internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken))
throw new ArgumentOutOfRangeException(nameof(typeToken),
Environment.GetResourceString("Argument_InvalidToken", typeToken, new ModuleHandle(module)));
int typeInstCount, methodInstCount;
IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
RuntimeType type = null;
ResolveType(module, typeToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return type;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ResolveType(RuntimeModule module,
int typeToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack type);
// SQL-CLR LKG9 Compiler dependency
public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { return ResolveMethodHandle(methodToken); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken) { return ResolveMethodHandle(methodToken, null, null); }
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken) { return ModuleHandle.ResolveMethodHandleInternal(module, methodToken, null, null); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext));
}
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
int typeInstCount, methodInstCount;
IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
RuntimeMethodHandleInternal handle = ResolveMethodHandleInternalCore(module, methodToken, typeInstantiationContextHandles, typeInstCount, methodInstantiationContextHandles, methodInstCount);
IRuntimeMethodInfo retVal = new RuntimeMethodInfoStub(handle, RuntimeMethodHandle.GetLoaderAllocator(handle));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return retVal;
}
internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[] typeInstantiationContext, int typeInstCount, IntPtr[] methodInstantiationContext, int methodInstCount)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken))
throw new ArgumentOutOfRangeException(nameof(methodToken),
Environment.GetResourceString("Argument_InvalidToken", methodToken, new ModuleHandle(module)));
fixed (IntPtr* typeInstArgs = typeInstantiationContext, methodInstArgs = methodInstantiationContext)
{
return ResolveMethod(module.GetNativeHandle(), methodToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount);
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static RuntimeMethodHandleInternal ResolveMethod(RuntimeModule module,
int methodToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount);
// SQL-CLR LKG9 Compiler dependency
public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, null, null)); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{ return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken))
throw new ArgumentOutOfRangeException(nameof(fieldToken),
Environment.GetResourceString("Argument_InvalidToken", fieldToken, new ModuleHandle(module)));
// defensive copy to be sure array is not mutated from the outside during processing
int typeInstCount, methodInstCount;
IntPtr [] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr [] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
IRuntimeFieldInfo field = null;
ResolveField(module.GetNativeHandle(), fieldToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref field));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return field;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ResolveField(RuntimeModule module,
int fieldToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack retField);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static bool _ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash);
internal static bool ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash)
{
return _ContainsPropertyMatchingHash(module.GetNativeHandle(), propertyToken, hash);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetAssembly(RuntimeModule handle, ObjectHandleOnStack retAssembly);
internal static RuntimeAssembly GetAssembly(RuntimeModule module)
{
RuntimeAssembly retAssembly = null;
GetAssembly(module.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref retAssembly));
return retAssembly;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static void GetModuleType(RuntimeModule handle, ObjectHandleOnStack type);
internal static RuntimeType GetModuleType(RuntimeModule module)
{
RuntimeType type = null;
GetModuleType(module.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetPEKind(RuntimeModule handle, out int peKind, out int machine);
// making this internal, used by Module.GetPEKind
internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
int lKind, lMachine;
GetPEKind(module.GetNativeHandle(), out lKind, out lMachine);
peKind = (PortableExecutableKinds)lKind;
machine = (ImageFileMachine)lMachine;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMDStreamVersion(RuntimeModule module);
public int MDStreamVersion
{
get { return GetMDStreamVersion(GetRuntimeModule().GetNativeHandle()); }
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr _GetMetadataImport(RuntimeModule module);
internal static MetadataImport GetMetadataImport(RuntimeModule module)
{
return new MetadataImport(_GetMetadataImport(module.GetNativeHandle()), module);
}
#endregion
}
internal unsafe class Signature
{
#region Definitions
internal enum MdSigCallingConvention : byte
{
Generics = 0x10,
HasThis = 0x20,
ExplicitThis = 0x40,
CallConvMask = 0x0F,
Default = 0x00,
C = 0x01,
StdCall = 0x02,
ThisCall = 0x03,
FastCall = 0x04,
Vararg = 0x05,
Field = 0x06,
LocalSig = 0x07,
Property = 0x08,
Unmgd = 0x09,
GenericInst = 0x0A,
Max = 0x0B,
}
#endregion
#region FCalls
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void GetSignature(
void* pCorSig, int cCorSig,
RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType);
#endregion
#region Private Data Members
//
// Keep the layout in sync with SignatureNative in the VM
//
internal RuntimeType[] m_arguments;
internal RuntimeType m_declaringType;
internal RuntimeType m_returnTypeORfieldType;
internal object m_keepalive;
internal void* m_sig;
internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags
internal int m_nSizeOfArgStack;
internal int m_csig;
internal RuntimeMethodHandleInternal m_pMethod;
#endregion
#region Constructors
public Signature (
IRuntimeMethodInfo method,
RuntimeType[] arguments,
RuntimeType returnType,
CallingConventions callingConvention)
{
m_pMethod = method.Value;
m_arguments = arguments;
m_returnTypeORfieldType = returnType;
m_managedCallingConventionAndArgIteratorFlags = (byte)callingConvention;
GetSignature(null, 0, new RuntimeFieldHandleInternal(), method, null);
}
public Signature(IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
{
GetSignature(null, 0, new RuntimeFieldHandleInternal(), methodHandle, declaringType);
}
public Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType)
{
GetSignature(null, 0, fieldHandle.Value, null, declaringType);
GC.KeepAlive(fieldHandle);
}
public Signature(void* pCorSig, int cCorSig, RuntimeType declaringType)
{
GetSignature(pCorSig, cCorSig, new RuntimeFieldHandleInternal(), null, declaringType);
}
#endregion
#region Internal Members
internal CallingConventions CallingConvention { get { return (CallingConventions)(byte)m_managedCallingConventionAndArgIteratorFlags; } }
internal RuntimeType[] Arguments { get { return m_arguments; } }
internal RuntimeType ReturnType { get { return m_returnTypeORfieldType; } }
internal RuntimeType FieldType { get { return m_returnTypeORfieldType; } }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool CompareSig(Signature sig1, Signature sig2);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern Type[] GetCustomModifiers(int position, bool required);
#endregion
}
internal abstract class Resolver
{
internal struct CORINFO_EH_CLAUSE
{
internal int Flags;
internal int TryOffset;
internal int TryLength;
internal int HandlerOffset;
internal int HandlerLength;
internal int ClassTokenOrFilterOffset;
}
// ILHeader info
internal abstract RuntimeType GetJitContext(ref int securityControlFlags);
internal abstract byte[] GetCodeInfo(ref int stackSize, ref int initLocals, ref int EHCount);
internal abstract byte[] GetLocalsSignature();
internal abstract unsafe void GetEHInfo(int EHNumber, void* exception);
internal abstract unsafe byte[] GetRawEHInfo();
// token resolution
internal abstract String GetStringLiteral(int token);
internal abstract void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle);
internal abstract byte[] ResolveSignature(int token, int fromMethod);
//
internal abstract MethodInfo GetDynamicMethod();
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
namespace NLog.Targets
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Security;
using Internal.Fakeables;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Writes log message to the Event Log.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/EventLog-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/EventLog/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" />
/// </example>
[Target("EventLog")]
public class EventLogTarget : TargetWithLayout, IInstallable
{
private const int MaxMessageSize = 16384;
private EventLog eventLogInstance;
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
public EventLogTarget()
: this(AppDomainWrapper.CurrentDomain)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventLogTarget"/> class.
/// </summary>
public EventLogTarget(IAppDomain appDomain)
{
this.Source = appDomain.FriendlyName;
this.Log = "Application";
this.MachineName = ".";
}
/// <summary>
/// Gets or sets the name of the machine on which Event Log service is running.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue(".")]
public string MachineName { get; set; }
/// <summary>
/// Gets or sets the layout that renders event ID.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout EventId { get; set; }
/// <summary>
/// Gets or sets the layout that renders event Category.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
public Layout Category { get; set; }
/// <summary>
/// Optional entrytype. When not set, or when not convertable to <see cref="LogLevel"/> then determined by <see cref="NLog.LogLevel"/>
/// </summary>
public Layout EntryType { get; set; }
/// <summary>
/// Gets or sets the value to be used as the event Source.
/// </summary>
/// <remarks>
/// By default this is the friendly name of the current AppDomain.
/// </remarks>
/// <docgen category='Event Log Options' order='10' />
public Layout Source { get; set; }
/// <summary>
/// Gets or sets the name of the Event Log to write to. This can be System, Application or
/// any user-defined name.
/// </summary>
/// <docgen category='Event Log Options' order='10' />
[DefaultValue("Application")]
public string Log { get; set; }
/// <summary>
/// Gets or sets the action to take if the message is larger than the Event Log max message size.
/// </summary>
/// <docgen category='Event Log Overflow Action' order='10' />
[DefaultValue(EventLogTargetOverflowAction.Truncate)]
public EventLogTargetOverflowAction OnOverflow { get; set; }
/// <summary>
/// Performs installation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Install(InstallationContext installationContext)
{
var fixedSource = GetFixedSource();
//always throw error to keep backwardscomp behavior.
CreateEventSourceIfNeeded(fixedSource, true);
}
/// <summary>
/// Performs uninstallation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Uninstall(InstallationContext installationContext)
{
var fixedSource = GetFixedSource();
if (string.IsNullOrEmpty(fixedSource))
{
InternalLogger.Debug("Skipping removing of event source because it contains layout renderers");
}
else
{
EventLog.DeleteEventSource(fixedSource, this.MachineName);
}
}
/// <summary>
/// Determines whether the item is installed.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <returns>
/// Value indicating whether the item is installed or null if it is not possible to determine.
/// </returns>
public bool? IsInstalled(InstallationContext installationContext)
{
var fixedSource = GetFixedSource();
if (!string.IsNullOrEmpty(fixedSource))
{
return EventLog.SourceExists(fixedSource, this.MachineName);
}
InternalLogger.Debug("Unclear if event source exists because it contains layout renderers");
return null; //unclear!
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
var fixedSource = GetFixedSource();
if (string.IsNullOrEmpty(fixedSource))
{
InternalLogger.Debug("Skipping creation of event source because it contains layout renderers");
}
else
{
var currentSourceName = EventLog.LogNameFromSourceName(fixedSource, this.MachineName);
if (!currentSourceName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
{
this.CreateEventSourceIfNeeded(fixedSource, false);
}
}
}
/// <summary>
/// Writes the specified logging event to the event log.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
string message = this.Layout.Render(logEvent);
var entryType = GetEntryType(logEvent);
int eventId = 0;
if (this.EventId != null)
{
eventId = Convert.ToInt32(this.EventId.Render(logEvent), CultureInfo.InvariantCulture);
}
short category = 0;
if (this.Category != null)
{
category = Convert.ToInt16(this.Category.Render(logEvent), CultureInfo.InvariantCulture);
}
var eventLog = GetEventLog(logEvent);
// limitation of EventLog API
if (message.Length > MaxMessageSize)
{
if (OnOverflow == EventLogTargetOverflowAction.Truncate)
{
message = message.Substring(0, MaxMessageSize);
eventLog.WriteEntry(message, entryType, eventId, category);
}
else if (OnOverflow == EventLogTargetOverflowAction.Split)
{
int index = 0;
while (index + MaxMessageSize < message.Length)
{
string chunk = message.Substring(index, MaxMessageSize);
eventLog.WriteEntry(chunk);
index += MaxMessageSize;
}
if (index < message.Length)
eventLog.WriteEntry(message.Substring(index));
}
else if (OnOverflow == EventLogTargetOverflowAction.Discard)
{
//message will not be written
return;
}
}
else
{
eventLog.WriteEntry(message, entryType, eventId, category);
}
}
/// <summary>
/// Get the entry type for logging the message.
/// </summary>
/// <param name="logEvent">The logging event - for rendering the <see cref="EntryType"/></param>
/// <returns></returns>
private EventLogEntryType GetEntryType(LogEventInfo logEvent)
{
if (this.EntryType != null)
{
//try parse, if fail, determine auto
var value = this.EntryType.Render(logEvent);
EventLogEntryType eventLogEntryType;
if (EnumHelpers.TryParse(value, true, out eventLogEntryType))
{
return eventLogEntryType;
}
}
// determine auto
if (logEvent.Level >= LogLevel.Error)
{
return EventLogEntryType.Error;
}
if (logEvent.Level >= LogLevel.Warn)
{
return EventLogEntryType.Warning;
}
return EventLogEntryType.Information;
}
/// <summary>
/// Get the source, if and only if the source is fixed.
/// </summary>
/// <returns><c>null</c> when not <see cref="SimpleLayout.IsFixedText"/></returns>
/// <remarks>Internal for unit tests</remarks>
internal string GetFixedSource()
{
if (this.Source == null)
{
return null;
}
var simpleLayout = Source as SimpleLayout;
if (simpleLayout != null && simpleLayout.IsFixedText)
{
return simpleLayout.FixedText;
}
return null;
}
/// <summary>
/// Get the eventlog to write to.
/// </summary>
/// <param name="logEvent">Event if the source needs to be rendered.</param>
/// <returns></returns>
private EventLog GetEventLog(LogEventInfo logEvent)
{
return eventLogInstance ?? (eventLogInstance = new EventLog(this.Log, this.MachineName, this.Source.Render(logEvent)));
}
/// <summary>
/// (re-)create a event source, if it isn't there. Works only with fixed sourcenames.
/// </summary>
/// <param name="fixedSource">sourcenaam. If source is not fixed (see <see cref="SimpleLayout.IsFixedText"/>, then pass <c>null</c> or emptystring.</param>
/// <param name="alwaysThrowError">always throw an Exception when there is an error</param>
private void CreateEventSourceIfNeeded(string fixedSource, bool alwaysThrowError)
{
if (string.IsNullOrEmpty(fixedSource))
{
InternalLogger.Debug("Skipping creation of event source because it contains layout renderers");
//we can only create event sources if the source is fixed (no layout)
return;
}
// if we throw anywhere, we remain non-operational
try
{
if (EventLog.SourceExists(fixedSource, this.MachineName))
{
string currentLogName = EventLog.LogNameFromSourceName(fixedSource, this.MachineName);
if (!currentLogName.Equals(this.Log, StringComparison.CurrentCultureIgnoreCase))
{
// re-create the association between Log and Source
EventLog.DeleteEventSource(fixedSource, this.MachineName);
var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(eventSourceCreationData);
}
}
else
{
var eventSourceCreationData = new EventSourceCreationData(fixedSource, this.Log)
{
MachineName = this.MachineName
};
EventLog.CreateEventSource(eventSourceCreationData);
}
}
catch (Exception exception)
{
InternalLogger.Error("Error when connecting to EventLog: {0}", exception);
if (alwaysThrowError || exception.MustBeRethrown())
{
throw;
}
throw;
}
}
}
}
#endif
| |
using System;
using System.Numerics;
using GraphQL.Language.AST;
namespace GraphQL.Types
{
/// <summary>
/// Scalar types represent the leaves of the query - those fields that don't have any sub-fields.
/// <br/><br/>
/// <see href="https://github.com/graphql-dotnet/graphql-dotnet/blob/master/docs2/site/docs/getting-started/custom-scalars.md">More info</see> about scalars.
/// </summary>
public abstract class ScalarGraphType : GraphType
{
/// <summary>
/// Result (output) coercion. It takes the result of a resolver and converts it into an
/// appropriate value for the output result. In other words it transforms a scalar from
/// its server-side representation to a representation suitable for the client.
/// <br/><br/>
/// Since GraphQL specifies no response format, Serialize is not
/// responsible for preparing the scalar for transport to the client. It is only responsible
/// for generating an object which can eventually be serialized by some transport-focused API.
/// <br/><br/>
/// This method should handle a value of <see langword="null"/>, but may throw an exception
/// if <see langword="null"/> is an invalid internal scalar representation.
/// </summary>
/// <param name="value">Resolved value (internal scalar representation). May be <see langword="null"/>.</param>
/// <returns>
/// The returned value of a the result coercion is part of the overall execution result.
/// Normally this value is a primitive value like String or Integer to make it easy for
/// the serialization layer. For complex types like a Date or Money scalar this involves
/// formatting the value. Thus, the returned value for some scalars by their nature may
/// already have a string value and it is impossible (or rather difficult) to change that
/// value by the serialization layer. Returning <see langword="null"/> is valid.
/// </returns>
public virtual object? Serialize(object? value) => ParseValue(value);
/// <summary>
/// Literal input coercion. It takes an abstract syntax tree (AST) element from a schema
/// definition or query and converts it into an appropriate internal value. In other words
/// it transforms a scalar from its client-side representation as an argument to its
/// server-side representation. Input coercion may not only return primitive values like
/// String but rather complex ones when appropriate.
/// <br/><br/>
/// This method must handle a value of <see cref="NullValue"/>.
/// </summary>
/// <param name="value">AST value node. Must not be <see langword="null"/>, but may be <see cref="NullValue"/>.</param>
/// <returns>Internal scalar representation. Returning <see langword="null"/> is valid.</returns>
public virtual object? ParseLiteral(IValue value) => value switch
{
BooleanValue b => ParseValue(b.Value.Boxed()),
IntValue i => ParseValue(i.Value),
LongValue l => ParseValue(l.Value),
BigIntValue bi => ParseValue(bi.Value),
FloatValue f => ParseValue(f.Value),
DecimalValue d => ParseValue(d.Value),
StringValue s => ParseValue(s.Value),
NullValue _ => ParseValue(null),
_ => ThrowLiteralConversionError(value)
};
/// <summary>
/// Value input coercion. Argument values can not only provided via GraphQL syntax inside a
/// query, but also via variable. It transforms a scalar from its client-side representation
/// as a variable to its server-side representation.
/// <br/><br/>
/// Parsing for arguments and variables are handled separately because while arguments must
/// always be expressed in GraphQL query syntax, variable format is transport-specific (usually JSON).
/// <br/><br/>
/// This method must handle a value of <see langword="null"/>.
/// </summary>
/// <param name="value">Runtime object from variables. May be <see langword="null"/>.</param>
/// <returns>Internal scalar representation. Returning <see langword="null"/> is valid.</returns>
public abstract object? ParseValue(object? value);
/// <summary>
/// Checks for literal input coercion possibility. It takes an abstract syntax tree (AST) element from a schema
/// definition or query and checks if it can be converted into an appropriate internal value. In other words
/// it checks if a scalar can be converted from its client-side representation as an argument to its
/// server-side representation.
/// <br/><br/>
/// This method can be overridden to validate input values without directly getting those values, i.e. without boxing.
/// <br/><br/>
/// This method must return <see langword="true"/> when passed a <see cref="NullValue"/> node.
/// </summary>
/// <param name="value">AST value node. Must not be <see langword="null"/>, but may be <see cref="NullValue"/>.</param>
public virtual bool CanParseLiteral(IValue value)
{
try
{
_ = ParseLiteral(value);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Checks for value input coercion possibility. Argument values can not only provided via GraphQL syntax inside a
/// query, but also via variable. It checks if a scalar can be converted from its client-side representation
/// as a variable to its server-side representation.
/// <br/><br/>
/// Parsing for arguments and variables are handled separately because while arguments must
/// always be expressed in GraphQL query syntax, variable format is transport-specific (usually JSON).
/// <br/><br/>
/// This method can be overridden to validate input values without directly getting those values, i.e. without boxing.
/// <br/><br/>
/// This method must return <see langword="true"/> when passed a <see langword="null"/> value.
/// </summary>
/// <param name="value">Runtime object from variables. May be <see langword="null"/>.</param>
public virtual bool CanParseValue(object? value)
{
try
{
_ = ParseValue(value);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Checks that the provided value is a valid default value.
/// This method should not throw an exception.
/// </summary>
/// <param name="value">The value to examine. Must not be <see langword="null"/>, as that indicates the lack of a default value.</param>
public virtual bool IsValidDefault(object value)
{
if (value == null)
return false;
try
{
return ToAST(value) != null;
}
catch
{
return false;
}
}
/// <summary>
/// Converts a value to an AST representation. This is necessary for introspection queries
/// to return the default values of this scalar type when used on input fields or field and directive arguments.
/// This method may throw an exception or return <see langword="null"/> for a failed conversion.
/// May return <see cref="NullValue"/>.
/// </summary>
/// <param name="value">The value to convert. May be <see langword="null"/>.</param>
/// <returns>AST representation of the specified value. Returning <see langword="null"/> indicates a failed conversion. Returning <see cref="NullValue"/> is valid.</returns>
public virtual IValue? ToAST(object? value)
{
var serialized = Serialize(value);
return serialized switch
{
bool b => new BooleanValue(b),
byte b => new IntValue(b),
sbyte sb => new IntValue(sb),
short s => new IntValue(s),
ushort us => new IntValue(us),
int i => new IntValue(i),
uint ui => new LongValue(ui),
long l => new LongValue(l),
ulong ul => new BigIntValue(ul),
BigInteger bi => new BigIntValue(bi),
decimal d => new DecimalValue(d),
float f => new FloatValue(f),
double d => new FloatValue(d),
string s => new StringValue(s),
null => new NullValue(),
_ => throw new NotImplementedException($"Please override the '{nameof(ToAST)}' method of the '{GetType().Name}' scalar to support this operation.")
};
}
/// <summary>
/// Throws an exception indicating that a value cannot be converted to its AST representation. Typically called by
/// <see cref="ToAST(object)"/> if the provided object (an internal representation) is not valid for this scalar type.
/// </summary>
protected internal IValue ThrowASTConversionError(object? value)
{
throw new InvalidOperationException($"Unable to convert '{value ?? "(null)"}' to its AST representation for the scalar type '{Name}'.");
}
/// <summary>
/// Throws an exception indicating that an AST scalar node cannot be converted to a value. Typically called by
/// <see cref="ParseLiteral(IValue)"/> if the node type is invalid or cannot be parsed.
/// </summary>
protected object ThrowLiteralConversionError(IValue input)
{
throw new InvalidOperationException($"Unable to convert '{input}' literal from AST representation to the scalar type '{Name}'");
}
/// <summary>
/// Throws an exception indicating that an external value (typically provided through a variable) cannot be converted
/// to an internal representation. Typically called by <see cref="ParseValue(object)"/> if the provided object is invalid
/// or cannot be parsed.
/// </summary>
/// <remarks>
/// This is often called for serialization errors, since <see cref="Serialize(object)"/> calls <see cref="ParseValue(object)"/> by default.
/// This also may be called for serialization errors during <see cref="ToAST(object)"/>, since <see cref="ToAST(object)"/> calls <see cref="Serialize(object)"/>
/// by default, which by default calls <see cref="ParseValue(object)"/>.
/// </remarks>
protected object ThrowValueConversionError(object? value)
{
throw new InvalidOperationException($"Unable to convert '{value ?? "(null)"}' to the scalar type '{Name}'");
}
/// <summary>
/// Throws an exception indicating that an internal value (typically returned from a field resolver) cannot be converted
/// to its external representation. Typically called by <see cref="Serialize(object)"/> if the object is not valid for this
/// scalar type.
/// </summary>
/// <remarks>
/// This may be called for serialization errors during <see cref="ToAST(object)"/>, since the default implementation
/// of <see cref="ToAST(object)"/> calls <see cref="Serialize(object)"/> to serialize the value before converting the
/// result to an AST node.
/// </remarks>
protected object ThrowSerializationError(object? value)
{
throw new InvalidOperationException($"Unable to serialize '{value ?? "(null)"}' to the scalar type '{Name}'.");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance |
SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions: SymbolDisplayParameterOptions.None,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeRef |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions:
SymbolDisplayLocalOptions.IncludeRef |
SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_descriptionStyle =
new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword);
private static readonly SymbolDisplayFormat s_globalNamespaceStyle =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
private readonly ISymbolDisplayService _displayService;
private readonly SemanticModel _semanticModel;
private readonly int _position;
private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService;
private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap =
new Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>>();
protected readonly Workspace Workspace;
protected readonly CancellationToken CancellationToken;
protected AbstractSymbolDescriptionBuilder(
ISymbolDisplayService displayService,
SemanticModel semanticModel,
int position,
Workspace workspace,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
CancellationToken cancellationToken)
{
_displayService = displayService;
_anonymousTypeDisplayService = anonymousTypeDisplayService;
this.Workspace = workspace;
this.CancellationToken = cancellationToken;
_semanticModel = semanticModel;
_position = position;
}
protected abstract void AddExtensionPrefix();
protected abstract void AddAwaitablePrefix();
protected abstract void AddAwaitableExtensionPrefix();
protected abstract void AddDeprecatedPrefix();
protected abstract Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol);
protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; }
protected void AddPrefixTextForAwaitKeyword()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.Awaited_task_returns),
Space());
}
protected void AddTextForSystemVoid()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.no_value));
}
protected SemanticModel GetSemanticModel(SyntaxTree tree)
{
if (_semanticModel.SyntaxTree == tree)
{
return _semanticModel;
}
var model = _semanticModel.GetOriginalSemanticModel();
if (model.Compilation.ContainsSyntaxTree(tree))
{
return model.Compilation.GetSemanticModel(tree);
}
// it is from one of its p2p references
foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations())
{
// find the reference that contains the given tree
if (referencedCompilation.ContainsSyntaxTree(tree))
{
return referencedCompilation.GetSemanticModel(tree);
}
}
// the tree, a source symbol is defined in, doesn't exist in universe
// how this can happen?
Contract.Requires(false, "How?");
return null;
}
private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols)
{
await AddDescriptionPartAsync(symbols[0]).ConfigureAwait(false);
AddOverloadCountPart(symbols);
FixAllAnonymousTypes(symbols[0]);
AddExceptions(symbols[0]);
}
private void AddExceptions(ISymbol symbol)
{
var exceptionTypes = symbol.GetDocumentationComment().ExceptionTypes;
if (exceptionTypes.Any())
{
var parts = new List<SymbolDisplayPart>();
parts.Add(new SymbolDisplayPart(kind: SymbolDisplayPartKind.Text, symbol: null, text: $"\r\n{WorkspacesResources.Exceptions_colon}"));
foreach (var exceptionString in exceptionTypes)
{
parts.AddRange(LineBreak());
parts.AddRange(Space(count: 2));
parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel));
}
AddToGroup(SymbolDescriptionGroups.Exceptions, parts);
}
}
public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync(
ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescription(groups);
}
public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescriptionSections();
}
private async Task AddDescriptionPartAsync(ISymbol symbol)
{
if (symbol.GetAttributes().Any(x => x.AttributeClass.MetadataName == "ObsoleteAttribute"))
{
AddDeprecatedPrefix();
}
if (symbol is IDynamicTypeSymbol)
{
AddDescriptionForDynamicType();
}
else if (symbol is IFieldSymbol field)
{
await AddDescriptionForFieldAsync(field).ConfigureAwait(false);
}
else if (symbol is ILocalSymbol local)
{
await AddDescriptionForLocalAsync(local).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol method)
{
AddDescriptionForMethod(method);
}
else if (symbol is ILabelSymbol label)
{
AddDescriptionForLabel(label);
}
else if (symbol is INamedTypeSymbol namedType)
{
await AddDescriptionForNamedTypeAsync(namedType).ConfigureAwait(false);
}
else if (symbol is INamespaceSymbol namespaceSymbol)
{
AddDescriptionForNamespace(namespaceSymbol);
}
else if (symbol is IParameterSymbol parameter)
{
await AddDescriptionForParameterAsync(parameter).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol property)
{
AddDescriptionForProperty(property);
}
else if (symbol is IRangeVariableSymbol rangeVariable)
{
AddDescriptionForRangeVariable(rangeVariable);
}
else if (symbol is ITypeParameterSymbol typeParameter)
{
AddDescriptionForTypeParameter(typeParameter);
}
else if (symbol is IAliasSymbol alias)
{
await AddDescriptionPartAsync(alias.Target).ConfigureAwait(false);
}
else
{
AddDescriptionForArbitrarySymbol(symbol);
}
}
private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
{
var finalParts = new List<SymbolDisplayPart>();
var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);
foreach (var group in orderedGroups)
{
if ((groups & group) == 0)
{
continue;
}
if (!finalParts.IsEmpty())
{
var newLines = GetPrecedingNewLineCount(group);
finalParts.AddRange(LineBreak(newLines));
}
var parts = _groupMap[group];
finalParts.AddRange(parts);
}
return finalParts.AsImmutable();
}
private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group)
{
switch (group)
{
case SymbolDescriptionGroups.MainDescription:
// these parts are continuations of whatever text came before them
return 0;
case SymbolDescriptionGroups.Documentation:
return 1;
case SymbolDescriptionGroups.AnonymousTypes:
return 0;
case SymbolDescriptionGroups.Exceptions:
case SymbolDescriptionGroups.TypeParameterMap:
// Everything else is in a group on its own
return 2;
default:
return Contract.FailWithReturn<int>("unknown part kind");
}
}
private IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> BuildDescriptionSections()
{
return _groupMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToTaggedText());
}
private void AddDescriptionForDynamicType()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Keyword("dynamic"));
AddToGroup(SymbolDescriptionGroups.Documentation,
PlainText(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime));
}
private async Task AddDescriptionForNamedTypeAsync(INamedTypeSymbol symbol)
{
if (symbol.IsAwaitableNonDynamic(_semanticModel, _position))
{
AddAwaitablePrefix();
}
var token = await _semanticModel.SyntaxTree.GetTouchingTokenAsync(_position, this.CancellationToken).ConfigureAwait(false);
if (token != default(SyntaxToken))
{
var syntaxFactsService = this.Workspace.Services.GetLanguageServices(token.Language).GetService<ISyntaxFactsService>();
if (syntaxFactsService.IsAwaitKeyword(token))
{
AddPrefixTextForAwaitKeyword();
if (symbol.SpecialType == SpecialType.System_Void)
{
AddTextForSystemVoid();
return;
}
}
}
if (symbol.TypeKind == TypeKind.Delegate)
{
var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, style));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, s_descriptionStyle));
}
if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol))
{
var allTypeParameters = symbol.GetAllTypeParameters().ToList();
var allTypeArguments = symbol.GetAllTypeArguments().ToList();
AddTypeParameterMapPart(allTypeParameters, allTypeArguments);
}
}
private bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol)
{
var typeArguments = symbol.GetAllTypeArguments().ToList();
var typeParameters = symbol.GetAllTypeParameters().ToList();
for (int i = 0; i < typeArguments.Count; i++)
{
var typeArgument = typeArguments[i];
var typeParameter = typeParameters[i];
if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name)
{
continue;
}
return false;
}
return true;
}
private void AddDescriptionForNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_globalNamespaceStyle));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_descriptionStyle));
}
}
private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol)
{
var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false);
// Don't bother showing disambiguating text for enum members. The icon displayed
// on Quick Info should be enough.
if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum)
{
AddToGroup(SymbolDescriptionGroups.MainDescription, parts);
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.constant)
: Description(FeaturesResources.field),
parts);
}
}
private async Task<ImmutableArray<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (!initializerParts.IsDefaultOrEmpty)
{
var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance();
parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat));
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts.ToImmutableAndFree();
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol)
{
var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false);
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.local_constant)
: Description(FeaturesResources.local_variable),
parts);
}
private async Task<ImmutableArray<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance();
parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat));
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts.ToImmutableAndFree();
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private void AddDescriptionForLabel(ILabelSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.label),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.range_variable),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForMethod(IMethodSymbol method)
{
// TODO : show duplicated member case
var awaitable = method.IsAwaitableNonDynamic(_semanticModel, _position);
var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension;
if (awaitable && extension)
{
AddAwaitableExtensionPrefix();
}
else if (awaitable)
{
AddAwaitablePrefix();
}
else if (extension)
{
AddExtensionPrefix();
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat));
if (awaitable)
{
AddAwaitableUsageText(method, _semanticModel, _position);
}
}
protected abstract void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position);
private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol)
{
if (symbol.IsOptional)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (!initializerParts.IsDefaultOrEmpty)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.parameter), parts);
return;
}
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.parameter),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
protected void AddDescriptionForProperty(IPropertySymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
}
private void AddDescriptionForArbitrarySymbol(ISymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol)
{
Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol),
Space(),
PlainText(FeaturesResources.in_),
Space(),
ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat));
}
private void AddOverloadCountPart(
ImmutableArray<ISymbol> symbolGroup)
{
var count = GetOverloadCount(symbolGroup);
if (count >= 1)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Space(),
Punctuation("("),
Punctuation("+"),
Space(),
PlainText(count.ToString()),
Space(),
count == 1 ? PlainText(FeaturesResources.overload) : PlainText(FeaturesResources.overloads_),
Punctuation(")"));
}
}
private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup)
{
return symbolGroup.Select(s => s.OriginalDefinition)
.Where(s => !s.Equals(symbolGroup.First().OriginalDefinition))
.Where(s => s is IMethodSymbol || s.IsIndexer())
.Count();
}
protected void AddTypeParameterMapPart(
List<ITypeParameterSymbol> typeParameters,
List<ITypeSymbol> typeArguments)
{
var parts = new List<SymbolDisplayPart>();
var count = typeParameters.Count;
for (int i = 0; i < count; i++)
{
parts.AddRange(TypeParameterName(typeParameters[i].Name));
parts.AddRange(Space());
parts.AddRange(PlainText(FeaturesResources.is_));
parts.AddRange(Space());
parts.AddRange(ToMinimalDisplayParts(typeArguments[i]));
if (i < count - 1)
{
parts.AddRange(LineBreak());
}
}
AddToGroup(SymbolDescriptionGroups.TypeParameterMap,
parts);
}
protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray)
{
AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray);
}
protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray)
{
var partsList = partsArray.Flatten().ToList();
if (partsList.Count > 0)
{
if (!_groupMap.TryGetValue(group, out var existingParts))
{
existingParts = new List<SymbolDisplayPart>();
_groupMap.Add(group, existingParts);
}
existingParts.AddRange(partsList);
}
}
private IEnumerable<SymbolDisplayPart> Description(string description)
{
return Punctuation("(")
.Concat(PlainText(description))
.Concat(Punctuation(")"))
.Concat(Space());
}
protected IEnumerable<SymbolDisplayPart> Keyword(string text)
{
return Part(SymbolDisplayPartKind.Keyword, text);
}
protected IEnumerable<SymbolDisplayPart> LineBreak(int count = 1)
{
for (int i = 0; i < count; i++)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
}
}
protected IEnumerable<SymbolDisplayPart> PlainText(string text)
{
return Part(SymbolDisplayPartKind.Text, text);
}
protected IEnumerable<SymbolDisplayPart> Punctuation(string text)
{
return Part(SymbolDisplayPartKind.Punctuation, text);
}
protected IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
protected ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
format = format ?? MinimallyQualifiedFormat;
return _displayService.ToMinimalDisplayParts(_semanticModel, _position, symbol, format);
}
protected IEnumerable<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
return _displayService.ToDisplayParts(symbol, format);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text)
{
yield return new SymbolDisplayPart(kind, symbol, text);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text)
{
return Part(kind, null, text);
}
private IEnumerable<SymbolDisplayPart> TypeParameterName(string text)
{
return Part(SymbolDisplayPartKind.TypeParameterName, text);
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Security.AccessControl.ObjectSecurity.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Security.AccessControl
{
abstract public partial class ObjectSecurity
{
#region Methods and constructors
public abstract AccessRule AccessRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type);
public abstract AuditRule AuditRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags);
public System.Security.Principal.IdentityReference GetGroup(Type targetType)
{
return default(System.Security.Principal.IdentityReference);
}
public System.Security.Principal.IdentityReference GetOwner(Type targetType)
{
return default(System.Security.Principal.IdentityReference);
}
public byte[] GetSecurityDescriptorBinaryForm()
{
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(System.Security.AccessControl.GenericSecurityDescriptor.Revision == 1);
return default(byte[]);
}
public string GetSecurityDescriptorSddlForm(AccessControlSections includeSections)
{
Contract.Ensures(System.Security.AccessControl.GenericSecurityDescriptor.Revision == 1);
return default(string);
}
public static bool IsSddlConversionSupported()
{
Contract.Ensures(Contract.Result<bool>() == true);
return default(bool);
}
protected abstract bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified);
public virtual new bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified)
{
Contract.Requires(this.AccessRuleType != null);
modified = default(bool);
return default(bool);
}
protected abstract bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified);
public virtual new bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified)
{
Contract.Requires(this.AuditRuleType != null);
modified = default(bool);
return default(bool);
}
protected ObjectSecurity(bool isContainer, bool isDS)
{
}
protected virtual new void Persist(System.Runtime.InteropServices.SafeHandle handle, AccessControlSections includeSections)
{
}
protected virtual new void Persist(string name, AccessControlSections includeSections)
{
}
protected virtual new void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections)
{
}
public virtual new void PurgeAccessRules(System.Security.Principal.IdentityReference identity)
{
}
public virtual new void PurgeAuditRules(System.Security.Principal.IdentityReference identity)
{
}
protected void ReadLock()
{
}
protected void ReadUnlock()
{
}
public void SetAccessRuleProtection(bool isProtected, bool preserveInheritance)
{
}
public void SetAuditRuleProtection(bool isProtected, bool preserveInheritance)
{
}
public void SetGroup(System.Security.Principal.IdentityReference identity)
{
}
public void SetOwner(System.Security.Principal.IdentityReference identity)
{
}
public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSections includeSections)
{
}
public void SetSecurityDescriptorBinaryForm(byte[] binaryForm)
{
}
public void SetSecurityDescriptorSddlForm(string sddlForm, AccessControlSections includeSections)
{
}
public void SetSecurityDescriptorSddlForm(string sddlForm)
{
}
protected void WriteLock()
{
}
protected void WriteUnlock()
{
}
#endregion
#region Properties and indexers
public abstract Type AccessRightType
{
get;
}
protected bool AccessRulesModified
{
get
{
return default(bool);
}
set
{
}
}
public abstract Type AccessRuleType
{
get;
}
public bool AreAccessRulesCanonical
{
get
{
return default(bool);
}
}
public bool AreAccessRulesProtected
{
get
{
return default(bool);
}
}
public bool AreAuditRulesCanonical
{
get
{
return default(bool);
}
}
public bool AreAuditRulesProtected
{
get
{
return default(bool);
}
}
protected bool AuditRulesModified
{
get
{
return default(bool);
}
set
{
}
}
public abstract Type AuditRuleType
{
get;
}
protected bool GroupModified
{
get
{
return default(bool);
}
set
{
}
}
protected bool IsContainer
{
get
{
return default(bool);
}
}
protected bool IsDS
{
get
{
return default(bool);
}
}
protected bool OwnerModified
{
get
{
return default(bool);
}
set
{
}
}
#endregion
}
}
| |
// <copyright file="FieldAttribute.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Xml;
using BeanIO.Builder;
using BeanIO.Types;
namespace BeanIO.Annotation
{
/// <summary>
/// Field annotation applied to fields, properties, methods or constructor parameters.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method)]
public class FieldAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="FieldAttribute"/> class.
/// </summary>
public FieldAttribute()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FieldAttribute"/> class.
/// </summary>
/// <param name="name">The field name</param>
public FieldAttribute(string name)
{
Name = name;
At = int.MinValue;
Until = int.MinValue;
Ordinal = int.MinValue;
Length = int.MinValue;
Padding = int.MinValue;
MinLength = MaxLength = int.MinValue;
MinOccurs = MaxOccurs = int.MinValue;
XmlType = XmlNodeType.None;
}
/// <summary>
/// Gets the field name.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets or sets the absolute position of the field.
/// </summary>
public int At { get; set; }
/// <summary>
/// Gets or sets the maximum position of a field that repeats for an indeterminate number of times.
/// </summary>
public int Until { get; set; }
/// <summary>
/// Gets or sets the relative position of the field.
/// </summary>
public int Ordinal { get; set; }
/// <summary>
/// Gets or sets the padded length of the field.
/// </summary>
public int Length { get; set; }
/// <summary>
/// Gets or sets the character used to pad the field.
/// </summary>
public int Padding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to keep the field padding during unmarshalling.
/// </summary>
/// <remarks>
/// Only applies to fixed length formatted streams.
/// </remarks>
public bool KeepPadding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to enforce the padding length during unmarshalling.
/// </summary>
/// <remarks>
/// Only applies to fixed length formatted streams.
/// </remarks>
public bool LenientPadding { get; set; }
/// <summary>
/// Gets or sets the alignment of a padded field.
/// </summary>
public Align Align { get; set; }
/// <summary>
/// Gets or sets the getter method.
/// </summary>
public string Getter { get; set; }
/// <summary>
/// Gets or sets the setter method.
/// </summary>
public string Setter { get; set; }
/// <summary>
/// Gets or sets the field type, if it can not be detected from the method or field declaration.
/// </summary>
public Type Type { get; set; }
/// <summary>
/// Gets or sets the <see cref="ITypeHandler" /> implementation class for this field.
/// </summary>
public Type HandlerType { get; set; }
/// <summary>
/// Gets or sets the name of a registered <see cref="ITypeHandler" />.
/// </summary>
public string HandlerName { get; set; }
/// <summary>
/// Gets or sets the format passed to the <see cref="ITypeHandler" />.
/// </summary>
public string Format { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to trim the field text before validation and type handling.
/// </summary>
public bool Trim { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the field is used to identify the record.
/// </summary>
public bool IsRecordIdentifier { get; set; }
/// <summary>
/// Gets or sets the regular expression for validating and/or matching field text.
/// </summary>
public string RegEx { get; set; }
/// <summary>
/// Gets or sets the literal text for validating or matching field text.
/// </summary>
public string Literal { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this field text is required.
/// </summary>
/// <remarks>
/// true if field text must be at least one character (after trimming if enabled), or false otherwise.
/// </remarks>
public bool IsRequired { get; set; }
/// <summary>
/// Gets or sets the default value for this field.
/// </summary>
/// <remarks>
/// The value is parsed into a Java object using the assigned type handler.
/// </remarks>
public string DefaultValue { get; set; }
/// <summary>
/// Gets or sets the minimum length of the field text (after trimming if enabled).
/// </summary>
public int MinLength { get; set; }
/// <summary>
/// Gets or sets the maximum length of the field text (after trimming if enabled).
/// </summary>
public int MaxLength { get; set; }
/// <summary>
/// Gets or sets the collection type for repeating fields, if it cannot be detected from the field or method declaration.
/// </summary>
public Type CollectionType { get; set; }
/// <summary>
/// Gets or sets a value indicating whether an empty string should be converted to null, or null
/// returned for an empty collection.
/// </summary>
public bool IsLazy { get; set; }
/// <summary>
/// Gets or sets the minimum occurrences of the field.
/// </summary>
public int MinOccurs { get; set; }
/// <summary>
/// Gets or sets the maximum occurrences of the field if it repeats.
/// </summary>
public int MaxOccurs { get; set; }
/// <summary>
/// Gets or sets the name of a preceding field that governs the number of occurrences of this field.
/// </summary>
/// <remarks>
/// Does not apply to XML formatted streams.
/// </remarks>
public string OccursRef { get; set; }
/// <summary>
/// Gets or sets the XML type of this field.
/// </summary>
public XmlNodeType XmlType { get; set; }
/// <summary>
/// Gets or sets the XML attribute or element name.
/// </summary>
public string XmlName { get; set; }
/// <summary>
/// Gets or sets the XML namespace prefix of this field.
/// </summary>
public string XmlPrefix { get; set; }
/// <summary>
/// Gets or sets the XML namespace URI of this field.
/// </summary>
public string XmlNamespace { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the element is nillable.
/// </summary>
public bool IsNullable { get; set; }
/// <summary>
/// Gets or sets the behavior if the default value should be unmarshalled during configuration
/// </summary>
public ParseDefaultBehavior ParseDefault { get; set; }
/// <summary>
/// Gets or sets a value which specifies the validation mode when marshalling fields.
/// </summary>
public ValidationMode ValidationMode { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System.IO;
using System;
using System.Collections;
using System.ComponentModel;
using System.Xml;
public delegate void XmlAttributeEventHandler(object sender, XmlAttributeEventArgs e);
public class XmlAttributeEventArgs : EventArgs
{
private object _o;
private XmlAttribute _attr;
private string _qnames;
private int _lineNumber;
private int _linePosition;
internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o, string qnames)
{
_attr = attr;
_o = o;
_qnames = qnames;
_lineNumber = lineNumber;
_linePosition = linePosition;
}
public object ObjectBeingDeserialized
{
get { return _o; }
}
public XmlAttribute Attr
{
get { return _attr; }
}
/// <summary>
/// Gets the current line number.
/// </summary>
public int LineNumber
{
get { return _lineNumber; }
}
/// <summary>
/// Gets the current line position.
/// </summary>
public int LinePosition
{
get { return _linePosition; }
}
/// <summary>
/// List the qnames of attributes expected in the current context.
/// </summary>
public string ExpectedAttributes
{
get { return _qnames == null ? string.Empty : _qnames; }
}
}
public delegate void XmlElementEventHandler(object sender, XmlElementEventArgs e);
public class XmlElementEventArgs : EventArgs
{
private object _o;
private XmlElement _elem;
private string _qnames;
private int _lineNumber;
private int _linePosition;
internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, object o, string qnames)
{
_elem = elem;
_o = o;
_qnames = qnames;
_lineNumber = lineNumber;
_linePosition = linePosition;
}
public object ObjectBeingDeserialized
{
get { return _o; }
}
public XmlElement Element
{
get { return _elem; }
}
public int LineNumber
{
get { return _lineNumber; }
}
public int LinePosition
{
get { return _linePosition; }
}
/// <summary>
/// List of qnames of elements expected in the current context.
/// </summary>
public string ExpectedElements
{
get { return _qnames == null ? string.Empty : _qnames; }
}
}
public delegate void XmlNodeEventHandler(object sender, XmlNodeEventArgs e);
public class XmlNodeEventArgs : EventArgs
{
private object _o;
private XmlNode _xmlNode;
private int _lineNumber;
private int _linePosition;
internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, object o)
{
_o = o;
_xmlNode = xmlNode;
_lineNumber = lineNumber;
_linePosition = linePosition;
}
public object ObjectBeingDeserialized
{
get { return _o; }
}
public XmlNodeType NodeType
{
get { return _xmlNode.NodeType; }
}
public string Name
{
get { return _xmlNode.Name; }
}
public string LocalName
{
get { return _xmlNode.LocalName; }
}
public string NamespaceURI
{
get { return _xmlNode.NamespaceURI; }
}
public string Text
{
get { return _xmlNode.Value; }
}
/// <summary>
/// Gets the current line number.
/// </summary>
public int LineNumber
{
get { return _lineNumber; }
}
/// <summary>
/// Gets the current line position.
/// </summary>
public int LinePosition
{
get { return _linePosition; }
}
}
public delegate void UnreferencedObjectEventHandler(object sender, UnreferencedObjectEventArgs e);
public class UnreferencedObjectEventArgs : EventArgs
{
private object _o;
private string _id;
public UnreferencedObjectEventArgs(object o, string id)
{
_o = o;
_id = id;
}
public object UnreferencedObject
{
get { return _o; }
}
public string UnreferencedId
{
get { return _id; }
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
public partial class Scene
{
protected void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent, bool broadcast)
{
OSChatMessage args = new OSChatMessage();
args.Message = Utils.BytesToString(message);
args.Channel = channel;
args.Type = type;
args.Position = fromPos;
args.SenderUUID = fromID;
args.Scene = this;
if (fromAgent)
{
ScenePresence user = GetScenePresence(fromID);
if (user != null)
args.Sender = user.ControllingClient;
}
else
{
SceneObjectPart obj = GetSceneObjectPart(fromID);
args.SenderObject = obj;
}
args.From = fromName;
//args.
if (broadcast)
EventManager.TriggerOnChatBroadcast(this, args);
else
EventManager.TriggerOnChatFromWorld(this, args);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
/// <param name="fromPos"></param>
/// <param name="fromName"></param>
/// <param name="fromAgentID"></param>
public void SimChat(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent)
{
SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, false);
}
public void SimChat(string message, ChatTypeEnum type, Vector3 fromPos, string fromName, UUID fromID, bool fromAgent)
{
SimChat(Utils.StringToBytes(message), type, 0, fromPos, fromName, fromID, fromAgent);
}
public void SimChat(string message, string fromName)
{
SimChat(message, ChatTypeEnum.Broadcast, Vector3.Zero, fromName, UUID.Zero, false);
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
/// <param name="type"></param>
/// <param name="fromPos"></param>
/// <param name="fromName"></param>
/// <param name="fromAgentID"></param>
public void SimChatBroadcast(byte[] message, ChatTypeEnum type, int channel, Vector3 fromPos, string fromName,
UUID fromID, bool fromAgent)
{
SimChat(message, type, channel, fromPos, fromName, fromID, fromAgent, true);
}
/// <summary>
/// Invoked when the client requests a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void RequestPrim(uint primLocalID, IClientAPI remoteClient)
{
EntityBase[] entityList = GetEntities();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
if (((SceneObjectGroup)ent).LocalId == primLocalID)
{
((SceneObjectGroup)ent).SendFullUpdateToClient(remoteClient);
return;
}
}
}
}
/// <summary>
/// Invoked when the client selects a prim.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void SelectPrim(uint primLocalID, IClientAPI remoteClient)
{
EntityBase[] entityList = GetEntities();
foreach (EntityBase ent in entityList)
{
if (ent is SceneObjectGroup)
{
if (((SceneObjectGroup) ent).LocalId == primLocalID)
{
((SceneObjectGroup) ent).GetProperties(remoteClient);
((SceneObjectGroup) ent).IsSelected = true;
// A prim is only tainted if it's allowed to be edited by the person clicking it.
if (Permissions.CanEditObject(((SceneObjectGroup)ent).UUID, remoteClient.AgentId)
|| Permissions.CanMoveObject(((SceneObjectGroup)ent).UUID, remoteClient.AgentId))
{
EventManager.TriggerParcelPrimCountTainted();
}
break;
}
else
{
// We also need to check the children of this prim as they
// can be selected as well and send property information
bool foundPrim = false;
SceneObjectGroup sog = ent as SceneObjectGroup;
SceneObjectPart[] partList = sog.Parts;
foreach (SceneObjectPart part in partList)
{
if (part.LocalId == primLocalID)
{
part.GetProperties(remoteClient);
foundPrim = true;
break;
}
}
if (foundPrim)
break;
}
}
}
}
/// <summary>
/// Handle the deselection of a prim from the client.
/// </summary>
/// <param name="primLocalID"></param>
/// <param name="remoteClient"></param>
public void DeselectPrim(uint primLocalID, IClientAPI remoteClient)
{
SceneObjectPart part = GetSceneObjectPart(primLocalID);
if (part == null)
return;
// The prim is in the process of being deleted.
if (null == part.ParentGroup.RootPart)
return;
// A deselect packet contains all the local prims being deselected. However, since selection is still
// group based we only want the root prim to trigger a full update - otherwise on objects with many prims
// we end up sending many duplicate ObjectUpdates
if (part.ParentGroup.RootPart.LocalId != part.LocalId)
return;
bool isAttachment = false;
// This is wrong, wrong, wrong. Selection should not be
// handled by group, but by prim. Legacy cruft.
// TODO: Make selection flagging per prim!
//
part.ParentGroup.IsSelected = false;
if (part.ParentGroup.IsAttachment)
isAttachment = true;
else
part.ParentGroup.ScheduleGroupForFullUpdate();
// If it's not an attachment, and we are allowed to move it,
// then we might have done so. If we moved across a parcel
// boundary, we will need to recount prims on the parcels.
// For attachments, that makes no sense.
//
if (!isAttachment)
{
if (Permissions.CanEditObject(
part.UUID, remoteClient.AgentId)
|| Permissions.CanMoveObject(
part.UUID, remoteClient.AgentId))
EventManager.TriggerParcelPrimCountTainted();
}
}
public virtual void ProcessMoneyTransferRequest(UUID source, UUID destination, int amount,
int transactiontype, string description)
{
EventManager.MoneyTransferArgs args = new EventManager.MoneyTransferArgs(source, destination, amount,
transactiontype, description);
EventManager.TriggerMoneyTransfer(this, args);
}
public virtual void ProcessParcelBuy(UUID agentId, UUID groupId, bool final, bool groupOwned,
bool removeContribution, int parcelLocalID, int parcelArea, int parcelPrice, bool authenticated)
{
EventManager.LandBuyArgs args = new EventManager.LandBuyArgs(agentId, groupId, final, groupOwned,
removeContribution, parcelLocalID, parcelArea,
parcelPrice, authenticated);
// First, allow all validators a stab at it
m_eventManager.TriggerValidateLandBuy(this, args);
// Then, check validation and transfer
m_eventManager.TriggerLandBuy(this, args);
}
public virtual void ProcessObjectGrab(uint localID, Vector3 offsetPos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
EntityBase[] EntityList = GetEntities();
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
foreach (EntityBase ent in EntityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup obj = ent as SceneObjectGroup;
if (obj != null)
{
// Is this prim part of the group
if (obj.HasChildPrim(localID))
{
// Currently only grab/touch for the single prim
// the client handles rez correctly
obj.ObjectGrabHandler(localID, offsetPos, remoteClient);
SceneObjectPart part = obj.GetChildPart(localID);
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
if ((part.ScriptEvents & scriptEvents.touch_start) != 0)
EventManager.TriggerObjectGrab(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg);
// Deliver to the root prim if the touched prim doesn't handle touches
// or if we're meant to pass on touches anyway. Don't send to root prim
// if prim touched is the root prim as we just did it
if (((part.ScriptEvents & scriptEvents.touch_start) == 0) ||
(part.PassTouches && (part.LocalId != obj.RootPart.LocalId)))
{
EventManager.TriggerObjectGrab(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg);
}
return;
}
}
}
}
}
public virtual void ProcessObjectGrabUpdate(UUID objectID, Vector3 offset, Vector3 pos, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
EntityBase[] EntityList = GetEntities();
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
foreach (EntityBase ent in EntityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup obj = ent as SceneObjectGroup;
if (obj != null)
{
// Is this prim part of the group
if (obj.HasChildPrim(objectID))
{
SceneObjectPart part = obj.GetChildPart(objectID);
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
if ((part.ScriptEvents & scriptEvents.touch) != 0)
EventManager.TriggerObjectGrabbing(part.LocalId, 0, part.OffsetPosition, remoteClient, surfaceArg);
// Deliver to the root prim if the touched prim doesn't handle touches
// or if we're meant to pass on touches anyway. Don't send to root prim
// if prim touched is the root prim as we just did it
if (((part.ScriptEvents & scriptEvents.touch) == 0) ||
(part.PassTouches && (part.LocalId != obj.RootPart.LocalId)))
{
EventManager.TriggerObjectGrabbing(obj.RootPart.LocalId, part.LocalId, part.OffsetPosition, remoteClient, surfaceArg);
}
return;
}
}
}
}
}
public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs)
{
EntityBase[] EntityList = GetEntities();
SurfaceTouchEventArgs surfaceArg = null;
if (surfaceArgs != null && surfaceArgs.Count > 0)
surfaceArg = surfaceArgs[0];
foreach (EntityBase ent in EntityList)
{
if (ent is SceneObjectGroup)
{
SceneObjectGroup obj = ent as SceneObjectGroup;
// Is this prim part of the group
if (obj.HasChildPrim(localID))
{
SceneObjectPart part=obj.GetChildPart(localID);
if (part != null)
{
// If the touched prim handles touches, deliver it
// If not, deliver to root prim
if ((part.ScriptEvents & scriptEvents.touch_end) != 0)
EventManager.TriggerObjectDeGrab(part.LocalId, 0, remoteClient, surfaceArg);
else
EventManager.TriggerObjectDeGrab(obj.RootPart.LocalId, part.LocalId, remoteClient, surfaceArg);
return;
}
return;
}
}
}
}
public void ProcessAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query)
{
//EventManager.TriggerAvatarPickerRequest();
List<UserAccount> accounts = UserAccountService.GetUserAccounts(RegionInfo.ScopeID, query);
if (accounts == null)
return;
AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket) PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply);
// TODO: don't create new blocks if recycling an old packet
AvatarPickerReplyPacket.DataBlock[] searchData =
new AvatarPickerReplyPacket.DataBlock[accounts.Count];
AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock();
agentData.AgentID = avatarID;
agentData.QueryID = RequestID;
replyPacket.AgentData = agentData;
//byte[] bytes = new byte[AvatarResponses.Count*32];
int i = 0;
foreach (UserAccount item in accounts)
{
UUID translatedIDtem = item.PrincipalID;
searchData[i] = new AvatarPickerReplyPacket.DataBlock();
searchData[i].AvatarID = translatedIDtem;
searchData[i].FirstName = Utils.StringToBytes((string) item.FirstName);
searchData[i].LastName = Utils.StringToBytes((string) item.LastName);
i++;
}
if (accounts.Count == 0)
{
searchData = new AvatarPickerReplyPacket.DataBlock[0];
}
replyPacket.Data = searchData;
AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs();
agent_data.AgentID = replyPacket.AgentData.AgentID;
agent_data.QueryID = replyPacket.AgentData.QueryID;
List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>();
for (i = 0; i < replyPacket.Data.Length; i++)
{
AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs();
data_arg.AvatarID = replyPacket.Data[i].AvatarID;
data_arg.FirstName = replyPacket.Data[i].FirstName;
data_arg.LastName = replyPacket.Data[i].LastName;
data_args.Add(data_arg);
}
client.SendAvatarPickerReply(agent_data, data_args);
}
public void ProcessScriptReset(IClientAPI remoteClient, UUID objectID,
UUID itemID)
{
SceneObjectPart part=GetSceneObjectPart(objectID);
if (part == null)
return;
if (Permissions.CanResetScript(objectID, itemID, remoteClient.AgentId))
{
EventManager.TriggerScriptReset(part.LocalId, itemID);
}
}
void ProcessViewerEffect(IClientAPI remoteClient, List<ViewerEffectEventHandlerArg> args)
{
// TODO: don't create new blocks if recycling an old packet
ViewerEffectPacket.EffectBlock[] effectBlockArray = new ViewerEffectPacket.EffectBlock[args.Count];
for (int i = 0; i < args.Count; i++)
{
ViewerEffectPacket.EffectBlock effect = new ViewerEffectPacket.EffectBlock();
effect.AgentID = args[i].AgentID;
effect.Color = args[i].Color;
effect.Duration = args[i].Duration;
effect.ID = args[i].ID;
effect.Type = args[i].Type;
effect.TypeData = args[i].TypeData;
effectBlockArray[i] = effect;
}
ForEachClient(
delegate(IClientAPI client)
{
if (client.AgentId != remoteClient.AgentId)
client.SendViewerEffect(effectBlockArray);
}
);
}
/// <summary>
/// Handle a fetch inventory request from the client
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="itemID"></param>
/// <param name="ownerID"></param>
public void HandleFetchInventory(IClientAPI remoteClient, UUID itemID, UUID ownerID)
{
if (LibraryService != null && LibraryService.LibraryRootFolder != null && ownerID == LibraryService.LibraryRootFolder.Owner)
{
//m_log.Debug("request info for library item");
return;
}
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item);
if (item != null)
{
remoteClient.SendInventoryItemDetails(ownerID, item);
}
// else shouldn't we send an alert message?
}
/// <summary>
/// Tell the client about the various child items and folders contained in the requested folder.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="ownerID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <param name="sortOrder"></param>
public void HandleFetchInventoryDescendents(IClientAPI remoteClient, UUID folderID, UUID ownerID,
bool fetchFolders, bool fetchItems, int sortOrder)
{
if (folderID == UUID.Zero)
return;
// FIXME MAYBE: We're not handling sortOrder!
// TODO: This code for looking in the folder for the library should be folded somewhere else
// so that this class doesn't have to know the details (and so that multiple libraries, etc.
// can be handled transparently).
InventoryFolderImpl fold = null;
if (LibraryService != null && LibraryService.LibraryRootFolder != null)
if ((fold = LibraryService.LibraryRootFolder.FindFolder(folderID)) != null)
{
remoteClient.SendInventoryFolderDetails(
fold.Owner, folderID, fold.RequestListOfItems(),
fold.RequestListOfFolders(), fold.Version, fetchFolders, fetchItems);
return;
}
// We're going to send the reply async, because there may be
// an enormous quantity of packets -- basically the entire inventory!
// We don't want to block the client thread while all that is happening.
SendInventoryDelegate d = SendInventoryAsync;
d.BeginInvoke(remoteClient, folderID, ownerID, fetchFolders, fetchItems, sortOrder, SendInventoryComplete, d);
}
delegate void SendInventoryDelegate(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder);
void SendInventoryAsync(IClientAPI remoteClient, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder)
{
SendInventoryUpdate(remoteClient, new InventoryFolderBase(folderID), fetchFolders, fetchItems);
}
void SendInventoryComplete(IAsyncResult iar)
{
SendInventoryDelegate d = (SendInventoryDelegate)iar.AsyncState;
d.EndInvoke(iar);
}
/// <summary>
/// Handle the caps inventory descendents fetch.
///
/// Since the folder structure is sent to the client on login, I believe we only need to handle items.
/// Diva comment 8/13/2009: what if someone gave us a folder in the meantime??
/// </summary>
/// <param name="agentID"></param>
/// <param name="folderID"></param>
/// <param name="ownerID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <param name="sortOrder"></param>
/// <returns>null if the inventory look up failed</returns>
public InventoryCollection HandleFetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID,
bool fetchFolders, bool fetchItems, int sortOrder, out int version)
{
m_log.DebugFormat(
"[INVENTORY CACHE]: Fetching folders ({0}), items ({1}) from {2} for agent {3}",
fetchFolders, fetchItems, folderID, agentID);
// FIXME MAYBE: We're not handling sortOrder!
// TODO: This code for looking in the folder for the library should be folded back into the
// CachedUserInfo so that this class doesn't have to know the details (and so that multiple libraries, etc.
// can be handled transparently).
InventoryFolderImpl fold;
if (LibraryService != null && LibraryService.LibraryRootFolder != null)
if ((fold = LibraryService.LibraryRootFolder.FindFolder(folderID)) != null)
{
version = 0;
InventoryCollection ret = new InventoryCollection();
ret.Folders = new List<InventoryFolderBase>();
ret.Items = fold.RequestListOfItems();
return ret;
}
InventoryCollection contents = new InventoryCollection();
if (folderID != UUID.Zero)
{
contents = InventoryService.GetFolderContent(agentID, folderID);
InventoryFolderBase containingFolder = new InventoryFolderBase();
containingFolder.ID = folderID;
containingFolder.Owner = agentID;
containingFolder = InventoryService.GetFolder(containingFolder);
version = containingFolder.Version;
}
else
{
// Lost itemsm don't really need a version
version = 1;
}
return contents;
}
/// <summary>
/// Handle an inventory folder creation request from the client.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="folderType"></param>
/// <param name="folderName"></param>
/// <param name="parentID"></param>
public void HandleCreateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort folderType,
string folderName, UUID parentID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, folderName, remoteClient.AgentId, (short)folderType, parentID, 1);
if (!InventoryService.AddFolder(folder))
{
m_log.WarnFormat(
"[AGENT INVENTORY]: Failed to move create folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
}
}
/// <summary>
/// Handle a client request to update the inventory folder
/// </summary>
///
/// FIXME: We call add new inventory folder because in the data layer, we happen to use an SQL REPLACE
/// so this will work to rename an existing folder. Needless to say, to rely on this is very confusing,
/// and needs to be changed.
///
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
/// <param name="type"></param>
/// <param name="name"></param>
/// <param name="parentID"></param>
public void HandleUpdateInventoryFolder(IClientAPI remoteClient, UUID folderID, ushort type, string name,
UUID parentID)
{
// m_log.DebugFormat(
// "[AGENT INVENTORY]: Updating inventory folder {0} {1} for {2} {3}", folderID, name, remoteClient.Name, remoteClient.AgentId);
InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId);
folder = InventoryService.GetFolder(folder);
if (folder != null)
{
folder.Name = name;
folder.Type = (short)type;
folder.ParentID = parentID;
if (!InventoryService.UpdateFolder(folder))
{
m_log.ErrorFormat(
"[AGENT INVENTORY]: Failed to update folder for user {0} {1}",
remoteClient.Name, remoteClient.AgentId);
}
}
}
public void HandleMoveInventoryFolder(IClientAPI remoteClient, UUID folderID, UUID parentID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, remoteClient.AgentId);
folder = InventoryService.GetFolder(folder);
if (folder != null)
{
folder.ParentID = parentID;
if (!InventoryService.MoveFolder(folder))
m_log.WarnFormat("[AGENT INVENTORY]: could not move folder {0}", folderID);
else
m_log.DebugFormat("[AGENT INVENTORY]: folder {0} moved to parent {1}", folderID, parentID);
}
else
{
m_log.WarnFormat("[AGENT INVENTORY]: request to move folder {0} but folder not found", folderID);
}
}
/// <summary>
/// This should delete all the items and folders in the given directory.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="folderID"></param>
delegate void PurgeFolderDelegate(UUID userID, UUID folder);
public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, UUID folderID)
{
PurgeFolderDelegate d = PurgeFolderAsync;
try
{
d.BeginInvoke(remoteClient.AgentId, folderID, PurgeFolderCompleted, d);
}
catch (Exception e)
{
m_log.WarnFormat("[AGENT INVENTORY]: Exception on purge folder for user {0}: {1}", remoteClient.AgentId, e.Message);
}
}
private void PurgeFolderAsync(UUID userID, UUID folderID)
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, userID);
if (InventoryService.PurgeFolder(folder))
m_log.DebugFormat("[AGENT INVENTORY]: folder {0} purged successfully", folderID);
else
m_log.WarnFormat("[AGENT INVENTORY]: could not purge folder {0}", folderID);
}
private void PurgeFolderCompleted(IAsyncResult iar)
{
PurgeFolderDelegate d = (PurgeFolderDelegate)iar.AsyncState;
d.EndInvoke(iar);
}
}
}
| |
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 PrimusFlex.WebApi.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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Logging;
using Ocelot.Middleware;
using Ocelot.Request.Middleware;
using Ocelot.Requester;
using Ocelot.Responses;
using Shouldly;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Requester
{
public class HttpClientBuilderTests : IDisposable
{
private HttpClientBuilder _builder;
private readonly Mock<IDelegatingHandlerHandlerFactory> _factory;
private IHttpClient _httpClient;
private HttpResponseMessage _response;
private DownstreamContext _context;
private readonly Mock<IHttpClientCache> _cacheHandlers;
private readonly Mock<IOcelotLogger> _logger;
private int _count;
private IWebHost _host;
private IHttpClient _againHttpClient;
private IHttpClient _firstHttpClient;
private MemoryHttpClientCache _realCache;
public HttpClientBuilderTests()
{
_cacheHandlers = new Mock<IHttpClientCache>();
_logger = new Mock<IOcelotLogger>();
_factory = new Mock<IDelegatingHandlerHandlerFactory>();
_builder = new HttpClientBuilder(_factory.Object, _cacheHandlers.Object, _logger.Object);
}
[Fact]
public void should_build_http_client()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRoute))
.When(x => WhenIBuild())
.Then(x => ThenTheHttpClientShouldNotBeNull())
.BDDfy();
}
[Fact]
public void should_get_from_cache()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(x => GivenARealCache())
.And(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRoute))
.And(x => WhenIBuildTheFirstTime())
.And(x => WhenISave())
.And(x => WhenIBuildAgain())
.And(x => WhenISave())
.When(x => WhenIBuildAgain())
.Then(x => ThenTheHttpClientIsFromTheCache())
.BDDfy();
}
[Fact]
public void should_get_from_cache_with_different_query_string()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(x => GivenARealCache())
.And(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRoute, "http://wwww.someawesomewebsite.com/woot?badman=1"))
.And(x => WhenIBuildTheFirstTime())
.And(x => WhenISave())
.And(x => WhenIBuildAgain())
.And(x => GivenARequest(reRoute, "http://wwww.someawesomewebsite.com/woot?badman=2"))
.And(x => WhenISave())
.When(x => WhenIBuildAgain())
.Then(x => ThenTheHttpClientIsFromTheCache())
.BDDfy();
}
[Fact]
public void should_not_get_from_cache_with_different_query_string()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRouteA = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithContainsQueryString(true).WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
var reRouteB = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithContainsQueryString(true).WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(x => GivenARealCache())
.And(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRouteA, "http://wwww.someawesomewebsite.com/woot?badman=1"))
.And(x => WhenIBuildTheFirstTime())
.And(x => WhenISave())
.And(x => WhenIBuildAgain())
.And(x => GivenARequest(reRouteB, "http://wwww.someawesomewebsite.com/woot?badman=2"))
.And(x => WhenISave())
.When(x => WhenIBuildAgain())
.Then(x => ThenTheHttpClientIsNotFromTheCache())
.BDDfy();
}
[Fact]
public void should_log_if_ignoring_ssl_errors()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.WithDangerousAcceptAnyServerCertificateValidator(true)
.Build();
this.Given(x => GivenTheFactoryReturns())
.And(x => GivenARequest(reRoute))
.When(x => WhenIBuild())
.Then(x => ThenTheHttpClientShouldNotBeNull())
.Then(x => ThenTheDangerousAcceptAnyServerCertificateValidatorWarningIsLogged())
.BDDfy();
}
[Fact]
public void should_call_delegating_handlers_in_order()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
var fakeOne = new FakeDelegatingHandler();
var fakeTwo = new FakeDelegatingHandler();
var handlers = new List<Func<DelegatingHandler>>()
{
() => fakeOne,
() => fakeTwo
};
this.Given(x => GivenTheFactoryReturns(handlers))
.And(x => GivenARequest(reRoute))
.And(x => WhenIBuild())
.When(x => WhenICallTheClient())
.Then(x => ThenTheFakeAreHandledInOrder(fakeOne, fakeTwo))
.And(x => ThenSomethingIsReturned())
.BDDfy();
}
[Fact]
public void should_re_use_cookies_from_container()
{
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, true, false, true, int.MaxValue))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(_ => GivenADownstreamService())
.And(_ => GivenARequest(reRoute))
.And(_ => GivenTheFactoryReturnsNothing())
.And(_ => WhenIBuild())
.And(_ => WhenICallTheClient("http://localhost:5003"))
.And(_ => ThenTheCookieIsSet())
.And(_ => GivenTheClientIsCached())
.And(_ => WhenIBuild())
.When(_ => WhenICallTheClient("http://localhost:5003"))
.Then(_ => ThenTheResponseIsOk())
.BDDfy();
}
[Theory]
[InlineData("GET")]
[InlineData("POST")]
[InlineData("PUT")]
[InlineData("DELETE")]
[InlineData("PATCH")]
public void should_add_verb_to_cache_key(string verb)
{
var downstreamUrl = "http://localhost:5012/";
var method = new HttpMethod(verb);
var qosOptions = new QoSOptionsBuilder()
.Build();
var reRoute = new DownstreamReRouteBuilder()
.WithQosOptions(qosOptions)
.WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue))
.WithLoadBalancerKey("")
.WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build())
.WithQosOptions(new QoSOptionsBuilder().Build())
.Build();
this.Given(_ => GivenADownstreamService())
.And(_ => GivenARequestWithAUrlAndMethod(reRoute, downstreamUrl, method))
.And(_ => GivenTheFactoryReturnsNothing())
.And(_ => WhenIBuild())
.And(_ => GivenCacheIsCalledWithExpectedKey($"{method.ToString()}:{downstreamUrl}"))
.BDDfy();
}
private void GivenARealCache()
{
_realCache = new MemoryHttpClientCache();
_builder = new HttpClientBuilder(_factory.Object, _realCache, _logger.Object);
}
private void ThenTheHttpClientIsFromTheCache()
{
_againHttpClient.ShouldBe(_firstHttpClient);
}
private void ThenTheHttpClientIsNotFromTheCache()
{
_againHttpClient.ShouldNotBe(_firstHttpClient);
}
private void WhenISave()
{
_builder.Save();
}
private void GivenCacheIsCalledWithExpectedKey(string expectedKey)
{
_cacheHandlers.Verify(x => x.Get(It.IsAny<DownstreamReRoute>()), Times.Once);
}
private void ThenTheDangerousAcceptAnyServerCertificateValidatorWarningIsLogged()
{
_logger.Verify(x => x.LogWarning($"You have ignored all SSL warnings by using DangerousAcceptAnyServerCertificateValidator for this DownstreamReRoute, UpstreamPathTemplate: {_context.DownstreamReRoute.UpstreamPathTemplate}, DownstreamPathTemplate: {_context.DownstreamReRoute.DownstreamPathTemplate}"), Times.Once);
}
private void GivenTheClientIsCached()
{
_cacheHandlers.Setup(x => x.Get(It.IsAny<DownstreamReRoute>())).Returns(_httpClient);
}
private void ThenTheCookieIsSet()
{
_response.Headers.TryGetValues("Set-Cookie", out var test).ShouldBeTrue();
}
private void WhenICallTheClient(string url)
{
_response = _httpClient
.SendAsync(new HttpRequestMessage(HttpMethod.Get, url))
.GetAwaiter()
.GetResult();
}
private void ThenTheResponseIsOk()
{
_response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
private void GivenADownstreamService()
{
_host = new WebHostBuilder()
.UseUrls("http://localhost:5003")
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.Configure(app =>
{
app.Run(context =>
{
if (_count == 0)
{
context.Response.Cookies.Append("test", "0");
context.Response.StatusCode = 200;
_count++;
return Task.CompletedTask;
}
if (_count == 1)
{
if (context.Request.Cookies.TryGetValue("test", out var cookieValue) || context.Request.Headers.TryGetValue("Set-Cookie", out var headerValue))
{
context.Response.StatusCode = 200;
return Task.CompletedTask;
}
context.Response.StatusCode = 500;
}
return Task.CompletedTask;
});
})
.Build();
_host.Start();
}
private void GivenARequest(DownstreamReRoute downstream)
{
GivenARequest(downstream, "http://localhost:5003");
}
private void GivenARequest(DownstreamReRoute downstream, string downstreamUrl)
{
GivenARequestWithAUrlAndMethod(downstream, downstreamUrl, HttpMethod.Get);
}
private void GivenARequestWithAUrlAndMethod(DownstreamReRoute downstream, string url, HttpMethod method)
{
var context = new DownstreamContext(new DefaultHttpContext())
{
DownstreamReRoute = downstream,
DownstreamRequest = new DownstreamRequest(new HttpRequestMessage() { RequestUri = new Uri(url), Method = method }),
};
_context = context;
}
private void ThenSomethingIsReturned()
{
_response.ShouldNotBeNull();
}
private void WhenICallTheClient()
{
_response = _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://test.com")).GetAwaiter().GetResult();
}
private void ThenTheFakeAreHandledInOrder(FakeDelegatingHandler fakeOne, FakeDelegatingHandler fakeTwo)
{
fakeOne.TimeCalled.ShouldBeGreaterThan(fakeTwo.TimeCalled);
}
private void GivenTheFactoryReturns()
{
var handlers = new List<Func<DelegatingHandler>>() { () => new FakeDelegatingHandler() };
_factory
.Setup(x => x.Get(It.IsAny<DownstreamReRoute>()))
.Returns(new OkResponse<List<Func<DelegatingHandler>>>(handlers));
}
private void GivenTheFactoryReturnsNothing()
{
var handlers = new List<Func<DelegatingHandler>>();
_factory
.Setup(x => x.Get(It.IsAny<DownstreamReRoute>()))
.Returns(new OkResponse<List<Func<DelegatingHandler>>>(handlers));
}
private void GivenTheFactoryReturns(List<Func<DelegatingHandler>> handlers)
{
_factory
.Setup(x => x.Get(It.IsAny<DownstreamReRoute>()))
.Returns(new OkResponse<List<Func<DelegatingHandler>>>(handlers));
}
private void WhenIBuild()
{
_httpClient = _builder.Create(_context);
}
private void WhenIBuildTheFirstTime()
{
_firstHttpClient = _builder.Create(_context);
}
private void WhenIBuildAgain()
{
_builder = new HttpClientBuilder(_factory.Object, _realCache, _logger.Object);
_againHttpClient = _builder.Create(_context);
}
private void ThenTheHttpClientShouldNotBeNull()
{
_httpClient.ShouldNotBeNull();
}
public void Dispose()
{
_response?.Dispose();
_host?.Dispose();
}
}
}
| |
/// OSVR-Unity Connection
///
/// http://sensics.com/osvr
///
/// <copyright>
/// Copyright 2014 Sensics, 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.
/// </copyright>
using UnityEngine;
using System.Collections;
namespace OSVR
{
namespace Unity
{
[RequireComponent(typeof(Camera))]
public class VRViewer : MonoBehaviour
{
#region Public Variables
public DisplayController DisplayController { get { return _displayController; } set { _displayController = value; } }
public VREye[] Eyes { get { return _eyes; } }
public uint EyeCount { get { return _eyeCount; } }
public uint ViewerIndex { get { return _viewerIndex; } set { _viewerIndex = value; } }
[HideInInspector]
public Transform cachedTransform;
public Camera Camera
{
get
{
if (_camera == null)
{
_camera = GetComponent<Camera>();
}
return _camera;
}
set { _camera = value; }
}
#endregion
#region Private Variables
private DisplayController _displayController;
private VREye[] _eyes;
private uint _eyeCount;
private uint _viewerIndex;
private Camera _camera;
private bool _disabledCamera = true;
private bool _hmdConnectionError = false;
private Rect _emptyViewport = new Rect(0, 0, 0, 0);
private IEnumerator _endOfFrameCoroutine;
#endregion
void Awake()
{
Init();
}
void Init()
{
if (_camera == null)
{
_camera = GetComponent<Camera>();
//cache:
cachedTransform = transform;
if (DisplayController == null)
{
DisplayController = FindObjectOfType<DisplayController>();
}
_endOfFrameCoroutine = EndOfFrame();
}
}
void OnEnable()
{
Init();
if (DisplayController != null)
StartCoroutine(_endOfFrameCoroutine);
}
void OnDisable()
{
if (DisplayController != null)
{
StopCoroutine(_endOfFrameCoroutine);
if (DisplayController.UseRenderManager && DisplayController.RenderManager != null)
{
DisplayController.ExitRenderManager();
}
}
}
//Creates the Eyes of this Viewer
public void CreateEyes(uint eyeCount)
{
_eyeCount = eyeCount; //cache the number of eyes this viewer controls
_eyes = new VREye[_eyeCount];
uint eyeIndex = 0;
uint foundEyes = 0;
//Check if there are already VREyes in the scene.
//If so, use them instead of creating a new
VREye[] eyesInScene = FindObjectsOfType<VREye>();
foundEyes = (uint)eyesInScene.Length;
if (eyesInScene != null && foundEyes > 0)
{
for (eyeIndex = 0; eyeIndex < eyesInScene.Length; eyeIndex++)
{
VREye eye = eyesInScene[eyeIndex];
// get the VREye gameobject
GameObject eyeGameObject = eye.gameObject;
eyeGameObject.name = "VREye" + eyeIndex;
eye.Viewer = this;
eye.EyeIndex = eyeIndex; //set the eye's index
eyeGameObject.transform.parent = DisplayController.transform; //child of DisplayController
eyeGameObject.transform.localPosition = Vector3.zero;
eyeGameObject.transform.rotation = this.transform.rotation;
_eyes[eyeIndex] = eye;
uint eyeSurfaceCount = DisplayController.DisplayConfig.GetNumSurfacesForViewerEye(ViewerIndex, (byte)eyeIndex);
eye.CreateSurfaces(eyeSurfaceCount);
}
}
for (; eyeIndex < _eyeCount; eyeIndex++)
{
if(foundEyes == 0)
{
GameObject eyeGameObject = new GameObject("Eye" + eyeIndex); //add an eye gameobject to the scene
VREye eye = eyeGameObject.AddComponent<VREye>(); //add the VReye component
eye.Viewer = this; //ASSUME THERE IS ONLY ONE VIEWER
eye.EyeIndex = eyeIndex; //set the eye's index
eyeGameObject.transform.parent = DisplayController.transform; //child of DisplayController
eyeGameObject.transform.localPosition = Vector3.zero;
eyeGameObject.transform.rotation = this.transform.rotation;
_eyes[eyeIndex] = eye;
//create the eye's rendering surface
uint eyeSurfaceCount = DisplayController.DisplayConfig.GetNumSurfacesForViewerEye(ViewerIndex, (byte)eyeIndex);
eye.CreateSurfaces(eyeSurfaceCount);
}
else
{
//if we need to create a new VREye, and there is already one in the scene (eyeIndex > 0),
//duplicate the last eye found instead of creating new gameobjects
GameObject eyeGameObject = (GameObject)Instantiate(_eyes[eyeIndex - 1].gameObject);
VREye eye = eyeGameObject.GetComponent<VREye>(); //add the VReye component
eye.Viewer = this; //ASSUME THERE IS ONLY ONE VIEWER
eye.EyeIndex = eyeIndex; //set the eye's index
eyeGameObject.name = "VREye" + eyeIndex;
eyeGameObject.transform.parent = DisplayController.transform; //child of DisplayController
eyeGameObject.transform.localPosition = Vector3.zero;
eyeGameObject.transform.rotation = this.transform.rotation;
_eyes[eyeIndex] = eye;
uint eyeSurfaceCount = DisplayController.DisplayConfig.GetNumSurfacesForViewerEye(ViewerIndex, (byte)eyeIndex);
eye.CreateSurfaces(eyeSurfaceCount);
}
}
}
//Get an updated tracker position + orientation
public OSVR.ClientKit.Pose3 GetViewerPose(uint viewerIndex)
{
return DisplayController.DisplayConfig.GetViewerPose(viewerIndex);
}
//Updates the position and rotation of the head
public void UpdateViewerHeadPose(OSVR.ClientKit.Pose3 headPose)
{
cachedTransform.localPosition = Math.ConvertPosition(headPose.translation);
cachedTransform.localRotation = Math.ConvertOrientation(headPose.rotation);
}
//Update the pose of each eye, then update and render each eye's surfaces
public void UpdateEyes()
{
if (DisplayController.UseRenderManager)
{
//Update RenderInfo
#if UNITY_5_2 || UNITY_5_3 || UNITY_5_4
GL.IssuePluginEvent(DisplayController.RenderManager.GetRenderEventFunction(), OsvrRenderManager.UPDATE_RENDERINFO_EVENT);
#else
Debug.LogError("[OSVR-Unity] GL.IssuePluginEvent failed. This version of Unity cannot support RenderManager.");
DisplayController.UseRenderManager = false;
#endif
}
else
{
DisplayController.UpdateClient();
}
for (uint eyeIndex = 0; eyeIndex < EyeCount; eyeIndex++)
{
//update the eye pose
VREye eye = Eyes[eyeIndex];
if (DisplayController.UseRenderManager)
{
//get eye pose from RenderManager
eye.UpdateEyePose(DisplayController.RenderManager.GetRenderManagerEyePose((byte)eyeIndex));
}
else
{
//get eye pose from DisplayConfig
eye.UpdateEyePose(_displayController.DisplayConfig.GetViewerEyePose(ViewerIndex, (byte)eyeIndex));
}
// update the eye's surfaces, includes call to Render
eye.UpdateSurfaces();
}
}
//helper method for updating the client context
public void UpdateClient()
{
DisplayController.UpdateClient();
}
// Culling determines which objects are visible to the camera. OnPreCull is called just before this process.
// This gets called because we have a camera component, but we disable the camera here so it doesn't render.
// We have the "dummy" camera so existing Unity game code can refer to a MainCamera object.
// We update our viewer and eye transforms here because it is as late as possible before rendering happens.
// OnPreRender is not called because we disable the camera here.
void OnPreCull()
{
//leave the preview camera enabled if there is no display config
_camera.enabled = !DisplayController.CheckDisplayStartup();
DoRendering();
// Flag that we disabled the camera
_disabledCamera = true;
}
// The main rendering loop, should be called late in the pipeline, i.e. from OnPreCull
// Set our viewer and eye poses and render to each surface.
void DoRendering()
{
// update poses once DisplayConfig is ready
if (DisplayController.CheckDisplayStartup())
{
if(_hmdConnectionError)
{
_hmdConnectionError = false;
Debug.Log("[OSVR-Unity] HMD connection established. You can ignore previous error messages indicating Display Startup failure.");
}
// update the viewer's head pose
// currently getting viewer pose from DisplayConfig always
UpdateViewerHeadPose(GetViewerPose(ViewerIndex));
// each viewer updates its eye poses, viewports, projection matrices
UpdateEyes();
}
else
{
if(!_hmdConnectionError)
{
//report an error message once if the HMD is not connected
//it can take a few frames to connect under normal operation, so inidcate when this error has been resolved
_hmdConnectionError = true;
Debug.LogError("[OSVR-Unity] Display Startup failed. Check HMD connection.");
}
}
}
// This couroutine is called every frame.
IEnumerator EndOfFrame()
{
while (true)
{
yield return new WaitForEndOfFrame();
if (DisplayController.UseRenderManager && DisplayController.CheckDisplayStartup())
{
// Issue a RenderEvent, which copies Unity RenderTextures to RenderManager buffers
#if UNITY_5_2 || UNITY_5_3 || UNITY_5_4
GL.Viewport(_emptyViewport);
GL.Clear(false, true, Camera.backgroundColor);
GL.IssuePluginEvent(DisplayController.RenderManager.GetRenderEventFunction(), OsvrRenderManager.RENDER_EVENT);
if(DisplayController.showDirectModePreview)
{
Camera.Render();
}
#else
Debug.LogError("[OSVR-Unity] GL.IssuePluginEvent failed. This version of Unity cannot support RenderManager.");
DisplayController.UseRenderManager = false;
#endif
}
//if we disabled the dummy camera, enable it here
if (_disabledCamera)
{
Camera.enabled = true;
_disabledCamera = false;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace PracticeGit.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//#define DEBUGREADERS
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Excel.Core;
using System.Data;
using System.Xml;
using System.Globalization;
using ExcelDataReader.Portable.Core;
using ExcelDataReader.Portable.Core.OpenXmlFormat;
namespace Excel
{
public class ExcelOpenXmlReader : IExcelDataReader
{
#region Members
private XlsxWorkbook _workbook;
private bool _isValid;
private bool _isClosed;
private bool _isFirstRead;
private string _exceptionMessage;
private int _depth;
private int _resultIndex;
private int _emptyRowCount;
private IExcelWorker _zipWorker;
private XmlReader _xmlReader;
private Stream _sheetStream;
private object[] _cellsValues;
private object[] _savedCellsValues;
private bool disposed;
private bool _isFirstRowAsColumnNames;
private const string COLUMN = "Column";
private string instanceId = Guid.NewGuid().ToString();
private List<int> _defaultDateTimeStyles;
private string _namespaceUri;
private Encoding defaultEncoding = Encoding.UTF8;
private readonly ReadOption m_ReadOption = ReadOption.FileSystem;
#endregion
internal ExcelOpenXmlReader()
{
_isValid = true;
_isFirstRead = true;
_defaultDateTimeStyles = new List<int>(new int[]
{
14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47
});
}
internal ExcelOpenXmlReader(ReadOption readOption) : this()
{
m_ReadOption = readOption;
}
private void ReadGlobals()
{
_workbook = new XlsxWorkbook(
_zipWorker.GetWorkbookStream(),
_zipWorker.GetWorkbookRelsStream(),
_zipWorker.GetSharedStringsStream(),
_zipWorker.GetStylesStream());
CheckDateTimeNumFmts(_workbook.Styles.NumFmts);
}
private void CheckDateTimeNumFmts(List<XlsxNumFmt> list)
{
if (list.Count == 0) return;
foreach (XlsxNumFmt numFmt in list)
{
if (string.IsNullOrEmpty(numFmt.FormatCode)) continue;
string fc = numFmt.FormatCode.ToLower();
int pos;
while ((pos = fc.IndexOf('"')) > 0)
{
int endPos = fc.IndexOf('"', pos + 1);
if (endPos > 0) fc = fc.Remove(pos, endPos - pos + 1);
}
//it should only detect it as a date if it contains
//dd mm mmm yy yyyy
//h hh ss
//AM PM
//and only if these appear as "words" so either contained in [ ]
//or delimted in someway
//updated to not detect as date if format contains a #
var formatReader = new FormatReader() {FormatString = fc};
if (formatReader.IsDateFormatString())
{
_defaultDateTimeStyles.Add(numFmt.Id);
}
}
}
private void ReadSheetGlobals(XlsxWorksheet sheet)
{
if (_xmlReader != null) _xmlReader.Close();
if (_sheetStream != null) _sheetStream.Close();
_sheetStream = _zipWorker.GetWorksheetStream(sheet.Path);
if (null == _sheetStream) return;
_xmlReader = XmlReader.Create(_sheetStream);
//count rows and cols in case there is no dimension elements
int rows = 0;
int cols = 0;
_namespaceUri = null;
int biggestColumn = 0; //used when no col elements and no dimension
while (_xmlReader.Read())
{
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_worksheet)
{
//grab the namespaceuri from the worksheet element
_namespaceUri = _xmlReader.NamespaceURI;
}
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_dimension)
{
string dimValue = _xmlReader.GetAttribute(XlsxWorksheet.A_ref);
sheet.Dimension = new XlsxDimension(dimValue);
break;
}
//removed: Do not use col to work out number of columns as this is really for defining formatting, so may not contain all columns
//if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_col)
// cols++;
if (_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row)
rows++;
//check cells so we can find size of sheet if can't work it out from dimension or col elements (dimension should have been set before the cells if it was available)
//ditto for cols
if (sheet.Dimension == null && cols == 0 && _xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_c)
{
var refAttribute = _xmlReader.GetAttribute(XlsxWorksheet.A_r);
if (refAttribute != null)
{
var thisRef = ReferenceHelper.ReferenceToColumnAndRow(refAttribute);
if (thisRef[1] > biggestColumn)
biggestColumn = thisRef[1];
}
}
}
//if we didn't get a dimension element then use the calculated rows/cols to create it
if (sheet.Dimension == null)
{
if (cols == 0)
cols = biggestColumn;
if (rows == 0 || cols == 0)
{
sheet.IsEmpty = true;
return;
}
sheet.Dimension = new XlsxDimension(rows, cols);
//we need to reset our position to sheet data
_xmlReader.Close();
_sheetStream.Close();
_sheetStream = _zipWorker.GetWorksheetStream(sheet.Path);
_xmlReader = XmlReader.Create(_sheetStream);
}
//read up to the sheetData element. if this element is empty then there aren't any rows and we need to null out dimension
_xmlReader.ReadToFollowing(XlsxWorksheet.N_sheetData, _namespaceUri);
if (_xmlReader.IsEmptyElement)
{
sheet.IsEmpty = true;
}
}
private bool ReadSheetRow(XlsxWorksheet sheet)
{
if (null == _xmlReader) return false;
if (_emptyRowCount != 0)
{
_cellsValues = new object[sheet.ColumnsCount];
_emptyRowCount--;
_depth++;
return true;
}
if (_savedCellsValues != null)
{
_cellsValues = _savedCellsValues;
_savedCellsValues = null;
_depth++;
return true;
}
if ((_xmlReader.NodeType == XmlNodeType.Element && _xmlReader.LocalName == XlsxWorksheet.N_row) ||
_xmlReader.ReadToFollowing(XlsxWorksheet.N_row, _namespaceUri))
{
_cellsValues = new object[sheet.ColumnsCount];
int rowIndex = int.Parse(_xmlReader.GetAttribute(XlsxWorksheet.A_r));
if (rowIndex != (_depth + 1))
if (rowIndex != (_depth + 1))
{
_emptyRowCount = rowIndex - _depth - 1;
}
bool hasValue = false;
string a_s = String.Empty;
string a_t = String.Empty;
string a_r = String.Empty;
int col = 0;
int row = 0;
while (_xmlReader.Read())
{
if (_xmlReader.Depth == 2) break;
if (_xmlReader.NodeType == XmlNodeType.Element)
{
hasValue = false;
if (_xmlReader.LocalName == XlsxWorksheet.N_c)
{
a_s = _xmlReader.GetAttribute(XlsxWorksheet.A_s);
a_t = _xmlReader.GetAttribute(XlsxWorksheet.A_t);
a_r = _xmlReader.GetAttribute(XlsxWorksheet.A_r);
XlsxDimension.XlsxDim(a_r, out col, out row);
}
else if (_xmlReader.LocalName == XlsxWorksheet.N_v || _xmlReader.LocalName == XlsxWorksheet.N_t)
{
hasValue = true;
}
}
if (_xmlReader.NodeType == XmlNodeType.Text && hasValue)
{
double number;
object o = _xmlReader.Value;
var style = NumberStyles.Any;
var culture = CultureInfo.InvariantCulture;
if (double.TryParse(o.ToString(), style, culture, out number))
o = number;
if (null != a_t && a_t == XlsxWorksheet.A_s) //if string
{
o = Helpers.ConvertEscapeChars(_workbook.SST[int.Parse(o.ToString())]);
} // Requested change 4: missing (it appears that if should be else if)
else if (null != a_t && a_t == XlsxWorksheet.N_inlineStr) //if string inline
{
o = Helpers.ConvertEscapeChars(o.ToString());
}
else if (a_t == "b") //boolean
{
o = _xmlReader.Value == "1";
}
else if (null != a_s) //if something else
{
XlsxXf xf = _workbook.Styles.CellXfs[int.Parse(a_s)];
if (o != null && o.ToString() != string.Empty && IsDateTimeStyle(xf.NumFmtId))
o = Helpers.ConvertFromOATime(number);
else if (xf.NumFmtId == 49)
o = o.ToString();
}
if (col - 1 < _cellsValues.Length)
_cellsValues[col - 1] = o;
}
}
if (_emptyRowCount > 0)
{
_savedCellsValues = _cellsValues;
return ReadSheetRow(sheet);
}
_depth++;
return true;
}
_xmlReader.Close();
if (_sheetStream != null) _sheetStream.Close();
return false;
}
private bool InitializeSheetRead()
{
if (ResultsCount <= 0) return false;
ReadSheetGlobals(_workbook.Sheets[_resultIndex]);
if (_workbook.Sheets[_resultIndex].Dimension == null) return false;
_isFirstRead = false;
_depth = 0;
_emptyRowCount = 0;
return true;
}
private bool IsDateTimeStyle(int styleId)
{
return _defaultDateTimeStyles.Contains(styleId);
}
#region IExcelDataReader Members
public void Initialize(System.IO.Stream fileStream)
{
if (ReadOption == ReadOption.FileSystem)
_zipWorker = new ZipWorker();
else if (ReadOption == ReadOption.Memory)
_zipWorker = new MemoryWorker();
else throw new Exception("Unsupported ReadOption, please use FileSystem or Memory instead");
_zipWorker.Extract(fileStream);
if (!_zipWorker.IsValid)
{
_isValid = false;
_exceptionMessage = _zipWorker.ExceptionMessage;
Close();
return;
}
ReadGlobals();
}
public System.Data.DataSet AsDataSet()
{
return AsDataSet(true);
}
public System.Data.DataSet AsDataSet(bool convertOADateTime)
{
if (!_isValid) return null;
DataSet dataset = new DataSet();
for (int ind = 0; ind < _workbook.Sheets.Count; ind++)
{
DataTable table = new DataTable(_workbook.Sheets[ind].Name);
table.ExtendedProperties.Add("visiblestate", _workbook.Sheets[ind].VisibleState);
ReadSheetGlobals(_workbook.Sheets[ind]);
if (_workbook.Sheets[ind].Dimension == null) continue;
_depth = 0;
_emptyRowCount = 0;
//DataTable columns
if (!_isFirstRowAsColumnNames)
{
for (int i = 0; i < _workbook.Sheets[ind].ColumnsCount; i++)
{
table.Columns.Add(null, typeof(Object));
}
}
else if (ReadSheetRow(_workbook.Sheets[ind]))
{
for (int index = 0; index < _cellsValues.Length; index++)
{
if (_cellsValues[index] != null && _cellsValues[index].ToString().Length > 0)
Helpers.AddColumnHandleDuplicate(table, _cellsValues[index].ToString());
else
Helpers.AddColumnHandleDuplicate(table, string.Concat(COLUMN, index));
}
}
else continue;
table.BeginLoadData();
while (ReadSheetRow(_workbook.Sheets[ind]))
{
table.Rows.Add(_cellsValues);
}
if (table.Rows.Count > 0)
dataset.Tables.Add(table);
table.EndLoadData();
}
dataset.AcceptChanges();
Helpers.FixDataTypes(dataset);
return dataset;
}
public ReadOption ReadOption
{
get { return m_ReadOption; }
}
public bool IsFirstRowAsColumnNames
{
get
{
return _isFirstRowAsColumnNames;
}
set
{
_isFirstRowAsColumnNames = value;
}
}
public Encoding Encoding
{
get { return null; }
}
public Encoding DefaultEncoding
{
get { return defaultEncoding; }
}
public bool IsValid
{
get { return _isValid; }
}
public string ExceptionMessage
{
get { return _exceptionMessage; }
}
public string Name
{
get
{
return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].Name : null;
}
}
public string VisibleState
{
get
{
return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].VisibleState : null;
}
}
public void Close()
{
_isClosed = true;
if (_xmlReader != null) _xmlReader.Close();
if (_sheetStream != null) _sheetStream.Close();
if (_zipWorker != null) _zipWorker.Dispose();
}
public int Depth
{
get { return _depth; }
}
public int ResultsCount
{
get { return _workbook == null ? -1 : _workbook.Sheets.Count; }
}
public bool IsClosed
{
get { return _isClosed; }
}
public bool NextResult()
{
if (_resultIndex >= (this.ResultsCount - 1)) return false;
_resultIndex++;
_isFirstRead = true;
_savedCellsValues = null;
return true;
}
public bool Read()
{
if (!_isValid) return false;
if (_isFirstRead && !InitializeSheetRead())
{
return false;
}
return ReadSheetRow(_workbook.Sheets[_resultIndex]);
}
public int FieldCount
{
get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].ColumnsCount : -1; }
}
public bool GetBoolean(int i)
{
if (IsDBNull(i)) return false;
return Boolean.Parse(_cellsValues[i].ToString());
}
public DateTime GetDateTime(int i)
{
if (IsDBNull(i)) return DateTime.MinValue;
try
{
return (DateTime)_cellsValues[i];
}
catch (InvalidCastException)
{
return DateTime.MinValue;
}
}
public decimal GetDecimal(int i)
{
if (IsDBNull(i)) return decimal.MinValue;
return decimal.Parse(_cellsValues[i].ToString());
}
public double GetDouble(int i)
{
if (IsDBNull(i)) return double.MinValue;
return double.Parse(_cellsValues[i].ToString());
}
public float GetFloat(int i)
{
if (IsDBNull(i)) return float.MinValue;
return float.Parse(_cellsValues[i].ToString());
}
public short GetInt16(int i)
{
if (IsDBNull(i)) return short.MinValue;
return short.Parse(_cellsValues[i].ToString());
}
public int GetInt32(int i)
{
if (IsDBNull(i)) return int.MinValue;
return int.Parse(_cellsValues[i].ToString());
}
public long GetInt64(int i)
{
if (IsDBNull(i)) return long.MinValue;
return long.Parse(_cellsValues[i].ToString());
}
public string GetString(int i)
{
if (IsDBNull(i)) return null;
return _cellsValues[i].ToString();
}
public object GetValue(int i)
{
return _cellsValues[i];
}
public bool IsDBNull(int i)
{
return (null == _cellsValues[i]) || (DBNull.Value == _cellsValues[i]);
}
public object this[int i]
{
get { return _cellsValues[i]; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
if (disposing)
{
if (_xmlReader != null) ((IDisposable) _xmlReader).Dispose();
if (_sheetStream != null) _sheetStream.Dispose();
if (_zipWorker != null) _zipWorker.Dispose();
}
_zipWorker = null;
_xmlReader = null;
_sheetStream = null;
_workbook = null;
_cellsValues = null;
_savedCellsValues = null;
disposed = true;
}
}
~ExcelOpenXmlReader()
{
Dispose(false);
}
#endregion
#region Not Supported IDataReader Members
public DataTable GetSchemaTable()
{
throw new NotSupportedException();
}
public int RecordsAffected
{
get { throw new NotSupportedException(); }
}
#endregion
#region Not Supported IDataRecord Members
public byte GetByte(int i)
{
throw new NotSupportedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public char GetChar(int i)
{
throw new NotSupportedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public IDataReader GetData(int i)
{
throw new NotSupportedException();
}
public string GetDataTypeName(int i)
{
throw new NotSupportedException();
}
public Type GetFieldType(int i)
{
throw new NotSupportedException();
}
public Guid GetGuid(int i)
{
throw new NotSupportedException();
}
public string GetName(int i)
{
throw new NotSupportedException();
}
public int GetOrdinal(string name)
{
throw new NotSupportedException();
}
public int GetValues(object[] values)
{
throw new NotSupportedException();
}
public object this[string name]
{
get { throw new NotSupportedException(); }
}
#endregion
}
}
| |
using NBitcoin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using NBitpayClient.Extensions;
namespace NBitpayClient
{
public class Facade
{
public static Facade Merchant = new Facade("merchant");
public static Facade PointOfSale = new Facade("pos");
public static Facade User = new Facade("user");
public static Facade Payroll = new Facade("payroll");
readonly string _Value;
public Facade(string value)
{
if(value == null)
throw new ArgumentNullException(nameof(value));
_Value = value;
}
public override bool Equals(object obj)
{
Facade item = obj as Facade;
if(item == null)
return false;
return _Value.Equals(item._Value);
}
public static bool operator ==(Facade a, Facade b)
{
if(ReferenceEquals(a, b))
return true;
if((object)a == null || (object)b == null)
return false;
return a._Value == b._Value;
}
public static bool operator !=(Facade a, Facade b)
{
return !(a == b);
}
public override int GetHashCode()
{
return _Value.GetHashCode();
}
public override string ToString()
{
return _Value;
}
}
public class PairingCode
{
public PairingCode(string value)
{
_Value = value ?? throw new ArgumentNullException(nameof(value));
}
readonly string _Value;
public override string ToString()
{
return _Value;
}
public Uri CreateLink(Uri baseUrl)
{
var link = baseUrl.AbsoluteUri;
if(!link.EndsWith("/"))
link = link + "/";
link = link + "api-access-request?pairingCode=" + _Value;
return new Uri(link);
}
}
public class Bitpay
{
public class AccessToken
{
public string Key
{
get; set;
}
public string Value
{
get; set;
}
}
class AuthInformation
{
public AuthInformation(Key key)
{
if(key == null)
throw new ArgumentNullException(nameof(key));
SIN = key.PubKey.GetBitIDSIN();
Key = key;
}
public Key Key
{
get;
private set;
}
public string SIN
{
get;
private set;
}
internal void Sign(HttpRequestMessage message)
{
var uri = message.RequestUri.AbsoluteUri;
var body = message.Content?.ReadAsStringAsync()?.GetAwaiter().GetResult(); //no await is ok, no network access
message.Headers.Add("x-signature", Key.GetBitIDSignature(uri, body));
message.Headers.Add("x-identity", Key.PubKey.ToHex());
}
ConcurrentDictionary<string, AccessToken> _Tokens = new ConcurrentDictionary<string, AccessToken>();
public AccessToken GetAccessToken(Facade requirement)
{
var token = _Tokens.TryGet(requirement.ToString());
if(token == null && (requirement == Facade.User || requirement == Facade.PointOfSale))
{
token = _Tokens.TryGet(Facade.PointOfSale.ToString()) ?? _Tokens.TryGet(Facade.Merchant.ToString());
}
return token;
}
public void SaveTokens(AccessToken[] tokens)
{
foreach(var token in tokens)
_Tokens.TryAdd(token.Key, token);
}
public void SaveToken(string key, string value)
{
_Tokens.TryAdd(key, new AccessToken() { Key = key, Value = value });
}
}
private const String BITPAY_API_VERSION = "2.0.0";
private Uri _baseUrl = null;
AuthInformation _Auth;
static HttpClient _Client = new HttpClient();
public string SIN
{
get
{
return _Auth.SIN;
}
}
public Uri BaseUrl
{
get
{
return _baseUrl;
}
}
/// <summary>
/// Constructor for use if the keys and SIN were derived external to this library.
/// </summary>
/// <param name="ecKey">An elliptical curve key.</param>
/// <param name="clientName">The label for this client.</param>
/// <param name="envUrl">The target server URL.</param>
public Bitpay(Key ecKey, Uri envUrl)
{
if(ecKey == null)
throw new ArgumentNullException(nameof(ecKey));
if(envUrl == null)
throw new ArgumentNullException(nameof(envUrl));
_Auth = new AuthInformation(ecKey);
_baseUrl = envUrl;
}
/// <summary>
/// Authorize (pair) this client with the server using the specified pairing code.
/// </summary>
/// <param name="pairingCode">A code obtained from the server; typically from bitpay.com/api-tokens.</param>
public virtual async Task AuthorizeClient(PairingCode pairingCode)
{
Token token = new Token();
token.Id = _Auth.SIN;
token.Guid = Guid.NewGuid().ToString();
token.PairingCode = pairingCode.ToString();
token.Label = "DEFAULT";
String json = JsonConvert.SerializeObject(token);
HttpResponseMessage response = await this.PostAsync("tokens", json).ConfigureAwait(false);
var tokens = await this.ParseResponse<List<Token>>(response).ConfigureAwait(false);
foreach(Token t in tokens)
{
_Auth.SaveToken(t.Facade, t.Value);
}
}
/// <summary>
/// Request authorization (a token) for this client in the specified facade.
/// </summary>
/// <param name="label">The label of this token.</param>
/// <param name="facade">The facade for which authorization is requested.</param>
/// <returns>A pairing code for this client. This code must be used to authorize this client at BitPay.com/api-tokens.</returns>
public virtual PairingCode RequestClientAuthorization(string label, Facade facade)
{
return RequestClientAuthorizationAsync(label, facade).GetAwaiter().GetResult();
}
/// <summary>
/// Request authorization (a token) for this client in the specified facade.
/// </summary>
/// <param name="label">The label of this token.</param>
/// <param name="facade">The facade for which authorization is requested.</param>
/// <returns>A pairing code for this client. This code must be used to authorize this client at BitPay.com/api-tokens.</returns>
public virtual async Task<PairingCode> RequestClientAuthorizationAsync(string label, Facade facade)
{
Token token = new Token();
token.Id = _Auth.SIN;
token.Guid = Guid.NewGuid().ToString();
token.Facade = facade.ToString();
token.Count = 1;
token.Label = label ?? "DEFAULT";
String json = JsonConvert.SerializeObject(token);
HttpResponseMessage response = await this.PostAsync("tokens", json).ConfigureAwait(false);
var tokens = await this.ParseResponse<List<Token>>(response).ConfigureAwait(false);
// Expecting a single token resource.
if(tokens.Count != 1)
{
throw new BitPayException("Error - failed to get token resource; expected 1 token, got " + tokens.Count);
}
_Auth.SaveToken(tokens[0].Facade, tokens[0].Value);
return new PairingCode(tokens[0].PairingCode);
}
/// <summary>
/// Create an invoice using the specified facade.
/// </summary>
/// <param name="invoice">An invoice request object.</param>
/// <param name="facade">The facade used (default POS).</param>
/// <returns>A new invoice object returned from the server.</returns>
public virtual Invoice CreateInvoice(Invoice invoice, Facade facade = null)
{
return CreateInvoiceAsync(invoice, facade).GetAwaiter().GetResult();
}
/// <summary>
/// Create an invoice using the specified facade.
/// </summary>
/// <param name="invoice">An invoice request object.</param>
/// <param name="facade">The facade used (default POS).</param>
/// <returns>A new invoice object returned from the server.</returns>
public virtual async Task<Invoice> CreateInvoiceAsync(Invoice invoice, Facade facade = null)
{
facade = facade ?? Facade.PointOfSale;
invoice.Token = (await this.GetAccessTokenAsync(facade).ConfigureAwait(false)).Value;
invoice.Guid = Guid.NewGuid().ToString();
String json = JsonConvert.SerializeObject(invoice);
HttpResponseMessage response = await this.PostAsync("invoices", json, true).ConfigureAwait(false);
invoice = await this.ParseResponse<Invoice>(response).ConfigureAwait(false);
// Track the token for this invoice
//_Auth.SaveToken(invoice.Id, invoice.Token);
return invoice;
}
/// <summary>
/// Retrieve an invoice by id and token.
/// </summary>
/// <param name="invoiceId">The id of the requested invoice.</param>
/// <param name="facade">The facade used (default POS).</param>
/// <returns>The invoice object retrieved from the server.</returns>
public virtual Invoice GetInvoice(String invoiceId, Facade facade = null)
{
return GetInvoiceAsync(invoiceId, facade).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve an invoice by id and token.
/// </summary>
/// <param name="invoiceId">The id of the requested invoice.</param>
/// <param name="facade">The facade used (default POS).</param>
/// <returns>The invoice object retrieved from the server.</returns>
public virtual async Task<Invoice> GetInvoiceAsync(String invoiceId, Facade facade = null)
{
return await GetInvoiceAsync<Invoice>(invoiceId, facade);
}
/// <summary>
/// Retrieve an invoice by id and token.
/// </summary>
/// <param name="invoiceId">The id of the requested invoice.</param>
/// <param name="facade">The facade used (default POS).</param>
/// <returns>The invoice object retrieved from the server.</returns>
public virtual async Task<T> GetInvoiceAsync<T>(String invoiceId, Facade facade = null) where T : Invoice
{
facade = facade ?? Facade.Merchant;
// Provide the merchant token whenthe merchant facade is being used.
// GET/invoices expects the merchant token and not the merchant/invoice token.
HttpResponseMessage response = null;
if (facade == Facade.Merchant)
{
var token = (await GetAccessTokenAsync(facade).ConfigureAwait(false)).Value;
response = await this.GetAsync($"invoices/{invoiceId}?token={token}", true).ConfigureAwait(false);
}
else
{
response = await GetAsync($"invoices/" + invoiceId, true).ConfigureAwait(false);
}
return await ParseResponse<T>(response).ConfigureAwait(false);
}
/// <summary>
/// Retrieves settlement reports for the calling merchant filtered by query. The `limit` and `offset` parameters specify pages for large query sets.
/// </summary>
/// <param name="startDate">Date filter start (optional)</param>
/// <param name="endDate">Date filter end (optional)</param>
/// <param name="currency">Currency filter (optional)</param>
/// <param name="status">Status filter (optional)</param>
/// <param name="limit">Pagination entries ceiling (default:50)</param>
/// <param name="offset">Pagination quantity offset (default:0)</param>
/// <returns>Array of Settlements</returns>
public virtual SettlementSummary[] GetSettlements(DateTime? startDate = null, DateTime? endDate = null, string currency = null, string status = null, int limit = 50, int offset = 0)
{
return GetSettlementsAsync(startDate, endDate, currency, status, limit, offset).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves settlement reports for the calling merchant filtered by query. The `limit` and `offset` parameters specify pages for large query sets.
/// </summary>
/// <param name="startDate">Date filter start (optional)</param>
/// <param name="endDate">Date filter end (optional)</param>
/// <param name="currency">Currency filter (optional)</param>
/// <param name="status">Status filter (optional)</param>
/// <param name="limit">Pagination entries ceiling (default:50)</param>
/// <param name="offset">Pagination quantity offset (default:0)</param>
/// <returns>Array of Settlements</returns>
public virtual async Task<SettlementSummary[]> GetSettlementsAsync(DateTime? startDate = null, DateTime? endDate = null, string currency = null, string status = null, int limit = 50, int offset = 0)
{
var token = await this.GetAccessTokenAsync(Facade.Merchant).ConfigureAwait(false);
var parameters = new Dictionary<string, string>();
parameters.Add("token", token.Value);
if (startDate != null)
parameters.Add("startDate", startDate.Value.ToString("d", CultureInfo.InvariantCulture));
if (endDate != null)
parameters.Add("endDate", endDate.Value.ToString("d", CultureInfo.InvariantCulture));
if (currency != null)
parameters.Add("currency", currency);
if (status != null)
parameters.Add("status", status);
parameters.Add("limit", $"{limit}");
parameters.Add("offset", $"{offset}");
var response = await GetAsync("settlements" + BuildQuery(parameters), true).ConfigureAwait(false);
return await ParseResponse<SettlementSummary[]>(response).ConfigureAwait(false);
}
/// <summary>
/// Retrieves a summary of the specified settlement.
/// </summary>
/// <param name="settlementId">Id of the settlement to fetch</param>
/// <returns>Settlement object</returns>
public virtual SettlementSummary GetSettlementSummary(string settlementId)
{
return GetSettlementSummaryAsync(settlementId).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves a summary of the specified settlement.
/// </summary>
/// <param name="settlementId">Id of the settlement to fetch</param>
/// <returns>Settlement object</returns>
public virtual async Task<SettlementSummary> GetSettlementSummaryAsync(string settlementId)
{
var token = (await GetAccessTokenAsync(Facade.Merchant).ConfigureAwait(false)).Value;
var response = await GetAsync($"settlements/{settlementId}?token={token}", true).ConfigureAwait(false);
return await ParseResponse<SettlementSummary>(response).ConfigureAwait(false);
}
/// <summary>
/// Gets a detailed reconciliation report of the activity within the settlement period
/// </summary>
/// <param name="settlementId">Id of the settlement to fetch</param>
/// <param name="settlementSummaryToken">Resource token from /settlements/{settlementId}</param>
/// <returns>SettlementReconciliationReport object</returns>
public virtual SettlementReconciliationReport GetSettlementReconciliationReport(string settlementId, string settlementSummaryToken)
{
return GetSettlementReconciliationReportAsync(settlementId, settlementSummaryToken).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a detailed reconciliation report of the activity within the settlement period
/// </summary>
/// <param name="settlementId">Id of the settlement to fetch</param>
/// <param name="settlementSummaryToken">Resource token from /settlements/{settlementId}</param>
/// <returns>SettlementReconciliationReport object</returns>
public virtual async Task<SettlementReconciliationReport> GetSettlementReconciliationReportAsync(string settlementId, string settlementSummaryToken)
{
var response = await GetAsync($"settlements/{settlementId}/reconciliationReport?token={settlementSummaryToken}", true).ConfigureAwait(false);
return await ParseResponse<SettlementReconciliationReport>(response).ConfigureAwait(false);
}
/// <summary>
/// Retrieve a list of invoices by date range using the merchant facade.
/// </summary>
/// <param name="dateStart">The start date for the query.</param>
/// <param name="dateEnd">The end date for the query.</param>
/// <returns>A list of invoice objects retrieved from the server.</returns>
public virtual Invoice[] GetInvoices(DateTime? dateStart = null, DateTime? dateEnd = null)
{
return GetInvoicesAsync(dateStart, dateEnd).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of invoices by date range using the merchant facade.
/// </summary>
/// <param name="dateStart">The start date for the query.</param>
/// <param name="dateEnd">The end date for the query.</param>
/// <returns>A list of invoice objects retrieved from the server.</returns>
public virtual async Task<Invoice[]> GetInvoicesAsync(DateTime? dateStart = null, DateTime? dateEnd = null)
{
return await GetInvoicesAsync<Invoice>(dateStart, dateEnd);
}
/// <summary>
/// Retrieve a list of invoices by date range using the merchant facade.
/// </summary>
/// <param name="dateStart">The start date for the query.</param>
/// <param name="dateEnd">The end date for the query.</param>
/// <returns>A list of invoice objects retrieved from the server.</returns>
public virtual async Task<T[]> GetInvoicesAsync<T>(DateTime? dateStart = null, DateTime? dateEnd = null) where T:Invoice
{
var token = await this.GetAccessTokenAsync(Facade.Merchant).ConfigureAwait(false);
var parameters = new Dictionary<string, string>();
parameters.Add("token", token.Value);
if(dateStart != null)
parameters.Add("dateStart", dateStart.Value.ToString("d", CultureInfo.InvariantCulture));
if(dateEnd != null)
parameters.Add("dateEnd", dateEnd.Value.ToString("d", CultureInfo.InvariantCulture));
var response = await GetAsync($"invoices" + BuildQuery(parameters), true).ConfigureAwait(false);
return await ParseResponse<T[]>(response).ConfigureAwait(false);
}
private string BuildQuery(Dictionary<string, string> parameters)
{
var result = string.Join("&", parameters
.Select(p => $"{p.Key}={p.Value}")
.ToArray());
if(string.IsNullOrEmpty(result))
return string.Empty;
return "?" + result;
}
/// <summary>
/// Retrieve the exchange rate table using the public facade.
/// </summary>
/// <param name="baseCurrencyCode">What currency to base the result rates on</param>
/// <returns>The rate table as an object retrieved from the server.</returns>
public virtual Rates GetRates(string baseCurrencyCode = null)
{
return GetRatesAsync(baseCurrencyCode).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the exchange rate table using the public facade.
/// </summary>
/// <param name="baseCurrencyCode">What currency to base the result rates on</param>
/// <returns>The rate table as an object retrieved from the server.</returns>
public virtual async Task<Rates> GetRatesAsync(string baseCurrencyCode = null)
{
var url = $"rates{(string.IsNullOrEmpty(baseCurrencyCode) ? $"/{baseCurrencyCode}" : String.Empty)}";
HttpResponseMessage response = await this.GetAsync(url, true).ConfigureAwait(false);
var rates = await this.ParseResponse<List<Rate>>(response).ConfigureAwait(false);
return new Rates(rates);
}
/// <summary>
/// Retrieves the exchange rate for the given currency using the public facade.
/// </summary>
/// <param name="baseCurrencyCode">The currency to base the result rate on</param>
/// <param name="currencyCode">The target currency to get the rate for</param>
/// <returns>The rate as an object retrieved from the server.</returns>
public Rate GetRate(string baseCurrencyCode, string currencyCode)
{
return GetRateAsync(baseCurrencyCode, currencyCode).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves the exchange rate for the given currency using the public facade.
/// </summary>
/// <param name="baseCurrencyCode">The currency to base the result rate on</param>
/// <param name="currencyCode">The target currency to get the rate for</param>
/// <returns>The rate as an object retrieved from the server.</returns>
public virtual async Task<Rate> GetRateAsync(string baseCurrencyCode, string currencyCode)
{
var url = $"rates/{baseCurrencyCode}/{currencyCode}";
HttpResponseMessage response = await this.GetAsync(url, true).ConfigureAwait(false);
var rate = await this.ParseResponse<Rate>(response).ConfigureAwait(false);
return rate;
}
/// <summary>
/// Retrieves the caller's ledgers for each currency with summary.
/// </summary>
/// <returns>A list of ledger objects retrieved from the server.</returns>
public virtual List<Ledger> GetLedgers()
{
return GetLedgersAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves the caller's ledgers for each currency with summary.
/// </summary>
/// <returns>A list of ledger objects retrieved from the server.</returns>
public virtual async Task<List<Ledger>> GetLedgersAsync()
{
var token = await this.GetAccessTokenAsync(Facade.Merchant).ConfigureAwait(false);
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("token", token.Value);
HttpResponseMessage response = await this.GetAsync($"ledgers/" + BuildQuery(parameters), true).ConfigureAwait(false);
var ledgers = await this.ParseResponse<List<Ledger>>(response).ConfigureAwait(false);
return ledgers;
}
/// <summary>
/// Retrieve a list of ledger entries by date range using the merchant facade.
/// </summary>
/// <param name="currency">The three digit currency string for the ledger to retrieve.</param>
/// <param name="dateStart">The start date for the query.</param>
/// <param name="dateEnd">The end date for the query.</param>
/// <returns>A list of invoice objects retrieved from the server.</returns>
public virtual Ledger GetLedger(String currency, DateTime? dateStart = null, DateTime? dateEnd = null)
{
return GetLedgerAsync(currency, dateStart, dateEnd).GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of ledger entries by date range using the merchant facade.
/// </summary>
/// <param name="currency">The three digit currency string for the ledger to retrieve.</param>
/// <param name="dateStart">The start date for the query.</param>
/// <param name="dateEnd">The end date for the query.</param>
/// <returns>A list of invoice objects retrieved from the server.</returns>
public virtual async Task<Ledger> GetLedgerAsync(String currency, DateTime? dateStart = null, DateTime? dateEnd = null)
{
var token = await this.GetAccessTokenAsync(Facade.Merchant).ConfigureAwait(false);
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("token", token.Value);
if(dateStart != null)
parameters.Add("startDate", dateStart.Value.ToString("d", CultureInfo.InvariantCulture));
if(dateEnd != null)
parameters.Add("endDate", dateEnd.Value.ToString("d", CultureInfo.InvariantCulture));
HttpResponseMessage response = await this.GetAsync($"ledgers/{currency}" + BuildQuery(parameters), true).ConfigureAwait(false);
var entries = await this.ParseResponse<List<LedgerEntry>>(response).ConfigureAwait(false);
return new Ledger(null, 0, entries);
}
private AccessToken[] ParseTokens(string response)
{
List<AccessToken> tokens = new List<AccessToken>();
try
{
JArray obj = (JArray)JObject.Parse(response).First.First;
foreach(var jobj in obj.OfType<JObject>())
{
foreach(var prop in jobj.Properties())
{
tokens.Add(new AccessToken() { Key = prop.Name, Value = prop.Value.Value<string>() });
}
}
return tokens.ToArray();
}
catch(Exception ex)
{
throw new BitPayException("Error: response to GET /tokens could not be parsed - " + ex.ToString());
}
}
public virtual async Task<AccessToken[]> GetAccessTokensAsync()
{
HttpResponseMessage response = await this.GetAsync("tokens", true).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
return new AccessToken[0];
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return ParseTokens(result);
}
/// <summary>
/// Test access to a facade
/// </summary>
/// <param name="facade">The facade</param>
/// <returns>True authorized, else false</returns>
public virtual bool TestAccess(Facade facade)
{
return TestAccessAsync(facade).GetAwaiter().GetResult();
}
/// <summary>
/// Test access to a facade
/// </summary>
/// <param name="facade">The facade</param>
/// <returns>True if authorized, else false</returns>
public virtual async Task<bool> TestAccessAsync(Facade facade)
{
if(facade == null)
throw new ArgumentNullException(nameof(facade));
var auth = _Auth;
var token = auth.GetAccessToken(facade);
if(token != null)
return true;
var tokens = await GetAccessTokensAsync().ConfigureAwait(false);
auth.SaveTokens(tokens);
token = auth.GetAccessToken(facade);
return token != null;
}
public virtual async Task<AccessToken> GetAccessTokenAsync(Facade facade)
{
var auth = _Auth;
var token = auth.GetAccessToken(facade);
if(token != null)
return token;
var tokens = await GetAccessTokensAsync().ConfigureAwait(false);
auth.SaveTokens(tokens);
token = auth.GetAccessToken(facade);
if(token == null)
throw new BitPayException("Error: You do not have access to facade: " + facade);
return token;
}
private async Task<HttpResponseMessage> GetAsync(String path, bool sign)
{
try
{
var message = new HttpRequestMessage(HttpMethod.Get, GetFullUri(path));
message.Headers.Add("x-accept-version", BITPAY_API_VERSION);
if(sign)
{
_Auth.Sign(message);
}
var result = await _Client.SendAsync(message).ConfigureAwait(false);
return result;
}
catch(Exception ex)
{
throw new BitPayException("Error: " + ex.ToString());
}
}
private async Task<HttpResponseMessage> PostAsync(String path, String json, bool signatureRequired = false)
{
try
{
var message = new HttpRequestMessage(HttpMethod.Post, GetFullUri(path));
message.Headers.Add("x-accept-version", BITPAY_API_VERSION);
message.Content = new StringContent(json, Encoding.UTF8, "application/json");
if(signatureRequired)
{
_Auth.Sign(message);
}
var result = await _Client.SendAsync(message).ConfigureAwait(false);
return result;
}
catch(Exception ex)
{
throw new BitPayException("Error: " + ex.ToString());
}
}
private string GetFullUri(string relativePath)
{
var uri = _baseUrl.AbsoluteUri;
if(!uri.EndsWith("/", StringComparison.Ordinal))
uri += "/";
uri += relativePath;
return uri;
}
private async Task<T> ParseResponse<T>(HttpResponseMessage response)
{
if(response == null)
{
throw new BitPayException("Error: HTTP response is null");
}
// Get the response as a dynamic object for detecting possible error(s) or data object.
// An error(s) object raises an exception.
// A data object has its content extracted (throw away the data wrapper object).
String responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if(responseString.Length > 0 && responseString[0] == '[') {
// some endpoints return an array at the root (like /Ledgers/{currency}).
// without short circuiting here, the JObject.Parse will throw
return JsonConvert.DeserializeObject<T>(responseString);
}
JObject obj = null;
try
{
obj = JObject.Parse(responseString);
}
catch
{
// Probably a http error, send this instead of parsing error.
response.EnsureSuccessStatusCode();
throw;
}
// Check for error response.
if (obj.Property("error") != null)
{
var ex = new BitPayException();
ex.AddError(obj.Property("error").Value.ToString());
throw ex;
}
if(obj.Property("errors") != null)
{
var ex = new BitPayException();
foreach(var errorItem in ((JArray)obj.Property("errors").Value).OfType<JObject>())
{
ex.AddError(errorItem.Property("error").Value.ToString() + " " + errorItem.Property("param").Value.ToString());
}
throw ex;
}
T data = default(T);
// Check for and exclude a "data" object from the response.
if(obj.Property("data") != null)
{
responseString = JObject.Parse(responseString).SelectToken("data").ToString();
data = JsonConvert.DeserializeObject<T>(responseString);
}
return data;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void XorUInt64()
{
var test = new SimpleBinaryOpTest__XorUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorUInt64
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int Op2ElementCount = VectorSize / sizeof(UInt64);
private const int RetElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable;
static SimpleBinaryOpTest__XorUInt64()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__XorUInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Xor(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Xor(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Xor(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorUInt64();
var result = Sse2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
if ((ulong)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((ulong)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.AppService.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.AppService.Fluent.Models;
using System.Collections.Generic;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System;
/// <summary>
/// The implementation for DeploymentSlot.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmFwcHNlcnZpY2UuaW1wbGVtZW50YXRpb24uRGVwbG95bWVudFNsb3RCYXNlSW1wbA==
internal partial class DeploymentSlotBaseImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT, ParentT, ParentImplT, ParentWithCreateT, ParentDefAfterRegionT, ParentDefAfterGroupT, ParentUpdateT> :
WebAppBaseImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>
where FluentImplT : DeploymentSlotBaseImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT, ParentT, ParentImplT, ParentWithCreateT, ParentDefAfterRegionT, ParentDefAfterGroupT, ParentUpdateT>, FluentT
where FluentT : class, IWebAppBase
where ParentImplT : AppServiceBaseImpl<ParentT, ParentImplT, ParentWithCreateT, ParentDefAfterRegionT, ParentDefAfterGroupT, ParentUpdateT>, ParentT
where ParentT : class, IWebAppBase
where DefAfterRegionT : class
where DefAfterGroupT : class
where ParentWithCreateT: class
where ParentDefAfterGroupT: class
where ParentDefAfterRegionT: class
where UpdateT : class, WebAppBase.Update.IUpdate<FluentT>
where ParentUpdateT : class, WebAppBase.Update.IUpdate<ParentT>
{
private ParentImplT parent;
private string name;
internal IWebAppBase configurationSource;
///GENMHASH:A8A7ED895B55687EE960176ECD2570B6:A1DEA977D740E0ACAD3D94D991CA9F7F
internal override async Task<Models.SiteConfigResourceInner> CreateOrUpdateSiteConfigAsync(SiteConfigResourceInner siteConfig, CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.CreateOrUpdateConfigurationSlotAsync(ResourceGroupName, this.parent.Name, siteConfig, Name, cancellationToken);
}
///GENMHASH:FD5D5A8D6904B467321E345BE1FA424E:80F5862E3CF492064E2DDA45507B09B8
public ParentImplT Parent()
{
return this.parent;
}
///GENMHASH:924482EE7AA6A01820720743C2A59A72:E50B17913B8A65047092DD2C6D6AFE8C
public override void ApplySlotConfigurations(string slotName)
{
Extensions.Synchronize(() => ApplySlotConfigurationsAsync(slotName));
}
///GENMHASH:620993DCE6DF78140D8125DD97478452:897C9FB93A39950E97CA9111CAE33AAD
internal override async Task<Models.StringDictionaryInner> ListAppSettingsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.ListApplicationSettingsSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken);
}
///GENMHASH:FEB63CBC1CA7D22A121F19D94AB44052:4EE46F34B076F4B43C1E61C5E9ADD07C
public override async Task RestartAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.WebApps.RestartSlotAsync(ResourceGroupName, parent.Name, Name, null, null, cancellationToken);
await RefreshAsync(cancellationToken);
}
///GENMHASH:62F8B201D885123D1E906E306D144662:88BEE6CEAD1A9FC39C629C20B3DA3F56
internal override async Task<Models.SlotConfigNamesResourceInner> UpdateSlotConfigurationsAsync(SlotConfigNamesResourceInner inner, CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.UpdateSlotConfigurationNamesAsync(ResourceGroupName, parent.Name, inner, cancellationToken);
}
///GENMHASH:88806945F575AAA522C2E09EBC366CC0:648365CFF3D36F6215B51C13E63240EA
internal override async Task<Models.SiteSourceControlInner> CreateOrUpdateSourceControlAsync(SiteSourceControlInner inner, CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.CreateOrUpdateSourceControlSlotAsync(ResourceGroupName, parent.Name, inner, Name, cancellationToken);
}
///GENMHASH:1AD5C303B4B7C1709305A18733B506B2:0BA6545E2E5A5E654CE278DD5968E11F
public override void ResetSlotConfigurations()
{
Extensions.Synchronize(() => Manager.Inner.WebApps.ResetSlotConfigurationSlotAsync(ResourceGroupName, parent.Name, Name));
}
///GENMHASH:FCAC8C2F8D6E12CB6F5D7787A2837016:8A3C0887B28AA9A7371C1C4B64C83BCF
internal override async Task DeleteHostNameBindingAsync(string hostname, CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.WebApps.DeleteHostNameBindingSlotAsync(ResourceGroupName, parent.Name, Name, hostname, cancellationToken);
}
///GENMHASH:AE14C7C2170289895AEFF07E3516A2FC:0A62D57A2A28811F577B31E7B80922B8
public override async Task ResetSlotConfigurationsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.WebApps.ResetSlotConfigurationSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken);
await RefreshAsync(cancellationToken);
}
///GENMHASH:CB483EFD6E3479A51A8504AF23852854:6313AA480AD6478F672504A1348DE17E
internal override async Task<Models.SiteInner> SubmitAppSettingsAsync(SiteInner site, CancellationToken cancellationToken = default(CancellationToken))
{
if (configurationSource == null || !IsInCreateMode)
{
return await base.SubmitAppSettingsAsync(site, cancellationToken);
}
foreach (IAppSetting appSetting in (await configurationSource.GetAppSettingsAsync(cancellationToken)).Values)
{
if (appSetting.Sticky)
{
WithStickyAppSetting(appSetting.Key, appSetting.Value);
}
else
{
WithAppSetting(appSetting.Key, appSetting.Value);
}
}
return await base.SubmitAppSettingsAsync(Inner, cancellationToken);
}
///GENMHASH:D9CEBC2EF6EA60751F2BFE78FE5E22B3:86C919F4CA67F8BA602AC70FD7CCC9E0
internal override async Task<Models.SiteInner> SubmitConnectionStringsAsync(SiteInner site, CancellationToken cancellationToken = default(CancellationToken))
{
if (configurationSource == null || !IsInCreateMode)
{
return await base.SubmitConnectionStringsAsync(site, cancellationToken);
}
foreach (IConnectionString conn in (await configurationSource.GetConnectionStringsAsync(cancellationToken)).Values)
{
if (conn.Sticky)
{
WithStickyConnectionString(conn.Name, conn.Value, conn.Type);
}
else
{
WithConnectionString(conn.Name, conn.Value, conn.Type);
}
}
return await base.SubmitConnectionStringsAsync(Inner, cancellationToken);
}
///GENMHASH:07FBC6D492A2E1E463B39D4D7FFC40E9:6015327ABEB713972CA126D7A0F3C232
internal override async Task<Models.SiteInner> CreateOrUpdateInnerAsync(SiteInner site, CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.CreateOrUpdateSlotAsync(ResourceGroupName, parent.Name, site, Name, cancellationToken: cancellationToken);
}
///GENMHASH:21FDAEDB996672BE017C01C5DD8758D4:42826DB217BC1AEE5AAA977944F4318D
internal override async Task<Models.ConnectionStringDictionaryInner> UpdateConnectionStringsAsync(ConnectionStringDictionaryInner inner, CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.UpdateConnectionStringsSlotAsync(ResourceGroupName, parent.Name, inner, Name, cancellationToken);
}
///GENMHASH:8E71F8927E941B28152FA821CDDF0634:FE3484EE3177CF2A5BBF1D4825D24686
internal override async Task<Models.SiteAuthSettingsInner> GetAuthenticationAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.GetAuthSettingsSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken);
}
///GENMHASH:4F0DD1E3F09332DAEE78A7163765E0EA:DC09185D93597A9B3912ED6CC825299E
public override async Task<Microsoft.Azure.Management.AppService.Fluent.IPublishingProfile> GetPublishingProfileAsync(CancellationToken cancellationToken = default(CancellationToken))
{
using (var stream = await Manager.Inner.WebApps.ListPublishingProfileXmlWithSecretsSlotAsync(ResourceGroupName, parent.Name, Name, null, cancellationToken))
{
using (var reader = new StreamReader(stream))
{
string xml = reader.ReadToEnd();
return new PublishingProfileImpl(xml);
}
}
}
///GENMHASH:21D1748197F7ECC1EFA9660DF579B414:5C0A7336725B7FB6E200C1ED27F5CB4C
internal override async Task<Models.SiteAuthSettingsInner> UpdateAuthenticationAsync(SiteAuthSettingsInner inner, CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.UpdateAuthSettingsSlotAsync(ResourceGroupName, parent.Name, inner, Name, cancellationToken);
}
///GENMHASH:256905D5B839C64BFE9830503CB5607B:2A8EC434FA469B509BF4B734F95469CD
internal override async Task<Models.SiteConfigResourceInner> GetConfigInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.GetConfigurationSlotAsync(ResourceGroupName, parent.Name, Name);
}
///GENMHASH:D6FBED7FC7CBF34940541851FF5C3CC1:06F0D66A362CC364C51A49E48E7CA53B
public override async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.WebApps.StopSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken);
await RefreshAsync(cancellationToken);
}
///GENMHASH:8C5F8B18192B4F8FD7D43AB4D318EA69:3D9AAF779EB9D14F1D1CEB4D1C1D5CA2
public override IReadOnlyDictionary<string,Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding> GetHostNameBindings()
{
return Extensions.Synchronize(() => GetHostNameBindingsAsync());
}
///GENMHASH:3F0152723C985A22C1032733AB942C96:6FCE951A1B9813960CE8873DF107297F
public override IPublishingProfile GetPublishingProfile()
{
using (var stream = Extensions.Synchronize(() => Manager.Inner.WebApps.ListPublishingProfileXmlWithSecretsSlotAsync(ResourceGroupName, Parent().Name, Name)))
{
using (var reader = new StreamReader(stream))
{
string xml = reader.ReadToEnd();
return new PublishingProfileImpl(xml);
}
}
}
///GENMHASH:2BE74359D5F3E0281DC4391F52057FEB:1D9B01843585E3C1B592B91174E4A646
public override async Task<Microsoft.Azure.Management.AppService.Fluent.IWebAppSourceControl> GetSourceControlAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return new WebAppSourceControlImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>
(await Manager.Inner.WebApps.GetSourceControlSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken), this);
}
///GENMHASH:F04F63AA4669C2004D2264538A4A983F:ADB565DFC93401B12355B173EF0CC06A
public FluentImplT WithBrandNewConfiguration()
{
Inner.SiteConfig = new Models.SiteConfig();
return (FluentImplT) this;
}
///GENMHASH:DEC174D8970BF9488F3C635245A48467:C2605F11054FC66A805BECBAE7DAAB1F
public override async Task ApplySlotConfigurationsAsync(string slotName, CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.WebApps.ApplySlotConfigurationSlotAsync(ResourceGroupName, parent.Name, new CsmSlotEntity
{
TargetSlot = slotName
}, Name, cancellationToken);
await RefreshAsync(cancellationToken);
}
///GENMHASH:08CFC096AC6388D1C0E041ECDF099E3D:44C76716F153B9042AE98C1BCBC503F2
public override void Restart()
{
Extensions.Synchronize(() => Manager.Inner.WebApps.RestartSlotAsync(ResourceGroupName, parent.Name, Name));
}
///GENMHASH:DFC52755A97E7B13EB10FA2EB9538E4A:31BC86C370122E939BA1BA0EC17B6967
public override void Swap(string slotName)
{
Extensions.Synchronize(() => Manager.Inner.WebApps.SwapSlotSlotAsync(ResourceGroupName, parent.Name, new CsmSlotEntity()
{
TargetSlot = slotName
}, Name));
Refresh();
}
///GENMHASH:E7F5C40042323022AA5171FA979A6E79:3FE2818FBB1E53B61C9410D539937251
public override async Task SwapAsync(string slotName, CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.WebApps.SwapSlotSlotAsync(ResourceGroupName, parent.Name, new CsmSlotEntity
{
TargetSlot = slotName
}, Name, cancellationToken);
await RefreshAsync(cancellationToken);
}
///GENMHASH:0F38250A3837DF9C2C345D4A038B654B:01DA6136E32014808DDE7F0C637CF668
public override void Start()
{
Extensions.Synchronize(() => Manager.Inner.WebApps.StartSlotAsync(ResourceGroupName, parent.Name, Name));
}
///GENMHASH:62A0C790E618C837459BE1A5103CA0E5:DADE97E21BF8291BE266AB1DFA8E92FC
internal override async Task<Models.SlotConfigNamesResourceInner> ListSlotConfigurationsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.ListSlotConfigurationNamesAsync(ResourceGroupName, parent.Name);
}
///GENMHASH:D647EE2A3382CA78239A9DE35E508B8A:60DB075E48E5852A5A1AA4AFA0D83FD3
internal DeploymentSlotBaseImpl(
string name,
SiteInner innerObject,
SiteConfigResourceInner configObject,
SiteLogsConfigInner logConfig,
ParentImplT parent,
IAppServiceManager manager)
: base(Regex.Replace(name, ".*/", ""), innerObject, configObject, logConfig, manager)
{
this.name = Regex.Replace(name, ".*/", "");
this.parent = parent;
Inner.ServerFarmId = parent.AppServicePlanId();
}
///GENMHASH:E10A5B0FD0E95947B1A669D51E6BD5C9:D7D427883C2027A865C8AF45F16D7348
public override async Task<System.Collections.Generic.IReadOnlyDictionary<string,Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding>> GetHostNameBindingsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var bindingsList = await PagedCollection<IHostNameBinding, HostNameBindingInner>.LoadPage(
async (cancellation) => await Manager.Inner.WebApps.ListHostNameBindingsSlotAsync(ResourceGroupName, parent.Name, Name, cancellation),
Manager.Inner.WebApps.ListHostNameBindingsSlotNextAsync,
(inner) => new HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>(inner, (FluentImplT) this),
true, cancellationToken);
return bindingsList.ToDictionary(binding => binding.Name.Replace(this.Name + "/", ""));
}
///GENMHASH:D5AD274A3026D80CDF6A0DD97D9F20D4:4895185A183470C4839F69A47A61C826
public override async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.WebApps.StartSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken);
await RefreshAsync(cancellationToken);
}
///GENMHASH:807E62B6346803DB90804D0DEBD2FCA6:3660A2CDB06ACF2E101AA99CFACF48CD
internal override async Task DeleteSourceControlAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.WebApps.DeleteSourceControlSlotAsync(ResourceGroupName, parent.Name, Name);
}
///GENMHASH:0FE78F842439357DA0333AABD3B95D59:93410E420C7CA4E29C47B730671408CF
internal override async Task<Models.ConnectionStringDictionaryInner> ListConnectionStringsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.ListConnectionStringsSlotAsync(ResourceGroupName, parent.Name, Name);
}
///GENMHASH:CC6E0592F0BCD4CD83D832B40167E562:BBBE3BCF158566C63DBA770C071B146A
public override async Task VerifyDomainOwnershipAsync(string certificateOrderName, string domainVerificationToken, CancellationToken cancellationToken = default(CancellationToken))
{
IdentifierInner identifierInner = new IdentifierInner()
{
IdentifierId = domainVerificationToken
};
await Manager.Inner.WebApps.CreateOrUpdateDomainOwnershipIdentifierSlotAsync(ResourceGroupName, parent.Name, Name, identifierInner, certificateOrderName, cancellationToken);
}
///GENMHASH:6779D3D3C7AB7AAAE805BA0ABEE95C51:53A4EABE2126D220941754E8D00A25CF
internal override async Task<Models.StringDictionaryInner> UpdateAppSettingsAsync(StringDictionaryInner inner, CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.UpdateApplicationSettingsSlotAsync(ResourceGroupName, parent.Name, inner, Name, cancellationToken);
}
///GENMHASH:EB854F18026EDB6E01762FA4580BE789:E08F92567FBEC84BEB0BF3AD4DF89EDC
public override void Stop()
{
Extensions.Synchronize(() => Manager.Inner.WebApps.StopSlotAsync(ResourceGroupName, parent.Name, Name));
}
///GENMHASH:81C5A75C912A5059487CAA454304B8FC:E174ECD1F459D4BCFB76BF0692F555C9
public FluentImplT WithConfigurationFromDeploymentSlot(FluentT slot)
{
this.SiteConfig = ((WebAppBaseImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>) (IWebAppBase) slot).SiteConfig;
configurationSource = slot;
return (FluentImplT)this;
}
///GENMHASH:BC96AA8FDB678157AC1E6F0AA511AB65:55CBEA763E5EA0A02A785BC1273C63B0
public override IWebAppSourceControl GetSourceControl()
{
var siteSourceControlInner = Extensions.Synchronize(() => Manager.Inner.WebApps.GetSourceControlSlotAsync(ResourceGroupName, parent.Name, Name));
return new WebAppSourceControlImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>(
siteSourceControlInner,
(FluentImplT) this);
}
///GENMHASH:EB8C33DACE377CBB07C354F38C5BEA32:40B9A5AF5E2BAAC912A2E077A8B03C22
public override void VerifyDomainOwnership(string certificateOrderName, string domainVerificationToken)
{
Extensions.Synchronize(() => VerifyDomainOwnershipAsync(certificateOrderName, domainVerificationToken));
}
///GENMHASH:9EC0529BA0D08B75AD65E98A4BA01D5D:88C44586E83A2B7A08C556A1E66B6647
protected override async Task<Models.SiteInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.GetSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken);
}
protected override async Task<SiteInner> GetSiteAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.GetSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken);
}
///GENMHASH:4CF9E06F6C91A994117750A7F3E4F685:9456AE1AC3A256E704A9E044A478312E
internal override async Task<MSDeployStatusInner> CreateMSDeploy(MSDeploy msDeployInner, CancellationToken cancellationToken)
{
return await parent.Manager.Inner.WebApps.CreateMSDeployOperationSlotAsync(parent.ResourceGroupName, parent.Name, Name, msDeployInner, cancellationToken);
}
public override string Name
{
get
{
return name;
}
}
public override Stream GetContainerLogs()
{
return Extensions.Synchronize(() => GetContainerLogsAsync());
}
public override async Task<Stream> GetContainerLogsAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.GetWebSiteContainerLogsSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken);
}
public override Stream GetContainerLogsZip()
{
return Extensions.Synchronize(() => GetContainerLogsZipAsync());
}
public override async Task<Stream> GetContainerLogsZipAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.GetContainerLogsZipSlotAsync(ResourceGroupName, parent.Name, Name, cancellationToken);
}
internal override async Task<Models.SiteLogsConfigInner> UpdateDiagnosticLogsConfigAsync(SiteLogsConfigInner siteLogConfig, CancellationToken cancellationToken = default(CancellationToken))
{
return await Manager.Inner.WebApps.UpdateDiagnosticLogsConfigSlotAsync(ResourceGroupName, parent.Name, siteLogConfig, Name, cancellationToken);
}
}
}
| |
namespace android.text
{
[global::MonoJavaBridge.JavaClass()]
public partial class TextUtils : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static TextUtils()
{
InitJNI();
}
protected TextUtils(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.text.TextUtils.EllipsizeCallback_))]
public interface EllipsizeCallback : global::MonoJavaBridge.IJavaObject
{
void ellipsized(int arg0, int arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.text.TextUtils.EllipsizeCallback))]
public sealed partial class EllipsizeCallback_ : java.lang.Object, EllipsizeCallback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static EllipsizeCallback_()
{
InitJNI();
}
internal EllipsizeCallback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _ellipsized7899;
void android.text.TextUtils.EllipsizeCallback.ellipsized(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.TextUtils.EllipsizeCallback_._ellipsized7899, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.TextUtils.EllipsizeCallback_.staticClass, global::android.text.TextUtils.EllipsizeCallback_._ellipsized7899, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.TextUtils.EllipsizeCallback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/TextUtils$EllipsizeCallback"));
global::android.text.TextUtils.EllipsizeCallback_._ellipsized7899 = @__env.GetMethodIDNoThrow(global::android.text.TextUtils.EllipsizeCallback_.staticClass, "ellipsized", "(II)V");
}
}
[global::MonoJavaBridge.JavaClass()]
public partial class SimpleStringSplitter : java.lang.Object, StringSplitter, java.util.Iterator
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static SimpleStringSplitter()
{
InitJNI();
}
protected SimpleStringSplitter(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _iterator7900;
public virtual global::java.util.Iterator iterator()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter._iterator7900)) as java.util.Iterator;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter.staticClass, global::android.text.TextUtils.SimpleStringSplitter._iterator7900)) as java.util.Iterator;
}
internal static global::MonoJavaBridge.MethodId _hasNext7901;
public virtual bool hasNext()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter._hasNext7901);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter.staticClass, global::android.text.TextUtils.SimpleStringSplitter._hasNext7901);
}
internal static global::MonoJavaBridge.MethodId _next7902;
public virtual global::java.lang.Object next()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter._next7902)) as java.lang.Object;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter.staticClass, global::android.text.TextUtils.SimpleStringSplitter._next7902)) as java.lang.Object;
}
internal static global::MonoJavaBridge.MethodId _remove7903;
public virtual void remove()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter._remove7903);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter.staticClass, global::android.text.TextUtils.SimpleStringSplitter._remove7903);
}
internal static global::MonoJavaBridge.MethodId _setString7904;
public virtual void setString(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter._setString7904, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.TextUtils.SimpleStringSplitter.staticClass, global::android.text.TextUtils.SimpleStringSplitter._setString7904, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _SimpleStringSplitter7905;
public SimpleStringSplitter(char arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.text.TextUtils.SimpleStringSplitter.staticClass, global::android.text.TextUtils.SimpleStringSplitter._SimpleStringSplitter7905, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.TextUtils.SimpleStringSplitter.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/TextUtils$SimpleStringSplitter"));
global::android.text.TextUtils.SimpleStringSplitter._iterator7900 = @__env.GetMethodIDNoThrow(global::android.text.TextUtils.SimpleStringSplitter.staticClass, "iterator", "()Ljava/util/Iterator;");
global::android.text.TextUtils.SimpleStringSplitter._hasNext7901 = @__env.GetMethodIDNoThrow(global::android.text.TextUtils.SimpleStringSplitter.staticClass, "hasNext", "()Z");
global::android.text.TextUtils.SimpleStringSplitter._next7902 = @__env.GetMethodIDNoThrow(global::android.text.TextUtils.SimpleStringSplitter.staticClass, "next", "()Ljava/lang/Object;");
global::android.text.TextUtils.SimpleStringSplitter._remove7903 = @__env.GetMethodIDNoThrow(global::android.text.TextUtils.SimpleStringSplitter.staticClass, "remove", "()V");
global::android.text.TextUtils.SimpleStringSplitter._setString7904 = @__env.GetMethodIDNoThrow(global::android.text.TextUtils.SimpleStringSplitter.staticClass, "setString", "(Ljava/lang/String;)V");
global::android.text.TextUtils.SimpleStringSplitter._SimpleStringSplitter7905 = @__env.GetMethodIDNoThrow(global::android.text.TextUtils.SimpleStringSplitter.staticClass, "<init>", "(C)V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.text.TextUtils.StringSplitter_))]
public interface StringSplitter : java.lang.Iterable
{
void setString(java.lang.String arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.text.TextUtils.StringSplitter))]
public sealed partial class StringSplitter_ : java.lang.Object, StringSplitter
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static StringSplitter_()
{
InitJNI();
}
internal StringSplitter_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _setString7906;
void android.text.TextUtils.StringSplitter.setString(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.text.TextUtils.StringSplitter_._setString7906, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.text.TextUtils.StringSplitter_.staticClass, global::android.text.TextUtils.StringSplitter_._setString7906, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _iterator7907;
global::java.util.Iterator java.lang.Iterable.iterator()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallObjectMethod(this.JvmHandle, global::android.text.TextUtils.StringSplitter_._iterator7907)) as java.util.Iterator;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Iterator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.text.TextUtils.StringSplitter_.staticClass, global::android.text.TextUtils.StringSplitter_._iterator7907)) as java.util.Iterator;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.TextUtils.StringSplitter_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/TextUtils$StringSplitter"));
global::android.text.TextUtils.StringSplitter_._setString7906 = @__env.GetMethodIDNoThrow(global::android.text.TextUtils.StringSplitter_.staticClass, "setString", "(Ljava/lang/String;)V");
global::android.text.TextUtils.StringSplitter_._iterator7907 = @__env.GetMethodIDNoThrow(global::android.text.TextUtils.StringSplitter_.staticClass, "iterator", "()Ljava/util/Iterator;");
}
}
[global::MonoJavaBridge.JavaClass()]
public sealed partial class TruncateAt : java.lang.Enum
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static TruncateAt()
{
InitJNI();
}
internal TruncateAt(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _values7908;
public static global::android.text.TextUtils.TruncateAt[] values()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.text.TextUtils.TruncateAt>(@__env.CallStaticObjectMethod(android.text.TextUtils.TruncateAt.staticClass, global::android.text.TextUtils.TruncateAt._values7908)) as android.text.TextUtils.TruncateAt[];
}
internal static global::MonoJavaBridge.MethodId _valueOf7909;
public static global::android.text.TextUtils.TruncateAt valueOf(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.text.TextUtils.TruncateAt.staticClass, global::android.text.TextUtils.TruncateAt._valueOf7909, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.text.TextUtils.TruncateAt;
}
internal static global::MonoJavaBridge.FieldId _END7910;
public static global::android.text.TextUtils.TruncateAt END
{
get
{
return default(global::android.text.TextUtils.TruncateAt);
}
}
internal static global::MonoJavaBridge.FieldId _MARQUEE7911;
public static global::android.text.TextUtils.TruncateAt MARQUEE
{
get
{
return default(global::android.text.TextUtils.TruncateAt);
}
}
internal static global::MonoJavaBridge.FieldId _MIDDLE7912;
public static global::android.text.TextUtils.TruncateAt MIDDLE
{
get
{
return default(global::android.text.TextUtils.TruncateAt);
}
}
internal static global::MonoJavaBridge.FieldId _START7913;
public static global::android.text.TextUtils.TruncateAt START
{
get
{
return default(global::android.text.TextUtils.TruncateAt);
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.TextUtils.TruncateAt.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/TextUtils$TruncateAt"));
global::android.text.TextUtils.TruncateAt._values7908 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.TruncateAt.staticClass, "values", "()[Landroid/text/TextUtils/TruncateAt;");
global::android.text.TextUtils.TruncateAt._valueOf7909 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.TruncateAt.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/text/TextUtils$TruncateAt;");
}
}
internal static global::MonoJavaBridge.MethodId _equals7914;
public static bool equals(java.lang.CharSequence arg0, java.lang.CharSequence arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._equals7914, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _indexOf7915;
public static int indexOf(java.lang.CharSequence arg0, char arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._indexOf7915, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _indexOf7916;
public static int indexOf(java.lang.CharSequence arg0, char arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._indexOf7916, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _indexOf7917;
public static int indexOf(java.lang.CharSequence arg0, char arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._indexOf7917, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _indexOf7918;
public static int indexOf(java.lang.CharSequence arg0, java.lang.CharSequence arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._indexOf7918, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _indexOf7919;
public static int indexOf(java.lang.CharSequence arg0, java.lang.CharSequence arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._indexOf7919, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _indexOf7920;
public static int indexOf(java.lang.CharSequence arg0, java.lang.CharSequence arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._indexOf7920, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _isEmpty7921;
public static bool isEmpty(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._isEmpty7921, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getChars7922;
public static void getChars(java.lang.CharSequence arg0, int arg1, int arg2, char[] arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._getChars7922, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _regionMatches7923;
public static bool regionMatches(java.lang.CharSequence arg0, int arg1, java.lang.CharSequence arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._regionMatches7923, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _lastIndexOf7924;
public static int lastIndexOf(java.lang.CharSequence arg0, char arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._lastIndexOf7924, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _lastIndexOf7925;
public static int lastIndexOf(java.lang.CharSequence arg0, char arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._lastIndexOf7925, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _lastIndexOf7926;
public static int lastIndexOf(java.lang.CharSequence arg0, char arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._lastIndexOf7926, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _substring7927;
public static global::java.lang.String substring(java.lang.CharSequence arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._substring7927, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _concat7928;
public static global::java.lang.CharSequence concat(java.lang.CharSequence[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._concat7928, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _replace7929;
public static global::java.lang.CharSequence replace(java.lang.CharSequence arg0, java.lang.String[] arg1, java.lang.CharSequence[] arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._replace7929, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _split7930;
public static global::java.lang.String[] split(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._split7930, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String[];
}
internal static global::MonoJavaBridge.MethodId _split7931;
public static global::java.lang.String[] split(java.lang.String arg0, java.util.regex.Pattern arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._split7931, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String[];
}
internal static global::MonoJavaBridge.MethodId _join7932;
public static global::java.lang.String join(java.lang.CharSequence arg0, java.lang.Object[] arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._join7932, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _join7933;
public static global::java.lang.String join(java.lang.CharSequence arg0, java.lang.Iterable arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._join7933, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _ellipsize7934;
public static global::java.lang.CharSequence ellipsize(java.lang.CharSequence arg0, android.text.TextPaint arg1, float arg2, android.text.TextUtils.TruncateAt arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._ellipsize7934, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _ellipsize7935;
public static global::java.lang.CharSequence ellipsize(java.lang.CharSequence arg0, android.text.TextPaint arg1, float arg2, android.text.TextUtils.TruncateAt arg3, bool arg4, android.text.TextUtils.EllipsizeCallback arg5)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._ellipsize7935, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _writeToParcel7936;
public static void writeToParcel(java.lang.CharSequence arg0, android.os.Parcel arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._writeToParcel7936, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _stringOrSpannedString7937;
public static global::java.lang.CharSequence stringOrSpannedString(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._stringOrSpannedString7937, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _getTrimmedLength7938;
public static int getTrimmedLength(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._getTrimmedLength7938, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getReverse7939;
public static global::java.lang.CharSequence getReverse(java.lang.CharSequence arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._getReverse7939, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _dumpSpans7940;
public static void dumpSpans(java.lang.CharSequence arg0, android.util.Printer arg1, java.lang.String arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._dumpSpans7940, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _expandTemplate7941;
public static global::java.lang.CharSequence expandTemplate(java.lang.CharSequence arg0, java.lang.CharSequence[] arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._expandTemplate7941, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _getOffsetBefore7942;
public static int getOffsetBefore(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._getOffsetBefore7942, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getOffsetAfter7943;
public static int getOffsetAfter(java.lang.CharSequence arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._getOffsetAfter7943, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _copySpansFrom7944;
public static void copySpansFrom(android.text.Spanned arg0, int arg1, int arg2, java.lang.Class arg3, android.text.Spannable arg4, int arg5)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._copySpansFrom7944, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
}
internal static global::MonoJavaBridge.MethodId _commaEllipsize7945;
public static global::java.lang.CharSequence commaEllipsize(java.lang.CharSequence arg0, android.text.TextPaint arg1, float arg2, java.lang.String arg3, java.lang.String arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._commaEllipsize7945, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as java.lang.CharSequence;
}
internal static global::MonoJavaBridge.MethodId _htmlEncode7946;
public static global::java.lang.String htmlEncode(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._htmlEncode7946, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _isGraphic7947;
public static bool isGraphic(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._isGraphic7947, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isGraphic7948;
public static bool isGraphic(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._isGraphic7948, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isDigitsOnly7949;
public static bool isDigitsOnly(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._isDigitsOnly7949, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getCapsMode7950;
public static int getCapsMode(java.lang.CharSequence arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.text.TextUtils.staticClass, global::android.text.TextUtils._getCapsMode7950, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.FieldId _CHAR_SEQUENCE_CREATOR7951;
public static global::android.os.Parcelable_Creator CHAR_SEQUENCE_CREATOR
{
get
{
return default(global::android.os.Parcelable_Creator);
}
}
public static int CAP_MODE_CHARACTERS
{
get
{
return 4096;
}
}
public static int CAP_MODE_WORDS
{
get
{
return 8192;
}
}
public static int CAP_MODE_SENTENCES
{
get
{
return 16384;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.text.TextUtils.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/text/TextUtils"));
global::android.text.TextUtils._equals7914 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "equals", "(Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Z");
global::android.text.TextUtils._indexOf7915 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "indexOf", "(Ljava/lang/CharSequence;CI)I");
global::android.text.TextUtils._indexOf7916 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "indexOf", "(Ljava/lang/CharSequence;CII)I");
global::android.text.TextUtils._indexOf7917 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "indexOf", "(Ljava/lang/CharSequence;C)I");
global::android.text.TextUtils._indexOf7918 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "indexOf", "(Ljava/lang/CharSequence;Ljava/lang/CharSequence;)I");
global::android.text.TextUtils._indexOf7919 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "indexOf", "(Ljava/lang/CharSequence;Ljava/lang/CharSequence;I)I");
global::android.text.TextUtils._indexOf7920 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "indexOf", "(Ljava/lang/CharSequence;Ljava/lang/CharSequence;II)I");
global::android.text.TextUtils._isEmpty7921 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "isEmpty", "(Ljava/lang/CharSequence;)Z");
global::android.text.TextUtils._getChars7922 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "getChars", "(Ljava/lang/CharSequence;II[CI)V");
global::android.text.TextUtils._regionMatches7923 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "regionMatches", "(Ljava/lang/CharSequence;ILjava/lang/CharSequence;II)Z");
global::android.text.TextUtils._lastIndexOf7924 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "lastIndexOf", "(Ljava/lang/CharSequence;CI)I");
global::android.text.TextUtils._lastIndexOf7925 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "lastIndexOf", "(Ljava/lang/CharSequence;CII)I");
global::android.text.TextUtils._lastIndexOf7926 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "lastIndexOf", "(Ljava/lang/CharSequence;C)I");
global::android.text.TextUtils._substring7927 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "substring", "(Ljava/lang/CharSequence;II)Ljava/lang/String;");
global::android.text.TextUtils._concat7928 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "concat", "([Ljava/lang/CharSequence;)Ljava/lang/CharSequence;");
global::android.text.TextUtils._replace7929 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "replace", "(Ljava/lang/CharSequence;[Ljava/lang/String;[Ljava/lang/CharSequence;)Ljava/lang/CharSequence;");
global::android.text.TextUtils._split7930 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "split", "(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;");
global::android.text.TextUtils._split7931 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "split", "(Ljava/lang/String;Ljava/util/regex/Pattern;)[Ljava/lang/String;");
global::android.text.TextUtils._join7932 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "join", "(Ljava/lang/CharSequence;[Ljava/lang/Object;)Ljava/lang/String;");
global::android.text.TextUtils._join7933 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "join", "(Ljava/lang/CharSequence;Ljava/lang/Iterable;)Ljava/lang/String;");
global::android.text.TextUtils._ellipsize7934 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "ellipsize", "(Ljava/lang/CharSequence;Landroid/text/TextPaint;FLandroid/text/TextUtils$TruncateAt;)Ljava/lang/CharSequence;");
global::android.text.TextUtils._ellipsize7935 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "ellipsize", "(Ljava/lang/CharSequence;Landroid/text/TextPaint;FLandroid/text/TextUtils$TruncateAt;ZLandroid/text/TextUtils$EllipsizeCallback;)Ljava/lang/CharSequence;");
global::android.text.TextUtils._writeToParcel7936 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "writeToParcel", "(Ljava/lang/CharSequence;Landroid/os/Parcel;I)V");
global::android.text.TextUtils._stringOrSpannedString7937 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "stringOrSpannedString", "(Ljava/lang/CharSequence;)Ljava/lang/CharSequence;");
global::android.text.TextUtils._getTrimmedLength7938 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "getTrimmedLength", "(Ljava/lang/CharSequence;)I");
global::android.text.TextUtils._getReverse7939 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "getReverse", "(Ljava/lang/CharSequence;II)Ljava/lang/CharSequence;");
global::android.text.TextUtils._dumpSpans7940 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "dumpSpans", "(Ljava/lang/CharSequence;Landroid/util/Printer;Ljava/lang/String;)V");
global::android.text.TextUtils._expandTemplate7941 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "expandTemplate", "(Ljava/lang/CharSequence;[Ljava/lang/CharSequence;)Ljava/lang/CharSequence;");
global::android.text.TextUtils._getOffsetBefore7942 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "getOffsetBefore", "(Ljava/lang/CharSequence;I)I");
global::android.text.TextUtils._getOffsetAfter7943 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "getOffsetAfter", "(Ljava/lang/CharSequence;I)I");
global::android.text.TextUtils._copySpansFrom7944 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "copySpansFrom", "(Landroid/text/Spanned;IILjava/lang/Class;Landroid/text/Spannable;I)V");
global::android.text.TextUtils._commaEllipsize7945 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "commaEllipsize", "(Ljava/lang/CharSequence;Landroid/text/TextPaint;FLjava/lang/String;Ljava/lang/String;)Ljava/lang/CharSequence;");
global::android.text.TextUtils._htmlEncode7946 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "htmlEncode", "(Ljava/lang/String;)Ljava/lang/String;");
global::android.text.TextUtils._isGraphic7947 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "isGraphic", "(Ljava/lang/CharSequence;)Z");
global::android.text.TextUtils._isGraphic7948 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "isGraphic", "(C)Z");
global::android.text.TextUtils._isDigitsOnly7949 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "isDigitsOnly", "(Ljava/lang/CharSequence;)Z");
global::android.text.TextUtils._getCapsMode7950 = @__env.GetStaticMethodIDNoThrow(global::android.text.TextUtils.staticClass, "getCapsMode", "(Ljava/lang/CharSequence;II)I");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Transactions;
using Orleans.Utilities;
namespace Orleans.CodeGeneration
{
internal static class GrainInterfaceUtils
{
private static readonly IEqualityComparer<MethodInfo> MethodComparer = new MethodInfoComparer();
[Serializable]
internal class RulesViolationException : ArgumentException
{
public RulesViolationException(string message, List<string> violations)
: base(message)
{
Violations = violations;
}
protected RulesViolationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
this.Violations = info.GetValue(nameof(Violations), typeof(List<string>)) as List<string>;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue(nameof(Violations), this.Violations);
}
public List<string> Violations { get; private set; }
}
public static bool IsGrainInterface(Type t)
{
if (t.IsClass)
return false;
if (t == typeof(IGrainObserver) || t == typeof(IAddressable) || t == typeof(IGrainExtension))
return false;
if (t == typeof(IGrain) || t == typeof(IGrainWithGuidKey) || t == typeof(IGrainWithIntegerKey)
|| t == typeof(IGrainWithGuidCompoundKey) || t == typeof(IGrainWithIntegerCompoundKey))
return false;
if (t == typeof (ISystemTarget))
return false;
return typeof (IAddressable).IsAssignableFrom(t);
}
public static MethodInfo[] GetMethods(Type grainType, bool bAllMethods = true)
{
var methodInfos = new List<MethodInfo>();
GetMethodsImpl(grainType, grainType, methodInfos);
var flags = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance;
if (!bAllMethods)
flags |= BindingFlags.DeclaredOnly;
MethodInfo[] infos = grainType.GetMethods(flags);
foreach (var methodInfo in infos)
if (!methodInfos.Contains(methodInfo, MethodComparer))
methodInfos.Add(methodInfo);
return methodInfos.ToArray();
}
public static string GetParameterName(ParameterInfo info)
{
var n = info.Name;
return string.IsNullOrEmpty(n) ? "arg" + info.Position : n;
}
public static bool IsTaskType(Type t)
{
if (t == typeof(Task))
{
return true;
}
if (t.IsGenericType)
{
var typeName = t.GetGenericTypeDefinition().FullName;
return typeName == "System.Threading.Tasks.Task`1"
|| typeName == "System.Threading.Tasks.ValueTask`1";
}
return false;
}
/// <summary>
/// Whether method is read-only, i.e. does not modify grain state,
/// a method marked with [ReadOnly].
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
public static bool IsReadOnly(MethodInfo info)
{
return info.GetCustomAttributes(typeof (ReadOnlyAttribute), true).Any();
}
public static bool IsAlwaysInterleave(MethodInfo methodInfo)
{
return methodInfo.GetCustomAttributes(typeof (AlwaysInterleaveAttribute), true).Any();
}
public static bool IsUnordered(MethodInfo methodInfo)
{
var declaringType = methodInfo.DeclaringType;
return declaringType.GetCustomAttributes(typeof(UnorderedAttribute), true).Any()
|| (declaringType.GetInterfaces().Any(
i => i.GetCustomAttributes(typeof(UnorderedAttribute), true).Any()
&& declaringType.GetTypeInfo().GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo)))
|| IsStatelessWorker(methodInfo);
}
public static bool IsStatelessWorker(MethodInfo methodInfo)
{
var declaringType = methodInfo.DeclaringType;
return declaringType.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any() ||
(declaringType.GetInterfaces().Any(
i => i.GetCustomAttributes(typeof(StatelessWorkerAttribute), true).Any()
&& declaringType.GetTypeInfo().GetRuntimeInterfaceMap(i).TargetMethods.Contains(methodInfo)));
}
public static bool TryGetTransactionOption(MethodInfo methodInfo, out TransactionOption option)
{
option = TransactionOption.Suppress;
TransactionAttribute transactionAttribute = methodInfo.GetCustomAttribute<TransactionAttribute>(true);
if (transactionAttribute != null)
{
option = transactionAttribute.Requirement;
return true;
}
return false;
}
public static Dictionary<int, Type> GetRemoteInterfaces(Type type, bool checkIsGrainInterface = true)
{
var dict = new Dictionary<int, Type>();
if (IsGrainInterface(type))
dict.Add(GetGrainInterfaceId(type), type);
Type[] interfaces = type.GetInterfaces();
foreach (Type interfaceType in interfaces.Where(i => !checkIsGrainInterface || IsGrainInterface(i)))
dict.Add(GetGrainInterfaceId(interfaceType), interfaceType);
return dict;
}
public static int ComputeMethodId(MethodInfo methodInfo)
{
var attr = methodInfo.GetCustomAttribute<MethodIdAttribute>(true);
if (attr != null) return attr.MethodId;
var result = FormatMethodForIdComputation(methodInfo);
return Utils.CalculateIdHash(result);
}
internal static string FormatMethodForIdComputation(MethodInfo methodInfo)
{
var strMethodId = new StringBuilder(methodInfo.Name);
if (methodInfo.IsGenericMethodDefinition)
{
strMethodId.Append('<');
var first = true;
foreach (var arg in methodInfo.GetGenericArguments())
{
if (!first) strMethodId.Append(',');
else first = false;
strMethodId.Append(RuntimeTypeNameFormatter.Format(arg));
}
strMethodId.Append('>');
}
strMethodId.Append('(');
ParameterInfo[] parameters = methodInfo.GetParameters();
bool bFirstTime = true;
foreach (ParameterInfo info in parameters)
{
if (!bFirstTime)
strMethodId.Append(',');
var pt = info.ParameterType;
if (pt.IsGenericParameter)
{
strMethodId.Append(pt.Name);
}
else
{
strMethodId.Append(RuntimeTypeNameFormatter.Format(info.ParameterType));
}
bFirstTime = false;
}
strMethodId.Append(')');
var result = strMethodId.ToString();
return result;
}
public static int GetGrainInterfaceId(Type grainInterface)
{
return GetTypeCode(grainInterface);
}
public static ushort GetGrainInterfaceVersion(Type grainInterface)
{
if (typeof(IGrainExtension).IsAssignableFrom(grainInterface))
return 0;
var attr = grainInterface.GetCustomAttribute<VersionAttribute>();
return attr?.Version ?? Constants.DefaultInterfaceVersion;
}
public static bool IsTaskBasedInterface(Type type)
{
var methods = type.GetMethods();
// An interface is task-based if it has at least one method that returns a Task or at least one parent that's task-based.
return methods.Any(m => IsTaskType(m.ReturnType)) || type.GetInterfaces().Any(IsTaskBasedInterface);
}
public static bool IsGrainType(Type grainType)
{
return typeof (IGrain).IsAssignableFrom(grainType);
}
public static int GetGrainClassTypeCode(Type grainClass)
{
return GetTypeCode(grainClass);
}
internal static bool TryValidateInterfaceRules(Type type, out List<string> violations)
{
violations = new List<string>();
bool success = ValidateInterfaceMethods(type, violations);
return success && ValidateInterfaceProperties(type, violations);
}
internal static void ValidateInterfaceRules(Type type)
{
List<string> violations;
if (!TryValidateInterfaceRules(type, out violations))
{
if (ConsoleText.IsConsoleAvailable)
{
foreach (var violation in violations)
ConsoleText.WriteLine("ERROR: " + violation);
}
throw new RulesViolationException(
string.Format("{0} does not conform to the grain interface rules.", type.FullName), violations);
}
}
internal static void ValidateInterface(Type type)
{
if (!IsGrainInterface(type))
throw new ArgumentException(String.Format("{0} is not a grain interface", type.FullName));
ValidateInterfaceRules(type);
}
private static bool ValidateInterfaceMethods(Type type, List<string> violations)
{
bool success = true;
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
if (method.IsSpecialName)
continue;
if (IsPureObserverInterface(method.DeclaringType))
{
if (method.ReturnType != typeof (void))
{
success = false;
violations.Add(String.Format("Method {0}.{1} must return void because it is defined within an observer interface.",
type.FullName, method.Name));
}
}
else if (!IsTaskType(method.ReturnType))
{
success = false;
violations.Add(String.Format("Method {0}.{1} must return Task or Task<T> because it is defined within a grain interface.",
type.FullName, method.Name));
}
ParameterInfo[] parameters = method.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
if (parameter.IsOut)
{
success = false;
violations.Add(String.Format("Argument {0} of method {1}.{2} is an output parameter. Output parameters are not allowed in grain interfaces.",
GetParameterName(parameter), type.FullName, method.Name));
}
if (parameter.ParameterType.IsByRef)
{
success = false;
violations.Add(String.Format("Argument {0} of method {1}.{2} is an a reference parameter. Reference parameters are not allowed.",
GetParameterName(parameter), type.FullName, method.Name));
}
}
}
return success;
}
private static bool ValidateInterfaceProperties(Type type, List<string> violations)
{
bool success = true;
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
success = false;
violations.Add(String.Format("Properties are not allowed on grain interfaces: {0}.{1}.",
type.FullName, property.Name));
}
return success;
}
/// <summary>
/// decide whether the class is derived from Grain
/// </summary>
private static bool IsPureObserverInterface(Type t)
{
if (!typeof (IGrainObserver).IsAssignableFrom(t))
return false;
if (t == typeof (IGrainObserver))
return true;
if (t == typeof (IAddressable))
return false;
bool pure = false;
foreach (Type iface in t.GetInterfaces())
{
if (iface == typeof (IAddressable)) // skip IAddressable that will be in the list regardless
continue;
if (iface == typeof (IGrainExtension))
// Skip IGrainExtension, it's just a marker that can go on observer or grain interfaces
continue;
pure = IsPureObserverInterface(iface);
if (!pure)
return false;
}
return pure;
}
private class MethodInfoComparer : IEqualityComparer<MethodInfo>
{
public bool Equals(MethodInfo x, MethodInfo y)
{
return ComputeMethodId(x) == ComputeMethodId(y);
}
public int GetHashCode(MethodInfo obj)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Recurses through interface graph accumulating methods
/// </summary>
/// <param name="grainType">Grain type</param>
/// <param name="serviceType">Service interface type</param>
/// <param name="methodInfos">Accumulated </param>
private static void GetMethodsImpl(Type grainType, Type serviceType, List<MethodInfo> methodInfos)
{
Type[] iTypes = GetRemoteInterfaces(serviceType, false).Values.ToArray();
foreach (Type iType in iTypes)
{
var mapping = new InterfaceMapping();
if (grainType.IsClass)
mapping = grainType.GetTypeInfo().GetRuntimeInterfaceMap(iType);
if (grainType.IsInterface || mapping.TargetType == grainType)
{
foreach (var methodInfo in iType.GetMethods())
{
if (grainType.IsClass)
{
var mi = methodInfo;
var match = mapping.TargetMethods.Any(info => MethodComparer.Equals(mi, info) &&
info.DeclaringType == grainType);
if (match)
if (!methodInfos.Contains(mi, MethodComparer))
methodInfos.Add(mi);
}
else if (!methodInfos.Contains(methodInfo, MethodComparer))
{
methodInfos.Add(methodInfo);
}
}
}
}
}
private static int GetTypeCode(Type grainInterfaceOrClass)
{
var attr = grainInterfaceOrClass.GetCustomAttributes<TypeCodeOverrideAttribute>(false).FirstOrDefault();
if (attr != null && attr.TypeCode > 0)
{
return attr.TypeCode;
}
var fullName = TypeUtils.GetTemplatedName(
TypeUtils.GetFullName(grainInterfaceOrClass),
grainInterfaceOrClass,
grainInterfaceOrClass.GetGenericArguments(),
t => false);
return Utils.CalculateIdHash(fullName);
}
}
}
| |
using System;
using ChainUtils.BouncyCastle.Utilities;
namespace ChainUtils.BouncyCastle.Crypto.Digests
{
/// <remarks>
/// <p>Implementation of RipeMD 320.</p>
/// <p><b>Note:</b> this algorithm offers the same level of security as RipeMD160.</p>
/// </remarks>
public class RipeMD320Digest
: GeneralDigest
{
public override string AlgorithmName
{
get { return "RIPEMD320"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
private const int DigestLength = 40;
private int H0, H1, H2, H3, H4, H5, H6, H7, H8, H9; // IV's
private int[] X = new int[16];
private int xOff;
/// <summary> Standard constructor</summary>
public RipeMD320Digest()
{
Reset();
}
/// <summary> Copy constructor. This will copy the state of the provided
/// message digest.
/// </summary>
public RipeMD320Digest(RipeMD320Digest t)
: base(t)
{
CopyIn(t);
}
private void CopyIn(RipeMD320Digest t)
{
base.CopyIn(t);
H0 = t.H0;
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
H6 = t.H6;
H7 = t.H7;
H8 = t.H8;
H9 = t.H9;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8)
| ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24);
if (xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (int)(bitLength & 0xffffffff);
X[15] = (int)((ulong)bitLength >> 32);
}
private void UnpackWord(
int word,
byte[] outBytes,
int outOff)
{
outBytes[outOff] = (byte)word;
outBytes[outOff + 1] = (byte)((uint)word >> 8);
outBytes[outOff + 2] = (byte)((uint)word >> 16);
outBytes[outOff + 3] = (byte)((uint)word >> 24);
}
public override int DoFinal(byte[] output, int outOff)
{
Finish();
UnpackWord(H0, output, outOff);
UnpackWord(H1, output, outOff + 4);
UnpackWord(H2, output, outOff + 8);
UnpackWord(H3, output, outOff + 12);
UnpackWord(H4, output, outOff + 16);
UnpackWord(H5, output, outOff + 20);
UnpackWord(H6, output, outOff + 24);
UnpackWord(H7, output, outOff + 28);
UnpackWord(H8, output, outOff + 32);
UnpackWord(H9, output, outOff + 36);
Reset();
return DigestLength;
}
/// <summary> reset the chaining variables to the IV values.</summary>
public override void Reset()
{
base.Reset();
H0 = unchecked((int) 0x67452301);
H1 = unchecked((int) 0xefcdab89);
H2 = unchecked((int) 0x98badcfe);
H3 = unchecked((int) 0x10325476);
H4 = unchecked((int) 0xc3d2e1f0);
H5 = unchecked((int) 0x76543210);
H6 = unchecked((int) 0xFEDCBA98);
H7 = unchecked((int) 0x89ABCDEF);
H8 = unchecked((int) 0x01234567);
H9 = unchecked((int) 0x3C2D1E0F);
xOff = 0;
for (var i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
/*
* rotate int x left n bits.
*/
private int RL(
int x,
int n)
{
return (x << n) | (int)(((uint)x) >> (32 - n));
}
/*
* f1,f2,f3,f4,f5 are the basic RipeMD160 functions.
*/
/*
* rounds 0-15
*/
private int F1(int x, int y, int z)
{
return x ^ y ^ z;
}
/*
* rounds 16-31
*/
private int F2(int x, int y, int z)
{
return (x & y) | (~ x & z);
}
/*
* rounds 32-47
*/
private int F3(int x, int y, int z)
{
return (x | ~ y) ^ z;
}
/*
* rounds 48-63
*/
private int F4(int x, int y, int z)
{
return (x & z) | (y & ~ z);
}
/*
* rounds 64-79
*/
private int F5(int x, int y, int z)
{
return x ^ (y | ~z);
}
internal override void ProcessBlock()
{
int a, aa;
int b, bb;
int c, cc;
int d, dd;
int e, ee;
int t;
a = H0;
b = H1;
c = H2;
d = H3;
e = H4;
aa = H5;
bb = H6;
cc = H7;
dd = H8;
ee = H9;
//
// Rounds 1 - 16
//
// left
a = RL(a + F1(b, c, d) + X[0], 11) + e; c = RL(c, 10);
e = RL(e + F1(a, b, c) + X[1], 14) + d; b = RL(b, 10);
d = RL(d + F1(e, a, b) + X[2], 15) + c; a = RL(a, 10);
c = RL(c + F1(d, e, a) + X[3], 12) + b; e = RL(e, 10);
b = RL(b + F1(c, d, e) + X[4], 5) + a; d = RL(d, 10);
a = RL(a + F1(b, c, d) + X[5], 8) + e; c = RL(c, 10);
e = RL(e + F1(a, b, c) + X[6], 7) + d; b = RL(b, 10);
d = RL(d + F1(e, a, b) + X[7], 9) + c; a = RL(a, 10);
c = RL(c + F1(d, e, a) + X[8], 11) + b; e = RL(e, 10);
b = RL(b + F1(c, d, e) + X[9], 13) + a; d = RL(d, 10);
a = RL(a + F1(b, c, d) + X[10], 14) + e; c = RL(c, 10);
e = RL(e + F1(a, b, c) + X[11], 15) + d; b = RL(b, 10);
d = RL(d + F1(e, a, b) + X[12], 6) + c; a = RL(a, 10);
c = RL(c + F1(d, e, a) + X[13], 7) + b; e = RL(e, 10);
b = RL(b + F1(c, d, e) + X[14], 9) + a; d = RL(d, 10);
a = RL(a + F1(b, c, d) + X[15], 8) + e; c = RL(c, 10);
// right
aa = RL(aa + F5(bb, cc, dd) + X[5] + unchecked((int)0x50a28be6), 8) + ee; cc = RL(cc, 10);
ee = RL(ee + F5(aa, bb, cc) + X[14] + unchecked((int)0x50a28be6), 9) + dd; bb = RL(bb, 10);
dd = RL(dd + F5(ee, aa, bb) + X[7] + unchecked((int)0x50a28be6), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F5(dd, ee, aa) + X[0] + unchecked((int)0x50a28be6), 11) + bb; ee = RL(ee, 10);
bb = RL(bb + F5(cc, dd, ee) + X[9] + unchecked((int)0x50a28be6), 13) + aa; dd = RL(dd, 10);
aa = RL(aa + F5(bb, cc, dd) + X[2] + unchecked((int)0x50a28be6), 15) + ee; cc = RL(cc, 10);
ee = RL(ee + F5(aa, bb, cc) + X[11] + unchecked((int)0x50a28be6), 15) + dd; bb = RL(bb, 10);
dd = RL(dd + F5(ee, aa, bb) + X[4] + unchecked((int)0x50a28be6), 5) + cc; aa = RL(aa, 10);
cc = RL(cc + F5(dd, ee, aa) + X[13] + unchecked((int)0x50a28be6), 7) + bb; ee = RL(ee, 10);
bb = RL(bb + F5(cc, dd, ee) + X[6] + unchecked((int)0x50a28be6), 7) + aa; dd = RL(dd, 10);
aa = RL(aa + F5(bb, cc, dd) + X[15] + unchecked((int)0x50a28be6), 8) + ee; cc = RL(cc, 10);
ee = RL(ee + F5(aa, bb, cc) + X[8] + unchecked((int)0x50a28be6), 11) + dd; bb = RL(bb, 10);
dd = RL(dd + F5(ee, aa, bb) + X[1] + unchecked((int)0x50a28be6), 14) + cc; aa = RL(aa, 10);
cc = RL(cc + F5(dd, ee, aa) + X[10] + unchecked((int)0x50a28be6), 14) + bb; ee = RL(ee, 10);
bb = RL(bb + F5(cc, dd, ee) + X[3] + unchecked((int)0x50a28be6), 12) + aa; dd = RL(dd, 10);
aa = RL(aa + F5(bb, cc, dd) + X[12] + unchecked((int)0x50a28be6), 6) + ee; cc = RL(cc, 10);
t = a; a = aa; aa = t;
//
// Rounds 16-31
//
// left
e = RL(e + F2(a, b, c) + X[7] + unchecked((int)0x5a827999), 7) + d; b = RL(b, 10);
d = RL(d + F2(e, a, b) + X[4] + unchecked((int)0x5a827999), 6) + c; a = RL(a, 10);
c = RL(c + F2(d, e, a) + X[13] + unchecked((int)0x5a827999), 8) + b; e = RL(e, 10);
b = RL(b + F2(c, d, e) + X[1] + unchecked((int)0x5a827999), 13) + a; d = RL(d, 10);
a = RL(a + F2(b, c, d) + X[10] + unchecked((int)0x5a827999), 11) + e; c = RL(c, 10);
e = RL(e + F2(a, b, c) + X[6] + unchecked((int)0x5a827999), 9) + d; b = RL(b, 10);
d = RL(d + F2(e, a, b) + X[15] + unchecked((int)0x5a827999), 7) + c; a = RL(a, 10);
c = RL(c + F2(d, e, a) + X[3] + unchecked((int)0x5a827999), 15) + b; e = RL(e, 10);
b = RL(b + F2(c, d, e) + X[12] + unchecked((int)0x5a827999), 7) + a; d = RL(d, 10);
a = RL(a + F2(b, c, d) + X[0] + unchecked((int)0x5a827999), 12) + e; c = RL(c, 10);
e = RL(e + F2(a, b, c) + X[9] + unchecked((int)0x5a827999), 15) + d; b = RL(b, 10);
d = RL(d + F2(e, a, b) + X[5] + unchecked((int)0x5a827999), 9) + c; a = RL(a, 10);
c = RL(c + F2(d, e, a) + X[2] + unchecked((int)0x5a827999), 11) + b; e = RL(e, 10);
b = RL(b + F2(c, d, e) + X[14] + unchecked((int)0x5a827999), 7) + a; d = RL(d, 10);
a = RL(a + F2(b, c, d) + X[11] + unchecked((int)0x5a827999), 13) + e; c = RL(c, 10);
e = RL(e + F2(a, b, c) + X[8] + unchecked((int)0x5a827999), 12) + d; b = RL(b, 10);
// right
ee = RL(ee + F4(aa, bb, cc) + X[6] + unchecked((int)0x5c4dd124), 9) + dd; bb = RL(bb, 10);
dd = RL(dd + F4(ee, aa, bb) + X[11] + unchecked((int)0x5c4dd124), 13) + cc; aa = RL(aa, 10);
cc = RL(cc + F4(dd, ee, aa) + X[3] + unchecked((int)0x5c4dd124), 15) + bb; ee = RL(ee, 10);
bb = RL(bb + F4(cc, dd, ee) + X[7] + unchecked((int)0x5c4dd124), 7) + aa; dd = RL(dd, 10);
aa = RL(aa + F4(bb, cc, dd) + X[0] + unchecked((int)0x5c4dd124), 12) + ee; cc = RL(cc, 10);
ee = RL(ee + F4(aa, bb, cc) + X[13] + unchecked((int)0x5c4dd124), 8) + dd; bb = RL(bb, 10);
dd = RL(dd + F4(ee, aa, bb) + X[5] + unchecked((int)0x5c4dd124), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F4(dd, ee, aa) + X[10] + unchecked((int)0x5c4dd124), 11) + bb; ee = RL(ee, 10);
bb = RL(bb + F4(cc, dd, ee) + X[14] + unchecked((int)0x5c4dd124), 7) + aa; dd = RL(dd, 10);
aa = RL(aa + F4(bb, cc, dd) + X[15] + unchecked((int)0x5c4dd124), 7) + ee; cc = RL(cc, 10);
ee = RL(ee + F4(aa, bb, cc) + X[8] + unchecked((int)0x5c4dd124), 12) + dd; bb = RL(bb, 10);
dd = RL(dd + F4(ee, aa, bb) + X[12] + unchecked((int)0x5c4dd124), 7) + cc; aa = RL(aa, 10);
cc = RL(cc + F4(dd, ee, aa) + X[4] + unchecked((int)0x5c4dd124), 6) + bb; ee = RL(ee, 10);
bb = RL(bb + F4(cc, dd, ee) + X[9] + unchecked((int)0x5c4dd124), 15) + aa; dd = RL(dd, 10);
aa = RL(aa + F4(bb, cc, dd) + X[1] + unchecked((int)0x5c4dd124), 13) + ee; cc = RL(cc, 10);
ee = RL(ee + F4(aa, bb, cc) + X[2] + unchecked((int)0x5c4dd124), 11) + dd; bb = RL(bb, 10);
t = b; b = bb; bb = t;
//
// Rounds 32-47
//
// left
d = RL(d + F3(e, a, b) + X[3] + unchecked((int)0x6ed9eba1), 11) + c; a = RL(a, 10);
c = RL(c + F3(d, e, a) + X[10] + unchecked((int)0x6ed9eba1), 13) + b; e = RL(e, 10);
b = RL(b + F3(c, d, e) + X[14] + unchecked((int)0x6ed9eba1), 6) + a; d = RL(d, 10);
a = RL(a + F3(b, c, d) + X[4] + unchecked((int)0x6ed9eba1), 7) + e; c = RL(c, 10);
e = RL(e + F3(a, b, c) + X[9] + unchecked((int)0x6ed9eba1), 14) + d; b = RL(b, 10);
d = RL(d + F3(e, a, b) + X[15] + unchecked((int)0x6ed9eba1), 9) + c; a = RL(a, 10);
c = RL(c + F3(d, e, a) + X[8] + unchecked((int)0x6ed9eba1), 13) + b; e = RL(e, 10);
b = RL(b + F3(c, d, e) + X[1] + unchecked((int)0x6ed9eba1), 15) + a; d = RL(d, 10);
a = RL(a + F3(b, c, d) + X[2] + unchecked((int)0x6ed9eba1), 14) + e; c = RL(c, 10);
e = RL(e + F3(a, b, c) + X[7] + unchecked((int)0x6ed9eba1), 8) + d; b = RL(b, 10);
d = RL(d + F3(e, a, b) + X[0] + unchecked((int)0x6ed9eba1), 13) + c; a = RL(a, 10);
c = RL(c + F3(d, e, a) + X[6] + unchecked((int)0x6ed9eba1), 6) + b; e = RL(e, 10);
b = RL(b + F3(c, d, e) + X[13] + unchecked((int)0x6ed9eba1), 5) + a; d = RL(d, 10);
a = RL(a + F3(b, c, d) + X[11] + unchecked((int)0x6ed9eba1), 12) + e; c = RL(c, 10);
e = RL(e + F3(a, b, c) + X[5] + unchecked((int)0x6ed9eba1), 7) + d; b = RL(b, 10);
d = RL(d + F3(e, a, b) + X[12] + unchecked((int)0x6ed9eba1), 5) + c; a = RL(a, 10);
// right
dd = RL(dd + F3(ee, aa, bb) + X[15] + unchecked((int)0x6d703ef3), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F3(dd, ee, aa) + X[5] + unchecked((int)0x6d703ef3), 7) + bb; ee = RL(ee, 10);
bb = RL(bb + F3(cc, dd, ee) + X[1] + unchecked((int)0x6d703ef3), 15) + aa; dd = RL(dd, 10);
aa = RL(aa + F3(bb, cc, dd) + X[3] + unchecked((int)0x6d703ef3), 11) + ee; cc = RL(cc, 10);
ee = RL(ee + F3(aa, bb, cc) + X[7] + unchecked((int)0x6d703ef3), 8) + dd; bb = RL(bb, 10);
dd = RL(dd + F3(ee, aa, bb) + X[14] + unchecked((int)0x6d703ef3), 6) + cc; aa = RL(aa, 10);
cc = RL(cc + F3(dd, ee, aa) + X[6] + unchecked((int)0x6d703ef3), 6) + bb; ee = RL(ee, 10);
bb = RL(bb + F3(cc, dd, ee) + X[9] + unchecked((int)0x6d703ef3), 14) + aa; dd = RL(dd, 10);
aa = RL(aa + F3(bb, cc, dd) + X[11] + unchecked((int)0x6d703ef3), 12) + ee; cc = RL(cc, 10);
ee = RL(ee + F3(aa, bb, cc) + X[8] + unchecked((int)0x6d703ef3), 13) + dd; bb = RL(bb, 10);
dd = RL(dd + F3(ee, aa, bb) + X[12] + unchecked((int)0x6d703ef3), 5) + cc; aa = RL(aa, 10);
cc = RL(cc + F3(dd, ee, aa) + X[2] + unchecked((int)0x6d703ef3), 14) + bb; ee = RL(ee, 10);
bb = RL(bb + F3(cc, dd, ee) + X[10] + unchecked((int)0x6d703ef3), 13) + aa; dd = RL(dd, 10);
aa = RL(aa + F3(bb, cc, dd) + X[0] + unchecked((int)0x6d703ef3), 13) + ee; cc = RL(cc, 10);
ee = RL(ee + F3(aa, bb, cc) + X[4] + unchecked((int)0x6d703ef3), 7) + dd; bb = RL(bb, 10);
dd = RL(dd + F3(ee, aa, bb) + X[13] + unchecked((int)0x6d703ef3), 5) + cc; aa = RL(aa, 10);
t = c; c = cc; cc = t;
//
// Rounds 48-63
//
// left
c = RL(c + F4(d, e, a) + X[1] + unchecked((int)0x8f1bbcdc), 11) + b; e = RL(e, 10);
b = RL(b + F4(c, d, e) + X[9] + unchecked((int)0x8f1bbcdc), 12) + a; d = RL(d, 10);
a = RL(a + F4(b, c, d) + X[11] + unchecked((int)0x8f1bbcdc), 14) + e; c = RL(c, 10);
e = RL(e + F4(a, b, c) + X[10] + unchecked((int)0x8f1bbcdc), 15) + d; b = RL(b, 10);
d = RL(d + F4(e, a, b) + X[0] + unchecked((int)0x8f1bbcdc), 14) + c; a = RL(a, 10);
c = RL(c + F4(d, e, a) + X[8] + unchecked((int)0x8f1bbcdc), 15) + b; e = RL(e, 10);
b = RL(b + F4(c, d, e) + X[12] + unchecked((int)0x8f1bbcdc), 9) + a; d = RL(d, 10);
a = RL(a + F4(b, c, d) + X[4] + unchecked((int)0x8f1bbcdc), 8) + e; c = RL(c, 10);
e = RL(e + F4(a, b, c) + X[13] + unchecked((int)0x8f1bbcdc), 9) + d; b = RL(b, 10);
d = RL(d + F4(e, a, b) + X[3] + unchecked((int)0x8f1bbcdc), 14) + c; a = RL(a, 10);
c = RL(c + F4(d, e, a) + X[7] + unchecked((int)0x8f1bbcdc), 5) + b; e = RL(e, 10);
b = RL(b + F4(c, d, e) + X[15] + unchecked((int)0x8f1bbcdc), 6) + a; d = RL(d, 10);
a = RL(a + F4(b, c, d) + X[14] + unchecked((int)0x8f1bbcdc), 8) + e; c = RL(c, 10);
e = RL(e + F4(a, b, c) + X[5] + unchecked((int)0x8f1bbcdc), 6) + d; b = RL(b, 10);
d = RL(d + F4(e, a, b) + X[6] + unchecked((int)0x8f1bbcdc), 5) + c; a = RL(a, 10);
c = RL(c + F4(d, e, a) + X[2] + unchecked((int)0x8f1bbcdc), 12) + b; e = RL(e, 10);
// right
cc = RL(cc + F2(dd, ee, aa) + X[8] + unchecked((int)0x7a6d76e9), 15) + bb; ee = RL(ee, 10);
bb = RL(bb + F2(cc, dd, ee) + X[6] + unchecked((int)0x7a6d76e9), 5) + aa; dd = RL(dd, 10);
aa = RL(aa + F2(bb, cc, dd) + X[4] + unchecked((int)0x7a6d76e9), 8) + ee; cc = RL(cc, 10);
ee = RL(ee + F2(aa, bb, cc) + X[1] + unchecked((int)0x7a6d76e9), 11) + dd; bb = RL(bb, 10);
dd = RL(dd + F2(ee, aa, bb) + X[3] + unchecked((int)0x7a6d76e9), 14) + cc; aa = RL(aa, 10);
cc = RL(cc + F2(dd, ee, aa) + X[11] + unchecked((int)0x7a6d76e9), 14) + bb; ee = RL(ee, 10);
bb = RL(bb + F2(cc, dd, ee) + X[15] + unchecked((int)0x7a6d76e9), 6) + aa; dd = RL(dd, 10);
aa = RL(aa + F2(bb, cc, dd) + X[0] + unchecked((int)0x7a6d76e9), 14) + ee; cc = RL(cc, 10);
ee = RL(ee + F2(aa, bb, cc) + X[5] + unchecked((int)0x7a6d76e9), 6) + dd; bb = RL(bb, 10);
dd = RL(dd + F2(ee, aa, bb) + X[12] + unchecked((int)0x7a6d76e9), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F2(dd, ee, aa) + X[2] + unchecked((int)0x7a6d76e9), 12) + bb; ee = RL(ee, 10);
bb = RL(bb + F2(cc, dd, ee) + X[13] + unchecked((int)0x7a6d76e9), 9) + aa; dd = RL(dd, 10);
aa = RL(aa + F2(bb, cc, dd) + X[9] + unchecked((int)0x7a6d76e9), 12) + ee; cc = RL(cc, 10);
ee = RL(ee + F2(aa, bb, cc) + X[7] + unchecked((int)0x7a6d76e9), 5) + dd; bb = RL(bb, 10);
dd = RL(dd + F2(ee, aa, bb) + X[10] + unchecked((int)0x7a6d76e9), 15) + cc; aa = RL(aa, 10);
cc = RL(cc + F2(dd, ee, aa) + X[14] + unchecked((int)0x7a6d76e9), 8) + bb; ee = RL(ee, 10);
t = d; d = dd; dd = t;
//
// Rounds 64-79
//
// left
b = RL(b + F5(c, d, e) + X[4] + unchecked((int)0xa953fd4e), 9) + a; d = RL(d, 10);
a = RL(a + F5(b, c, d) + X[0] + unchecked((int)0xa953fd4e), 15) + e; c = RL(c, 10);
e = RL(e + F5(a, b, c) + X[5] + unchecked((int)0xa953fd4e), 5) + d; b = RL(b, 10);
d = RL(d + F5(e, a, b) + X[9] + unchecked((int)0xa953fd4e), 11) + c; a = RL(a, 10);
c = RL(c + F5(d, e, a) + X[7] + unchecked((int)0xa953fd4e), 6) + b; e = RL(e, 10);
b = RL(b + F5(c, d, e) + X[12] + unchecked((int)0xa953fd4e), 8) + a; d = RL(d, 10);
a = RL(a + F5(b, c, d) + X[2] + unchecked((int)0xa953fd4e), 13) + e; c = RL(c, 10);
e = RL(e + F5(a, b, c) + X[10] + unchecked((int)0xa953fd4e), 12) + d; b = RL(b, 10);
d = RL(d + F5(e, a, b) + X[14] + unchecked((int)0xa953fd4e), 5) + c; a = RL(a, 10);
c = RL(c + F5(d, e, a) + X[1] + unchecked((int)0xa953fd4e), 12) + b; e = RL(e, 10);
b = RL(b + F5(c, d, e) + X[3] + unchecked((int)0xa953fd4e), 13) + a; d = RL(d, 10);
a = RL(a + F5(b, c, d) + X[8] + unchecked((int)0xa953fd4e), 14) + e; c = RL(c, 10);
e = RL(e + F5(a, b, c) + X[11] + unchecked((int)0xa953fd4e), 11) + d; b = RL(b, 10);
d = RL(d + F5(e, a, b) + X[6] + unchecked((int)0xa953fd4e), 8) + c; a = RL(a, 10);
c = RL(c + F5(d, e, a) + X[15] + unchecked((int)0xa953fd4e), 5) + b; e = RL(e, 10);
b = RL(b + F5(c, d, e) + X[13] + unchecked((int)0xa953fd4e), 6) + a; d = RL(d, 10);
// right
bb = RL(bb + F1(cc, dd, ee) + X[12], 8) + aa; dd = RL(dd, 10);
aa = RL(aa + F1(bb, cc, dd) + X[15], 5) + ee; cc = RL(cc, 10);
ee = RL(ee + F1(aa, bb, cc) + X[10], 12) + dd; bb = RL(bb, 10);
dd = RL(dd + F1(ee, aa, bb) + X[4], 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F1(dd, ee, aa) + X[1], 12) + bb; ee = RL(ee, 10);
bb = RL(bb + F1(cc, dd, ee) + X[5], 5) + aa; dd = RL(dd, 10);
aa = RL(aa + F1(bb, cc, dd) + X[8], 14) + ee; cc = RL(cc, 10);
ee = RL(ee + F1(aa, bb, cc) + X[7], 6) + dd; bb = RL(bb, 10);
dd = RL(dd + F1(ee, aa, bb) + X[6], 8) + cc; aa = RL(aa, 10);
cc = RL(cc + F1(dd, ee, aa) + X[2], 13) + bb; ee = RL(ee, 10);
bb = RL(bb + F1(cc, dd, ee) + X[13], 6) + aa; dd = RL(dd, 10);
aa = RL(aa + F1(bb, cc, dd) + X[14], 5) + ee; cc = RL(cc, 10);
ee = RL(ee + F1(aa, bb, cc) + X[0], 15) + dd; bb = RL(bb, 10);
dd = RL(dd + F1(ee, aa, bb) + X[3], 13) + cc; aa = RL(aa, 10);
cc = RL(cc + F1(dd, ee, aa) + X[9], 11) + bb; ee = RL(ee, 10);
bb = RL(bb + F1(cc, dd, ee) + X[11], 11) + aa; dd = RL(dd, 10);
//
// do (e, ee) swap as part of assignment.
//
H0 += a;
H1 += b;
H2 += c;
H3 += d;
H4 += ee;
H5 += aa;
H6 += bb;
H7 += cc;
H8 += dd;
H9 += e;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
for (var i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
public override IMemoable Copy()
{
return new RipeMD320Digest(this);
}
public override void Reset(IMemoable other)
{
var d = (RipeMD320Digest)other;
CopyIn(d);
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Threading;
using System.Reflection;
namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests
{
using System.Collections.ObjectModel;
using System.Management.Automation;
using Microsoft.WindowsAzure.ServiceManagement;
using Microsoft.WindowsAzure.Management.Model;
using Microsoft.WindowsAzure.Management.ServiceManagement.Model;
using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties;
using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo;
using System.IO;
[TestClass]
public class FunctionalTest
{
private ServiceManagementCmdletTestHelper vmPowershellCmdlets;
private SubscriptionData defaultAzureSubscription;
private StorageServiceKeyOperationContext storageAccountKey;
bool cleanup = true;
bool pass = false;
string testName;
private string locationName;
private string imageName;
private string serviceName = "DefaultServiceName";
private string vmName = "DefaultVmName";
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
//private string perfFile;
[TestInitialize]
public void Initialize()
{
vmPowershellCmdlets = new ServiceManagementCmdletTestHelper();
vmPowershellCmdlets.ImportAzurePublishSettingsFile(); // Import-AzurePublishSettingsFile
defaultAzureSubscription = vmPowershellCmdlets.SetDefaultAzureSubscription(Resource.DefaultSubscriptionName); // Set-AzureSubscription
Assert.AreEqual(Resource.DefaultSubscriptionName, defaultAzureSubscription.SubscriptionName);
storageAccountKey = vmPowershellCmdlets.GetAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccount); // Get-AzureStorageKey
Assert.AreEqual(defaultAzureSubscription.CurrentStorageAccount, storageAccountKey.StorageAccountName);
locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { Resource.Location }, false); // Get-AzureLocation
Console.WriteLine("Location Name: {0}", locationName);
imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "MSFT", "testvmimage" }, false); // Get-AzureVMImage
Console.WriteLine("Image Name: {0}", imageName);
if (vmPowershellCmdlets.TestAzureServiceName(serviceName))
{
Console.WriteLine("Service Name: {0} already exists.", serviceName);
if (vmPowershellCmdlets.GetAzureVM(vmName, serviceName) == null)
{
vmPowershellCmdlets.RemoveAzureService(serviceName);
vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, "p@ssw0rd", locationName);
}
}
else
{
vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, "p@ssw0rd", locationName);
Console.WriteLine("Service Name: {0} is created.", serviceName);
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureStorageAccount)")]
public void ScriptTestSample()
{
var result = vmPowershellCmdlets.RunPSScript("Get-Help Save-AzureVhd -full");
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove)-AzureAffinityGroup)")]
public void AzureAffinityGroupTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
string affinityName1 = "affinityName1";
string affinityLabel1 = affinityName1;
string location1 = "West US";
string description1 = "Affinity group for West US";
string affinityName2 = "affinityName2";
string affinityLabel2 = "label2";
string location2 = "East US";
string description2 = "Affinity group for East US";
try
{
ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper();
// Remove previously created affinity groups
foreach (var aff in vmPowershellCmdlets.GetAzureAffinityGroup(null))
{
if (aff.Name == affinityName1 || aff.Name == affinityName2)
{
vmPowershellCmdlets.RemoveAzureAffinityGroup(aff.Name);
}
}
// New-AzureAffinityGroup
vmPowershellCmdlets.NewAzureAffinityGroup(affinityName1, location1, affinityLabel1, description1);
vmPowershellCmdlets.NewAzureAffinityGroup(affinityName2, location2, affinityLabel2, description2);
Console.WriteLine("Affinity groups created: {0}, {1}", affinityName1, affinityName2);
// Get-AzureAffinityGroup
foreach (var aff in vmPowershellCmdlets.GetAzureAffinityGroup(affinityName1))
{
Console.WriteLine("Get-AzureAffinityGroup returned: Name - {0}, Location - {1}, Label - {2}, Description - {3}", aff.Name, aff.Location, aff.Label, aff.Description);
Assert.AreEqual(aff.Name, affinityName1, "Error: Affinity Name is not equal!");
Assert.AreEqual(aff.Label, affinityLabel1, "Error: Affinity Label is not equal!");
Assert.AreEqual(aff.Location, location1, "Error: Affinity Location is not equal!");
Assert.AreEqual(aff.Description, description1, "Error: Affinity Description is not equal!");
}
foreach (var aff in vmPowershellCmdlets.GetAzureAffinityGroup(affinityName2))
{
Console.WriteLine("Get-AzureAffinityGroup returned: Name - {0}, Location - {1}, Label - {2}, Description - {3}", aff.Name, aff.Location, aff.Label, aff.Description);
Assert.AreEqual(aff.Name, affinityName2, "Error: Affinity Name is not equal!");
Assert.AreEqual(aff.Label, affinityLabel2, "Error: Affinity Label is not equal!");
Assert.AreEqual(aff.Location, location2, "Error: Affinity Location is not equal!");
Assert.AreEqual(aff.Description, description2, "Error: Affinity Description is not equal!");
}
// Set-AzureAffinityGroup
vmPowershellCmdlets.SetAzureAffinityGroup(affinityName2, affinityLabel1, description1);
Console.WriteLine("update affinity group: {0}", affinityName2);
foreach (var aff in vmPowershellCmdlets.GetAzureAffinityGroup(affinityName2))
{
Console.WriteLine("Get-AzureAffinityGroup returned: Name - {0}, Location - {1}, Label - {2}, Description - {3}", aff.Name, aff.Location, aff.Label, aff.Description);
Assert.AreEqual(aff.Name, affinityName2, "Error: Affinity Name is not equal!");
Assert.AreEqual(aff.Label, affinityLabel1, "Error: Affinity Label is not equal!");
Assert.AreEqual(aff.Location, location2, "Error: Affinity Location is not equal!");
Assert.AreEqual(aff.Description, description1, "Error: Affinity Description is not equal!");
}
// Remove-AzureAffinityGroup
vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityName2);
Console.WriteLine("affinity group removed: {0}", affinityName2);
try
{
vmPowershellCmdlets.GetAzureAffinityGroup(affinityName2);
Assert.Fail("The affinity group should have been removed!");
}
catch (Exception e)
{
if (e.ToString().ToLowerInvariant().Contains("does not exist"))
{
Console.WriteLine("the affinity group, {0}, is successfully removed.", affinityName2);
}
else
{
Assert.Fail("Error during get-azureAffinityGroup: {0}", e.ToString());
}
}
vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityName1);
pass = true;
}
catch (Exception e)
{
Assert.Fail(e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Remove)-AzureCertificate)")]
public void AzureCertificateTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
string certLocation = "cert:\\CurrentUser\\My\\";
string thumbprint1 = "C5AF4AEE8FD278F9D9FCFAB7DC5436B8DF3A5074";
PSObject cert1 = vmPowershellCmdlets.RunPSScript("Get-Item " + certLocation + thumbprint1)[0];
string thumbprint2 = "2FB0786115F0C2E7575F31C0A5FBBAC559E7F96F";
PSObject cert2 = vmPowershellCmdlets.RunPSScript("Get-Item " + certLocation + thumbprint2)[0];
try
{
vmPowershellCmdlets.AddAzureCertificate(serviceName, cert1);
vmPowershellCmdlets.AddAzureCertificate(serviceName, cert2);
CertificateContext getCert1 = vmPowershellCmdlets.GetAzureCertificate(serviceName, thumbprint1, "sha1")[0];
Console.WriteLine("Cert is added: {0}", getCert1.Thumbprint);
Assert.AreEqual(getCert1.Thumbprint, thumbprint1); // Currently fails because of a bug
CertificateContext getCert2 = vmPowershellCmdlets.GetAzureCertificate(serviceName, thumbprint2, "sha1")[0];
Console.WriteLine("Cert is added: {0}", getCert2.Thumbprint);
Assert.AreEqual(getCert2.Thumbprint, thumbprint2);
vmPowershellCmdlets.RemoveAzureCertificate(serviceName, thumbprint1, "sha1");
foreach (var cert in vmPowershellCmdlets.GetAzureCertificate(serviceName))
{
Assert.AreNotEqual(cert.Thumbprint, thumbprint1, String.Format("Cert is not removed:", thumbprint1));
}
Console.WriteLine("Cert, {0}, is successfully removed.");
pass = true;
}
catch (Exception e)
{
Assert.Fail(e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("priya"), Description("Test the cmdlet (Get-Module)")]
public void AzureCertificateSettingTest()
{
cleanup = true;
testName = MethodBase.GetCurrentMethod().Name;
string thumbprint = "C5AF4AEE8FD278F9D9FCFAB7DC5436B8DF3A5074";
string store = "My";
try
{
vmName = Utilities.GetUniqueShortName("PSTestVM");
serviceName = Utilities.GetUniqueShortName("PSTestService");
vmPowershellCmdlets.NewAzureService(serviceName, locationName);
CertificateSetting cert = vmPowershellCmdlets.NewAzureCertificateSetting(thumbprint, store);
CertificateSettingList certList = new CertificateSettingList();
certList.Add(cert);
AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, VMSizeInfo.Small, imageName);
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, certList, "Cert1234!");
PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null);
PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo);
vmPowershellCmdlets.NewAzureVM(serviceName, new [] {vm});
PersistentVMRoleContext result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName);
Console.WriteLine("{0} is created", result.Name);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureDataDisk)")]
public void AzureDataDiskTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
string diskLabel1 = "disk1";
int diskSize1 = 30;
int lunSlot1 = 0;
string diskLabel2 = "disk2";
int diskSize2 = 50;
int lunSlot2 = 2;
try
{
AddAzureDataDiskConfig dataDiskInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize1, diskLabel1, lunSlot1);
AddAzureDataDiskConfig dataDiskInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize2, diskLabel2, lunSlot2);
vmPowershellCmdlets.AddDataDisk(vmName, serviceName, new [] {dataDiskInfo1, dataDiskInfo2}); // Add-AzureEndpoint with Get-AzureVM and Update-AzureVm
Assert.IsTrue(CheckDataDisk(vmName, serviceName, dataDiskInfo1, HostCaching.None), "Data disk is not properly added");
Console.WriteLine("Data disk added correctly.");
Assert.IsTrue(CheckDataDisk(vmName, serviceName, dataDiskInfo2, HostCaching.None), "Data disk is not properly added");
Console.WriteLine("Data disk added correctly.");
vmPowershellCmdlets.SetDataDisk(vmName, serviceName, HostCaching.ReadOnly, lunSlot1);
Assert.IsTrue(CheckDataDisk(vmName, serviceName, dataDiskInfo1, HostCaching.ReadOnly), "Data disk is not properly changed");
Console.WriteLine("Data disk is changed correctly.");
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
// Remove DataDisks created
vmPowershellCmdlets.RemoveDataDisk(vmName, serviceName, new [] {lunSlot1, lunSlot2}); // Remove-AzureDataDisk
// ToDo: Verify removal
}
}
private bool CheckDataDisk(string vmName, string serviceName, AddAzureDataDiskConfig dataDiskInfo, HostCaching hc)
{
bool found = false;
foreach (DataVirtualHardDisk disk in vmPowershellCmdlets.GetAzureDataDisk(vmName, serviceName))
{
Console.WriteLine("DataDisk - Name:{0}, Label:{1}, Size:{2}, LUN:{3}, HostCaching: {4}", disk.DiskName, disk.DiskLabel, disk.LogicalDiskSizeInGB, disk.Lun, disk.HostCaching);
if (disk.DiskLabel == dataDiskInfo.DiskLabel && disk.LogicalDiskSizeInGB == dataDiskInfo.DiskSizeGB && disk.Lun == dataDiskInfo.LunSlot)
{
if (disk.HostCaching == hc.ToString())
{
found = true;
Console.WriteLine("DataDisk found: {0}", disk.DiskLabel);
}
}
}
return found;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Update,Remove)-AzureDisk)")]
public void AzureDiskTest()
{
testName = MethodBase.GetCurrentMethod().Name;
cleanup = false;
string vhdName = "128GBOS.vhd";
string vhdLocalPath = "http://"+defaultAzureSubscription.CurrentStorageAccount+".blob.core.windows.net/vhdstore/"+vhdName;
try
{
vmPowershellCmdlets.AddAzureDisk(vhdName, vhdLocalPath, vhdName, null);
bool found = false;
foreach (DiskContext disk in vmPowershellCmdlets.GetAzureDisk(vhdName))
{
Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk.DiskName, disk.Label, disk.DiskSizeInGB);
if (disk.DiskName == vhdName && disk.Label == vhdName)
{
found = true;
Console.WriteLine("{0} is found", disk.DiskName);
}
}
Assert.IsTrue(found, "Error: Disk is not added");
string newLabel = "NewLabel";
vmPowershellCmdlets.UpdateAzureDisk(vhdName, newLabel);
DiskContext disk2 = vmPowershellCmdlets.GetAzureDisk(vhdName)[0];
Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk2.DiskName, disk2.Label, disk2.DiskSizeInGB);
Assert.AreEqual(newLabel, disk2.Label);
Console.WriteLine("Disk Label is successfully updated");
vmPowershellCmdlets.RemoveAzureDisk(vhdName, false);
Assert.IsTrue(CheckRemove(vmPowershellCmdlets.GetAzureDisk, vhdName), "The disk was not removed");
}
catch (Exception e)
{
pass = false;
Console.WriteLine("Exception occurs: {0}", e.ToString());
}
finally
{
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove,Move)-AzureDeployment)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", ".\\package.csv", "package#csv", DataAccessMethod.Sequential)]
public void AzureDeploymentTest()
{
testName = MethodBase.GetCurrentMethod().Name;
cleanup = true;
// Choose the package and config files from local machine
string packageName = Convert.ToString(TestContext.DataRow["packageName"]);
string configName = Convert.ToString(TestContext.DataRow["configName"]);
string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]);
string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]);
var packagePath1 = new FileInfo(@".\" + packageName);
var configPath1 = new FileInfo(@".\" + configName);
var packagePath2 = new FileInfo(@".\" + upgradePackageName);
var configPath2 = new FileInfo(@".\" + upgradeConfigName);
Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1);
Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1);
string deploymentName = "deployment1";
string deploymentLabel = "label1";
DeploymentInfoContext result;
try
{
serviceName = Utilities.GetUniqueShortName("PSTestService");
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
Console.WriteLine("service, {0}, is created.", serviceName);
vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Staging, deploymentLabel, deploymentName, false, false);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Staging);
PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Staging, null, 1);
Console.WriteLine("successfully deployed the package");
// Move the deployment from 'Staging' to 'Production'
vmPowershellCmdlets.MoveAzureDeployment(serviceName);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 1);
Console.WriteLine("successfully moved");
// Set the deployment status to 'Suspended'
vmPowershellCmdlets.SetAzureDeploymentStatus(serviceName, DeploymentSlotType.Production, DeploymentStatus.Suspended);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, DeploymentStatus.Suspended, 1);
Console.WriteLine("successfully changed the status");
// Update the deployment
vmPowershellCmdlets.SetAzureDeploymentConfig(serviceName, DeploymentSlotType.Production, configPath2.FullName);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2);
Console.WriteLine("successfully updated the deployment");
// Upgrade the deployment
vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Auto, packagePath2.FullName, configPath2.FullName);
result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 2);
Console.WriteLine("successfully updated the deployment");
vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true);
try
{
vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production);
Assert.Fail("the deployment is not removed!");
}
catch(Exception e1)
{
if (e1.ToString().Contains("ResourceNotFound"))
{
Console.WriteLine("Successfully removed the deployment");
}
else
{
Assert.Fail("Exception occurred: {0}", e1.ToString());
}
}
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
}
}
private bool PrintAndCompareDeployment(DeploymentInfoContext deployment, string serviceName, string deploymentName, string deploymentLabel, string slot, string status, int instanceCount)
{
Console.WriteLine("ServiceName:{0}, DeploymentID: {1}, Uri: {2}", deployment.ServiceName, deployment.DeploymentId, deployment.Url.AbsoluteUri);
Console.WriteLine("Name - {0}, Label - {1}, Slot - {2}, Status - {3}",
deployment.DeploymentName, deployment.Label, deployment.Slot, deployment.Status);
Console.WriteLine("RoleInstance: {0}", deployment.RoleInstanceList.Count);
foreach (var instance in deployment.RoleInstanceList)
{
Console.WriteLine("InstanceName - {0}, InstanceStatus - {1}", instance.InstanceName, instance.InstanceStatus);
}
Assert.AreEqual(deployment.ServiceName, serviceName);
Assert.AreEqual(deployment.DeploymentName, deploymentName);
Assert.AreEqual(deployment.Label, deploymentLabel);
Assert.AreEqual(deployment.Slot, slot);
if (status != null)
{
Assert.AreEqual(deployment.Status, status);
}
Assert.AreEqual(deployment.RoleInstanceList.Count, instanceCount);
return true;
}
/// <summary>
///
/// </summary>
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get)-AzureDns)")]
public void AzureDnsTest()
{
cleanup = true;
testName = MethodBase.GetCurrentMethod().Name;
string dnsName = "OpenDns1";
string ipAddress = "208.67.222.222";
try
{
serviceName = Utilities.GetUniqueShortName("PSTestService");
vmPowershellCmdlets.NewAzureService(serviceName, locationName);
DnsServer dns = vmPowershellCmdlets.NewAzureDns(dnsName, ipAddress);
AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, VMSizeInfo.ExtraSmall, imageName);
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, "password1234!");
PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null);
PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo);
vmPowershellCmdlets.NewAzureVM(serviceName, new []{vm}, null, new[]{dns}, null, null, null, null, null, null);
DnsServerList dnsList = vmPowershellCmdlets.GetAzureDns(vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production).DnsSettings);
foreach (DnsServer dnsServer in dnsList)
{
Console.WriteLine("DNS Server Name: {0}, DNS Server Address: {1}", dnsServer.Name, dnsServer.Address);
Assert.AreEqual(dnsServer.Name, dns.Name);
Assert.AreEqual(dnsServer.Address, dns.Address);
}
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureEndpoint)")]
public void AzureEndpointTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
string epName1 = "tcp1";
int localPort1 = 60010;
int port1 = 60011;
string epName2 = "tcp2";
int localPort2 = 60020;
int port2 = 60021;
try
{
// Add two new endpoints
AzureEndPointConfigInfo epInfo1 = new AzureEndPointConfigInfo(ProtocolInfo.tcp, localPort1, port1, epName1);
AzureEndPointConfigInfo epInfo2 = new AzureEndPointConfigInfo(ProtocolInfo.tcp, localPort2, port2, epName2);
vmPowershellCmdlets.AddEndPoint(vmName, serviceName, new[] { epInfo1, epInfo2 }); // Add-AzureEndpoint with Get-AzureVM and Update-AzureVm
Assert.IsTrue(CheckEndpoint(vmName, serviceName, epInfo1), "Error: Endpoint was not added!");
Assert.IsTrue(CheckEndpoint(vmName, serviceName, epInfo2), "Error: Endpoint was not added!");
// Change the endpoint
AzureEndPointConfigInfo epInfo3 = new AzureEndPointConfigInfo(ProtocolInfo.tcp, 60030, 60031, epName2);
vmPowershellCmdlets.SetEndPoint(vmName, serviceName, epInfo3); // Set-AzureEndpoint with Get-AzureVM and Update-AzureVm
Assert.IsTrue(CheckEndpoint(vmName, serviceName, epInfo3), "Error: Endpoint was not changed!");
// Remove Endpoint
vmPowershellCmdlets.RemoveEndPoint(vmName, serviceName, new[] { epName1, epName2 }); // Remove-AzureEndpoint
Assert.IsFalse(CheckEndpoint(vmName, serviceName, epInfo1), "Error: Endpoint was not removed!");
Assert.IsFalse(CheckEndpoint(vmName, serviceName, epInfo3), "Error: Endpoint was not removed!");
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
}
}
private bool CheckEndpoint(string vmName, string serviceName, AzureEndPointConfigInfo epInfo)
{
bool found = false;
foreach (InputEndpointContext ep in vmPowershellCmdlets.GetAzureEndPoint(vmPowershellCmdlets.GetAzureVM(vmName, serviceName)))
{
Console.WriteLine("Endpoint - Name:{0}, Protocol:{1}, Port:{2}, LocalPort:{3}, Vip:{4}", ep.Name, ep.Protocol, ep.Port, ep.LocalPort, ep.Vip);
if (ep.Name == epInfo.EndpointName && ep.LocalPort == epInfo.InternalPort && ep.Port == epInfo.ExternalPort && ep.Protocol == epInfo.Protocol.ToString())
{
found = true;
Console.WriteLine("Endpoint found: {0}", epInfo.EndpointName);
}
}
return found;
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureLocation)")]
public void AzureLocationTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
try
{
foreach (LocationsContext loc in vmPowershellCmdlets.GetAzureLocation())
{
Console.WriteLine("Location: Name - {0}, DisplayName - {1}", loc.Name, loc.DisplayName);
}
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureOSDisk)")]
public void AzureOSDiskTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
try
{
PersistentVM vm = vmPowershellCmdlets.GetAzureVM(vmName, serviceName).VM;
OSVirtualHardDisk osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm);
Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS);
Assert.IsTrue(osdisk.Equals(vm.OSVirtualHardDisk), "OS disk returned is not the same!");
PersistentVM vm2 = vmPowershellCmdlets.SetAzureOSDisk(HostCaching.ReadOnly, vm);
osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm2);
Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS);
Assert.IsTrue(osdisk.Equals(vm2.OSVirtualHardDisk), "OS disk returned is not the same!");
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureOSVersion)")]
public void AzureOSVersionTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
try
{
foreach (OSVersionsContext osVersions in vmPowershellCmdlets.GetAzureOSVersion())
{
Console.WriteLine("OS Version: Family - {0}, FamilyLabel - {1}, Version - {2}", osVersions.Family, osVersions.FamilyLabel, osVersions.Version);
}
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureRole)")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", ".\\package.csv", "package#csv", DataAccessMethod.Sequential)]
public void AzureRoleTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
// Choose the package and config files from local machine
string packageName = Convert.ToString(TestContext.DataRow["packageName"]);
string configName = Convert.ToString(TestContext.DataRow["configName"]);
string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]);
string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]);
var packagePath1 = new FileInfo(@".\" + packageName);
var configPath1 = new FileInfo(@".\" + configName);
Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1);
Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1);
string deploymentName = "deployment1";
string deploymentLabel = "label1";
string slot = DeploymentSlotType.Production;
//DeploymentInfoContext result;
string roleName = "";
try
{
serviceName = Utilities.GetUniqueShortName("PSTestService");
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, slot, deploymentLabel, deploymentName, false, false);
foreach (RoleContext role in vmPowershellCmdlets.GetAzureRole(serviceName, slot, null, false))
{
Console.WriteLine("Role: Name - {0}, ServiceName - {1}, DeploymenntID - {2}, InstanceCount - {3}", role.RoleName, role.ServiceName, role.DeploymentID, role.InstanceCount);
Assert.AreEqual(serviceName, role.ServiceName);
roleName = role.RoleName;
}
vmPowershellCmdlets.SetAzureRole(serviceName, slot, roleName, 2);
foreach (RoleContext role in vmPowershellCmdlets.GetAzureRole(serviceName, slot, null, false))
{
Console.WriteLine("Role: Name - {0}, ServiceName - {1}, DeploymenntID - {2}, InstanceCount - {3}", role.RoleName, role.ServiceName, role.DeploymentID, role.InstanceCount);
Assert.AreEqual(serviceName, role.ServiceName);
Assert.AreEqual(2, role.InstanceCount);
}
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureSubnet)")]
public void AzureSubnetTest()
{
cleanup = true;
testName = MethodBase.GetCurrentMethod().Name;
try
{
serviceName = Utilities.GetUniqueShortName("PSTestService");
vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName);
PersistentVM vm = vmPowershellCmdlets.NewAzureVMConfig(new AzureVMConfigInfo(vmName, VMSizeInfo.Small, imageName));
AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, "password1234!");
azureProvisioningConfig.Vm = vm;
string [] subs = new [] {"subnet1", "subnet2", "subnet3"};
vm = vmPowershellCmdlets.SetAzureSubnet(vmPowershellCmdlets.AddAzureProvisioningConfig(azureProvisioningConfig), subs);
SubnetNamesCollection subnets = vmPowershellCmdlets.GetAzureSubnet(vm);
foreach (string subnet in subnets)
{
Console.WriteLine("Subnet: {0}", subnet);
}
CollectionAssert.AreEqual(subnets, subs);
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get)-AzureStorageKey)")]
public void AzureStorageKeyTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
try
{
StorageServiceKeyOperationContext key1 = vmPowershellCmdlets.GetAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccount); // Get-AzureStorageAccountKey
Console.WriteLine("Primary - {0}", key1.Primary);
Console.WriteLine("Secondary - {0}", key1.Secondary);
StorageServiceKeyOperationContext key2 = vmPowershellCmdlets.NewAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccount, KeyType.Primary);
Console.WriteLine("Primary - {0}", key2.Primary);
Console.WriteLine("Secondary - {0}", key2.Secondary);
Assert.AreNotEqual(key1.Primary, key2.Primary);
Assert.AreEqual(key1.Secondary, key2.Secondary);
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove)-AzureStorageAccount)")]
public void AzureStorageAccountTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
string storageName1 = Utilities.GetUniqueShortName("psteststorage");
string locationName1 = "West US";
string storageName2 = Utilities.GetUniqueShortName("psteststorage");
string locationName2 = "East US";
try
{
vmPowershellCmdlets.NewAzureStorageAccount(storageName1, locationName1, null, null, null);
vmPowershellCmdlets.NewAzureStorageAccount(storageName2, locationName2, null, null, null);
Assert.IsNotNull(vmPowershellCmdlets.GetAzureStorageAccount(storageName1));
Console.WriteLine("{0} is created", storageName1);
Assert.IsNotNull(vmPowershellCmdlets.GetAzureStorageAccount(storageName2));
Console.WriteLine("{0} is created", storageName2);
vmPowershellCmdlets.SetAzureStorageAccount(storageName1, "newLabel", "newDescription", false);
StorageServicePropertiesOperationContext storage = vmPowershellCmdlets.GetAzureStorageAccount(storageName1)[0];
Console.WriteLine("Name: {0}, Label: {1}, Description: {2}, GeoReplication: {3}", storage.StorageAccountName, storage.Label, storage.StorageAccountDescription, storage.GeoReplicationEnabled.ToString());
Assert.IsTrue((storage.Label == "newLabel" && storage.StorageAccountDescription == "newDescription" && storage.GeoReplicationEnabled == false), "storage account is not changed correctly");
vmPowershellCmdlets.RemoveAzureStorageAccount(storageName1);
vmPowershellCmdlets.RemoveAzureStorageAccount(storageName2);
Assert.IsTrue(CheckRemove(vmPowershellCmdlets.GetAzureStorageAccount, storageName1), "The storage account was not removed");
Assert.IsTrue(CheckRemove(vmPowershellCmdlets.GetAzureStorageAccount, storageName2), "The storage account was not removed");
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Save,Update,Remove)-AzureVMImage)")]
public void AzureVMImageTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
string newImageName = Utilities.GetUniqueShortName("vmimage");
string blobUrlRoot = string.Format(@"http://{0}.blob.core.windows.net/", defaultAzureSubscription.CurrentStorageAccount);
string mediaLocation = string.Format("{0}vhdstore/128GBOS.vhd", blobUrlRoot);
string oldLabel = "old label";
string newLabel = "new label";
try
{
OSImageContext result = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OSType.Windows, oldLabel);
OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
if (!result.Equals(resultReturned))
{
pass = false;
}
result = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, newLabel);
resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0];
//Assert.AreEqual(result, resultReturned);
if (!result.Equals(resultReturned))
{
pass = false;
}
vmPowershellCmdlets.RemoveAzureVMImage(newImageName);
//pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
}
}
/// <summary>
/// AzureVNetGatewayTest()
/// </summary>
/// Note: Create a VNet, a LocalNet from the portal without creating a gateway.
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove)-AzureVNetGateway)")]
public void AzureVNetGatewayTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
string vnetName1 = "NewVNet1"; // For connect test
string vnetName2 = "NewVNet2"; // For disconnect test
string vnetName3 = "NewVNet3"; // For create test
string localNet = "LocalNet1"; // Your local network site name.
try
{
// New-AzureVNetGateway
vmPowershellCmdlets.NewAzureVNetGateway(vnetName3);
foreach (VirtualNetworkSiteContext site in vmPowershellCmdlets.GetAzureVNetSite(vnetName3))
{
Console.WriteLine("Name: {0}, AffinityGroup: {1}", site.Name, site.AffinityGroup);
}
// Remove-AzureVnetGateway
vmPowershellCmdlets.RemoveAzureVNetGateway(vnetName3);
foreach (VirtualNetworkGatewayContext gateway in vmPowershellCmdlets.GetAzureVNetGateway(vnetName3))
{
Console.WriteLine("State: {0}, VIP: {1}", gateway.State.ToString(), gateway.VIPAddress);
}
// Set-AzureVNetGateway -Connect Test
vmPowershellCmdlets.SetAzureVNetGateway("connect", vnetName1, localNet);
foreach (GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnetName1))
{
Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName);
Assert.IsFalse(connection.ConnectivityState.ToLowerInvariant().Contains("notconnected"));
}
foreach (VirtualNetworkGatewayContext gateway in vmPowershellCmdlets.GetAzureVNetGateway(vnetName1))
{
Console.WriteLine("State: {0}, VIP: {1}", gateway.State.ToString(), gateway.VIPAddress);
}
// Set-AzureVNetGateway -Disconnect
vmPowershellCmdlets.SetAzureVNetGateway("disconnect", vnetName2, localNet);
foreach (GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnetName2))
{
Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName);
if (connection.LocalNetworkSiteName == localNet)
{
Assert.IsTrue(connection.ConnectivityState.ToLowerInvariant().Contains("notconnected"));
}
}
foreach (VirtualNetworkGatewayContext gateway in vmPowershellCmdlets.GetAzureVNetGateway(vnetName2))
{
Console.WriteLine("State: {0}, VIP: {1}", gateway.State.ToString(), gateway.VIPAddress);
}
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
finally
{
}
}
/// <summary>
///
/// </summary>
/// Note: You have to manually create a virtual network, a Local network, a gateway, and connect them.
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureVNetGatewayKey, Get-AzureVNetConnection)")]
public void AzureVNetGatewayKeyTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
string vnetName = "NewVNet1";
try
{
SharedKeyContext result = vmPowershellCmdlets.GetAzureVNetGatewayKey(vnetName, vmPowershellCmdlets.GetAzureVNetConnection(vnetName)[0].LocalNetworkSiteName);
Console.WriteLine(result.Value);
pass = true;
}
catch (Exception e)
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
[TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set,Remove)-AzureVNetConfig)")]
public void AzureVNetConfigTest()
{
cleanup = false;
testName = MethodBase.GetCurrentMethod().Name;
string filePath = "C:\\vnetconfig.netcfg";
try
{
var result = vmPowershellCmdlets.GetAzureVNetConfig(filePath);
vmPowershellCmdlets.SetAzureVNetConfig(filePath);
Collection<VirtualNetworkSiteContext> vnetSites = vmPowershellCmdlets.GetAzureVNetSite(null);
foreach (var re in vnetSites)
{
Console.WriteLine("VNet: {0}", re.Name);
}
vmPowershellCmdlets.RemoveAzureVNetConfig();
Collection<VirtualNetworkSiteContext> vnetSitesAfter = vmPowershellCmdlets.GetAzureVNetSite(null);
Assert.AreNotEqual(vnetSites.Count, vnetSitesAfter.Count, "No Vnet is removed");
foreach (var re in vnetSitesAfter)
{
Console.WriteLine("VNet: {0}", re.Name);
}
pass = true;
}
catch (Exception e)
{
if (e.ToString().Contains("while in use"))
{
Console.WriteLine(e.InnerException.ToString());
}
else
{
Assert.Fail("Exception occurred: {0}", e.ToString());
}
}
finally
{
}
}
// CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name'
private bool CheckRemove<T>(Func<string, T> fn, string name)
{
try
{
fn(name);
return false;
}
catch (Exception e)
{
if (e.ToString().Contains("ResourceNotFound"))
{
Console.WriteLine("{0} is successfully removed", name);
return true;
}
else
{
Console.WriteLine("Error: {0}", e.ToString());
return false;
}
}
}
[TestCleanup]
public virtual void CleanUp()
{
if (pass)
{
Console.WriteLine("{0} passed.", testName);
}
// Cleanup
//vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName);
/* RemoveAzureService doesn't work */
if (cleanup)
{
vmPowershellCmdlets.RemoveAzureService(serviceName);
Console.WriteLine("Service, {0}, is deleted", serviceName);
}
//Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Runtime.Versioning;
using EnvDTE;
using NuGet.Resources;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Resources;
namespace NuGet.PowerShell.Commands
{
/// <summary>
/// This class acts as the base class for InstallPackage, UninstallPackage and UpdatePackage commands.
/// </summary>
public abstract class ProcessPackageBaseCommand : NuGetBaseCommand
{
// If this command is executed by getting the project from the pipeline, then we need we keep track of all of the
// project managers since the same cmdlet instance can be used across invocations.
private readonly Dictionary<string, IProjectManager> _projectManagers = new Dictionary<string, IProjectManager>();
private readonly Dictionary<IProjectManager, Project> _projectManagerToProject = new Dictionary<IProjectManager, Project>();
private string _readmeFile;
private readonly IVsCommonOperations _vsCommonOperations;
private readonly IDeleteOnRestartManager _deleteOnRestartManager;
private IDisposable _expandedNodesDisposable;
protected ProcessPackageBaseCommand(
ISolutionManager solutionManager,
IVsPackageManagerFactory packageManagerFactory,
IHttpClientEvents httpClientEvents,
IVsCommonOperations vsCommonOperations,
IDeleteOnRestartManager deleteOnRestartManager)
: base(solutionManager, packageManagerFactory, httpClientEvents)
{
Debug.Assert(vsCommonOperations != null);
_vsCommonOperations = vsCommonOperations;
_deleteOnRestartManager = deleteOnRestartManager;
}
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)]
public virtual string Id { get; set; }
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
public virtual string ProjectName { get; set; }
protected IProjectManager ProjectManager
{
get
{
// We take a snapshot of the default project, the first time it is accessed so if it changes during
// the executing of this cmdlet we won't take it into consideration. (which is really an edge case anyway)
string name = ProjectName ?? String.Empty;
IProjectManager projectManager;
if (!_projectManagers.TryGetValue(name, out projectManager))
{
Tuple<IProjectManager, Project> tuple = GetProjectManager();
if (tuple != null)
{
projectManager = tuple.Item1;
if (projectManager != null)
{
_projectManagers.Add(name, projectManager);
}
}
}
return projectManager;
}
}
protected override void BeginProcessing()
{
base.BeginProcessing();
_readmeFile = null;
if (PackageManager != null)
{
PackageManager.PackageInstalling += OnPackageInstalling;
PackageManager.PackageInstalled += OnPackageInstalled;
}
// remember currently expanded nodes so that we can leave them expanded
// after the operation has finished.
SaveExpandedNodes();
}
protected override void EndProcessing()
{
base.EndProcessing();
if (PackageManager != null)
{
PackageManager.PackageInstalling -= OnPackageInstalling;
PackageManager.PackageInstalled -= OnPackageInstalled;
}
foreach (var projectManager in _projectManagers.Values)
{
projectManager.PackageReferenceAdded -= OnPackageReferenceAdded;
projectManager.PackageReferenceRemoving -= OnPackageReferenceRemoving;
}
IList<string> packageDirectoriesMarkedForDeletion = _deleteOnRestartManager.GetPackageDirectoriesMarkedForDeletion();
if (packageDirectoriesMarkedForDeletion != null && packageDirectoriesMarkedForDeletion.Count != 0)
{
var message = string.Format(
CultureInfo.CurrentCulture,
VsResources.RequestRestartToCompleteUninstall,
string.Join(", ", packageDirectoriesMarkedForDeletion));
WriteWarning(message);
}
WriteLine();
OpenReadMeFile();
CollapseNodes();
}
private Tuple<IProjectManager, Project> GetProjectManager()
{
if (PackageManager == null)
{
return null;
}
Project project = GetProject(throwIfNotExists: true);
if (project == null)
{
// No project specified and default project was null
return null;
}
return GetProjectManager(project);
}
private Project GetProject(bool throwIfNotExists)
{
Project project = null;
// If the user specified a project then use it
if (!String.IsNullOrEmpty(ProjectName))
{
project = SolutionManager.GetProject(ProjectName);
// If that project was invalid then throw
if (project == null && throwIfNotExists)
{
ErrorHandler.ThrowNoCompatibleProjectsTerminatingError();
}
}
else if (!String.IsNullOrEmpty(SolutionManager.DefaultProjectName))
{
// If there is a default project then use it
project = SolutionManager.GetProject(SolutionManager.DefaultProjectName);
Debug.Assert(project != null, "default project should never be invalid");
}
return project;
}
private Tuple<IProjectManager, Project> GetProjectManager(Project project)
{
IProjectManager projectManager = RegisterProjectEvents(project);
return Tuple.Create(projectManager, project);
}
protected IProjectManager RegisterProjectEvents(Project project)
{
IProjectManager projectManager = PackageManager.GetProjectManager(project);
if (!_projectManagerToProject.ContainsKey(projectManager))
{
projectManager.PackageReferenceAdded += OnPackageReferenceAdded;
projectManager.PackageReferenceRemoving += OnPackageReferenceRemoving;
// Associate the project manager with this project
_projectManagerToProject[projectManager] = project;
}
return projectManager;
}
private void OnPackageInstalling(object sender, PackageOperationEventArgs e)
{
// Write disclaimer text before a package is installed
WriteDisclaimerText(e.Package);
}
private void OnPackageInstalled(object sender, PackageOperationEventArgs e)
{
AddToolsFolderToEnvironmentPath(e.InstallPath);
ExecuteScript(e.InstallPath, PowerShellScripts.Init, e.Package, targetFramework: null, project: null);
PrepareOpenReadMeFile(e);
}
private void PrepareOpenReadMeFile(PackageOperationEventArgs e)
{
// only open the read me file for the first package that initiates this operation.
if (e.Package.Id.Equals(this.Id, StringComparison.OrdinalIgnoreCase) && e.Package.HasReadMeFileAtRoot())
{
_readmeFile = Path.Combine(e.InstallPath, NuGetConstants.ReadmeFileName);
}
}
private void OpenReadMeFile()
{
if (_readmeFile != null )
{
_vsCommonOperations.OpenFile(_readmeFile);
}
}
protected virtual void AddToolsFolderToEnvironmentPath(string installPath)
{
string toolsPath = Path.Combine(installPath, "tools");
if (Directory.Exists(toolsPath))
{
var envPath = (string)GetVariableValue("env:path");
if (!envPath.EndsWith(";", StringComparison.OrdinalIgnoreCase))
{
envPath = envPath + ";";
}
envPath += toolsPath;
SessionState.PSVariable.Set("env:path", envPath);
}
}
private void OnPackageReferenceAdded(object sender, PackageOperationEventArgs e)
{
var projectManager = (IProjectManager)sender;
Project project;
if (!_projectManagerToProject.TryGetValue(projectManager, out project))
{
throw new ArgumentException(Resources.Cmdlet_InvalidProjectManagerInstance, "sender");
}
ExecuteScript(e.InstallPath, PowerShellScripts.Install, e.Package, project.GetTargetFrameworkName(), project);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void OnPackageReferenceRemoving(object sender, PackageOperationEventArgs e)
{
var projectManager = (IProjectManager)sender;
Project project;
if (!_projectManagerToProject.TryGetValue(projectManager, out project))
{
throw new ArgumentException(Resources.Cmdlet_InvalidProjectManagerInstance, "sender");
}
try
{
ExecuteScript(
e.InstallPath,
PowerShellScripts.Uninstall,
e.Package,
projectManager.GetTargetFrameworkForPackage(e.Package.Id),
project);
}
catch (Exception ex)
{
LogCore(MessageLevel.Warning, ex.Message);
}
}
protected void ExecuteScript(
string rootPath,
string scriptFileName,
IPackage package,
FrameworkName targetFramework,
Project project)
{
string fullPath;
IPackageFile scriptFile;
if (package.FindCompatibleToolFiles(scriptFileName, targetFramework, out scriptFile))
{
fullPath = Path.Combine(rootPath, scriptFile.Path);
}
else
{
return;
}
if (File.Exists(fullPath))
{
if (project != null && scriptFile != null)
{
// targetFramework can be null for unknown project types
string shortFramework = targetFramework == null ? string.Empty : VersionUtility.GetShortFrameworkName(targetFramework);
WriteVerbose(String.Format(CultureInfo.CurrentCulture, NuGetResources.Debug_TargetFrameworkInfoPrefix,
package.GetFullName(), project.Name, shortFramework));
WriteVerbose(String.Format(CultureInfo.CurrentCulture, NuGetResources.Debug_TargetFrameworkInfo_PowershellScripts,
Path.GetDirectoryName(scriptFile.Path), VersionUtility.GetTargetFrameworkLogString(scriptFile.TargetFramework)));
}
var psVariable = SessionState.PSVariable;
string toolsPath = Path.GetDirectoryName(fullPath);
// set temp variables to pass to the script
psVariable.Set("__rootPath", rootPath);
psVariable.Set("__toolsPath", toolsPath);
psVariable.Set("__package", package);
psVariable.Set("__project", project);
string command = "& " + PathHelper.EscapePSPath(fullPath) + " $__rootPath $__toolsPath $__package $__project";
WriteVerbose(String.Format(CultureInfo.CurrentCulture, VsResources.ExecutingScript, fullPath));
InvokeCommand.InvokeScript(command, false, PipelineResultTypes.Error, null, null);
// clear temp variables
psVariable.Remove("__rootPath");
psVariable.Remove("__toolsPath");
psVariable.Remove("__package");
psVariable.Remove("__project");
}
}
protected virtual void WriteDisclaimerText(IPackageMetadata package)
{
if (package.RequireLicenseAcceptance)
{
string message = String.Format(
CultureInfo.CurrentCulture,
Resources.Cmdlet_InstallSuccessDisclaimerText,
package.Id,
String.Join(", ", package.Authors),
package.LicenseUrl);
WriteLine(message);
}
}
private void SaveExpandedNodes()
{
// remember which nodes are currently open so that we can keep them open after the operation
_expandedNodesDisposable = _vsCommonOperations.SaveSolutionExplorerNodeStates(SolutionManager);
}
private void CollapseNodes()
{
// collapse all nodes in solution explorer that we expanded during the operation
if (_expandedNodesDisposable != null)
{
_expandedNodesDisposable.Dispose();
_expandedNodesDisposable = null;
}
}
protected override void OnSendingRequest(object sender, WebRequestEventArgs e)
{
Project project = GetProject(throwIfNotExists: false);
var projectGuids = project == null ? null : project.GetAllProjectTypeGuid();
HttpUtility.SetUserAgent(e.Request, DefaultUserAgent, projectGuids);
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// OrderByClause
/// </summary>
[DataContract]
public partial class OrderByClause : IEquatable<OrderByClause>, IValidatableObject
{
/// <summary>
/// Gets or Sets Direction
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum DirectionEnum
{
/// <summary>
/// Enum Ascending for "Ascending"
/// </summary>
[EnumMember(Value = "Ascending")]
Ascending,
/// <summary>
/// Enum Descending for "Descending"
/// </summary>
[EnumMember(Value = "Descending")]
Descending
}
/// <summary>
/// Gets or Sets Direction
/// </summary>
[DataMember(Name="direction", EmitDefaultValue=true)]
public DirectionEnum? Direction { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="OrderByClause" /> class.
/// </summary>
/// <param name="ThenBy">ThenBy.</param>
/// <param name="Expression">Expression.</param>
/// <param name="Direction">Direction.</param>
/// <param name="RangeVariable">RangeVariable.</param>
/// <param name="ItemType">ItemType.</param>
public OrderByClause(OrderByClause ThenBy = null, SingleValueNode Expression = null, DirectionEnum? Direction = null, RangeVariable RangeVariable = null, IEdmTypeReference ItemType = null)
{
this.ThenBy = ThenBy;
this.Expression = Expression;
this.Direction = Direction;
this.RangeVariable = RangeVariable;
this.ItemType = ItemType;
}
/// <summary>
/// Gets or Sets ThenBy
/// </summary>
[DataMember(Name="thenBy", EmitDefaultValue=true)]
public OrderByClause ThenBy { get; set; }
/// <summary>
/// Gets or Sets Expression
/// </summary>
[DataMember(Name="expression", EmitDefaultValue=true)]
public SingleValueNode Expression { get; set; }
/// <summary>
/// Gets or Sets RangeVariable
/// </summary>
[DataMember(Name="rangeVariable", EmitDefaultValue=true)]
public RangeVariable RangeVariable { get; set; }
/// <summary>
/// Gets or Sets ItemType
/// </summary>
[DataMember(Name="itemType", EmitDefaultValue=true)]
public IEdmTypeReference ItemType { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class OrderByClause {\n");
sb.Append(" ThenBy: ").Append(ThenBy).Append("\n");
sb.Append(" Expression: ").Append(Expression).Append("\n");
sb.Append(" Direction: ").Append(Direction).Append("\n");
sb.Append(" RangeVariable: ").Append(RangeVariable).Append("\n");
sb.Append(" ItemType: ").Append(ItemType).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as OrderByClause);
}
/// <summary>
/// Returns true if OrderByClause instances are equal
/// </summary>
/// <param name="other">Instance of OrderByClause to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OrderByClause other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ThenBy == other.ThenBy ||
this.ThenBy != null &&
this.ThenBy.Equals(other.ThenBy)
) &&
(
this.Expression == other.Expression ||
this.Expression != null &&
this.Expression.Equals(other.Expression)
) &&
(
this.Direction == other.Direction ||
this.Direction != null &&
this.Direction.Equals(other.Direction)
) &&
(
this.RangeVariable == other.RangeVariable ||
this.RangeVariable != null &&
this.RangeVariable.Equals(other.RangeVariable)
) &&
(
this.ItemType == other.ItemType ||
this.ItemType != null &&
this.ItemType.Equals(other.ItemType)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ThenBy != null)
hash = hash * 59 + this.ThenBy.GetHashCode();
if (this.Expression != null)
hash = hash * 59 + this.Expression.GetHashCode();
if (this.Direction != null)
hash = hash * 59 + this.Direction.GetHashCode();
if (this.RangeVariable != null)
hash = hash * 59 + this.RangeVariable.GetHashCode();
if (this.ItemType != null)
hash = hash * 59 + this.ItemType.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using SR = System.Reflection;
using System.Runtime.CompilerServices;
using Mono.Cecil.Cil;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class ImportReflectionTests : BaseTestFixture {
[Test]
public void ImportString ()
{
var get_string = Compile<Func<string>> ((_, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldstr, "yo dawg!");
il.Emit (OpCodes.Ret);
});
Assert.AreEqual ("yo dawg!", get_string ());
}
[Test]
public void ImportInt ()
{
var add = Compile<Func<int, int, int>> ((_, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Add);
il.Emit (OpCodes.Ret);
});
Assert.AreEqual (42, add (40, 2));
}
[Test]
public void ImportStringByRef ()
{
var get_string = Compile<Func<string, string>> ((module, body) => {
var type = module.Types [1];
var method_by_ref = new MethodDefinition {
Name = "ModifyString",
IsPrivate = true,
IsStatic = true,
};
type.Methods.Add (method_by_ref);
method_by_ref.MethodReturnType.ReturnType = module.ImportReference (typeof (void));
method_by_ref.Parameters.Add (new ParameterDefinition (module.ImportReference (typeof (string))));
method_by_ref.Parameters.Add (new ParameterDefinition (module.ImportReference (typeof (string).MakeByRefType ())));
var m_il = method_by_ref.Body.GetILProcessor ();
m_il.Emit (OpCodes.Ldarg_1);
m_il.Emit (OpCodes.Ldarg_0);
m_il.Emit (OpCodes.Stind_Ref);
m_il.Emit (OpCodes.Ret);
var v_0 = new VariableDefinition (module.ImportReference (typeof (string)));
body.Variables.Add (v_0);
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldnull);
il.Emit (OpCodes.Stloc, v_0);
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldloca, v_0);
il.Emit (OpCodes.Call, method_by_ref);
il.Emit (OpCodes.Ldloc_0);
il.Emit (OpCodes.Ret);
});
Assert.AreEqual ("foo", get_string ("foo"));
}
[Test]
public void ImportStringArray ()
{
var identity = Compile<Func<string [,], string [,]>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ret);
});
var array = new string [2, 2];
Assert.AreEqual (array, identity (array));
}
[Test]
public void ImportFieldStringEmpty ()
{
var get_empty = Compile<Func<string>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldsfld, module.ImportReference (typeof (string).GetField ("Empty")));
il.Emit (OpCodes.Ret);
});
Assert.AreEqual ("", get_empty ());
}
[Test]
public void ImportStringConcat ()
{
var concat = Compile<Func<string, string, string>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Call, module.ImportReference (typeof (string).GetMethod ("Concat", new [] { typeof (string), typeof (string) })));
il.Emit (OpCodes.Ret);
});
Assert.AreEqual ("FooBar", concat ("Foo", "Bar"));
}
[Test]
public void GeneratedAssemblyCulture ()
{
var id = Compile<Func<int, int>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ret);
});
Assert.AreEqual ("", id.Method.DeclaringType.Assembly.GetName ().CultureInfo.Name);
}
public class Generic<T> {
public T Field;
public T Method (T t)
{
return t;
}
public TS GenericMethod<TS> (T t, TS s)
{
return s;
}
public Generic<TS> ComplexGenericMethod<TS> (T t, TS s)
{
return new Generic<TS> { Field = s };
}
}
[Test]
public void ImportGenericField ()
{
var get_field = Compile<Func<Generic<string>, string>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldfld, module.ImportReference (typeof (Generic<string>).GetField ("Field")));
il.Emit (OpCodes.Ret);
});
var generic = new Generic<string> {
Field = "foo",
};
Assert.AreEqual ("foo", get_field (generic));
}
[Test]
public void ImportGenericMethod ()
{
var generic_identity = Compile<Func<Generic<int>, int, int>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Callvirt, module.ImportReference (typeof (Generic<int>).GetMethod ("Method")));
il.Emit (OpCodes.Ret);
});
Assert.AreEqual (42, generic_identity (new Generic<int> (), 42));
}
[Test]
public void ImportGenericMethodSpec ()
{
var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldnull);
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Callvirt, module.ImportReference (typeof (Generic<string>).GetMethod ("GenericMethod").MakeGenericMethod (typeof (int))));
il.Emit (OpCodes.Ret);
});
Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42));
}
[Test]
public void ImportComplexGenericMethodSpec ()
{
var gen_spec_id = Compile<Func<Generic<string>, int, int>> ((module, body) => {
var il = body.GetILProcessor ();
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Ldnull);
il.Emit (OpCodes.Ldarg_1);
il.Emit (OpCodes.Ldfld, module.Import (typeof (Generic<int>).GetField ("Field")));
il.Emit (OpCodes.Callvirt, module.ImportReference (typeof (Generic<string>).GetMethod ("ComplexGenericMethod").MakeGenericMethod (typeof (int))));
il.Emit (OpCodes.Ldfld, module.ImportReference (typeof (Generic<int>).GetField ("Field")));
il.Emit (OpCodes.Ret);
});
Assert.AreEqual (42, gen_spec_id (new Generic<string> (), 42));
}
public class Foo<TFoo> {
public List<TFoo> list;
}
[Test]
public void ImportGenericTypeDefOrOpen ()
{
var module = typeof (Foo<>).ToDefinition ().Module;
var foo_def = module.ImportReference (typeof (Foo<>));
var foo_open = module.ImportReference (typeof (Foo<>), foo_def);
Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Foo`1", foo_def.FullName);
Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Foo`1<TFoo>", foo_open.FullName);
}
[Test]
public void ImportGenericTypeFromContext ()
{
var list_foo = typeof (Foo<>).GetField ("list").FieldType;
var generic_list_foo_open = typeof (Generic<>).MakeGenericType (list_foo);
var foo_def = typeof (Foo<>).ToDefinition ();
var module = foo_def.Module;
var generic_foo = module.ImportReference (generic_list_foo_open, foo_def);
Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Generic`1<System.Collections.Generic.List`1<TFoo>>",
generic_foo.FullName);
}
[Test]
public void ImportGenericTypeDefFromContext ()
{
var foo_open = typeof (Foo<>).MakeGenericType (typeof (Foo<>).GetGenericArguments () [0]);
var generic_foo_open = typeof (Generic<>).MakeGenericType (foo_open);
var foo_def = typeof (Foo<>).ToDefinition ();
var module = foo_def.Module;
var generic_foo = module.ImportReference (generic_foo_open, foo_def);
Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Generic`1<Mono.Cecil.Tests.ImportReflectionTests/Foo`1<TFoo>>",
generic_foo.FullName);
}
[Test]
public void ImportArrayTypeDefFromContext ()
{
var foo_open = typeof (Foo<>).MakeGenericType (typeof (Foo<>).GetGenericArguments () [0]);
var foo_open_array = foo_open.MakeArrayType ();
var foo_def = typeof (Foo<>).ToDefinition ();
var module = foo_def.Module;
var array_foo = module.ImportReference (foo_open_array, foo_def);
Assert.AreEqual ("Mono.Cecil.Tests.ImportReflectionTests/Foo`1<TFoo>[]",
array_foo.FullName);
}
[Test]
public void ImportGenericFieldFromContext ()
{
var list_foo = typeof (Foo<>).GetField ("list").FieldType;
var generic_list_foo_open = typeof (Generic<>).MakeGenericType (list_foo);
var generic_list_foo_open_field = generic_list_foo_open.GetField ("Field");
var foo_def = typeof (Foo<>).ToDefinition ();
var module = foo_def.Module;
var generic_field = module.ImportReference (generic_list_foo_open_field, foo_def);
Assert.AreEqual ("T Mono.Cecil.Tests.ImportReflectionTests/Generic`1<System.Collections.Generic.List`1<TFoo>>::Field",
generic_field.FullName);
}
[Test]
public void ImportGenericMethodFromContext ()
{
var list_foo = typeof (Foo<>).GetField ("list").FieldType;
var generic_list_foo_open = typeof (Generic<>).MakeGenericType (list_foo);
var generic_list_foo_open_method = generic_list_foo_open.GetMethod ("Method");
var foo_def = typeof (Foo<>).ToDefinition ();
var module = foo_def.Module;
var generic_method = module.ImportReference (generic_list_foo_open_method, foo_def);
Assert.AreEqual ("T Mono.Cecil.Tests.ImportReflectionTests/Generic`1<System.Collections.Generic.List`1<TFoo>>::Method(T)",
generic_method.FullName);
}
[Test]
public void ImportMethodOnOpenGenericType ()
{
var module = typeof (Generic<>).ToDefinition ().Module;
var method = module.ImportReference (typeof (Generic<>).GetMethod ("Method"));
Assert.AreEqual ("T Mono.Cecil.Tests.ImportReflectionTests/Generic`1<T>::Method(T)", method.FullName);
}
[Test]
public void ImportGenericMethodOnOpenGenericType ()
{
var module = typeof (Generic<>).ToDefinition ().Module;
var generic_method = module.ImportReference (typeof (Generic<>).GetMethod ("GenericMethod"));
Assert.AreEqual ("TS Mono.Cecil.Tests.ImportReflectionTests/Generic`1<T>::GenericMethod(T,TS)", generic_method.FullName);
generic_method = module.ImportReference (typeof (Generic<>).GetMethod ("GenericMethod"), generic_method);
Assert.AreEqual ("TS Mono.Cecil.Tests.ImportReflectionTests/Generic`1<T>::GenericMethod<TS>(T,TS)", generic_method.FullName);
}
delegate void Emitter (ModuleDefinition module, MethodBody body);
[MethodImpl (MethodImplOptions.NoInlining)]
static TDelegate Compile<TDelegate> (Emitter emitter)
where TDelegate : class
{
var name = GetTestCaseName ();
var module = CreateTestModule<TDelegate> (name, emitter);
var assembly = LoadTestModule (module);
return CreateRunDelegate<TDelegate> (GetTestCase (name, assembly));
}
static TDelegate CreateRunDelegate<TDelegate> (Type type)
where TDelegate : class
{
return (TDelegate) (object) Delegate.CreateDelegate (typeof (TDelegate), type.GetMethod ("Run"));
}
static Type GetTestCase (string name, SR.Assembly assembly)
{
return assembly.GetType (name);
}
static SR.Assembly LoadTestModule (ModuleDefinition module)
{
using (var stream = new MemoryStream ()) {
module.Write (stream);
File.WriteAllBytes (Path.Combine (Path.Combine (Path.GetTempPath (), "cecil"), module.Name + ".dll"), stream.ToArray ());
return SR.Assembly.Load (stream.ToArray ());
}
}
static ModuleDefinition CreateTestModule<TDelegate> (string name, Emitter emitter)
{
var module = CreateModule (name);
var type = new TypeDefinition (
"",
name,
TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Abstract,
module.ImportReference (typeof (object)));
module.Types.Add (type);
var method = CreateMethod (type, typeof (TDelegate).GetMethod ("Invoke"));
emitter (module, method.Body);
return module;
}
static MethodDefinition CreateMethod (TypeDefinition type, SR.MethodInfo pattern)
{
var module = type.Module;
var method = new MethodDefinition {
Name = "Run",
IsPublic = true,
IsStatic = true,
};
type.Methods.Add (method);
method.MethodReturnType.ReturnType = module.ImportReference (pattern.ReturnType);
foreach (var parameter_pattern in pattern.GetParameters ())
method.Parameters.Add (new ParameterDefinition (module.ImportReference (parameter_pattern.ParameterType)));
return method;
}
static ModuleDefinition CreateModule (string name)
{
return ModuleDefinition.CreateModule (name, ModuleKind.Dll);
}
[MethodImpl (MethodImplOptions.NoInlining)]
static string GetTestCaseName ()
{
var stack_trace = new StackTrace ();
var stack_frame = stack_trace.GetFrame (2);
return "ImportReflection_" + stack_frame.GetMethod ().Name;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Compute
{
using System;
using System.Collections.Generic;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Portable;
using NUnit.Framework;
/// <summary>
/// Closure execution tests for portable objects.
/// </summary>
public class PortableClosureTaskTest : ClosureTaskTest
{
/// <summary>
/// Constructor.
/// </summary>
public PortableClosureTaskTest() : base(false) { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="fork">Fork flag.</param>
protected PortableClosureTaskTest(bool fork) : base(fork) { }
/** <inheritDoc /> */
protected override void PortableTypeConfigurations(ICollection<PortableTypeConfiguration> portTypeCfgs)
{
portTypeCfgs.Add(new PortableTypeConfiguration(typeof(PortableOutFunc)));
portTypeCfgs.Add(new PortableTypeConfiguration(typeof(PortableFunc)));
portTypeCfgs.Add(new PortableTypeConfiguration(typeof(PortableResult)));
portTypeCfgs.Add(new PortableTypeConfiguration(typeof(PortableException)));
}
/** <inheritDoc /> */
protected override IComputeFunc<object> OutFunc(bool err)
{
return new PortableOutFunc(err);
}
/** <inheritDoc /> */
protected override IComputeFunc<object, object> Func(bool err)
{
return new PortableFunc(err);
}
/** <inheritDoc /> */
protected override void CheckResult(object res)
{
Assert.IsTrue(res != null);
PortableResult res0 = res as PortableResult;
Assert.IsTrue(res0 != null);
Assert.AreEqual(1, res0.Res);
}
/** <inheritDoc /> */
protected override void CheckError(Exception err)
{
Assert.IsTrue(err != null);
PortableException err0 = err as PortableException;
Assert.IsTrue(err0 != null);
Assert.AreEqual(ErrMsg, err0.Msg);
}
/// <summary>
///
/// </summary>
private class PortableOutFunc : IComputeFunc<object>
{
/** Error. */
private bool _err;
/// <summary>
///
/// </summary>
public PortableOutFunc()
{
// No-op.
}
/// <summary>
///
/// </summary>
/// <param name="err"></param>
public PortableOutFunc(bool err)
{
_err = err;
}
/** <inheritDoc /> */
public object Invoke()
{
if (_err)
throw new PortableException(ErrMsg);
return new PortableResult(1);
}
}
/// <summary>
///
/// </summary>
private class PortableFunc : IComputeFunc<object, object>
{
/** Error. */
private bool _err;
/// <summary>
///
/// </summary>
public PortableFunc()
{
// No-op.
}
/// <summary>
///
/// </summary>
/// <param name="err"></param>
public PortableFunc(bool err)
{
_err = err;
}
/** <inheritDoc /> */
public object Invoke(object arg)
{
if (_err)
throw new PortableException(ErrMsg);
return new PortableResult(1);
}
}
/// <summary>
///
/// </summary>
private class PortableException : Exception, IPortableMarshalAware
{
/** */
public string Msg;
/// <summary>
///
/// </summary>
public PortableException()
{
// No-op.
}
/// <summary>
///
/// </summary>
/// <param name="msg"></param>
public PortableException(string msg) : this()
{
Msg = msg;
}
/** <inheritDoc /> */
public void WritePortable(IPortableWriter writer)
{
writer.RawWriter().WriteString(Msg);
}
/** <inheritDoc /> */
public void ReadPortable(IPortableReader reader)
{
Msg = reader.RawReader().ReadString();
}
}
/// <summary>
///
/// </summary>
private class PortableResult
{
/** */
public int Res;
/// <summary>
///
/// </summary>
public PortableResult()
{
// No-op.
}
/// <summary>
///
/// </summary>
/// <param name="res"></param>
public PortableResult(int res)
{
Res = res;
}
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Represents a symbol writer for managed code. Provides methods to
** define documents, sequence points, lexical scopes, and variables.
**
**
===========================================================*/
namespace System.Diagnostics.SymbolStore {
using System;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
// Interface does not need to be marked with the serializable attribute
[System.Runtime.InteropServices.ComVisible(true)]
public interface ISymbolWriter
{
// Set the IMetadataEmitter that this symbol writer is associated
// with. This must be done only once before any other ISymbolWriter
// methods are called.
void Initialize(IntPtr emitter, String filename, bool fFullBuild);
// Define a source document. Guid's will be provided for the
// languages, vendors, and document types that we currently know
// about.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
ISymbolDocumentWriter DefineDocument(String url,
Guid language,
Guid languageVendor,
Guid documentType);
// Define the method that the user has defined as their entrypoint
// for this module. This would be, perhaps, the user's main method
// rather than compiler generated stubs before main.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void SetUserEntryPoint(SymbolToken entryMethod);
// Open a method to emit symbol information into. The given method
// becomes the current method for calls do define sequence points,
// parameters and lexical scopes. There is an implicit lexical
// scope around the entire method. Re-opening a method that has
// been previously closed effectivley erases any previously
// defined symbols for that method.
//
// There can be only one open method at a time.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void OpenMethod(SymbolToken method);
// Close the current method. Once a method is closed, no more
// symbols can be defined within it.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void CloseMethod();
// Define a group of sequence points within the current method.
// Each line/column defines the start of a statement within a
// method. The arrays should be sorted by offset. The offset is
// always the offset from the start of the method, in bytes.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void DefineSequencePoints(ISymbolDocumentWriter document,
int[] offsets,
int[] lines,
int[] columns,
int[] endLines,
int[] endColumns);
// Open a new lexical scope in the current method. The scope
// becomes the new current scope and is effectivley pushed onto a
// stack of scopes. startOffset is the offset, in bytes from the
// beginning of the method, of the first instruction in the
// lexical scope. Scopes must form a hierarchy. Siblings are not
// allowed to overlap.
//
// OpenScope returns an opaque scope id that can be used with
// SetScopeRange to define a scope's start/end offset at a later
// time. In this case, the offsets passed to OpenScope and
// CloseScope are ignored.
//
// Note: scope id's are only valid in the current method.
//
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
int OpenScope(int startOffset);
// Close the current lexical scope. Once a scope is closed no more
// variables can be defined within it. endOffset points past the
// last instruction in the scope.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void CloseScope(int endOffset);
// Define the offset range for a given lexical scope.
void SetScopeRange(int scopeID, int startOffset, int endOffset);
// Define a single variable in the current lexical
// scope. startOffset and endOffset are optional. If 0, then they
// are ignored and the variable is defined over the entire
// scope. If non-zero, then they must fall within the offsets of
// the current scope. This can be called multiple times for a
// variable of the same name that has multiple homes throughout a
// scope. (Note: start/end offsets must not overlap in such a
// case.)
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void DefineLocalVariable(String name,
FieldAttributes attributes,
byte[] signature,
SymAddressKind addrKind,
int addr1,
int addr2,
int addr3,
int startOffset,
int endOffset);
// Define a single parameter in the current method. The type of
// each parameter is taken from its position (sequence) within the
// method's signature.
//
// Note: if parameters are defined in the metadata for a given
// method, then clearly one would not have to define them again
// with calls to this method. The symbol readers will have to be
// smart enough to check the normal metadata for these first then
// fall back to the symbol store.
void DefineParameter(String name,
ParameterAttributes attributes,
int sequence,
SymAddressKind addrKind,
int addr1,
int addr2,
int addr3);
// Define a single variable not within a method. This is used for
// certian fields in classes, bitfields, etc.
void DefineField(SymbolToken parent,
String name,
FieldAttributes attributes,
byte[] signature,
SymAddressKind addrKind,
int addr1,
int addr2,
int addr3);
// Define a single global variable.
void DefineGlobalVariable(String name,
FieldAttributes attributes,
byte[] signature,
SymAddressKind addrKind,
int addr1,
int addr2,
int addr3);
// Close will close the ISymbolWriter and commit the symbols
// to the symbol store. The ISymbolWriter becomes invalid
// after this call for further updates.
void Close();
// Defines a custom attribute based upon its name. Not to be
// confused with Metadata custom attributes, these attributes are
// held in the symbol store.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void SetSymAttribute(SymbolToken parent, String name, byte[] data);
// Opens a new namespace. Call this before defining methods or
// variables that live within a namespace. Namespaces can be nested.
void OpenNamespace(String name);
// Close the most recently opened namespace.
void CloseNamespace();
// Specifies that the given, fully qualified namespace name is
// being used within the currently open lexical scope. Closing the
// current scope will also stop using the namespace, and the
// namespace will be in use in all scopes that inherit from the
// currently open scope.
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
void UsingNamespace(String fullName);
// Specifies the true start and end of a method within a source
// file. Use this to specify the extent of a method independently
// of what sequence points exist within the method.
void SetMethodSourceRange(ISymbolDocumentWriter startDoc,
int startLine,
int startColumn,
ISymbolDocumentWriter endDoc,
int endLine,
int endColumn);
// Used to set the underlying ISymUnmanagedWriter that a
// managed ISymbolWriter may use to emit symbols with.
void SetUnderlyingWriter(IntPtr underlyingWriter);
}
}
| |
#region Imported Types
using DeviceSQL.SQLTypes.ROC.Data;
using Microsoft.SqlServer.Server;
using System;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
#endregion
namespace DeviceSQL.SQLTypes.ROC
{
[Serializable()]
[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = false, IsFixedLength = false, MaxByteSize = 27)]
public struct ROCPlusEventRecord : INullable, IBinarySerialize
{
#region Fields
private byte[] data;
#endregion
#region Properties
public bool IsNull
{
get;
internal set;
}
public static ROCPlusEventRecord Null
{
get
{
return new ROCPlusEventRecord() { IsNull = true };
}
}
public byte[] Data
{
get
{
if (data == null)
{
data = new byte[22];
}
return data;
}
internal set
{
data = value;
}
}
public int Index
{
get;
internal set;
}
public SqlDateTime DateTimeStamp
{
get
{
var dateTimeStamp = new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DateTimeStamp;
return dateTimeStamp.HasValue ? dateTimeStamp.Value : SqlDateTime.Null;
}
}
public SqlString EventType
{
get
{
return new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).EventType.ToString();
}
}
public SqlString EventCode
{
get
{
var eventCode = new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).EventCode;
return eventCode.HasValue ? eventCode.Value.ToString() : SqlString.Null;
}
}
public string OperatorId
{
get
{
return new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).OperatorId;
}
}
internal Tlp Tlp
{
get
{
return new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).Tlp;
}
}
public SqlByte PointType
{
get
{
return Tlp.PointType;
}
}
public SqlByte LogicalNumber
{
get
{
return Tlp.LogicalNumber;
}
}
public SqlByte Parameter
{
get
{
return Tlp.Parameter;
}
}
public SqlString DataType
{
get
{
var dataType = new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DataType;
return dataType.HasValue ? dataType.Value.ToString() : SqlString.Null;
}
}
public SqlBinary OldValue
{
get
{
return new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).OldValue;
}
}
public SqlBinary NewValue
{
get
{
return new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).NewValue;
}
}
public SqlInt32 Spare
{
get
{
return new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).Spare;
}
}
public SqlString Description
{
get
{
return new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).Description;
}
}
public SqlByte FstNumber
{
get
{
var fstNumber = new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).FstNumber;
return fstNumber.HasValue ? fstNumber.Value : SqlByte.Null;
}
}
public SqlSingle FstValue
{
get
{
var fstValue = new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).FstValue;
return fstValue.HasValue ? fstValue.Value : SqlSingle.Null;
}
}
public SqlDateTime DateTimeValue
{
get
{
var dateTimeValue = new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DateTimeValue;
return dateTimeValue.HasValue ? dateTimeValue.Value : SqlDateTime.Null;
}
}
public SqlSingle CalibrationRawValue
{
get
{
var calibrationRawValue = new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).CalibrationRawValue;
return calibrationRawValue.HasValue ? calibrationRawValue.Value : SqlSingle.Null;
}
}
public SqlSingle CalibrationCalibratedValue
{
get
{
var calibrationCalibratedValue = new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).CalibrationCalibratedValue;
return calibrationCalibratedValue.HasValue ? calibrationCalibratedValue.Value : SqlSingle.Null;
}
}
public Parameter OldParameterValue
{
get
{
if (!PointType.IsNull && !Parameter.IsNull)
{
switch (new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DataType)
{
case ParameterType.AC3:
return new Parameter() { RawType = ParameterType.AC3, RawValue = OldValue.Value.Take(3).ToArray() };
case ParameterType.BIN:
return new Parameter() { RawType = ParameterType.BIN, RawValue = OldValue.Value.Take(1).ToArray() };
case ParameterType.FL:
return new Parameter() { RawType = ParameterType.FL, RawValue = OldValue.Value };
case ParameterType.INT16:
return new Parameter() { RawType = ParameterType.INT16, RawValue = OldValue.Value.Take(2).ToArray() };
case ParameterType.INT32:
return new Parameter() { RawType = ParameterType.INT32, RawValue = OldValue.Value };
case ParameterType.INT8:
return new Parameter() { RawType = ParameterType.INT8, RawValue = OldValue.Value.Take(1).ToArray() };
case ParameterType.TLP:
return new Parameter() { RawType = ParameterType.TLP, RawValue = OldValue.Value.Take(3).ToArray() };
case ParameterType.UINT16:
return new Parameter() { RawType = ParameterType.UINT16, RawValue = OldValue.Value.Take(2).ToArray() };
case ParameterType.UINT32:
return new Parameter() { RawType = ParameterType.UINT32, RawValue = OldValue.Value };
case ParameterType.TIME:
return new Parameter() { RawType = ParameterType.TIME, RawValue = OldValue.Value };
case ParameterType.UINT8:
return new Parameter() { RawType = ParameterType.UINT8, RawValue = OldValue.Value.Take(1).ToArray() };
default:
return ROC.Parameter.Null;
}
}
else
{
return ROC.Parameter.Null;
}
}
}
public Parameter NewParameterValue
{
get
{
if (!PointType.IsNull && !Parameter.IsNull)
{
switch (new Data.ROCPlusEventRecord(Convert.ToUInt16(Index), Data).DataType)
{
case ParameterType.AC3:
return new Parameter() { RawType = ParameterType.AC3, RawValue = NewValue.Value.Take(3).ToArray() };
case ParameterType.AC7:
return new Parameter() { RawType = ParameterType.AC7, RawValue = NewValue.Value.Union(new byte[3]).ToArray() };
case ParameterType.AC10:
return new Parameter() { RawType = ParameterType.AC10, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).ToArray() };
case ParameterType.AC12:
return new Parameter() { RawType = ParameterType.AC12, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[2]).ToArray() };
case ParameterType.AC20:
return new Parameter() { RawType = ParameterType.AC20, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[10]).ToArray() };
case ParameterType.AC30:
return new Parameter() { RawType = ParameterType.AC30, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[20]).ToArray() };
case ParameterType.AC40:
return new Parameter() { RawType = ParameterType.AC40, RawValue = NewValue.Value.Union(OldValue.Value).Union(BitConverter.GetBytes(Convert.ToUInt16(Spare.Value))).Union(new byte[30]).ToArray() };
case ParameterType.BIN:
return new Parameter() { RawType = ParameterType.BIN, RawValue = NewValue.Value.Take(1).ToArray() };
case ParameterType.FL:
return new Parameter() { RawType = ParameterType.FL, RawValue = NewValue.Value };
case ParameterType.DOUBLE:
return new Parameter() { RawType = ParameterType.DOUBLE, RawValue = NewValue.Value.Union(OldValue.Value).ToArray() };
case ParameterType.INT16:
return new Parameter() { RawType = ParameterType.INT16, RawValue = NewValue.Value.Take(2).ToArray() };
case ParameterType.INT32:
return new Parameter() { RawType = ParameterType.INT32, RawValue = NewValue.Value };
case ParameterType.INT8:
return new Parameter() { RawType = ParameterType.INT8, RawValue = NewValue.Value.Take(1).ToArray() };
case ParameterType.TLP:
return new Parameter() { RawType = ParameterType.TLP, RawValue = NewValue.Value.Take(3).ToArray() };
case ParameterType.UINT16:
return new Parameter() { RawType = ParameterType.UINT16, RawValue = NewValue.Value.Take(2).ToArray() };
case ParameterType.UINT32:
return new Parameter() { RawType = ParameterType.UINT32, RawValue = NewValue.Value };
case ParameterType.TIME:
return new Parameter() { RawType = ParameterType.TIME, RawValue = NewValue.Value };
case ParameterType.UINT8:
return new Parameter() { RawType = ParameterType.UINT8, RawValue = NewValue.Value.Take(1).ToArray() };
default:
return ROC.Parameter.Null;
}
}
else
{
return ROC.Parameter.Null;
}
}
}
#endregion
#region Helper Methods
public static ROCPlusEventRecord Parse(SqlString stringToParse)
{
var parsedEventRecord = stringToParse.Value.Split(",".ToCharArray());
var base64Bytes = Convert.FromBase64String(parsedEventRecord[1]);
if (base64Bytes.Length == 22)
{
return new ROCPlusEventRecord() { Index = ushort.Parse(parsedEventRecord[0]), Data = base64Bytes };
}
else
{
throw new ArgumentException("Input must be exactly 22 bytes");
}
}
public override string ToString()
{
return string.Format("{0},{1}", Index, Convert.ToBase64String(Data));
}
#endregion
#region Serialization Methods
public void Read(BinaryReader binaryReader)
{
IsNull = binaryReader.ReadBoolean();
Index = binaryReader.ReadInt32();
if (!IsNull)
{
Data = binaryReader.ReadBytes(22);
}
}
public void Write(BinaryWriter binaryWriter)
{
binaryWriter.Write(IsNull);
binaryWriter.Write(Index);
if (!IsNull)
{
binaryWriter.Write(Data, 0, 22);
}
}
#endregion
}
}
| |
// ReSharper disable All
//
// Options.cs
//
// Authors:
// Jonathan Pryor <[email protected]>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NDESK_OPTIONS
namespace NDesk.Options
#else
namespace Mono.Options
#endif
{
public class OptionValueCollection : IList, IList<string> {
List<string> values = new List<string> ();
OptionContext c;
internal OptionValueCollection (OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
#endregion
#region ICollection<T>
public void Add (string item) {values.Add (item);}
public void Clear () {values.Clear ();}
public bool Contains (string item) {return values.Contains (item);}
public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
public bool Remove (string item) {return values.Remove (item);}
public int Count {get {return values.Count;}}
public bool IsReadOnly {get {return false;}}
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
#endregion
#region IList
int IList.Add (object value) {return (values as IList).Add (value);}
bool IList.Contains (object value) {return (values as IList).Contains (value);}
int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
void IList.Remove (object value) {(values as IList).Remove (value);}
void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
bool IList.IsFixedSize {get {return false;}}
object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
#endregion
#region IList<T>
public int IndexOf (string item) {return values.IndexOf (item);}
public void Insert (int index, string item) {values.Insert (index, item);}
public void RemoveAt (int index) {values.RemoveAt (index);}
private void AssertValid (int index)
{
if (c.Option == null)
throw new InvalidOperationException ("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException ("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException (string.Format (
c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this [int index] {
get {
AssertValid (index);
return index >= values.Count ? null : values [index];
}
set {
values [index] = value;
}
}
#endregion
public List<string> ToList ()
{
return new List<string> (values);
}
public string[] ToArray ()
{
return values.ToArray ();
}
public override string ToString ()
{
return string.Join (", ", values.ToArray ());
}
}
public class OptionContext {
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext (OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection (this);
}
public Option Option {
get {return option;}
set {option = value;}
}
public string OptionName {
get {return name;}
set {name = value;}
}
public int OptionIndex {
get {return index;}
set {index = value;}
}
public OptionSet OptionSet {
get {return set;}
}
public OptionValueCollection OptionValues {
get {return c;}
}
}
public enum OptionValueType {
None,
Optional,
Required,
}
public abstract class Option {
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
protected Option (string prototype, string description)
: this (prototype, description, 1)
{
}
protected Option (string prototype, string description, int maxValueCount)
{
if (prototype == null)
throw new ArgumentNullException ("prototype");
if (prototype.Length == 0)
throw new ArgumentException ("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException ("maxValueCount");
this.prototype = prototype;
this.names = prototype.Split ('|');
this.description = description;
this.count = maxValueCount;
this.type = ParsePrototype ();
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException (
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException (
string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf (names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException (
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype {get {return prototype;}}
public string Description {get {return description;}}
public OptionValueType OptionValueType {get {return type;}}
public int MaxValueCount {get {return count;}}
public string[] GetNames ()
{
return (string[]) names.Clone ();
}
public string[] GetValueSeparators ()
{
if (separators == null)
return new string [0];
return (string[]) separators.Clone ();
}
protected static T Parse<T> (string value, OptionContext c)
{
Type tt = typeof (T);
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition () == typeof (Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
TypeConverter conv = TypeDescriptor.GetConverter (targetType);
T t = default (T);
try {
if (value != null)
t = (T) conv.ConvertFromString (value);
}
catch (Exception e) {
throw new OptionException (
string.Format (
c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names {get {return names;}}
internal string[] ValueSeparators {get {return separators;}}
static readonly char[] NameTerminator = new char[]{'=', ':'};
private OptionValueType ParsePrototype ()
{
char type = '\0';
List<string> seps = new List<string> ();
for (int i = 0; i < names.Length; ++i) {
string name = names [i];
if (name.Length == 0)
throw new ArgumentException ("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny (NameTerminator);
if (end == -1)
continue;
names [i] = name.Substring (0, end);
if (type == '\0' || type == name [end])
type = name [end];
else
throw new ArgumentException (
string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
"prototype");
AddSeparators (name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException (
string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1) {
if (seps.Count == 0)
this.separators = new string[]{":", "="};
else if (seps.Count == 1 && seps [0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray ();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators (string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end+1; i < name.Length; ++i) {
switch (name [i]) {
case '{':
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i+1;
break;
case '}':
if (start == -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add (name.Substring (start, i-start));
start = -1;
break;
default:
if (start == -1)
seps.Add (name [i].ToString ());
break;
}
}
if (start != -1)
throw new ArgumentException (
string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke (OptionContext c)
{
OnParseComplete (c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear ();
}
protected abstract void OnParseComplete (OptionContext c);
public override string ToString ()
{
return Prototype;
}
}
[Serializable]
public class OptionException : Exception {
private string option;
public OptionException ()
{
}
public OptionException (string message, string optionName)
: base (message)
{
this.option = optionName;
}
public OptionException (string message, string optionName, Exception innerException)
: base (message, innerException)
{
this.option = optionName;
}
protected OptionException (SerializationInfo info, StreamingContext context)
: base (info, context)
{
this.option = info.GetString ("OptionName");
}
public string OptionName {
get {return this.option;}
}
[SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData (SerializationInfo info, StreamingContext context)
{
base.GetObjectData (info, context);
info.AddValue ("OptionName", option);
}
}
public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option>
{
public OptionSet ()
: this (delegate (string f) {return f;})
{
}
public OptionSet (Converter<string, string> localizer)
{
this.localizer = localizer;
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer {
get {return localizer;}
}
protected override string GetKeyForItem (Option item)
{
if (item == null)
throw new ArgumentNullException ("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names [0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException ("Option has no names!");
}
[Obsolete ("Use KeyedCollection.this[string]")]
protected Option GetOptionForName (string option)
{
if (option == null)
throw new ArgumentNullException ("option");
try {
return base [option];
}
catch (KeyNotFoundException) {
return null;
}
}
protected override void InsertItem (int index, Option item)
{
base.InsertItem (index, item);
AddImpl (item);
}
protected override void RemoveItem (int index)
{
base.RemoveItem (index);
Option p = Items [index];
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i) {
Dictionary.Remove (p.Names [i]);
}
}
protected override void SetItem (int index, Option item)
{
base.SetItem (index, item);
RemoveItem (index);
AddImpl (item);
}
private void AddImpl (Option option)
{
if (option == null)
throw new ArgumentNullException ("option");
List<string> added = new List<string> (option.Names.Length);
try {
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i) {
Dictionary.Add (option.Names [i], option);
added.Add (option.Names [i]);
}
}
catch (Exception) {
foreach (string name in added)
Dictionary.Remove (name);
throw;
}
}
public new OptionSet Add (Option option)
{
base.Add (option);
return this;
}
sealed class ActionOption : Option {
Action<OptionValueCollection> action;
public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
: base (prototype, description, count)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (c.OptionValues);
}
}
public OptionSet Add (string prototype, Action<string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, Action<string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 1,
delegate (OptionValueCollection v) { action (v [0]); });
base.Add (p);
return this;
}
public OptionSet Add (string prototype, OptionAction<string, string> action)
{
return Add (prototype, null, action);
}
public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
{
if (action == null)
throw new ArgumentNullException ("action");
Option p = new ActionOption (prototype, description, 2,
delegate (OptionValueCollection v) {action (v [0], v [1]);});
base.Add (p);
return this;
}
sealed class ActionOption<T> : Option {
Action<T> action;
public ActionOption (string prototype, string description, Action<T> action)
: base (prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (Parse<T> (c.OptionValues [0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option {
OptionAction<TKey, TValue> action;
public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
: base (prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException ("action");
this.action = action;
}
protected override void OnParseComplete (OptionContext c)
{
action (
Parse<TKey> (c.OptionValues [0], c),
Parse<TValue> (c.OptionValues [1], c));
}
}
public OptionSet Add<T> (string prototype, Action<T> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<T> (string prototype, string description, Action<T> action)
{
return Add (new ActionOption<T> (prototype, description, action));
}
public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
{
return Add (prototype, null, action);
}
public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add (new ActionOption<TKey, TValue> (prototype, description, action));
}
protected virtual OptionContext CreateOptionContext ()
{
return new OptionContext (this);
}
#if LINQ
public List<string> Parse (IEnumerable<string> arguments)
{
bool process = true;
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
var def = Contains("<>") ? this["<>"] : null;
var unprocessed =
from argument in arguments
where ++c.OptionIndex >= 0 && (process || def != null)
? process
? argument == "--"
? (process = false)
: !Parse (argument, c)
? def != null
? Unprocessed (null, def, c, argument)
: true
: false
: def != null
? Unprocessed (null, def, c, argument)
: true
: true
select argument;
List<string> r = unprocessed.ToList ();
if (c.Option != null)
c.Option.Invoke (c);
return r;
}
#else
public List<string> Parse (IEnumerable<string> arguments)
{
OptionContext c = CreateOptionContext ();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string> ();
Option def = Contains ("<>") ? this ["<>"] : null;
foreach (string argument in arguments) {
++c.OptionIndex;
if (argument == "--") {
process = false;
continue;
}
if (!process) {
Unprocessed (unprocessed, def, c, argument);
continue;
}
if (!Parse (argument, c))
Unprocessed (unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke (c);
return unprocessed;
}
#endif
private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null) {
extra.Add (argument);
return false;
}
c.OptionValues.Add (argument);
c.Option = def;
c.Option.Invoke (c);
return false;
}
private readonly Regex ValueOption = new Regex (
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException ("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match (argument);
if (!m.Success) {
return false;
}
flag = m.Groups ["flag"].Value;
name = m.Groups ["name"].Value;
if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
sep = m.Groups ["sep"].Value;
value = m.Groups ["value"].Value;
}
return true;
}
protected virtual bool Parse (string argument, OptionContext c)
{
if (c.Option != null) {
ParseValue (argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts (argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains (n)) {
p = this [n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType) {
case OptionValueType.None:
c.OptionValues.Add (n);
c.Option.Invoke (c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue (v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool (argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue (f, string.Concat (n + s + v), c))
return true;
return false;
}
private void ParseValue (string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
: new string[]{option}) {
c.OptionValues.Add (o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke (c);
else if (c.OptionValues.Count > c.Option.MaxValueCount) {
throw new OptionException (localizer (string.Format (
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool (string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
Contains ((rn = n.Substring (0, n.Length-1)))) {
p = this [rn];
string v = n [n.Length-1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add (v);
p.Invoke (c);
return true;
}
return false;
}
private bool ParseBundledValue (string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i) {
Option p;
string opt = f + n [i].ToString ();
string rn = n [i].ToString ();
if (!Contains (rn)) {
if (i == 0)
return false;
throw new OptionException (string.Format (localizer (
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this [rn];
switch (p.OptionValueType) {
case OptionValueType.None:
Invoke (c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required: {
string v = n.Substring (i+1);
c.Option = p;
c.OptionName = opt;
ParseValue (v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke (OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add (value);
option.Invoke (c);
}
private const int OptionWidth = 29;
public void WriteOptionDescriptions (TextWriter o)
{
foreach (Option p in this) {
int written = 0;
if (!WriteOptionPrototype (o, p, ref written))
continue;
if (written < OptionWidth)
o.Write (new string (' ', OptionWidth - written));
else {
o.WriteLine ();
o.Write (new string (' ', OptionWidth));
}
bool indent = false;
string prefix = new string (' ', OptionWidth+2);
foreach (string line in GetLines (localizer (GetDescription (p.Description)))) {
if (indent)
o.Write (prefix);
o.WriteLine (line);
indent = true;
}
}
}
bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex (names, 0);
if (i == names.Length)
return false;
if (names [i].Length == 1) {
Write (o, ref written, " -");
Write (o, ref written, names [0]);
}
else {
Write (o, ref written, " --");
Write (o, ref written, names [0]);
}
for ( i = GetNextOptionIndex (names, i+1);
i < names.Length; i = GetNextOptionIndex (names, i+1)) {
Write (o, ref written, ", ");
Write (o, ref written, names [i].Length == 1 ? "-" : "--");
Write (o, ref written, names [i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required) {
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("["));
}
Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators [0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c) {
Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional) {
Write (o, ref written, localizer ("]"));
}
}
return true;
}
static int GetNextOptionIndex (string[] names, int i)
{
while (i < names.Length && names [i] == "<>") {
++i;
}
return i;
}
static void Write (TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write (s);
}
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription (string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder (description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i) {
switch (description [i]) {
case '{':
if (i == start) {
sb.Append ('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0) {
if ((i+1) == description.Length || description [i+1] != '}')
throw new InvalidOperationException ("Invalid option description: " + description);
++i;
sb.Append ("}");
}
else {
sb.Append (description.Substring (start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append (description [i]);
break;
}
}
return sb.ToString ();
}
private static IEnumerable<string> GetLines (string description)
{
if (string.IsNullOrEmpty (description)) {
yield return string.Empty;
yield break;
}
int length = 80 - OptionWidth - 1;
int start = 0, end;
do {
end = GetLineEnd (start, length, description);
char c = description [end-1];
if (char.IsWhiteSpace (c))
--end;
bool writeContinuation = end != description.Length && !IsEolChar (c);
string line = description.Substring (start, end - start) +
(writeContinuation ? "-" : "");
yield return line;
start = end;
if (char.IsWhiteSpace (c))
++start;
length = 80 - OptionWidth - 2 - 1;
} while (end < description.Length);
}
private static bool IsEolChar (char c)
{
return !char.IsLetterOrDigit (c);
}
private static int GetLineEnd (int start, int length, string description)
{
int end = System.Math.Min (start + length, description.Length);
int sep = -1;
for (int i = start+1; i < end; ++i) {
if (description [i] == '\n')
return i+1;
if (IsEolChar (description [i]))
sep = i+1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using MLifter.DAL.Interfaces;
using MLifter.DAL.Interfaces.DB;
using Npgsql;
using MLifter.DAL.Tools;
namespace MLifter.DAL.DB.PostgreSQL
{
/// <summary>
/// The PostgreSQL connector for the IWords interface.
/// </summary>
/// <remarks>Documented by Dev05, 2008-07-31</remarks>
class PgSqlWordsConnector : IDbWordsConnector
{
private static Dictionary<ConnectionStringStruct, PgSqlWordsConnector> instances = new Dictionary<ConnectionStringStruct, PgSqlWordsConnector>();
public static PgSqlWordsConnector GetInstance(ParentClass parentClass)
{
lock (instances)
{
ConnectionStringStruct connection = parentClass.CurrentUser.ConnectionString;
if (!instances.ContainsKey(connection))
instances.Add(connection, new PgSqlWordsConnector(parentClass));
return instances[connection];
}
}
private ParentClass Parent;
private PgSqlWordsConnector(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 IDbWordsConnector Members
public IWord CreateNewWord(int id, string word, Side side, WordType type, bool isDefault)
{
if (word != null)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO \"TextContent\" (cards_id, text, side, type, position, is_default) VALUES (:id, :text, :side, :type, " +
"(COALESCE((SELECT position FROM \"TextContent\" WHERE cards_id=:id AND side=:side AND type=:type ORDER BY position DESC LIMIT 1), 0) + 10), " +
":isdefault) RETURNING id";
cmd.Parameters.Add("id", id);
cmd.Parameters.Add("text", word);
cmd.Parameters.Add("side", side.ToString());
cmd.Parameters.Add("type", type.ToString());
cmd.Parameters.Add("isdefault", isDefault);
Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(ObjectLifetimeIdentifier.GetCacheObject(side, type), id));
return new DbWord(Convert.ToInt32(PostgreSQLConn.ExecuteScalar(cmd, Parent.CurrentUser)), word, type, isDefault, Parent);
}
}
}
else
return null;
}
public IList<IWord> GetTextContent(int id, Side side, WordType type)
{
return GetWords(id, side, type);
}
public void ClearAllWords(int id, Side side, WordType type)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "DELETE FROM \"TextContent\" WHERE cards_id=:id AND side=:side AND type=:type";
cmd.Parameters.Add("id", id);
cmd.Parameters.Add("side", side.ToString());
cmd.Parameters.Add("type", type.ToString());
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(ObjectLifetimeIdentifier.GetCacheObject(side, type), id));
}
}
}
public void AddWord(int id, Side side, WordType type, IWord word)
{
if (word != null && word.Word.Length > 0)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT \"InsertWordIfNotExists\"(:id,:cardid,:isdefault,:text,:side,:type);";
cmd.Parameters.Add("id", word.Id);
cmd.Parameters.Add("isdefault", word.Default);
cmd.Parameters.Add("cardid", id);
cmd.Parameters.Add("text", word.Word);
cmd.Parameters.Add("side", side.ToString());
cmd.Parameters.Add("type", type.ToString());
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(ObjectLifetimeIdentifier.GetCacheObject(side, type), id));
}
}
}
}
public void AddWords(int id, Side side, WordType type, List<IWord> words)
{
if (words.Count > 0)
{
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = string.Empty;
int paramnum = 0;
string textparamname, idparametername, isdefaultparametername;
foreach (IWord word in words)
{
if (word != null && word.Word.Length > 0)
{
paramnum++;
textparamname = string.Format("text{0}", paramnum);
idparametername = string.Format("id{0}", paramnum);
isdefaultparametername = string.Format("isdefault{0}", paramnum);
cmd.CommandText += string.Format("SELECT \"InsertWordIfNotExists\"(:{0},:cardid,:{1},:{2},:side,:type);",
idparametername, isdefaultparametername, textparamname);
cmd.Parameters.Add(textparamname, word.Word);
cmd.Parameters.Add(idparametername, word.Id);
cmd.Parameters.Add(isdefaultparametername, word.Default);
}
}
cmd.Parameters.Add("cardid", id);
cmd.Parameters.Add("side", side.ToString());
cmd.Parameters.Add("type", type.ToString());
PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);
Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(ObjectLifetimeIdentifier.GetCacheObject(side, type), id));
}
}
}
}
#endregion
private DbWord GetWord(int textid, int cardid)
{
DbWord wordCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.Word, textid)] as DbWord;
if (wordCache != null)
return wordCache;
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT id, text, type, is_default FROM \"TextContent\" WHERE cards_id=:id;";
cmd.Parameters.Add("id", cardid);
NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
IList<IWord> list = new List<IWord>();
while (reader.Read())
{
int tid = Convert.ToInt32(reader["id"]);
DbWord word = new DbWord(tid, reader["text"].ToString(),
(WordType)Enum.Parse(typeof(WordType), reader["type"].ToString(), true), Convert.ToBoolean(reader["is_default"]), Parent);
if (tid == textid)
wordCache = word;
if (Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(CacheObject.Word, tid)] == null)
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.Word, tid)] = word;
}
}
}
return wordCache;
}
private IList<IWord> GetWords(int cardid, Side side, WordType type)
{
CacheObject obj = ObjectLifetimeIdentifier.GetCacheObject(side, type);
IList<IWord> wordsCache = Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.GetIdentifier(obj, cardid)] as IList<IWord>;
if (wordsCache != null)
return wordsCache;
IList<IWord> question = new List<IWord>();
IList<IWord> questionExample = new List<IWord>();
IList<IWord> questionDistractor = new List<IWord>();
IList<IWord> answer = new List<IWord>();
IList<IWord> answerExample = new List<IWord>();
IList<IWord> answerDistractor = new List<IWord>();
using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
{
using (NpgsqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT id, side, type, text, is_default FROM \"TextContent\" WHERE cards_id=:id ORDER BY position ASC;";
cmd.Parameters.Add("id", cardid);
NpgsqlDataReader reader = PostgreSQLConn.ExecuteReader(cmd, Parent.CurrentUser);
while (reader.Read())
{
int id = Convert.ToInt32(reader["id"]);
Side wside = (Side)Enum.Parse(typeof(Side), reader["side"].ToString(), true);
WordType wtype = (WordType)Enum.Parse(typeof(WordType), reader["type"].ToString(), false);
string text = reader["text"].ToString();
bool isDefault = Convert.ToBoolean(reader["is_default"]);
switch (wside)
{
case Side.Question:
switch (wtype)
{
case WordType.Word:
question.Add(new DbWord(id, text, wtype, isDefault, Parent));
break;
case WordType.Sentence:
questionExample.Add(new DbWord(id, text, wtype, isDefault, Parent));
break;
case WordType.Distractor:
questionDistractor.Add(new DbWord(id, text, wtype, isDefault, Parent));
break;
}
break;
case Side.Answer:
switch (wtype)
{
case WordType.Word:
answer.Add(new DbWord(id, text, wtype, isDefault, Parent));
break;
case WordType.Sentence:
answerExample.Add(new DbWord(id, text, wtype, isDefault, Parent));
break;
case WordType.Distractor:
answerDistractor.Add(new DbWord(id, text, wtype, isDefault, Parent));
break;
}
break;
}
}
}
}
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.QuestionWords, cardid)] = question;
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.QuestionExampleWords, cardid)] = questionExample;
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.QuestionDistractorWords, cardid)] = questionDistractor;
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.AnswerWords, cardid)] = answer;
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.AnswerExampleWords, cardid)] = answerExample;
Parent.CurrentUser.Cache[ObjectLifetimeIdentifier.Create(CacheObject.AnswerDistractorWords, cardid)] = answerDistractor;
switch (side)
{
case Side.Question:
switch (type)
{
case WordType.Word:
return question;
case WordType.Sentence:
return questionExample;
case WordType.Distractor:
return questionDistractor;
}
break;
case Side.Answer:
switch (type)
{
case WordType.Word:
return answer;
case WordType.Sentence:
return answerExample;
case WordType.Distractor:
return answerDistractor;
}
break;
}
return new List<IWord>();
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Apache License, Version 2.0.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Security;
using Common;
using System.Collections.ObjectModel;
namespace Randoop
{
public class ConstructorCallTransformer : Transformer
{
public readonly ConstructorInfo fconstructor;
public readonly ConstructorInfo coverageInfo;
public int timesExecuted = 0;
public double executionTimeAccum = 0;
private static Dictionary<ConstructorInfo, ConstructorCallTransformer> cachedTransformers =
new Dictionary<ConstructorInfo, ConstructorCallTransformer>();
public static ConstructorCallTransformer Get(ConstructorInfo field)
{
ConstructorCallTransformer t;
cachedTransformers.TryGetValue(field, out t);
if (t == null)
cachedTransformers[field] = t = new ConstructorCallTransformer(field);
return t;
}
public override string MemberName
{
get
{
return fconstructor.DeclaringType.FullName;
}
}
public override int TupleIndexOfIthInputParam(int i)
{
if (i < 0 && i > resultTypes.Length - 1) throw new ArgumentException("index out of range.");
return (i + 1); // skip new object.
}
private readonly Type[] resultTypes;
private bool[] defaultActiveResultTypes;
public override Type[] TupleTypes
{
get { return resultTypes; }
}
public override bool[] DefaultActiveTupleTypes
{
get { return defaultActiveResultTypes; }
}
public override Type[] ParameterTypes
{
get
{
ParameterInfo[] parameters = fconstructor.GetParameters();
Type[] retval = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
retval[i] = parameters[i].ParameterType;
return retval;
}
}
public override string ToString()
{
return fconstructor.DeclaringType.FullName + " constructor " + fconstructor.ToString();
}
public override bool Equals(object obj)
{
ConstructorCallTransformer c = obj as ConstructorCallTransformer;
if (c == null)
return false;
return (this.fconstructor.Equals(c.fconstructor));
}
public override int GetHashCode()
{
return fconstructor.GetHashCode();
}
private ConstructorCallTransformer(ConstructorInfo constructor)
{
Util.Assert(constructor is ConstructorInfo);
this.fconstructor = constructor as ConstructorInfo;
this.coverageInfo = constructor;
ParameterInfo[] pis = constructor.GetParameters();
resultTypes = new Type[pis.Length + 1];
defaultActiveResultTypes = new bool[pis.Length + 1];
resultTypes[0] = constructor.DeclaringType;
defaultActiveResultTypes[0] = true;
for (int i = 0; i < pis.Length; i++)
{
resultTypes[i + 1] = pis[i].ParameterType;
//if (pis[i].IsOut)
// defaultActiveResultTypes[i + 1] = true;
//else
defaultActiveResultTypes[i + 1] = false;
}
}
public override string ToCSharpCode(ReadOnlyCollection<string> arguments, String newValueName)
{
// TODO assert that arguments.Count is correct.
StringBuilder b = new StringBuilder();
string retType =
SourceCodePrinting.ToCodeString(fconstructor.DeclaringType);
b.Append(retType + " " + newValueName + " = ");
b.Append(" new " + SourceCodePrinting.ToCodeString(fconstructor.DeclaringType));
b.Append("(");
for (int i = 0; i < arguments.Count; i++)
{
if (i > 0)
b.Append(" , ");
// Cast.
b.Append("(");
b.Append(SourceCodePrinting.ToCodeString(ParameterTypes[i]));
b.Append(")");
b.Append(arguments[i]);
}
b.Append(");");
return b.ToString();
}
////[email protected] adds for capture return value for regression assertion
//public override string ToCSharpCode(ReadOnlyCollection<string> arguments, string newValueName, string return_val)
//{
// return ToCSharpCode(arguments, newValueName);
//}
public override bool Execute(out ResultTuple ret, ResultTuple[] results,
Plan.ParameterChooser[] parameterMap, TextWriter executionLog, TextWriter debugLog, out Exception exceptionThrown, out bool contractViolated, bool forbidNull)
{
contractViolated = false;
this.timesExecuted++;
long startTime = 0;
Timer.QueryPerformanceCounter(ref startTime);
object[] objects = new object[fconstructor.GetParameters().Length];
// Get the actual objects from the results using parameterIndices;
for (int i = 0; i < fconstructor.GetParameters().Length; i++)
{
Plan.ParameterChooser pair = parameterMap[i];
objects[i] = results[pair.planIndex].tuple[pair.resultIndex];
}
if (forbidNull)
foreach (object o in objects)
Util.Assert(o != null);
object newObject = null;
CodeExecutor.CodeToExecute call =
delegate() { newObject = fconstructor.Invoke(objects); };
executionLog.WriteLine("execute constructor " + this.fconstructor.DeclaringType);
debugLog.WriteLine("execute constructor " + this.fconstructor.DeclaringType); //[email protected] adds
executionLog.Flush();
bool retval = true;
if (!CodeExecutor.ExecuteReflectionCall(call, debugLog, out exceptionThrown))
{
ret = null;
if (exceptionThrown is AccessViolationException)
{
//Console.WriteLine("SECOND CHANCE AV!" + this.ToString());
//Logging.LogLine(Logging.GENERAL, "SECOND CHANCE AV!" + this.ToString());
}
//for exns we can ony add the class to faulty classes when its a guideline violation
if (Util.GuidelineViolation(exceptionThrown.GetType()))
{
PlanManager.numDistinctContractViolPlans++;
KeyValuePair<MethodBase, Type> k = new KeyValuePair<MethodBase, Type>(this.fconstructor, exceptionThrown.GetType());
if (!exnViolatingMethods.ContainsKey(k))
{
PlanManager.numContractViolatingPlans++;
exnViolatingMethods[k] = true;
}
//add this class to the faulty classes
contractExnViolatingClasses[fconstructor.GetType()] = true;
contractExnViolatingMethods[fconstructor] = true;
}
executionLog.WriteLine("execution failure."); //[email protected] adds
return false;
}
else
ret = new ResultTuple(fconstructor, newObject, objects);
//check if the objects in the output tuple violated basic contracts
if (ret != null)
{
foreach (object o in ret.tuple)
{
if (o == null) continue;
bool toStrViol, hashCodeViol, equalsViol;
int count;
if (Util.ViolatesContracts(o, out count, out toStrViol, out hashCodeViol, out equalsViol))
{
contractViolated = true;
contractExnViolatingMethods[fconstructor] = true;
bool newcontractViolation = false;
PlanManager.numDistinctContractViolPlans++;
if (toStrViol)
{
if (!toStrViolatingMethods.ContainsKey(fconstructor))
newcontractViolation = true;
toStrViolatingMethods[fconstructor] = true;
}
if (hashCodeViol)
{
if (!hashCodeViolatingMethods.ContainsKey(fconstructor))
newcontractViolation = true;
hashCodeViolatingMethods[fconstructor] = true;
}
if (equalsViol)
{
if (!equalsViolatingMethods.ContainsKey(fconstructor))
newcontractViolation = true;
equalsViolatingMethods[fconstructor] = true;
}
if (newcontractViolation)
PlanManager.numContractViolatingPlans++;
//add this class to the faulty classes
contractExnViolatingClasses[fconstructor.DeclaringType] = true;
retval = false;
}
}
}
long endTime = 0;
Timer.QueryPerformanceCounter(ref endTime);
executionTimeAccum += ((double)(endTime - startTime)) / ((double)(Timer.PerfTimerFrequency));
if (contractViolated) //[email protected] adds
executionLog.WriteLine("contract violation."); //[email protected] adds
return retval;
}
public override string Namespace
{
get
{
return this.fconstructor.DeclaringType.Namespace;
}
}
public override ReadOnlyCollection<Assembly> Assemblies
{
get
{
return ReflectionUtils.GetRelatedAssemblies(this.fconstructor);
}
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.Versioning;
using FluentMigrator.Infrastructure.Extensions;
namespace FluentMigrator.Runner
{
public class MigrationRunner : IMigrationRunner
{
private Assembly _migrationAssembly;
private IAnnouncer _announcer;
private IStopWatch _stopWatch;
private bool _alreadyOutputPreviewOnlyModeWarning;
private readonly MigrationValidator _migrationValidator;
private readonly MigrationScopeHandler _migrationScopeHandler;
/// <summary>The arbitrary application context passed to the task runner.</summary>
public object ApplicationContext { get; private set; }
public bool TransactionPerSession { get; private set; }
public bool SilentlyFail { get; set; }
public IMigrationProcessor Processor { get; private set; }
public IMigrationInformationLoader MigrationLoader { get; set; }
public IProfileLoader ProfileLoader { get; set; }
public IMigrationConventions Conventions { get; private set; }
public IList<Exception> CaughtExceptions { get; private set; }
public IMigrationScope CurrentScope
{
get
{
return _migrationScopeHandler.CurrentScope;
}
set
{
_migrationScopeHandler.CurrentScope = value;
}
}
public MigrationRunner(Assembly assembly, IRunnerContext runnerContext, IMigrationProcessor processor)
{
_migrationAssembly = assembly;
_announcer = runnerContext.Announcer;
Processor = processor;
_stopWatch = runnerContext.StopWatch;
ApplicationContext = runnerContext.ApplicationContext;
TransactionPerSession = runnerContext.TransactionPerSession;
SilentlyFail = false;
CaughtExceptions = null;
Conventions = new MigrationConventions();
if (!string.IsNullOrEmpty(runnerContext.WorkingDirectory))
Conventions.GetWorkingDirectory = () => runnerContext.WorkingDirectory;
_migrationScopeHandler = new MigrationScopeHandler(Processor);
_migrationValidator = new MigrationValidator(_announcer, Conventions);
VersionLoader = new VersionLoader(this, _migrationAssembly, Conventions);
MigrationLoader = new DefaultMigrationInformationLoader(Conventions, _migrationAssembly, runnerContext.Namespace, runnerContext.NestedNamespaces, runnerContext.Tags);
ProfileLoader = new ProfileLoader(runnerContext, this, Conventions);
}
public IVersionLoader VersionLoader { get; set; }
public void ApplyProfiles()
{
ProfileLoader.ApplyProfiles();
}
public void MigrateUp()
{
MigrateUp(true);
}
public void MigrateUp(bool useAutomaticTransactionManagement)
{
var migrations = MigrationLoader.LoadMigrations();
using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession))
{
foreach (var pair in migrations)
{
ApplyMigrationUp(pair.Value, useAutomaticTransactionManagement && pair.Value.TransactionBehavior == TransactionBehavior.Default);
}
ApplyProfiles();
scope.Complete();
}
VersionLoader.LoadVersionInfo();
}
public void MigrateUp(long targetVersion)
{
MigrateUp(targetVersion, true);
}
public void MigrateUp(long targetVersion, bool useAutomaticTransactionManagement)
{
var migrationInfos = GetUpMigrationsToApply(targetVersion);
using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession))
{
foreach (var migrationInfo in migrationInfos)
{
ApplyMigrationUp(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default);
}
scope.Complete();
}
VersionLoader.LoadVersionInfo();
}
private IEnumerable<IMigrationInfo> GetUpMigrationsToApply(long version)
{
var migrations = MigrationLoader.LoadMigrations();
return from pair in migrations
where IsMigrationStepNeededForUpMigration(pair.Key, version)
select pair.Value;
}
private bool IsMigrationStepNeededForUpMigration(long versionOfMigration, long targetVersion)
{
if (versionOfMigration <= targetVersion && !VersionLoader.VersionInfo.HasAppliedMigration(versionOfMigration))
{
return true;
}
return false;
}
public void MigrateDown(long targetVersion)
{
MigrateDown(targetVersion, true);
}
public void MigrateDown(long targetVersion, bool useAutomaticTransactionManagement)
{
var migrationInfos = GetDownMigrationsToApply(targetVersion);
using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession))
{
foreach (var migrationInfo in migrationInfos)
{
ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default);
}
scope.Complete();
}
VersionLoader.LoadVersionInfo();
}
private IEnumerable<IMigrationInfo> GetDownMigrationsToApply(long targetVersion)
{
var migrations = MigrationLoader.LoadMigrations();
var migrationsToApply = (from pair in migrations
where IsMigrationStepNeededForDownMigration(pair.Key, targetVersion)
select pair.Value)
.ToList();
return migrationsToApply.OrderByDescending(x => x.Version);
}
private bool IsMigrationStepNeededForDownMigration(long versionOfMigration, long targetVersion)
{
if (versionOfMigration > targetVersion && VersionLoader.VersionInfo.HasAppliedMigration(versionOfMigration))
{
return true;
}
return false;
}
public virtual void ApplyMigrationUp(IMigrationInfo migrationInfo, bool useTransaction)
{
if (migrationInfo == null) throw new ArgumentNullException("migrationInfo");
if (!_alreadyOutputPreviewOnlyModeWarning && Processor.Options.PreviewOnly)
{
_announcer.Heading("PREVIEW-ONLY MODE");
_alreadyOutputPreviewOnlyModeWarning = true;
}
if (!migrationInfo.IsAttributed() || !VersionLoader.VersionInfo.HasAppliedMigration(migrationInfo.Version))
{
var name = migrationInfo.GetName();
_announcer.Heading(string.Format("{0} migrating", name));
_stopWatch.Start();
using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useTransaction))
{
ExecuteMigration(migrationInfo.Migration, (m, c) => m.GetUpExpressions(c));
if (migrationInfo.IsAttributed())
{
VersionLoader.UpdateVersionInfo(migrationInfo.Version, migrationInfo.Description ?? migrationInfo.Migration.GetType().Name);
}
scope.Complete();
_stopWatch.Stop();
_announcer.Say(string.Format("{0} migrated", name));
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
}
}
public virtual void ApplyMigrationDown(IMigrationInfo migrationInfo, bool useTransaction)
{
if (migrationInfo == null) throw new ArgumentNullException("migrationInfo");
var name = migrationInfo.GetName();
_announcer.Heading(string.Format("{0} reverting", name));
_stopWatch.Start();
using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useTransaction))
{
ExecuteMigration(migrationInfo.Migration, (m, c) => m.GetDownExpressions(c));
if (migrationInfo.IsAttributed()) VersionLoader.DeleteVersion(migrationInfo.Version);
scope.Complete();
_stopWatch.Stop();
_announcer.Say(string.Format("{0} reverted", name));
_announcer.ElapsedTime(_stopWatch.ElapsedTime());
}
}
public void Rollback(int steps)
{
Rollback(steps, true);
}
public void Rollback(int steps, bool useAutomaticTransactionManagement)
{
var availableMigrations = MigrationLoader.LoadMigrations();
var migrationsToRollback = new List<IMigrationInfo>();
foreach (long version in VersionLoader.VersionInfo.AppliedMigrations())
{
IMigrationInfo migrationInfo;
if (availableMigrations.TryGetValue(version, out migrationInfo)) migrationsToRollback.Add(migrationInfo);
}
using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession))
{
foreach (IMigrationInfo migrationInfo in migrationsToRollback.Take(steps))
{
ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default);
}
scope.Complete();
}
VersionLoader.LoadVersionInfo();
if (!VersionLoader.VersionInfo.AppliedMigrations().Any())
VersionLoader.RemoveVersionTable();
}
public void RollbackToVersion(long version)
{
RollbackToVersion(version, true);
}
public void RollbackToVersion(long version, bool useAutomaticTransactionManagement)
{
var availableMigrations = MigrationLoader.LoadMigrations();
var migrationsToRollback = new List<IMigrationInfo>();
foreach (long appliedVersion in VersionLoader.VersionInfo.AppliedMigrations())
{
IMigrationInfo migrationInfo;
if (availableMigrations.TryGetValue(appliedVersion, out migrationInfo)) migrationsToRollback.Add(migrationInfo);
}
using (IMigrationScope scope = _migrationScopeHandler.CreateOrWrapMigrationScope(useAutomaticTransactionManagement && TransactionPerSession))
{
foreach (IMigrationInfo migrationInfo in migrationsToRollback)
{
if (version >= migrationInfo.Version) continue;
ApplyMigrationDown(migrationInfo, useAutomaticTransactionManagement && migrationInfo.TransactionBehavior == TransactionBehavior.Default);
}
scope.Complete();
}
VersionLoader.LoadVersionInfo();
if (version == 0 && !VersionLoader.VersionInfo.AppliedMigrations().Any())
VersionLoader.RemoveVersionTable();
}
public Assembly MigrationAssembly
{
get { return _migrationAssembly; }
}
public void Up(IMigration migration)
{
var migrationInfoAdapter = new NonAttributedMigrationToMigrationInfoAdapter(migration);
ApplyMigrationUp(migrationInfoAdapter, true);
}
private void ExecuteMigration(IMigration migration, Action<IMigration, IMigrationContext> getExpressions)
{
CaughtExceptions = new List<Exception>();
var context = new MigrationContext(Conventions, Processor, MigrationAssembly, ApplicationContext, Processor.ConnectionString);
getExpressions(migration, context);
_migrationValidator.ApplyConventionsToAndValidateExpressions(migration, context.Expressions);
ExecuteExpressions(context.Expressions);
}
public void Down(IMigration migration)
{
var migrationInfoAdapter = new NonAttributedMigrationToMigrationInfoAdapter(migration);
ApplyMigrationDown(migrationInfoAdapter, true);
}
/// <summary>
/// execute each migration expression in the expression collection
/// </summary>
/// <param name="expressions"></param>
protected void ExecuteExpressions(ICollection<IMigrationExpression> expressions)
{
long insertTicks = 0;
int insertCount = 0;
foreach (IMigrationExpression expression in expressions)
{
try
{
if (expression is InsertDataExpression)
{
insertTicks += _stopWatch.Time(() => expression.ExecuteWith(Processor)).Ticks;
insertCount++;
}
else
{
AnnounceTime(expression.ToString(), () => expression.ExecuteWith(Processor));
}
}
catch (Exception er)
{
_announcer.Error(er.Message);
//catch the error and move onto the next expression
if (SilentlyFail)
{
CaughtExceptions.Add(er);
continue;
}
throw;
}
}
if (insertCount > 0)
{
var avg = new TimeSpan(insertTicks / insertCount);
var msg = string.Format("-> {0} Insert operations completed in {1} taking an average of {2}", insertCount, new TimeSpan(insertTicks), avg);
_announcer.Say(msg);
}
}
private void AnnounceTime(string message, Action action)
{
_announcer.Say(message);
_announcer.ElapsedTime(_stopWatch.Time(action));
}
public void ValidateVersionOrder()
{
var unappliedVersions = MigrationLoader.LoadMigrations().Where(kvp => MigrationVersionLessThanGreatestAppliedMigration(kvp.Key)).ToList();
if (unappliedVersions.Any())
throw new VersionOrderInvalidException(unappliedVersions);
_announcer.Say("Version ordering valid.");
}
public void ListMigrations()
{
IVersionInfo currentVersionInfo = this.VersionLoader.VersionInfo;
long currentVersion = currentVersionInfo.Latest();
_announcer.Heading("Migrations");
foreach(KeyValuePair<long, IMigrationInfo> migration in MigrationLoader.LoadMigrations())
{
string migrationName = migration.Value.GetName();
bool isCurrent = migration.Key == currentVersion;
string message = string.Format("{0}{1}",
migrationName,
isCurrent ? " (current)" : string.Empty);
if(isCurrent)
_announcer.Emphasize(message);
else
_announcer.Say(message);
}
}
private bool MigrationVersionLessThanGreatestAppliedMigration(long version)
{
return !VersionLoader.VersionInfo.HasAppliedMigration(version) && version < VersionLoader.VersionInfo.Latest();
}
public IMigrationScope BeginScope()
{
return _migrationScopeHandler.BeginScope();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Collections;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Execution;
using Microsoft.Build.Shared;
using Xunit;
using System;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.Build.UnitTests.Evaluation
{
/// <summary>
/// Unit tests for Importing from $(MSBuildExtensionsPath*)
/// </summary>
public class ImportFromMSBuildExtensionsPathTests : IDisposable
{
string toolsVersionToUse = null;
public ImportFromMSBuildExtensionsPathTests()
{
toolsVersionToUse = new ProjectCollection().DefaultToolsVersion;
}
public void Dispose()
{
ToolsetConfigurationReaderTestHelper.CleanUp();
}
[Fact]
public void ImportFromExtensionsPathFound()
{
CreateAndBuildProjectForImportFromExtensionsPath("MSBuildExtensionsPath", (p, l) => Assert.True(p.Build()));
}
[Fact]
public void ImportFromExtensionsPathNotFound()
{
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), GetExtensionTargetsFileContent1());
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
var projColln = GetProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1, Path.Combine("tmp", "nonexistent")));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath));
logger.AssertLogContains("MSB4226");
}
finally
{
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
}
}
[Fact]
public void ConditionalImportFromExtensionsPathNotFound()
{
string extnTargetsFileContentWithCondition = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FooBar</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\bar\extn2.proj' Condition=""Exists('$(MSBuildExtensionsPath)\bar\extn2.proj')""/>
</Project>
";
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContentWithCondition);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] { extnDir1, Path.Combine("tmp", "nonexistent") },
null,
(p, l) => {
Assert.True(p.Build());
l.AssertLogContains("Running FromExtn");
l.AssertLogContains("PropertyFromExtn1: FooBar");
});
}
[Fact]
public void ImportFromExtensionsPathCircularImportError()
{
string extnTargetsFileContent1 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\foo\extn2.proj' />
</Project>
";
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn2'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='{0}'/>
</Project>
";
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1);
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn2.proj"),
String.Format(extnTargetsFileContent2, mainProjectPath));
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath",
new string[] { extnDir2, Path.Combine("tmp", "nonexistent"), extnDir1 },
null,
(p, l) => l.AssertLogContains("MSB4210"));
}
[Fact]
public void ExtensionPathFallbackIsCaseInsensitive()
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='Main'>
<Message Text='Running Main'/>
</Target>
<Import Project='$(msbuildExtensionsPath)\foo\extn.proj'/>
</Project>";
string extnTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running {0}'/>
</Target>
</Project>
";
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent);
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath",
new[] { extnDir1 },
null,
(project, logger) =>
{
Console.WriteLine(logger.FullLog);
Console.WriteLine("checking FromExtn");
Assert.True(project.Build("FromExtn"));
Console.WriteLine("checking logcontains");
logger.AssertLogDoesntContain("MSB4057"); // Should not contain TargetDoesNotExist
});
}
[Fact]
public void ImportFromExtensionsPathWithWildCard()
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='Main'>
<Message Text='Running Main'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\foo\*.proj'/>
</Project>";
string extnTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='{0}'>
<Message Text='Running {0}'/>
</Target>
</Project>
";
// Importing a wildcard will union all matching results from all fallback locations.
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
string.Format(extnTargetsFileContent, "FromExtn1"));
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"),
string.Format(extnTargetsFileContent, "FromExtn2"));
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent);
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath",
new[] { extnDir1, Path.Combine("tmp", "nonexistent"), extnDir2 },
null,
(project, logger) =>
{
Console.WriteLine(logger.FullLog);
Console.WriteLine("checking FromExtn1");
Assert.True(project.Build("FromExtn1"));
Console.WriteLine("checking FromExtn2");
Assert.True(project.Build("FromExtn2"));
Console.WriteLine("checking logcontains");
logger.AssertLogDoesntContain("MSB4057"); // Should not contain TargetDoesNotExist
});
}
[Fact]
public void ImportFromExtensionsPathWithWildCardAndSelfImport()
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='Main'>
<Message Text='Running Main'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\circularwildcardtest\*.proj'/>
</Project>";
string extnTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='{0}'>
<Message Text='Running {0}'/>
</Target>
</Project>";
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='$(MSBuildExtensionsPath)\circularwildcardtest\*.proj'/>
<Target Name='{0}'>
<Message Text='Running {0}'/>
</Target>
</Project>";
// Importing a wildcard will union all matching results from all fallback locations.
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("circularwildcardtest", "extn.proj"),
string.Format(extnTargetsFileContent, "FromExtn1"));
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("circularwildcardtest", "extn.proj"),
string.Format(extnTargetsFileContent, "FromExtn2"));
string extnDir3 = GetNewExtensionsPathAndCreateFile("extensions3", Path.Combine("circularwildcardtest", "extn3.proj"),
string.Format(extnTargetsFileContent2, "FromExtn3"));
// Main project path is under "circularwildcardtest"
// Note: This project will try to be imported again and cause a warning (MSB4210). This test should ensure that the
// code does not stop looking in the fallback locations when this happens (extn3.proj should still be imported).
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory(Path.Combine("extensions2", "circularwildcardtest", "main.proj"), mainTargetsFileContent);
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath",
new[] { extnDir1, extnDir2, extnDir3 },
null,
(project, logger) =>
{
Console.WriteLine(logger.FullLog);
Assert.True(project.Build("FromExtn1"));
Assert.True(project.Build("FromExtn2"));
Assert.True(project.Build("FromExtn3"));
logger.AssertLogContains("MSB4210");
});
}
[Fact]
public void ImportFromExtensionsPathWithWildCardNothingFound()
{
string extnTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\non-existant\*.proj'/>
</Project>
";
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] { Path.Combine("tmp", "nonexistent"), extnDir1 },
null, (p, l) => Assert.True(p.Build()));
}
[Fact]
public void ImportFromExtensionsPathInvalidFile()
{
string extnTargetsFileContent = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >";
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
var projColln = GetProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", extnDir1,
Path.Combine("tmp", "nonexistent")));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
Assert.Throws<InvalidProjectFileException>(() => projColln.LoadProject(mainProjectPath));
logger.AssertLogContains("MSB4024");
}
finally
{
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
}
}
[Fact]
public void ImportFromExtensionsPathSearchOrder()
{
string extnTargetsFileContent1 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromFirstFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromSecondFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
// File with the same name available in two different extension paths, but the one from the first
// directory in MSBuildExtensionsPath environment variable should get loaded
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1);
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), extnTargetsFileContent2);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, "MSBuildExtensionsPath", new string[] { extnDir2, Path.Combine("tmp", "nonexistent"), extnDir1 },
null,
(p, l) => {
Assert.True(p.Build());
l.AssertLogContains("Running FromExtn");
l.AssertLogContains("PropertyFromExtn1: FromSecondFile");
});
}
[Fact]
public void ImportFromExtensionsPathSearchOrder2()
{
string extnTargetsFileContent1 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromFirstFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FromSecondFile</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>
";
// File with the same name available in two different extension paths, but the one from the first
// directory in MSBuildExtensionsPath environment variable should get loaded
string extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"), extnTargetsFileContent1);
string extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("foo", "extn.proj"), extnTargetsFileContent2);
string mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
// MSBuildExtensionsPath* property value has highest priority for the lookups
try
{
var projColln = GetProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader("MSBuildExtensionsPath", Path.Combine("tmp", "non-existent"), extnDir1));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
var project = projColln.LoadProject(mainProjectPath);
project.SetProperty("MSBuildExtensionsPath", extnDir2);
project.ReevaluateIfNecessary();
Assert.True(project.Build());
logger.AssertLogContains("Running FromExtn");
logger.AssertLogContains("PropertyFromExtn1: FromSecondFile");
}
finally
{
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
if (extnDir2 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
}
}
}
[Fact]
public void ImportOrderFromExtensionsPath32()
{
CreateAndBuildProjectForImportFromExtensionsPath("MSBuildExtensionsPath32", (p, l) => Assert.True(p.Build()));
}
[Fact]
public void ImportOrderFromExtensionsPath64()
{
CreateAndBuildProjectForImportFromExtensionsPath("MSBuildExtensionsPath64", (p, l) => Assert.True(p.Build()));
}
// Use MSBuildExtensionsPath, MSBuildExtensionsPath32 and MSBuildExtensionsPath64 in the build
[Fact]
public void ImportFromExtensionsPathAnd32And64()
{
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn{0}' DependsOnTargets='{1}'>
<Message Text='Running FromExtn{0}'/>
</Target>
{2}
</Project>
";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""" + toolsVersionToUse + @""">
<toolset toolsVersion=""" + toolsVersionToUse + @""">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value=""" + /*v4Folder*/"." + @"""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""MSBuildExtensionsPath"" value=""{0}"" />
<property name=""MSBuildExtensionsPath32"" value=""{1}"" />
<property name=""MSBuildExtensionsPath64"" value=""{2}"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null, extnDir2 = null, extnDir3 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
String.Format(extnTargetsFileContentTemplate, String.Empty, "FromExtn2", "<Import Project='$(MSBuildExtensionsPath32)\\bar\\extn2.proj' />"));
extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("bar", "extn2.proj"),
String.Format(extnTargetsFileContentTemplate, 2, "FromExtn3", "<Import Project='$(MSBuildExtensionsPath64)\\xyz\\extn3.proj' />"));
extnDir3 = GetNewExtensionsPathAndCreateFile("extensions3", Path.Combine("xyz", "extn3.proj"),
String.Format(extnTargetsFileContentTemplate, 3, String.Empty, String.Empty));
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent());
ToolsetConfigurationReaderTestHelper.WriteConfigFile(String.Format(configFileContents, extnDir1, extnDir2, extnDir3));
var reader = GetStandardConfigurationReader();
var projColln = GetProjectCollection();
projColln.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projColln.RegisterLogger(logger);
var project = projColln.LoadProject(mainProjectPath);
Assert.True(project.Build("Main"));
logger.AssertLogContains("Running FromExtn3");
logger.AssertLogContains("Running FromExtn2");
logger.AssertLogContains("Running FromExtn");
}
finally
{
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
if (extnDir2 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
}
if (extnDir3 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir3, recursive: true);
}
}
}
// Fall-back path that has a property in it: $(FallbackExpandDir1)
[Fact]
public void ExpandExtensionsPathFallback()
{
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\\foo\\extn.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" />
</Project>";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""" + toolsVersionToUse + @""">
<toolset toolsVersion=""" + toolsVersionToUse + @""">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value="".""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
extnTargetsFileContentTemplate);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj",
GetMainTargetFileContent());
ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
var reader = GetStandardConfigurationReader();
var projectCollection = GetProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 });
projectCollection.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projectCollection.RegisterLogger(logger);
var project = projectCollection.LoadProject(mainProjectPath);
Assert.True(project.Build("Main"));
logger.AssertLogContains("Running FromExtn");
}
finally
{
FileUtilities.DeleteNoThrow(mainProjectPath);
FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
}
}
// Fall-back path that has a property in it: $(FallbackExpandDir1)
[Fact]
public void ExpandExtensionsPathFallbackInErrorMessage()
{
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$(MSBuildExtensionsPath)\\foo\\extn2.proj' Condition=""Exists('$(MSBuildExtensionsPath)\foo\extn.proj')"" />
</Project>";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""" + toolsVersionToUse + @""">
<toolset toolsVersion=""" + toolsVersionToUse + @""">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value="".""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
extnTargetsFileContentTemplate);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj",
GetMainTargetFileContent());
ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
var reader = GetStandardConfigurationReader();
var projectCollection = GetProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 });
projectCollection.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projectCollection.RegisterLogger(logger);
Assert.Throws<InvalidProjectFileException>(() => projectCollection.LoadProject(mainProjectPath));
// Expanded $(FallbackExpandDir) will appear in quotes in the log
logger.AssertLogContains("\"" + extnDir1 + "\"");
}
finally
{
FileUtilities.DeleteNoThrow(mainProjectPath);
FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
}
}
// Fall-back search path with custom variable
[Fact]
public void FallbackImportWithIndirectReference()
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<VSToolsPath>$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v99</VSToolsPath>
</PropertyGroup>
<Import Project='$(VSToolsPath)\DNX\Microsoft.DNX.Props' Condition=""Exists('$(VSToolsPath)\DNX\Microsoft.DNX.Props')"" />
<Target Name='Main' DependsOnTargets='FromExtn' />
</Project>";
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""" + toolsVersionToUse + @""">
<toolset toolsVersion=""" + toolsVersionToUse + @""">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value="".""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""MSBuildExtensionsPath"" value=""$(FallbackExpandDir1)"" />
<property name=""VSToolsPath"" value=""$(FallbackExpandDir1)\Microsoft\VisualStudio\v99"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("Microsoft", "VisualStudio", "v99", "DNX", "Microsoft.DNX.Props"),
extnTargetsFileContentTemplate);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent);
ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
var reader = GetStandardConfigurationReader();
var projectCollection = GetProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 });
projectCollection.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projectCollection.RegisterLogger(logger);
var project = projectCollection.LoadProject(mainProjectPath);
Assert.True(project.Build("Main"));
logger.AssertLogContains("Running FromExtn");
}
finally
{
FileUtilities.DeleteNoThrow(mainProjectPath);
FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
}
}
// Fall-back search path on a property that is not defined.
[Fact]
public void FallbackImportWithUndefinedProperty()
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='$(UndefinedProperty)\file.props' Condition=""Exists('$(UndefinedProperty)\file.props')"" />
<Target Name='Main' DependsOnTargets='FromExtn' />
</Project>";
string extnTargetsFileContentTemplate = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
</Project>";
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""" + toolsVersionToUse + @""">
<toolset toolsVersion=""" + toolsVersionToUse + @""">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value="".""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""UndefinedProperty"" value=""$(FallbackExpandDir1)"" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
string extnDir1 = null;
string mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("file.props"),
extnTargetsFileContentTemplate);
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent);
ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
var reader = GetStandardConfigurationReader();
var projectCollection = GetProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 });
projectCollection.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projectCollection.RegisterLogger(logger);
var project = projectCollection.LoadProject(mainProjectPath);
Assert.True(project.Build("Main"));
logger.AssertLogContains("Running FromExtn");
}
finally
{
FileUtilities.DeleteNoThrow(mainProjectPath);
FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
}
}
[Fact]
public void FallbackImportWithFileNotFoundWhenPropertyNotDefined()
{
// Import something from $(UndefinedProperty)
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Import Project='$(UndefinedProperty)\filenotfound.props' />
<Target Name='Main' DependsOnTargets='FromExtn' />
</Project>";
string extnDir1 = null;
string mainProjectPath = null;
try
{
// The path to "extensions1" fallback should exist, but the file doesn't need to
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("file.props"), string.Empty);
// Implement fallback for UndefinedProperty, but don't define the property.
var configFileContents = @"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"" />
</configSections>
<msbuildToolsets default=""" + toolsVersionToUse + @""">
<toolset toolsVersion=""" + toolsVersionToUse + @""">
<property name=""MSBuildToolsPath"" value="".""/>
<property name=""MSBuildBinPath"" value="".""/>
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""UndefinedProperty"" value=""" + extnDir1 + @""" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>";
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", mainTargetsFileContent);
ToolsetConfigurationReaderTestHelper.WriteConfigFile(configFileContents);
var reader = GetStandardConfigurationReader();
var projectCollection = GetProjectCollection(new Dictionary<string, string> { ["FallbackExpandDir1"] = extnDir1 });
projectCollection.ResetToolsetsForTests(reader);
var logger = new MockLogger();
projectCollection.RegisterLogger(logger);
Assert.Throws<InvalidProjectFileException>(() => projectCollection.LoadProject(mainProjectPath));
logger.AssertLogContains(@"MSB4226: The imported project """ + Path.Combine("$(UndefinedProperty)", "filenotfound.props")
+ @""" was not found. Also, tried to find");
}
finally
{
FileUtilities.DeleteNoThrow(mainProjectPath);
FileUtilities.DeleteDirectoryNoThrow(extnDir1, true);
}
}
void CreateAndBuildProjectForImportFromExtensionsPath(string extnPathPropertyName, Action<Project, MockLogger> action)
{
string extnDir1 = null, extnDir2 = null, mainProjectPath = null;
try
{
extnDir1 = GetNewExtensionsPathAndCreateFile("extensions1", Path.Combine("foo", "extn.proj"),
GetExtensionTargetsFileContent1(extnPathPropertyName));
extnDir2 = GetNewExtensionsPathAndCreateFile("extensions2", Path.Combine("bar", "extn2.proj"),
GetExtensionTargetsFileContent2(extnPathPropertyName));
mainProjectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("main.proj", GetMainTargetFileContent(extnPathPropertyName));
CreateAndBuildProjectForImportFromExtensionsPath(mainProjectPath, extnPathPropertyName, new string[] { extnDir1, extnDir2 },
null,
action);
}
finally
{
if (extnDir1 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir1, recursive: true);
}
if (extnDir2 != null)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir2, recursive: true);
}
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
}
}
void CreateAndBuildProjectForImportFromExtensionsPath(string mainProjectPath, string extnPathPropertyName, string[] extnDirs, Action<string[]> setExtensionsPath,
Action<Project, MockLogger> action)
{
try
{
var projColln = GetProjectCollection();
projColln.ResetToolsetsForTests(WriteConfigFileAndGetReader(extnPathPropertyName, extnDirs));
var logger = new MockLogger();
projColln.RegisterLogger(logger);
var project = projColln.LoadProject(mainProjectPath);
action(project, logger);
}
finally
{
if (mainProjectPath != null)
{
FileUtilities.DeleteNoThrow(mainProjectPath);
}
if (extnDirs != null)
{
foreach (var extnDir in extnDirs)
{
FileUtilities.DeleteDirectoryNoThrow(extnDir, recursive: true);
}
}
}
}
private ToolsetConfigurationReader WriteConfigFileAndGetReader(string extnPathPropertyName, params string[] extnDirs)
{
string combinedExtnDirs = extnDirs != null ? String.Join(";", extnDirs) : String.Empty;
ToolsetConfigurationReaderTestHelper.WriteConfigFile(@"
<configuration>
<configSections>
<section name=""msbuildToolsets"" type=""Microsoft.Build.Evaluation.ToolsetConfigurationSection, Microsoft.Build"" />
</configSections>
<msbuildToolsets default=""" + toolsVersionToUse + @""">
<toolset toolsVersion=""" + toolsVersionToUse + @""">
<property name=""MSBuildToolsPath"" value=""."" />
<property name=""MSBuildBinPath"" value=""."" />
<projectImportSearchPaths>
<searchPaths os=""" + NativeMethodsShared.GetOSNameForExtensionsPath() + @""">
<property name=""" + extnPathPropertyName + @""" value=""" + combinedExtnDirs + @""" />
</searchPaths>
</projectImportSearchPaths>
</toolset>
</msbuildToolsets>
</configuration>");
return GetStandardConfigurationReader();
}
private ProjectCollection GetProjectCollection(IDictionary<string, string> globalProperties = null)
{
ProjectCollection projColln;
if (globalProperties == null)
{
#if FEATURE_SYSTEM_CONFIGURATION
projColln = new ProjectCollection();
#else
projColln = new ProjectCollection(ToolsetDefinitionLocations.ConfigurationFile);
#endif
}
else
{
#if FEATURE_SYSTEM_CONFIGURATION
projColln = new ProjectCollection(globalProperties);
#else
projColln = new ProjectCollection(globalProperties, loggers: null, ToolsetDefinitionLocations.ConfigurationFile);
#endif
}
return projColln;
}
string GetNewExtensionsPathAndCreateFile(string extnDirName, string relativeFilePath, string fileContents)
{
var extnDir = Path.Combine(ObjectModelHelpers.TempProjectDir, extnDirName);
Directory.CreateDirectory(Path.Combine(extnDir, Path.GetDirectoryName(relativeFilePath)));
File.WriteAllText(Path.Combine(extnDir, relativeFilePath), fileContents);
return extnDir;
}
string GetMainTargetFileContent(string extensionsPathPropertyName = "MSBuildExtensionsPath")
{
string mainTargetsFileContent = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<Target Name='Main' DependsOnTargets='FromExtn'>
<Message Text='PropertyFromExtn1: $(PropertyFromExtn1)'/>
</Target>
<Import Project='$({0})\foo\extn.proj'/>
</Project>";
return String.Format(mainTargetsFileContent, extensionsPathPropertyName);
}
string GetExtensionTargetsFileContent1(string extensionsPathPropertyName = "MSBuildExtensionsPath")
{
string extnTargetsFileContent1 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn1>FooBar</PropertyFromExtn1>
</PropertyGroup>
<Target Name='FromExtn'>
<Message Text='Running FromExtn'/>
</Target>
<Import Project='$({0})\bar\extn2.proj'/>
</Project>
";
return String.Format(extnTargetsFileContent1, extensionsPathPropertyName);
}
string GetExtensionTargetsFileContent2(string extensionsPathPropertyName = "MSBuildExtensionsPath")
{
string extnTargetsFileContent2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<PropertyGroup>
<PropertyFromExtn2>Abc</PropertyFromExtn2>
</PropertyGroup>
<Target Name='FromExtn2'>
<Message Text='Running FromExtn2'/>
</Target>
</Project>
";
return extnTargetsFileContent2;
}
private ToolsetConfigurationReader GetStandardConfigurationReader()
{
return new ToolsetConfigurationReader(new ProjectCollection().EnvironmentProperties, new PropertyDictionary<ProjectPropertyInstance>(), ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PictureBoxExtended.cs" company="">
//
// </copyright>
// <summary>
// This class extends the PictureBox control with the following:
// GetRelativeMousePosition()
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MineAPI.Editor.GUI
{
using System;
using System.Drawing;
using System.Windows.Forms;
/// <summary>
/// This class extends the PictureBox control with the following:
/// <list type="table">
/// <item><term>GetRelativeMousePosition()</term></item>
/// </list>
/// </summary>
public class PictureBoxExtended : PictureBox
{
#region Delegates
/// <summary>
/// Handler for when the mouse moves over the image part of the picture box
/// </summary>
public delegate void MouseMoveOverImageHandler(object sender, MouseEventArgs e);
#endregion
#region Public Events
/// <summary>
/// Occurs when the mouse have moved over the image part of a picture box
/// </summary>
public event MouseMoveOverImageHandler MouseMoveOverImage;
#endregion
#region Public Properties
/// <summary>
/// Gets the mouse position relative to the <see cref="PictureBox.Image">Image</see> top left corner
/// </summary>
/// <value>The location of the mouse translated onto the <see cref="PictureBox.Image">Image</see> .</value>
public Point MousePositionOnImage
{
get
{
Point local = PointToClient(MousePosition);
return TranslatePointToImageCoordinates(local);
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Translates a point to coordinates relative to the <see cref="PictureBox.Image">Image</see>.
/// The supplied point is taken relativce to the control's upper left corner
/// </summary>
/// <param name="controlCoordinates">
/// The point to translate, relative to the control's upper left corner.
/// </param>
/// <returns>
/// A new point representing where over the <see cref="PictureBox.Image">Image</see> the supplied point is.
/// </returns>
public Point TranslatePointToImageCoordinates(Point controlCoordinates)
{
switch (SizeMode)
{
case PictureBoxSizeMode.Normal:
return TranslateNormalMousePosition(controlCoordinates);
case PictureBoxSizeMode.AutoSize:
return TranslateAutoSizeMousePosition(controlCoordinates);
case PictureBoxSizeMode.CenterImage:
return TranslateCenterImageMousePosition(controlCoordinates);
case PictureBoxSizeMode.StretchImage:
return TranslateStretchImageMousePosition(controlCoordinates);
case PictureBoxSizeMode.Zoom:
return TranslateZoomMousePosition(controlCoordinates);
}
throw new NotImplementedException("PictureBox.SizeMode was not in a valid state");
}
#endregion
#region Methods
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Control.MouseMove"></see> event.
/// If the mouse is over the <see cref="PictureBox.Image">Image</see>, raises the <see cref="MouseMoveOverImage"></see> event.
/// </summary>
/// <param name="e">
/// A <see cref="T:System.Windows.Forms.MouseEventArgs"></see> that contains the event data.
/// </param>
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
if (Image != null)
{
if (MouseMoveOverImage != null)
{
Point p = TranslatePointToImageCoordinates(e.Location);
if (p.X >= 0 && p.X < Image.Width && p.Y >= 0 && p.Y < Image.Height)
{
MouseEventArgs ne = new MouseEventArgs(e.Button, e.Clicks, p.X, p.Y, e.Delta);
MouseMoveOverImage(this, ne);
}
}
}
}
/// <summary>
/// Gets the mouse position over the image when the <see cref="PictureBox">PictureBox's</see> <see cref="PictureBox.SizeMode">SizeMode</see> is set to AutoSize
/// </summary>
/// <param name="coordinates">
/// Point to translate
/// </param>
/// <returns>
/// A point relative to the top left corner of the <see cref="PictureBox.Image">Image</see>
/// </returns>
/// <remarks>
/// In AutoSize mode, the <see cref="PictureBox">PictureBox</see> is automagically resized* to the size of the <see cref="PictureBox.Image">Image.</see>
/// Thus, the image is at the top left corner of the control, and no translation takes place.
/// * This is not necessary true. The <see cref="PictureBox">PictureBox</see> may NOT be resized depending on how it is docked in it's parent.
/// However, even in these cases no translation is needed, as the image is rendered the same as if it was in Normal mode
/// </remarks>
protected Point TranslateAutoSizeMousePosition(Point coordinates)
{
// TODO: When we implement scrolling, we will have to make sure we test that properly. As of now, not sure how the rendering will take place
return coordinates;
}
/// <summary>
/// Gets the mouse position over the image when the <see cref="PictureBox">PictureBox's</see> <see cref="PictureBox.SizeMode">SizeMode</see> is set to Center
/// </summary>
/// <param name="coordinates">
/// Point to translate
/// </param>
/// <returns>
/// A point relative to the top left corner of the <see cref="PictureBox.Image">Image</see>
/// If the Image is null, no translation is performed
/// </returns>
protected Point TranslateCenterImageMousePosition(Point coordinates)
{
// Test to make sure our image is not null
if (Image == null)
{
return coordinates;
}
// First, get the top location (relative to the top left of the control) of the image itself
// To do this, we know that the image is centered, so we get the difference in size (width and height) of the image to the control
int diffWidth = Width - Image.Width;
int diffHeight = Height - Image.Height;
// We now divide in half to accommodate each side of the image
diffWidth /= 2;
diffHeight /= 2;
// Finally, we subtract this number from the original coordinates
// In the case that the image is larger than the picture box, this still works
coordinates.X -= diffWidth;
coordinates.Y -= diffHeight;
return coordinates;
}
/// <summary>
/// Gets the mouse position over the image when the <see cref="PictureBox">PictureBox's</see> <see cref="PictureBox.SizeMode">SizeMode</see> is set to Normal
/// </summary>
/// <param name="coordinates">
/// Point to translate
/// </param>
/// <returns>
/// A point relative to the top left corner of the <see cref="PictureBox.Image">Image</see>
/// </returns>
/// <remarks>
/// In normal mode, the image is placed in the top left corner, and as such the point does not need to be translated.
/// The resulting point is the same as the original point
/// </remarks>
protected Point TranslateNormalMousePosition(Point coordinates)
{
// TODO: When we implement scrolling in this, we will need to test for scroll offset
// NOTE: As it stands now, this could be made static, but in the future we will be making this handle scaling
return coordinates;
}
/// <summary>
/// Gets the mouse position over the image when the <see cref="PictureBox">PictureBox's</see> <see cref="PictureBox.SizeMode">SizeMode</see> is set to StretchImage
/// </summary>
/// <param name="coordinates">
/// Point to translate
/// </param>
/// <returns>
/// A point relative to the top left corner of the <see cref="PictureBox.Image">Image</see>
/// If the Image is null, no translation is performed
/// </returns>
protected Point TranslateStretchImageMousePosition(Point coordinates)
{
// test to make sure our image is not null
if (Image == null)
{
return coordinates;
}
// Make sure our control width and height are not 0
if (Width == 0 || Height == 0)
{
return coordinates;
}
// First, get the ratio (image to control) the height and width
float ratioWidth = (float)Image.Width / Width;
float ratioHeight = (float)Image.Height / Height;
// Scale the points by our ratio
float newX = coordinates.X;
float newY = coordinates.Y;
newX *= ratioWidth;
newY *= ratioHeight;
return new Point((int)newX, (int)newY);
}
/// <summary>
/// Gets the mouse position over the image when the <see cref="PictureBox">PictureBox's</see> <see cref="PictureBox.SizeMode">SizeMode</see> is set to Zoom
/// </summary>
/// <param name="coordinates">
/// Point to translate
/// </param>
/// <returns>
/// A point relative to the top left corner of the <see cref="PictureBox.Image">Image</see>
/// If the Image is null, no translation is performed
/// </returns>
protected Point TranslateZoomMousePosition(Point coordinates)
{
// test to make sure our image is not null
if (Image == null)
{
return coordinates;
}
// Make sure our control width and height are not 0 and our image width and height are not 0
if (Width == 0 || Height == 0 || Image.Width == 0 || Image.Height == 0)
{
return coordinates;
}
// This is the one that gets a little tricky. Essentially, need to check the aspect ratio of the image to the aspect ratio of the control
// to determine how it is being rendered
float imageAspect = (float)Image.Width / Image.Height;
float controlAspect = (float)Width / Height;
float newX = coordinates.X;
float newY = coordinates.Y;
if (imageAspect > controlAspect)
{
// This means that we are limited by width, meaning the image fills up the entire control from left to right
float ratioWidth = (float)Image.Width / Width;
newX *= ratioWidth;
float scale = (float)Width / Image.Width;
float displayHeight = scale * Image.Height;
float diffHeight = Height - displayHeight;
diffHeight /= 2;
newY -= diffHeight;
newY /= scale;
}
else
{
// This means that we are limited by height, meaning the image fills up the entire control from top to bottom
float ratioHeight = (float)Image.Height / Height;
newY *= ratioHeight;
float scale = (float)Height / Image.Height;
float displayWidth = scale * Image.Width;
float diffWidth = Width - displayWidth;
diffWidth /= 2;
newX -= diffWidth;
newX /= scale;
}
return new Point((int)newX, (int)newY);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureResource
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for AutoRestResourceFlatteningTestService.
/// </summary>
public static partial class AutoRestResourceFlatteningTestServiceExtensions
{
/// <summary>
/// Put External Resource as an Array
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceArray'>
/// External Resource as an Array to put
/// </param>
public static void PutArray(this IAutoRestResourceFlatteningTestService operations, IList<Resource> resourceArray = default(IList<Resource>))
{
Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutArrayAsync(resourceArray), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put External Resource as an Array
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceArray'>
/// External Resource as an Array to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutArrayAsync(this IAutoRestResourceFlatteningTestService operations, IList<Resource> resourceArray = default(IList<Resource>), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutArrayWithHttpMessagesAsync(resourceArray, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get External Resource as an Array
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IList<FlattenedProduct> GetArray(this IAutoRestResourceFlatteningTestService operations)
{
return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetArrayAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get External Resource as an Array
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<FlattenedProduct>> GetArrayAsync(this IAutoRestResourceFlatteningTestService operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetArrayWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put External Resource as a Dictionary
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceDictionary'>
/// External Resource as a Dictionary to put
/// </param>
public static void PutDictionary(this IAutoRestResourceFlatteningTestService operations, IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>))
{
Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutDictionaryAsync(resourceDictionary), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put External Resource as a Dictionary
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceDictionary'>
/// External Resource as a Dictionary to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutDictionaryWithHttpMessagesAsync(resourceDictionary, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get External Resource as a Dictionary
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IDictionary<string, FlattenedProduct> GetDictionary(this IAutoRestResourceFlatteningTestService operations)
{
return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetDictionaryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get External Resource as a Dictionary
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IDictionary<string, FlattenedProduct>> GetDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDictionaryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put External Resource as a ResourceCollection
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceComplexObject'>
/// External Resource as a ResourceCollection to put
/// </param>
public static void PutResourceCollection(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection))
{
Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutResourceCollectionAsync(resourceComplexObject), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put External Resource as a ResourceCollection
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceComplexObject'>
/// External Resource as a ResourceCollection to put
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutResourceCollectionWithHttpMessagesAsync(resourceComplexObject, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get External Resource as a ResourceCollection
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static ResourceCollection GetResourceCollection(this IAutoRestResourceFlatteningTestService operations)
{
return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetResourceCollectionAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get External Resource as a ResourceCollection
/// <see href="http://tempuri.org" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceCollection> GetResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetResourceCollectionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// MenuScreen.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Input;
#endregion
namespace Nano
{
/// <summary>
/// Base class for screens that contain a menu of options. The user can
/// move up and down to select an entry, or cancel to back out of the screen.
/// </summary>
abstract class MenuScreen : GameScreen
{
#region Fields
// the number of pixels to pad above and below menu entries for touch input
const int menuEntryPadding = 10;
List<MenuEntry> menuEntries = new List<MenuEntry>();
int selectedEntry = 0;
string menuTitle;
#endregion
#region Properties
/// <summary>
/// Gets the list of menu entries, so derived classes can add
/// or change the menu contents.
/// </summary>
protected IList<MenuEntry> MenuEntries
{
get { return menuEntries; }
}
#endregion
#region Initialization
/// <summary>
/// Constructor.
/// </summary>
public MenuScreen(string menuTitle)
{
// menus generally only need Tap for menu selection
EnabledGestures = GestureType.Tap;
this.menuTitle = menuTitle;
TransitionOnTime = TimeSpan.FromSeconds(0.5);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
}
#endregion
#region Handle Input
/// <summary>
/// Allows the screen to create the hit bounds for a particular menu entry.
/// </summary>
protected virtual Rectangle GetMenuEntryHitBounds(MenuEntry entry)
{
// the hit bounds are the entire width of the screen, and the height of the entry
// with some additional padding above and below.
return new Rectangle(
0,
(int)entry.Position.Y - menuEntryPadding,
ScreenManager.GraphicsDevice.Viewport.Width,
entry.GetHeight(this) + (menuEntryPadding * 2));
}
/// <summary>
/// Responds to user input, changing the selected entry and accepting
/// or cancelling the menu.
/// </summary>
public override void HandleInput(InputState input)
{
// we cancel the current menu screen if the user presses the back button
PlayerIndex player;
if (input.IsNewButtonPress(Buttons.Back, ControllingPlayer, out player))
{
OnCancel(player);
}
// look for any taps that occurred and select any entries that were tapped
foreach (GestureSample gesture in input.Gestures)
{
if (gesture.GestureType == GestureType.Tap)
{
// convert the position to a Point that we can test against a Rectangle
Point tapLocation = new Point((int)gesture.Position.X, (int)gesture.Position.Y);
// iterate the entries to see if any were tapped
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
if (GetMenuEntryHitBounds(menuEntry).Contains(tapLocation))
{
// select the entry. since gestures are only available on Windows Phone,
// we can safely pass PlayerIndex.One to all entries since there is only
// one player on Windows Phone.
OnSelectEntry(i, PlayerIndex.One);
}
}
}
}
}
/// <summary>
/// Handler for when the user has chosen a menu entry.
/// </summary>
protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
{
menuEntries[entryIndex].OnSelectEntry(playerIndex);
}
/// <summary>
/// Handler for when the user has cancelled the menu.
/// </summary>
protected virtual void OnCancel(PlayerIndex playerIndex)
{
ExitScreen();
}
/// <summary>
/// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
/// </summary>
protected void OnCancel(object sender, PlayerIndexEventArgs e)
{
OnCancel(e.PlayerIndex);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen the chance to position the menu entries. By default
/// all menu entries are lined up in a vertical list, centered on the screen.
/// </summary>
protected virtual void UpdateMenuEntryLocations()
{
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// start at Y = 175; each X value is generated per entry
Vector2 position = new Vector2(0f, 280f);
// update each menu entry's location in turn
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
// each entry is to be centered horizontally
position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2;
if (ScreenState == ScreenState.TransitionOn)
position.X -= transitionOffset * 256;
else
position.X += transitionOffset * 512;
// set the entry's position
menuEntry.Position = position;
// move down for the next entry the size of this entry plus our padding
position.Y += menuEntry.GetHeight(this) + (menuEntryPadding * 2);
}
}
/// <summary>
/// Updates the menu.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
// Update each nested MenuEntry object.
for (int i = 0; i < menuEntries.Count; i++)
{
bool isSelected = IsActive && (i == selectedEntry);
menuEntries[i].Update(this, isSelected, gameTime);
}
}
/// <summary>
/// Draws the menu.
/// </summary>
public override void Draw(GameTime gameTime)
{
// make sure our entries are in the right place before we draw them
UpdateMenuEntryLocations();
GraphicsDevice graphics = ScreenManager.GraphicsDevice;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
SpriteFont font = ScreenManager.Font;
spriteBatch.Begin();
// Draw each menu entry in turn.
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
bool isSelected = IsActive && (i == selectedEntry);
menuEntry.Draw(this, isSelected, gameTime);
}
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// Draw the menu title centered on the screen
Vector2 titlePosition = new Vector2(graphics.Viewport.Width / 2, 80);
Vector2 titleOrigin = font.MeasureString(menuTitle) / 2;
Color titleColor = new Color(192, 192, 192) * TransitionAlpha;
float titleScale = 1.25f;
titlePosition.Y -= transitionOffset * 100;
spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0,
titleOrigin, titleScale, SpriteEffects.None, 0);
spriteBatch.End();
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.Tools;
using Microsoft.DotNet.Tools.Test.Utilities;
using System;
using System.IO;
using System.Linq;
using Xunit;
namespace Microsoft.DotNet.Cli.Sln.Remove.Tests
{
public class GivenDotnetSlnRemove : TestBase
{
private const string HelpText = @"Usage: dotnet sln <SLN_FILE> remove [options] <args>
Arguments:
<SLN_FILE> Solution file to operate on. If not specified, the command will search the current directory for one.
<args> Remove the specified project(s) from the solution. The project is not impacted.
Options:
-h, --help Show help information.
";
private const string SlnCommandHelpText = @"Usage: dotnet sln [options] <SLN_FILE> [command]
Arguments:
<SLN_FILE> Solution file to operate on. If not specified, the command will search the current directory for one.
Options:
-h, --help Show help information.
Commands:
add <args> .NET Add project(s) to a solution file Command
list .NET List project(s) in a solution file Command
remove <args> .NET Remove project(s) from a solution file Command
";
private const string ExpectedSlnContentsAfterRemove = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26006.2
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86
EndGlobalSection
EndGlobal
";
private const string ExpectedSlnContentsAfterRemoveAllProjects = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26006.2
MinimumVisualStudioVersion = 10.0.40219.1
Global
EndGlobal
";
private const string ExpectedSlnContentsAfterRemoveNestedProj = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26006.2
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
Project(""{2150E333-8FDC-42A3-9474-1A3956D46DE8}"") = ""src"", ""src"", ""{7B86CE74-F620-4B32-99FE-82D40F8D6BF2}""
EndProject
Project(""{2150E333-8FDC-42A3-9474-1A3956D46DE8}"") = ""Lib"", ""Lib"", ""{EAB71280-AF32-4531-8703-43CDBA261AA3}""
EndProject
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""Lib"", ""src\Lib\Lib.csproj"", ""{84A45D44-B677-492D-A6DA-B3A71135AB8E}""
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|x64.ActiveCfg = Debug|x64
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|x64.Build.0 = Debug|x64
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|x86.ActiveCfg = Debug|x86
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Debug|x86.Build.0 = Debug|x86
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|Any CPU.Build.0 = Release|Any CPU
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|x64.ActiveCfg = Release|x64
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|x64.Build.0 = Release|x64
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|x86.ActiveCfg = Release|x86
{84A45D44-B677-492D-A6DA-B3A71135AB8E}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{EAB71280-AF32-4531-8703-43CDBA261AA3} = {7B86CE74-F620-4B32-99FE-82D40F8D6BF2}
{84A45D44-B677-492D-A6DA-B3A71135AB8E} = {EAB71280-AF32-4531-8703-43CDBA261AA3}
EndGlobalSection
EndGlobal
";
private const string ExpectedSlnContentsAfterRemoveLastNestedProj = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26006.2
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}""
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86
{7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86
EndGlobalSection
EndGlobal
";
[Theory]
[InlineData("--help")]
[InlineData("-h")]
public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"sln remove {helpArg}");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenTooManyArgumentsArePassedItPrintsError()
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput("sln one.sln two.sln three.sln remove");
cmd.Should().Fail();
cmd.StdErr.Should().BeVisuallyEquivalentTo($@"{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "two.sln")}
{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "three.sln")}
{CommonLocalizableStrings.SpecifyAtLeastOneProjectToRemove}");
}
[Theory]
[InlineData("")]
[InlineData("unknownCommandName")]
public void WhenNoCommandIsPassedItPrintsError(string commandName)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"sln {commandName}");
cmd.Should().Fail();
cmd.StdErr.Should().Be(CommonLocalizableStrings.RequiredCommandNotPassed);
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(SlnCommandHelpText);
}
[Theory]
[InlineData("idontexist.sln")]
[InlineData("ihave?invalidcharacters")]
[InlineData("ihaveinv@lidcharacters")]
[InlineData("ihaveinvalid/characters")]
[InlineData("ihaveinvalidchar\\acters")]
public void WhenNonExistingSolutionIsPassedItPrintsErrorAndUsage(string solutionName)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"sln {solutionName} remove p.csproj");
cmd.Should().Fail();
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindSolutionOrDirectory, solutionName));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenInvalidSolutionIsPassedItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("InvalidSolution")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln InvalidSolution.sln remove {projectToRemove}");
cmd.Should().Fail();
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.InvalidSolutionFormatString, "InvalidSolution.sln", LocalizableStrings.FileHeaderMissingError));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenInvalidSolutionIsFoundItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("InvalidSolution")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "InvalidSolution.sln");
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Fail();
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.InvalidSolutionFormatString, solutionPath, LocalizableStrings.FileHeaderMissingError));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenNoProjectIsPassedItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojFiles")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput(@"sln App.sln remove");
cmd.Should().Fail();
cmd.StdErr.Should().Be(CommonLocalizableStrings.SpecifyAtLeastOneProjectToRemove);
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenNoSolutionExistsInTheDirectoryItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojFiles")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App");
var cmd = new DotnetCommand()
.WithWorkingDirectory(solutionPath)
.ExecuteWithCapturedOutput(@"sln remove App.csproj");
cmd.Should().Fail();
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.SolutionDoesNotExist, solutionPath + Path.DirectorySeparatorChar));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenMoreThanOneSolutionExistsInTheDirectoryItPrintsErrorAndUsage()
{
var projectDirectory = TestAssets
.Get("TestAppWithMultipleSlnFiles")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Fail();
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.MoreThanOneSolutionInDirectory, projectDirectory + Path.DirectorySeparatorChar));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenPassedAReferenceNotInSlnItPrintsStatus()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndExistingCsprojReferences")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
var contentBefore = File.ReadAllText(solutionPath);
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput("sln remove referenceDoesNotExistInSln.csproj");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceCouldNotBeFound, "referenceDoesNotExistInSln.csproj"));
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(contentBefore);
}
[Fact]
public void WhenPassedAReferenceItRemovesTheReferenceButNotOtherReferences()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndExistingCsprojReferences")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, projectToRemove));
slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(1);
slnFile.Projects[0].FilePath.Should().Be(Path.Combine("App", "App.csproj"));
}
[Fact]
public void WhenDuplicateReferencesArePresentItRemovesThemAll()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndDuplicateProjectReferences")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(3);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
string outputText = string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, projectToRemove);
outputText += Environment.NewLine + outputText;
cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText);
slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(1);
slnFile.Projects[0].FilePath.Should().Be(Path.Combine("App", "App.csproj"));
}
[Fact]
public void WhenPassedMultipleReferencesAndOneOfThemDoesNotExistItRemovesTheOneThatExists()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndExistingCsprojReferences")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove idontexist.csproj {projectToRemove} idontexisteither.csproj");
cmd.Should().Pass();
string outputText = $@"{string.Format(CommonLocalizableStrings.ProjectReferenceCouldNotBeFound, "idontexist.csproj")}
{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, projectToRemove)}
{string.Format(CommonLocalizableStrings.ProjectReferenceCouldNotBeFound, "idontexisteither.csproj")}";
cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText);
slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(1);
slnFile.Projects[0].FilePath.Should().Be(Path.Combine("App", "App.csproj"));
}
[Fact]
public void WhenReferenceIsRemovedBuildConfigsAreAlsoRemoved()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemove);
}
[Fact]
public void WhenReferenceIsRemovedSlnBuilds()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var projectToRemove = Path.Combine("Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.Execute($"restore App.sln")
.Should().Pass();
new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.Execute("build App.sln --configuration Release")
.Should().Pass();
var reasonString = "should be built in release mode, otherwise it means build configurations are missing from the sln file";
var releaseDirectory = Directory.EnumerateDirectories(
Path.Combine(projectDirectory, "App", "bin"),
"Release",
SearchOption.AllDirectories);
releaseDirectory.Count().Should().Be(1, $"App {reasonString}");
Directory.EnumerateFiles(releaseDirectory.Single(), "App.dll", SearchOption.AllDirectories)
.Count().Should().Be(1, $"App {reasonString}");
}
[Fact]
public void WhenFinalReferenceIsRemovedEmptySectionsAreRemoved()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
SlnFile slnFile = SlnFile.Read(solutionPath);
slnFile.Projects.Count.Should().Be(2);
var appPath = Path.Combine("App", "App.csproj");
var libPath = Path.Combine("Lib", "Lib.csproj");
var projectsToRemove = $"{libPath} {appPath}";
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectsToRemove}");
cmd.Should().Pass();
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveAllProjects);
}
[Fact]
public void WhenNestedProjectIsRemovedItsSolutionFoldersAreRemoved()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndCsprojInSubDirToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
var projectToRemove = Path.Combine("src", "NotLastProjInSrc", "NotLastProjInSrc.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveNestedProj);
}
[Fact]
public void WhenFinalNestedProjectIsRemovedSolutionFoldersAreRemoved()
{
var projectDirectory = TestAssets
.Get("TestAppWithSlnAndLastCsprojInSubDirToRemove")
.CreateInstance()
.WithSourceFiles()
.Root
.FullName;
var solutionPath = Path.Combine(projectDirectory, "App.sln");
var projectToRemove = Path.Combine("src", "Lib", "Lib.csproj");
var cmd = new DotnetCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput($"sln remove {projectToRemove}");
cmd.Should().Pass();
File.ReadAllText(solutionPath)
.Should().BeVisuallyEquivalentTo(ExpectedSlnContentsAfterRemoveLastNestedProj);
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2016 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using CoreTweet.Core;
#if !NET35
using System.Threading;
using System.Threading.Tasks;
#endif
namespace CoreTweet.Streaming
{
/// <summary>
/// Provides the types of the Twitter Streaming API.
/// </summary>
public enum StreamingType
{
/// <summary>
/// The user stream.
/// </summary>
User,
/// <summary>
/// The site stream.
/// </summary>
Site,
/// <summary>
/// The filter stream.
/// </summary>
Filter,
/// <summary>
/// The sample stream.
/// </summary>
Sample,
/// <summary>
/// The firehose stream.
/// </summary>
Firehose
}
/// <summary>
/// Represents the wrapper for the Twitter Streaming API.
/// </summary>
public class StreamingApi : ApiProviderBase
{
/// <summary>
/// Initializes a new instance of the <see cref="StreamingApi"/> class with a specified token.
/// </summary>
/// <param name="tokens"></param>
protected internal StreamingApi(TokensBase tokens) : base(tokens) { }
internal string GetUrl(StreamingType type)
{
var options = Tokens.ConnectionOptions ?? new ConnectionOptions();
string baseUrl;
string apiName;
switch(type)
{
case StreamingType.User:
baseUrl = options.UserStreamUrl;
apiName = "user.json";
break;
case StreamingType.Site:
baseUrl = options.SiteStreamUrl;
apiName = "site.json";
break;
case StreamingType.Filter:
baseUrl = options.StreamUrl;
apiName = "statuses/filter.json";
break;
case StreamingType.Sample:
baseUrl = options.StreamUrl;
apiName = "statuses/sample.json";
break;
case StreamingType.Firehose:
baseUrl = options.StreamUrl;
apiName = "statuses/firehose.json";
break;
default:
throw new ArgumentException("Invalid StreamingType.");
}
return InternalUtils.GetUrl(options, baseUrl, true, apiName);
}
internal static MethodType GetMethodType(StreamingType type)
{
return type == StreamingType.Filter ? MethodType.Post : MethodType.Get;
}
private static IEnumerable<StreamingMessage> EnumerateMessages(Stream stream)
{
using(var reader = new StreamReader(stream))
{
foreach(var s in reader.EnumerateLines())
{
if(!string.IsNullOrEmpty(s))
{
StreamingMessage m;
try
{
m = StreamingMessage.Parse(s);
}
catch(ParsingException ex)
{
m = RawJsonMessage.Create(s, ex);
}
yield return m;
}
}
}
}
#region Obsolete
#if !ASYNC_ONLY
/// <summary>
/// Starts the Twitter stream.
/// </summary>
/// <param name="type">Type of streaming.</param>
/// <param name="parameters">The parameters of streaming.</param>
/// <returns>The stream messages.</returns>
[Obsolete("Use User() or other methods named after its endpoint.")]
public IEnumerable<StreamingMessage> StartStream(StreamingType type, StreamingParameters parameters = null)
{
if(parameters == null)
parameters = new StreamingParameters();
return this.AccessStreamingApiImpl(type, parameters.Parameters);
}
#endif
#if !NET35
/// <summary>
/// Starts the Twitter stream asynchronously.
/// </summary>
/// <param name="type">Type of streaming.</param>
/// <param name="parameters">The parameters of streaming.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The stream messages.</returns>
[Obsolete("Use observable methods, e.g. UserAsObservable().")]
public Task<IEnumerable<StreamingMessage>> StartStreamAsync(StreamingType type, StreamingParameters parameters = null, CancellationToken cancellationToken = default(CancellationToken))
{
if(parameters == null)
parameters = new StreamingParameters();
return this.Tokens.SendStreamingRequestAsync(GetMethodType(type), this.GetUrl(type), parameters.Parameters, cancellationToken)
.Done(res => res.GetResponseStreamAsync(), cancellationToken)
.Unwrap()
.Done(stream => EnumerateMessages(stream), cancellationToken);
}
#endif
#endregion
#if !ASYNC_ONLY
private IEnumerable<StreamingMessage> AccessStreamingApiImpl(StreamingType type, IEnumerable<KeyValuePair<string, object>> parameters)
{
return EnumerateMessages(
this.Tokens.SendStreamingRequest(GetMethodType(type), this.GetUrl(type), parameters).GetResponseStream()
);
}
private IEnumerable<StreamingMessage> AccessStreamingApi(StreamingType type, Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApiImpl(type, InternalUtils.ExpressionsToDictionary(parameters));
}
private IEnumerable<StreamingMessage> AccessStreamingApi(StreamingType type, IDictionary<string, object> parameters)
{
return this.AccessStreamingApiImpl(type, parameters);
}
private IEnumerable<StreamingMessage> AccessStreamingApi(StreamingType type, object parameters)
{
return this.AccessStreamingApiImpl(type, InternalUtils.ResolveObject(parameters));
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> User(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> User(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> User(object parameters)
{
return this.AccessStreamingApi(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// </summary>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <param name="with">Specifies whether to return information for just the authenticating user, or include messages from accounts the user follows.</param>
/// <param name="replies">Specifies whether to return additional @replies.</param>
/// <param name="track">Includes additional Tweets matching the specified keywords. Phrases of keywords are specified by a comma-separated list.</param>
/// <param name="locations">Includes additional Tweets falling within the specified bounding boxes.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> User(bool? stall_warnings = null, string with = null, string replies = null, string track = null, IEnumerable<double> locations = null)
{
var parameters = new Dictionary<string, object>();
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
if (with != null) parameters.Add(nameof(with), with);
if (replies != null) parameters.Add(nameof(replies), replies);
if (track != null) parameters.Add(nameof(track), track);
if (locations != null) parameters.Add(nameof(locations), locations);
return this.AccessStreamingApiImpl(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Site(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Site(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Site(object parameters)
{
return this.AccessStreamingApi(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// </summary>
/// <param name="follow">A comma separated list of user IDs, indicating the users to return statuses for in the stream.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <param name="with">Specifies whether to return information for just the users specified in the follow parameter, or include messages from accounts they follow.</param>
/// <param name="replies">Specifies whether to return additional @replies.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Site(IEnumerable<long> follow, bool? stall_warnings = null, string with = null, string replies = null)
{
if (follow == null) throw new ArgumentNullException(nameof(follow));
var parameters = new Dictionary<string, object>();
parameters.Add(nameof(follow), follow);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
if (with != null) parameters.Add(nameof(with), with);
if (replies != null) parameters.Add(nameof(replies), replies);
return this.AccessStreamingApiImpl(StreamingType.Site, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Filter(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Filter(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Filter(object parameters)
{
return this.AccessStreamingApi(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// </summary>
/// <param name="follow">A comma separated list of user IDs, indicating the users to return statuses for in the stream.</param>
/// <param name="track">Keywords to track. Phrases of keywords are specified by a comma-separated list.</param>
/// <param name="locations">Specifies a set of bounding boxes to track.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Filter(IEnumerable<long> follow = null, string track = null, IEnumerable<double> locations = null, bool? stall_warnings = null)
{
if (follow == null && track == null && locations == null)
throw new ArgumentException("At least one predicate parameter (follow, locations, or track) must be specified.");
var parameters = new Dictionary<string, object>();
if (follow != null) parameters.Add(nameof(follow), follow);
if (track != null) parameters.Add(nameof(track), track);
if (locations != null) parameters.Add(nameof(locations), locations);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return this.AccessStreamingApiImpl(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Sample(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Sample(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Sample(object parameters)
{
return this.AccessStreamingApi(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// </summary>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Sample(bool? stall_warnings = null)
{
var parameters = new Dictionary<string, object>();
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return this.AccessStreamingApiImpl(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Firehose(params Expression<Func<string, object>>[] parameters)
{
return this.AccessStreamingApi(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Firehose(IDictionary<string, object> parameters)
{
return this.AccessStreamingApi(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Firehose(object parameters)
{
return this.AccessStreamingApi(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// </summary>
/// <param name="count">The number of messages to backfill.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IEnumerable<StreamingMessage> Firehose(int? count = null, bool? stall_warnings = null)
{
var parameters = new Dictionary<string, object>();
if (count != null) parameters.Add(nameof(count), count);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return this.AccessStreamingApiImpl(StreamingType.Firehose, parameters);
}
#endif
#if !NET35
private IObservable<StreamingMessage> AccessStreamingApiAsObservableImpl(StreamingType type, IEnumerable<KeyValuePair<string, object>> parameters)
{
return new StreamingObservable(this, type, parameters);
}
private IObservable<StreamingMessage> AccessStreamingApiAsObservable(StreamingType type, Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservableImpl(type, InternalUtils.ExpressionsToDictionary(parameters));
}
private IObservable<StreamingMessage> AccessStreamingApiAsObservable(StreamingType type, IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservableImpl(type, parameters);
}
private IObservable<StreamingMessage> AccessStreamingApiAsObservable(StreamingType type, object parameters)
{
return AccessStreamingApiAsObservableImpl(type, InternalUtils.ResolveObject(parameters));
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> UserAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> UserAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> UserAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a single user.
/// </summary>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <param name="with">Specifies whether to return information for just the authenticating user, or include messages from accounts the user follows.</param>
/// <param name="replies">Specifies whether to return additional @replies.</param>
/// <param name="track">Includes additional Tweets matching the specified keywords. Phrases of keywords are specified by a comma-separated list.</param>
/// <param name="locations">Includes additional Tweets falling within the specified bounding boxes.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> UserAsObservable(bool? stall_warnings = null, string with = null, string replies = null, string track = null, IEnumerable<double> locations = null)
{
var parameters = new Dictionary<string, object>();
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
if (with != null) parameters.Add(nameof(with), with);
if (replies != null) parameters.Add(nameof(replies), replies);
if (track != null) parameters.Add(nameof(track), track);
if (locations != null) parameters.Add(nameof(locations), locations);
return AccessStreamingApiAsObservableImpl(StreamingType.User, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SiteAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SiteAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (required)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// <para>- <c>string</c> with (optional)</para>
/// <para>- <c>string</c> replies (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SiteAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Site, parameters);
}
/// <summary>
/// Streams messages for a set of users.
/// </summary>
/// <param name="follow">A comma separated list of user IDs, indicating the users to return statuses for in the stream.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <param name="with">Specifies whether to return information for just the users specified in the follow parameter, or include messages from accounts they follow.</param>
/// <param name="replies">Specifies whether to return additional @replies.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SiteAsObservable(IEnumerable<long> follow, bool? stall_warnings = null, string with = null, string replies = null)
{
if (follow == null) throw new ArgumentNullException(nameof(follow));
var parameters = new Dictionary<string, object>();
parameters.Add(nameof(follow), follow);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
if (with != null) parameters.Add(nameof(with), with);
if (replies != null) parameters.Add(nameof(replies), replies);
return AccessStreamingApiAsObservableImpl(StreamingType.Site, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FilterAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FilterAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para>Available parameters:</para>
/// <para>- <c>IEnumerable<long></c> follow (optional)</para>
/// <para>- <c>string</c> track (optional)</para>
/// <para>- <c>IEnumerable<double></c> locations (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FilterAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns public statuses that match one or more filter predicates.
/// <para>Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API.</para>
/// <para>Note: At least one predicate parameter (follow, locations, or track) must be specified.</para>
/// </summary>
/// <param name="follow">A comma separated list of user IDs, indicating the users to return statuses for in the stream.</param>
/// <param name="track">Keywords to track. Phrases of keywords are specified by a comma-separated list.</param>
/// <param name="locations">Specifies a set of bounding boxes to track.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FilterAsObservable(IEnumerable<long> follow = null, string track = null, IEnumerable<double> locations = null, bool? stall_warnings = null)
{
if (follow == null && track == null && locations == null)
throw new ArgumentException("At least one predicate parameter (follow, locations, or track) must be specified.");
var parameters = new Dictionary<string, object>();
if (follow != null) parameters.Add(nameof(follow), follow);
if (track != null) parameters.Add(nameof(track), track);
if (locations != null) parameters.Add(nameof(locations), locations);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return AccessStreamingApiAsObservableImpl(StreamingType.Filter, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SampleAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SampleAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// <para>Available parameters:</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SampleAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns a small random sample of all public statuses.
/// <para>The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.</para>
/// </summary>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> SampleAsObservable(bool? stall_warnings = null)
{
var parameters = new Dictionary<string, object>();
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return AccessStreamingApiAsObservableImpl(StreamingType.Sample, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FirehoseAsObservable(params Expression<Func<string, object>>[] parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FirehoseAsObservable(IDictionary<string, object> parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// <para>Available parameters:</para>
/// <para>- <c>int</c> count (optional)</para>
/// <para>- <c>string</c> delimited (optional, not affects CoreTweet)</para>
/// <para>- <c>bool</c> stall_warnings (optional)</para>
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FirehoseAsObservable(object parameters)
{
return AccessStreamingApiAsObservable(StreamingType.Firehose, parameters);
}
/// <summary>
/// Returns all public statuses. Few applications require this level of access.
/// <para>Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.</para>
/// </summary>
/// <param name="count">The number of messages to backfill.</param>
/// <param name="stall_warnings">Specifies whether stall warnings should be delivered.</param>
/// <returns>The stream messages.</returns>
public IObservable<StreamingMessage> FirehoseAsObservable(int? count = null, bool? stall_warnings = null)
{
var parameters = new Dictionary<string, object>();
if (count != null) parameters.Add(nameof(count), count);
if (stall_warnings != null) parameters.Add(nameof(stall_warnings), stall_warnings);
return AccessStreamingApiAsObservableImpl(StreamingType.Firehose, parameters);
}
#endif
}
/// <summary>
/// Represents the parameters for the Twitter Streaming API.
/// </summary>
[Obsolete]
public class StreamingParameters
{
/// <summary>
/// Gets the raw parameters.
/// </summary>
public List<KeyValuePair<string, object>> Parameters { get; }
/// <summary>
/// <para>Initializes a new instance of the <see cref="StreamingParameters"/> class with a specified option.</para>
/// <para>Available parameters: </para>
/// <para>*Note: In filter stream, at least one predicate parameter (follow, locations, or track) must be specified.</para>
/// <para><c>bool</c> stall_warnings (optional)" : Specifies whether stall warnings should be delivered.</para>
/// <para><c>string / IEnumerable<long></c> follow (optional*, required in site stream, ignored in user stream)</para>
/// <para><c>string / IEnumerable<string></c> track (optional*)</para>
/// <para><c>string / IEnumerable<string></c> location (optional*)</para>
/// <para><c>string</c> with (optional)</para>
/// </summary>
/// <param name="streamingParameters">The streaming parameters.</param>
public StreamingParameters(params Expression<Func<string, object>>[] streamingParameters)
: this(InternalUtils.ExpressionsToDictionary(streamingParameters)) { }
/// <summary>
/// Initializes a new instance of the <see cref="StreamingParameters"/> class with a specified option.
/// </summary>
/// <param name="streamingParameters">The streaming parameters.</param>
public StreamingParameters(IEnumerable<KeyValuePair<string, object>> streamingParameters)
{
Parameters = streamingParameters.ToList();
}
/// <summary>
/// Initializes a new instance of the <see cref="StreamingParameters"/> class with a specified option.
/// </summary>
/// <param name="streamingParameters">The streaming parameters.</param>
public static StreamingParameters Create<T>(T streamingParameters)
{
return new StreamingParameters(InternalUtils.ResolveObject(streamingParameters));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.LeaseProviders;
using Orleans.Runtime;
using Orleans.Hosting;
using Orleans.Configuration;
namespace Orleans.Streams
{
/// <summary>
/// IResourceSelector selects a centain amount of resource from a resource list
/// </summary>
/// <typeparam name="T"></typeparam>
internal interface IResourceSelector<T>
{
/// <summary>
/// Try to select certain count of resources from resource list, which doesn't overlap with existing selection
/// </summary>
/// <param name="newSelectionCount"></param>
/// <param name="existingSelection"></param>
/// <returns></returns>
List<T> NextSelection(int newSelectionCount, List<T> existingSelection);
}
/// <summary>
/// Selector using round robin algorithm
/// </summary>
/// <typeparam name="T"></typeparam>
internal class RoundRobinSelector<T> : IResourceSelector<T>
{
private ReadOnlyCollection<T> resources;
private int lastSelection;
public RoundRobinSelector(ReadOnlyCollection<T> resources)
{
this.resources = resources;
this.lastSelection = new Random().Next(this.resources.Count);
}
/// <summary>
/// Try to select certain count of resources from resource list, which doesn't overlap with existing resources
/// </summary>
/// <param name="newSelectionCount"></param>
/// <param name="existingSelection"></param>
/// <returns></returns>
public List<T> NextSelection(int newSelectionCount, List<T> existingSelection)
{
var selection = new List<T>(newSelectionCount);
while (selection.Count < newSelectionCount)
{
this.lastSelection = (++this.lastSelection) % (this.resources.Count - 1);
if(!existingSelection.Contains(this.resources[this.lastSelection]))
selection.Add(this.resources[this.lastSelection]);
}
return selection;
}
}
/// <summary>
/// Stream queue balancer that uses the cluster configuration to determine deployment information for load balancing.
/// This balancer supports queue balancing in cluster auto-scale scenario, unexpected server failure scenario, and try to support ideal distribution
/// </summary>
public class ClusterConfigDeploymentLeaseBasedBalancer : LeaseBasedQueueBalancer
{
public ClusterConfigDeploymentLeaseBasedBalancer(IServiceProvider serviceProvider, ISiloStatusOracle siloStatusOracle,
IOptions<StaticClusterDeploymentOptions> options, ILoggerFactory loggerFactory)
: base(serviceProvider, siloStatusOracle, options.Value, loggerFactory)
{ }
}
/// <summary>
/// LeaseBasedQueueBalancer. This balancer supports queue balancing in cluster auto-scale scenario, unexpected server failure scenario, and try to support ideal distribution
/// as much as possible.
/// </summary>
public class LeaseBasedQueueBalancer : QueueBalancerBase, IStreamQueueBalancer, IDisposable
{
/// <summary>
/// Lease category for LeaseBasedQueueBalancer
/// </summary>
public const string LeaseCategory = "QueueBalancer";
private class AcquiredQueue
{
public QueueId QueueId { get; set; }
public AcquiredLease AcquiredLease { get; set; }
public AcquiredQueue(QueueId queueId, AcquiredLease lease)
{
this.QueueId = queueId;
this.AcquiredLease = lease;
}
}
private ILeaseProvider leaseProvider;
private IDeploymentConfiguration deploymentConfig;
private readonly ISiloStatusOracle siloStatusOracle;
private ReadOnlyCollection<QueueId> allQueues;
private List<AcquiredQueue> myQueues;
private TimeSpan siloMaturityPeriod;
private bool isStarting;
private TimeSpan leaseLength;
private AsyncTaskSafeTimer renewLeaseTimer;
private AsyncTaskSafeTimer tryAcquireMaximumLeaseTimer;
private IResourceSelector<QueueId> queueSelector;
private int minimumResponsibilty;
private int maximumRespobsibility;
private IServiceProvider serviceProvider;
private ILogger logger;
private ILoggerFactory loggerFactory;
/// <summary>
/// Constructor
/// </summary>
/// <param name="serviceProvider"></param>
/// <param name="siloStatusOracle"></param>
/// <param name="deploymentConfig"></param>
/// <param name="loggerFactory"></param>
public LeaseBasedQueueBalancer(IServiceProvider serviceProvider, ISiloStatusOracle siloStatusOracle, IDeploymentConfiguration deploymentConfig, ILoggerFactory loggerFactory)
{
this.serviceProvider = serviceProvider;
this.deploymentConfig = deploymentConfig;
this.siloStatusOracle = siloStatusOracle;
this.myQueues = new List<AcquiredQueue>();
this.isStarting = true;
this.loggerFactory = loggerFactory;
this.logger = loggerFactory.CreateLogger<LeaseBasedQueueBalancer>();
}
/// <inheritdoc/>
public override Task Initialize(string strProviderName, IStreamQueueMapper queueMapper, TimeSpan siloMaturityPeriod)
{
if (queueMapper == null)
{
throw new ArgumentNullException("queueMapper");
}
var options = this.serviceProvider.GetRequiredService<IOptionsSnapshot<LeaseBasedQueueBalancerOptions>>().Get(strProviderName);
if (options == null)
throw new KeyNotFoundException($"No lease base queue balancer options was configured for provider {strProviderName}, nor was a default configured.");
this.leaseProvider = this.serviceProvider.GetRequiredService(options.LeaseProviderType) as ILeaseProvider;
this.leaseLength = options.LeaseLength;
this.allQueues = new ReadOnlyCollection<QueueId>(queueMapper.GetAllQueues().ToList());
this.siloMaturityPeriod = siloMaturityPeriod;
NotifyAfterStart().Ignore();
//make lease renew frequency to be every half of lease time, to avoid renew failing due to timing issues, race condition or clock difference.
var timerLogger = this.loggerFactory.CreateLogger<AsyncTaskSafeTimer>();
this.renewLeaseTimer = new AsyncTaskSafeTimer(timerLogger, this.MaintainAndBalanceQueues, null, this.siloMaturityPeriod, this.leaseLength.Divide(2));
//try to acquire maximum leases every leaseLength
this.tryAcquireMaximumLeaseTimer = new AsyncTaskSafeTimer(timerLogger, this.AcquireLeaseToMeetMaxResponsibilty, null, this.siloMaturityPeriod, this.leaseLength);
//Selector default to round robin selector now, but we can make a further change to make selector configurable if needed. Selector algorithm could
//be affecting queue balancing stablization time in cluster initializing and auto-scaling
this.queueSelector = new RoundRobinSelector<QueueId>(this.allQueues);
return MaintainAndBalanceQueues(null);
}
/// <inheritdoc/>
public override IEnumerable<QueueId> GetMyQueues()
{
return this.myQueues.Select(queue => queue.QueueId);
}
private async Task MaintainAndBalanceQueues(object state)
{
CalculateResponsibility();
var oldQueues = new HashSet<QueueId>(this.myQueues.Select(queue => queue.QueueId));
// step 1: renew existing leases
await this.RenewLeases();
// step 2: if after renewing leases, myQueues count doesn't fall in [minimumResponsibility, maximumResponsibilty] range, act accordingly
if (this.myQueues.Count < this.minimumResponsibilty)
{
await this.AcquireLeasesToMeetMinResponsibility();
}
else if (this.myQueues.Count > this.maximumRespobsibility)
{
await this.ReleaseLeasesToMeetResponsibility();
}
var newQueues = new HashSet<QueueId>(this.myQueues.Select(queue=> queue.QueueId));
//if queue changed, notify listeners
if (!oldQueues.SetEquals(newQueues))
await NotifyListeners();
}
private async Task ReleaseLeasesToMeetResponsibility()
{
var queueCountToRelease = this.myQueues.Count - this.maximumRespobsibility;
if (queueCountToRelease <= 0)
return;
var queuesToGiveUp = this.myQueues.GetRange(0, queueCountToRelease);
await this.leaseProvider.Release(LeaseCategory, queuesToGiveUp.Select(queue => queue.AcquiredLease).ToArray());
//remove queuesToGiveUp from myQueue list after the balancer released the leases on them
this.myQueues.RemoveRange(0, queueCountToRelease);
this.logger.Info($"ReleaseLeasesToMeetResponsibility: released {queueCountToRelease} queues, current queue Count: {this.myQueues.Count}");
}
private Task AcquireLeaseToMeetMaxResponsibilty(object state)
{
return AcquireLeasesToMeetExpectation(this.maximumRespobsibility);
}
private Task AcquireLeasesToMeetMinResponsibility()
{
return AcquireLeasesToMeetExpectation(this.minimumResponsibilty);
}
private async Task AcquireLeasesToMeetExpectation(int expectedTotalLeaseCount)
{
int maxAttempts = 5;
int attempts = 0;
int leasesToAquire = expectedTotalLeaseCount - this.myQueues.Count;
this.logger.Info($"AcquireLeasesToMeetExpectation : Try to acquire {leasesToAquire} queues");
while (attempts ++ <= maxAttempts && leasesToAquire > 0)
{
//select new queues to acquire
var expectedQueues = this.queueSelector.NextSelection(leasesToAquire, this.myQueues.Select(queue=>queue.QueueId).ToList()).ToList();
var leaseRequests = expectedQueues.Select(queue => new LeaseRequest() {
ResourceKey = queue.ToString(),
Duration = this.leaseLength
});
var results = await this.leaseProvider.Acquire(LeaseCategory, leaseRequests.ToArray());
//add successfully acquired queue to myQueues list
for (int i = 0; i < results.Length; i++)
{
if (results[i].StatusCode == ResponseCode.OK)
{
this.myQueues.Add(new AcquiredQueue(expectedQueues[i], results[i].AcquiredLease));
}
}
//if reached expectedTotalLeaseCount
if (this.myQueues.Count >= expectedTotalLeaseCount)
{
break;
}
}
this.logger.Info($"AcquireLeasesToMeetExpectation: finished. Now own {this.myQueues.Count} queues. Used attemps : {attempts}, Current minimumReponsibility : {this.minimumResponsibilty}, current maximumResponsibility : {this.maximumRespobsibility}");
}
private async Task RenewLeases()
{
var results = await this.leaseProvider.Renew(LeaseCategory, this.myQueues.Select(queue => queue.AcquiredLease).ToArray());
var updatedQueues = new List<AcquiredQueue>();
//update myQueues list with successfully renewed leases
for (int i = 0; i < results.Count(); i++)
{
var result = results[i];
if (result.StatusCode == ResponseCode.OK)
{
updatedQueues.Add(new AcquiredQueue(this.myQueues[i].QueueId, result.AcquiredLease));
}
}
this.myQueues.Clear();
this.myQueues = updatedQueues;
this.logger.Info($"RenewLeases: finished, currently own queues : {this.myQueues.Count}, current minimumResponsibilty : {this.minimumResponsibilty}, current maximunResponsibilty : {this.maximumRespobsibility}");
}
private void CalculateResponsibility()
{
int activeBuckets = 0;
if (isStarting)
{
activeBuckets = this.deploymentConfig.GetAllSiloNames().Count;
}
else
{
activeBuckets = GetActiveSiloCount(this.siloStatusOracle);
}
this.minimumResponsibilty = this.allQueues.Count / activeBuckets;
//if allQueues count is divisible by active bukets, then every bucket should take the same count of queues, otherwise, there should be one bucket take 1 more queue
if (this.allQueues.Count % activeBuckets == 0)
this.maximumRespobsibility = this.minimumResponsibilty;
else this.maximumRespobsibility = this.minimumResponsibilty + 1;
}
private static int GetActiveSiloCount(ISiloStatusOracle siloStatusOracle)
{
return siloStatusOracle.GetApproximateSiloStatuses(true).Count;
}
private async Task NotifyAfterStart()
{
await Task.Delay(siloMaturityPeriod);
this.isStarting = false;
await NotifyListeners();
}
private Task NotifyListeners()
{
List<IStreamQueueBalanceListener> queueBalanceListenersCopy;
lock (queueBalanceListeners)
{
queueBalanceListenersCopy = queueBalanceListeners.ToList(); // make copy
}
var notificatioTasks = new List<Task>(queueBalanceListenersCopy.Count);
foreach (IStreamQueueBalanceListener listener in queueBalanceListenersCopy)
{
notificatioTasks.Add(listener.QueueDistributionChangeNotification());
}
return Task.WhenAll(notificatioTasks);
}
/// <inheritdoc/>
public void Dispose()
{
this.renewLeaseTimer?.Dispose();
this.renewLeaseTimer = null;
this.tryAcquireMaximumLeaseTimer?.Dispose();
this.tryAcquireMaximumLeaseTimer = null;
//release all owned leases
this.maximumRespobsibility = 0;
this.minimumResponsibilty = 0;
this.ReleaseLeasesToMeetResponsibility().Ignore();
}
}
}
| |
/* ====================================================================
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.Collections.Generic;
using System;
using NPOI.XSSF.Util;
using System.IO;
using NPOI.OpenXml4Net.OPC;
using System.Text.RegularExpressions;
using NPOI.OpenXmlFormats.Vml;
using System.Xml.Serialization;
using System.Xml;
using System.Collections;
using NPOI.OpenXmlFormats.Vml.Office;
using NPOI.OpenXmlFormats.Vml.Spreadsheet;
using System.Text;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace NPOI.XSSF.UserModel
{
/**
* Represents a SpreadsheetML VML Drawing.
*
* <p>
* In Excel 2007 VML Drawings are used to describe properties of cell comments,
* although the spec says that VML is deprecated:
* </p>
* <p>
* The VML format is a legacy format originally introduced with Office 2000 and is included and fully defined
* in this Standard for backwards compatibility reasons. The DrawingML format is a newer and richer format
* Created with the goal of eventually replacing any uses of VML in the Office Open XML formats. VML should be
* considered a deprecated format included in Office Open XML for legacy reasons only and new applications that
* need a file format for Drawings are strongly encouraged to use preferentially DrawingML
* </p>
*
* <p>
* Warning - Excel is known to Put invalid XML into these files!
* For example, >br< without being closed or escaped crops up.
* </p>
*
* See 6.4 VML - SpreadsheetML Drawing in Office Open XML Part 4 - Markup Language Reference.pdf
*
* @author Yegor Kozlov
*/
public class XSSFVMLDrawing : POIXMLDocumentPart
{
private static XmlQualifiedName QNAME_SHAPE_LAYOUT = new XmlQualifiedName("shapelayout", "urn:schemas-microsoft-com:office:office");
private static XmlQualifiedName QNAME_SHAPE_TYPE = new XmlQualifiedName("shapetype", "urn:schemas-microsoft-com:vml");
private static XmlQualifiedName QNAME_SHAPE = new XmlQualifiedName("shape", "urn:schemas-microsoft-com:vml");
private static string COMMENT_SHAPE_TYPE_ID = "_x0000_t202"; // this ID value seems to have significance to Excel >= 2010; see https://issues.apache.org/bugzilla/show_bug.cgi?id=55409
/**
* regexp to parse shape ids, in VML they have weird form of id="_x0000_s1026"
*/
private static Regex ptrn_shapeId = new Regex("_x0000_s(\\d+)", RegexOptions.Compiled);
private static Regex ptrn_shapeTypeId = new Regex("_x0000_[tm](\\d+)", RegexOptions.Compiled);
private ArrayList _items = new ArrayList();
private string _shapeTypeId;
private int _shapeId = 1024;
/**
* Create a new SpreadsheetML Drawing
*
* @see XSSFSheet#CreateDrawingPatriarch()
*/
public XSSFVMLDrawing()
: base()
{
newDrawing();
}
/**
* Construct a SpreadsheetML Drawing from a namespace part
*
* @param part the namespace part holding the Drawing data,
* the content type must be <code>application/vnd.Openxmlformats-officedocument.Drawing+xml</code>
* @param rel the namespace relationship holding this Drawing,
* the relationship type must be http://schemas.Openxmlformats.org/officeDocument/2006/relationships/drawing
*/
protected XSSFVMLDrawing(PackagePart part)
: base(part)
{
Read(GetPackagePart().GetInputStream());
}
[Obsolete("deprecated in POI 3.14, scheduled for removal in POI 3.16")]
protected XSSFVMLDrawing(PackagePart part, PackageRelationship rel)
: this(part)
{
}
internal void Read(Stream is1)
{
XmlDocument doc = new XmlDocument();
//InflaterInputStream iis = (InflaterInputStream)is1;
StreamReader sr = new StreamReader(is1);
string data = sr.ReadToEnd();
//Stream vmlsm = new EvilUnclosedBRFixingInputStream(is1); --TODO:: add later
doc.LoadXml(
data.Replace("<br>","")
);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("o", "urn:schemas-microsoft-com:office:office");
nsmgr.AddNamespace("x", "urn:schemas-microsoft-com:office:excel");
nsmgr.AddNamespace("v", "urn:schemas-microsoft-com:vml");
_items = new ArrayList();
XmlNodeList nodes=doc.SelectNodes("/xml/*",nsmgr);
foreach (XmlNode nd in nodes)
{
string xmltext = nd.OuterXml;
if (nd.LocalName == QNAME_SHAPE_LAYOUT.Name)
{
CT_ShapeLayout sl=CT_ShapeLayout.Parse(nd, nsmgr);
_items.Add(sl);
}
else if (nd.LocalName == QNAME_SHAPE_TYPE.Name)
{
CT_Shapetype st = CT_Shapetype.Parse(nd, nsmgr);
_items.Add(st);
_shapeTypeId = st.id;
}
else if (nd.LocalName == QNAME_SHAPE.Name)
{
CT_Shape shape = CT_Shape.Parse(nd, nsmgr);
String id = shape.id;
if (id != null)
{
MatchCollection m = ptrn_shapeId.Matches(id);
if (m.Count>0)
_shapeId = Math.Max(_shapeId, int.Parse(m[0].Groups[1].Value));
}
_items.Add(shape);
}
else
{
/// How to port following java code??
//Document doc2;
//try
//{
// InputSource is2 = new InputSource(new StringReader(obj.xmlText()));
// doc2 = DocumentHelper.readDocument(is2);
//}
//catch (SAXException e)
//{
// throw new XmlException(e.getMessage(), e);
//}
_items.Add(nd);
}
}
}
internal ArrayList GetItems()
{
return _items;
}
internal void Write(Stream out1)
{
using (StreamWriter sw = new StreamWriter(out1))
{
sw.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sw.Write("<xml");
sw.Write(" xmlns:v=\"urn:schemas-microsoft-com:vml\"");
sw.Write(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
sw.Write(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
sw.Write(" xmlns:w=\"urn:schemas-microsoft-com:office:word\"");
sw.Write(" xmlns:p=\"urn:schemas-microsoft-com:office:powerpoint\"");
sw.Write(">");
for (int i = 0; i < _items.Count; i++)
{
object xc = _items[i];
if (xc is XmlNode)
{
sw.Write(((XmlNode)xc).OuterXml.Replace(" xmlns:v=\"urn:schemas-microsoft-com:vml\"", "").Replace(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"", "").Replace(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"", "").Replace("
", ""));
}
else if (xc is CT_Shapetype)
{
((CT_Shapetype)xc).Write(sw, "shapetype");
}
else if (xc is CT_ShapeLayout)
{
((CT_ShapeLayout)xc).Write(sw, "shapelayout");
}
else if (xc is CT_Shape)
{
((CT_Shape)xc).Write(sw, "shape");
}
else
{
sw.Write(xc.ToString().Replace(" xmlns:v=\"urn:schemas-microsoft-com:vml\"", "").Replace(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"", "").Replace(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"", "").Replace("
", ""));
}
}
sw.Write("</xml>");
}
//rootObject.save(out1);
}
protected internal override void Commit()
{
PackagePart part = GetPackagePart();
Stream out1 = part.GetOutputStream();
Write(out1);
out1.Close();
}
/**
* Initialize a new Speadsheet VML Drawing
*/
private void newDrawing()
{
CT_ShapeLayout layout = new CT_ShapeLayout();
layout.ext = (ST_Ext.edit);
CT_IdMap idmap = layout.AddNewIdmap();
idmap.ext = (ST_Ext.edit);
idmap.data = ("1");
_items.Add(layout);
CT_Shapetype shapetype = new CT_Shapetype();
_shapeTypeId = COMMENT_SHAPE_TYPE_ID;
shapetype.id = _shapeTypeId;// "_x0000_t" + _shapeTypeId;
shapetype.coordsize="21600,21600";
shapetype.spt=202;
//_shapeTypeId = 202;
shapetype.path2 = ("m,l,21600r21600,l21600,xe");
shapetype.AddNewStroke().joinstyle = (ST_StrokeJoinStyle.miter);
CT_Path path = shapetype.AddNewPath();
path.gradientshapeok = NPOI.OpenXmlFormats.Vml.ST_TrueFalse.t;
path.connecttype=(ST_ConnectType.rect);
_items.Add(shapetype);
}
internal CT_Shape newCommentShape()
{
CT_Shape shape = new CT_Shape();
shape.id = "_x0000_s" + (++_shapeId);
shape.type ="#" + _shapeTypeId;
shape.style="position:absolute; visibility:hidden";
shape.fillcolor = ("#ffffe1");
shape.insetmode = (ST_InsetMode.auto);
shape.AddNewFill().color=("#ffffe1");
CT_Shadow shadow = shape.AddNewShadow();
shadow.on= NPOI.OpenXmlFormats.Vml.ST_TrueFalse.t;
shadow.color = "black";
shadow.obscured = NPOI.OpenXmlFormats.Vml.ST_TrueFalse.t;
shape.AddNewPath().connecttype = (ST_ConnectType.none);
shape.AddNewTextbox().style = ("mso-direction-alt:auto");
CT_ClientData cldata = shape.AddNewClientData();
cldata.ObjectType=ST_ObjectType.Note;
cldata.AddNewMoveWithCells();
cldata.AddNewSizeWithCells();
cldata.AddNewAnchor("1, 15, 0, 2, 3, 15, 3, 16");
cldata.AddNewAutoFill(ST_TrueFalseBlank.@false);
cldata.AddNewRow(0);
cldata.AddNewColumn(0);
_items.Add(shape);
return shape;
}
/**
* Find a shape with ClientData of type "NOTE" and the specified row and column
*
* @return the comment shape or <code>null</code>
*/
internal CT_Shape FindCommentShape(int row, int col)
{
foreach (object itm in _items)
{
if (itm is CT_Shape)
{
CT_Shape sh = (CT_Shape)itm;
if (sh.sizeOfClientDataArray() > 0)
{
CT_ClientData cldata = sh.GetClientDataArray(0);
if (cldata.ObjectType == ST_ObjectType.Note)
{
int crow = cldata.GetRowArray(0);
int ccol = cldata.GetColumnArray(0);
if (crow == row && ccol == col)
{
return sh;
}
}
}
}
}
return null;
}
internal bool RemoveCommentShape(int row, int col)
{
CT_Shape shape = FindCommentShape(row, col);
if(shape == null)
return false;
_items.Remove(shape);
return true;
}
}
}
| |
//
// Will Strohl ([email protected])
// http://www.willstrohl.com
//
//Copyright (c) 2009-2016, Will Strohl
//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 Will Strohl, Content Injection, 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.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Exceptions;
using System;
using System.Globalization;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security;
using WillStrohl.Modules.Injection.Entities;
using WillStrohl.Modules.Injection.Components;
namespace WillStrohl.Modules.Injection
{
public partial class EditInjections : WNSPortalModuleBase
{
#region Private Members
private InjectionInfoCollection p_Injections = null;
private const string c_Command_Edit = "Edit";
private const string c_Command_MoveUp = "MoveUp";
private const string c_Command_MoveDown = "MoveDown";
private const string c_Command_Delete = "Delete";
private const string c_Command_Insert = "Insert";
private const string c_True = "True";
private int p_SearchParam = Null.NullInteger;
private string p_EnabledImage = string.Empty;
private string p_DisabledImage = string.Empty;
private string p_EnabledAltText = string.Empty;
private string p_DisabledAltText = string.Empty;
#endregion
#region Private Properties
private InjectionInfoCollection Injections
{
get
{
if (p_Injections == null)
{
InjectionController ctlModule = new InjectionController();
p_Injections = ctlModule.GetInjectionContents(ModuleId);
}
return p_Injections;
}
}
private string EnabledImage
{
get
{
if (!string.IsNullOrEmpty(p_EnabledImage))
{
return p_EnabledImage;
}
p_EnabledImage = string.Concat(DotNetNuke.Common.Globals.ApplicationPath, DotNetNuke.Entities.Icons.IconController.IconURL("Checked", "16x16"));
return p_EnabledImage;
}
}
private string DisabledImage
{
get
{
if (!string.IsNullOrEmpty(p_DisabledImage))
{
return p_DisabledImage;
}
p_DisabledImage = string.Concat(DotNetNuke.Common.Globals.ApplicationPath, DotNetNuke.Entities.Icons.IconController.IconURL("Unchecked", "16x16"));
return p_DisabledImage;
}
}
private string EnabledAltText
{
get
{
if (string.IsNullOrEmpty(p_EnabledAltText))
{
p_EnabledAltText = GetLocalizedString("Enabled.Alt");
}
return p_EnabledAltText;
}
}
private string DisabledAltText
{
get
{
if (string.IsNullOrEmpty(p_DisabledAltText))
{
p_DisabledAltText = GetLocalizedString("Disabled.Alt");
}
return p_DisabledAltText;
}
}
#endregion
#region Event Handlers
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
pnlAddNew.Visible = false;
pnlManage.Visible = true;
BindData();
}
// Module failed to load
}
catch (Exception exc)
{
Exceptions.ProcessModuleLoadException(this, exc, IsEditable);
}
}
protected void lnkAddNewInjection_Click(object sender, EventArgs e)
{
ClearForm();
TogglePanels();
cmdDelete.Visible = !string.IsNullOrEmpty(hidInjectionId.Value);
}
protected void cmdReturn_Click(object sender, EventArgs e)
{
Response.Redirect(DotNetNuke.Common.Globals.NavigateURL());
}
protected void cmdAdd_Click(object sender, EventArgs e)
{
if (Page.IsValid && !(string.IsNullOrEmpty(txtName.Text) | string.IsNullOrEmpty(txtContent.Text)))
{
SaveInjection();
ClearForm();
TogglePanels();
BindData();
}
}
protected void cvName_ServerValidate(object source, ServerValidateEventArgs args)
{
InjectionController ctlModule = new InjectionController();
args.IsValid = (!ctlModule.DoesInjectionNameExist(txtName.Text, ModuleId));
}
protected void dlInjection_ItemCommand(object source, DataListCommandEventArgs e)
{
switch (e.CommandName)
{
case c_Command_MoveUp:
SwapOrder(Convert.ToInt32(e.CommandArgument), c_Command_MoveUp);
BindData();
break;
case c_Command_MoveDown:
SwapOrder(Convert.ToInt32(e.CommandArgument), c_Command_MoveDown);
BindData();
break;
case c_Command_Edit:
BindForm(Convert.ToInt32(e.CommandArgument));
ToggleType();
TogglePanels();
break;
case c_Command_Insert:
ClearForm();
TogglePanels();
break;
case c_Command_Delete:
InjectionController ctlModule = new InjectionController();
ctlModule.DeleteInjectionContent(Convert.ToInt32(e.CommandArgument));
BindData();
break;
default:
return;
break;
}
}
protected void cmdCancel_Click(object sender, EventArgs e)
{
ClearForm();
TogglePanels();
BindData();
}
protected void cmdDelete_Click(object sender, EventArgs e)
{
if (Regex.IsMatch(hidInjectionId.Value, "^\\d+$"))
{
InjectionController ctlModule = new InjectionController();
ctlModule.DeleteInjectionContent(int.Parse(hidInjectionId.Value, System.Globalization.NumberStyles.Integer));
}
ClearForm();
TogglePanels();
BindData();
}
protected void radType_OnSelectedIndexChanged(object sender, EventArgs e)
{
ToggleType();
}
protected void cvContent_OnServerValidate(object source, ServerValidateEventArgs args)
{
if (radType.SelectedIndex == 0)
{
var isValidPathFormat = false;
var isValidFilePath = false;
var pathToTest = txtContent.Text.Trim();
isValidPathFormat = (InjectionController.IsValidCssInjectionType(pathToTest) ||
InjectionController.IsValidJavaScriptInjectionType(pathToTest));
if (pathToTest.StartsWith("http"))
{
// external file path
isValidFilePath = InjectionController.IsValidFilePath(pathToTest);
}
else
{
// local file path
var fullFilePath = Server.MapPath(pathToTest);
isValidFilePath = File.Exists(fullFilePath);
}
args.IsValid = (isValidPathFormat && isValidFilePath);
}
else
{
args.IsValid = true;
}
}
#endregion
#region Private Helper Functions
private void BindData()
{
LocalizeModule();
if (Injections.Count > 0)
{
dlInjection.DataSource = Injections;
dlInjection.DataBind();
dlInjection.Visible = true;
lblNoRecords.Visible = false;
}
else
{
dlInjection.Visible = false;
lblNoRecords.Visible = true;
}
if (radType.Items.Count == 0)
{
radType.Items.Add(new ListItem(GetLocalizedString("radType.0.Text")));
radType.Items.Add(new ListItem(GetLocalizedString("radType.1.Text")));
radType.ClearSelection();
// default injection type for NEW injections is 0 because that's the most common use case
radType.SelectedIndex = 0;
}
if (ddlCrmProvider.Items.Count == 0)
{
ddlCrmProvider.Items.Add(new ListItem(GetLocalizedString("ddlCrmProvider.0.Text")));
ddlCrmProvider.Items.Add(new ListItem(GetLocalizedString("ddlCrmProvider.1.Text")));
ddlCrmProvider.Items.Add(new ListItem(GetLocalizedString("ddlCrmProvider.2.Text")));
ddlCrmProvider.Items.Add(new ListItem(GetLocalizedString("ddlCrmProvider.3.Text")));
ddlCrmProvider.ClearSelection();
ddlCrmProvider.SelectedIndex = 0;
}
if (radInject.Items.Count == 0)
{
radInject.Items.Add(new ListItem(GetLocalizedString("radInject.0.Text")));
radInject.Items.Add(new ListItem(GetLocalizedString("radInject.1.Text")));
radInject.ClearSelection();
radInject.SelectedIndex = 0;
}
}
private void LocalizeModule()
{
txtName.Text = GetLocalizedString("txtName.Text");
lnkAddNewInjection.Text = GetLocalizedString("lnkAdd.Text");
cmdAdd.Text = GetLocalizedString("cmdAdd.Text");
cmdDelete.Text = GetLocalizedString("cmdDelete.Text");
rfvName.ErrorMessage = GetLocalizedString("rfvName.ErrorMessage");
rfvName.InitialValue = GetLocalizedString("txtName.Text");
rfvContent.ErrorMessage = GetLocalizedString("rfvContent.ErrorMessage");
cmdCancel.Text = GetLocalizedString("cmdCancel.Text");
cmdReturn.Text = GetLocalizedString("cmdReturn.Text");
cvName.ErrorMessage = GetLocalizedString("cvName.ErrorMessage");
cvContent.ErrorMessage = GetLocalizedString("cvContent.ErrorMessage");
rvCrmPriority.ErrorMessage = GetLocalizedString("rvCrmPriority.ErrorMessage");
}
private void ClearForm()
{
hidInjectionId.Value = string.Empty;
txtName.Text = GetLocalizedString("txtName.Text");
txtContent.Text = string.Empty;
chkEnabled.Checked = true;
radType.ClearSelection();
radType.Items.FindByText(GetLocalizedString("radType.0.Text")).Selected = true;
radInject.ClearSelection();
radInject.Items.FindByText(GetLocalizedString("radInject.0.Text")).Selected = true;
cvName.Enabled = true;
ddlCrmProvider.ClearSelection();
ddlCrmProvider.SelectedIndex = 0;
ToggleType();
}
private void BindForm(int ItemId)
{
var ctlModule = new InjectionController();
var injection = new InjectionInfo();
injection = ctlModule.GetInjectionContent(ItemId);
txtName.Text = injection.InjectName;
txtContent.Text = Server.HtmlDecode(injection.InjectContent);
radInject.ClearSelection();
if (injection.InjectTop)
{
radInject.Items.FindByText(GetLocalizedString("radInject.0.Text")).Selected = true;
}
else
{
radInject.Items.FindByText(GetLocalizedString("radInject.1.Text")).Selected = true;
}
chkEnabled.Checked = injection.IsEnabled;
hidInjectionId.Value = injection.InjectionId.ToString();
cvName.Enabled = false;
cmdDelete.Visible = !string.IsNullOrEmpty(hidInjectionId.Value);
if (injection.CustomProperties.Any(p => p.Name == InjectionInfoMembers.CrmPriorityField))
{
var priorityLevel = injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.CrmPriorityField).Value;
txtCrmPriority.Text = (priorityLevel == "-1") ? string.Empty : priorityLevel;
}
if (injection.CustomProperties.Any(p => p.Name == InjectionInfoMembers.CrmProviderField))
{
var provider = injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.CrmProviderField).Value;
ddlCrmProvider.ClearSelection();
ddlCrmProvider.SelectedIndex = int.Parse(provider);
}
if (injection.CustomProperties.Any(p => p.Name == InjectionInfoMembers.LastUpdatedByField))
{
var updatedBy = injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.LastUpdatedByField);
var updatedDate = injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.LastUpdatedDateField);
var user = UserController.GetUserById(PortalSettings.PortalId, int.Parse(updatedBy.Value, NumberStyles.Integer));
lblAudit.Text = string.Format(GetLocalizedString("lblAudit"), user.DisplayName, updatedDate.Value);
}
if (injection.CustomProperties.Any(p => p.Name == InjectionInfoMembers.InjectionTypeField))
{
var intType =int.Parse(
injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.InjectionTypeField)
.Value);
radType.SelectedIndex = intType;
}
else
{
// the default for existing injections is 1 because JS/CSS wasn't an option in the past
radType.SelectedIndex = 1;
}
ToggleType();
}
private void HandleException(Exception exc)
{
Exceptions.LogException(exc);
if (UserInfo.IsSuperUser | UserInfo.UserID == PortalSettings.AdministratorId)
{
DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, string.Concat(exc.Message, "<br />", exc.StackTrace), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
}
else
{
DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
}
}
private void SwapOrder(int ItemId, string UpDown)
{
// set the global id to match the one we're looking for
p_SearchParam = ItemId;
// change the order
InjectionController ctlModule = new InjectionController();
ctlModule.ChangeOrder(ItemId, UpDown);
}
#endregion
#region Data Access
private void SaveInjection()
{
try
{
var ctlModule = new InjectionController();
InjectionInfo objInj = null;
objInj = !string.IsNullOrEmpty(hidInjectionId.Value) ? ctlModule.GetInjectionContent(int.Parse(hidInjectionId.Value)) : new InjectionInfo();
PopulateInjectionForSave(ref objInj);
if (!string.IsNullOrEmpty(hidInjectionId.Value))
{
ctlModule.UpdateInjectionContent(objInj);
}
else
{
ctlModule.AddInjectionContent(objInj);
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private void PopulateInjectionForSave(ref InjectionInfo injection)
{
var security = new PortalSecurity();
injection.InjectContent = Server.HtmlEncode(txtContent.Text);
injection.InjectName = security.InputFilter(txtName.Text, PortalSecurity.FilterFlag.NoMarkup);
injection.InjectTop = radInject.Items.FindByText(GetLocalizedString("radInject.0.Text")).Selected;
injection.IsEnabled = chkEnabled.Checked;
injection.ModuleId = ModuleId;
if (injection.CustomProperties.Any(p => p.Name == InjectionInfoMembers.InjectionTypeField))
{
// update the existing injection type
injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.InjectionTypeField)
.Value = radType.SelectedIndex.ToString();
}
else
{
// create new injection type
injection.CustomProperties.Add(new CustomPropertyInfo()
{
Name = InjectionInfoMembers.InjectionTypeField,
Value = radType.SelectedIndex.ToString()
});
}
// CRM PRIORITY LEVEL
var priorityLevel = ParsePriotityLevel(security);
if (injection.CustomProperties.Any(p => p.Name == InjectionInfoMembers.CrmPriorityField))
{
// update existing CRM/CDF priority level
injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.CrmPriorityField)
.Value = priorityLevel.ToString();
}
else
{
// create new CRM/CDF priority level
injection.CustomProperties.Add(new CustomPropertyInfo()
{
Name = InjectionInfoMembers.CrmPriorityField,
Value = priorityLevel.ToString()
});
}
// CRM PAGE PROVIDER
var provider = ddlCrmProvider.SelectedIndex;
if (injection.CustomProperties.Any(p => p.Name == InjectionInfoMembers.CrmProviderField))
{
// update existing CRM/CDF provider
injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.CrmProviderField).Value = provider.ToString();
}
else
{
// create new CRM/CDF provider
injection.CustomProperties.Add(new CustomPropertyInfo()
{
Name = InjectionInfoMembers.CrmProviderField,
Value = provider.ToString()
});
}
if (injection.CustomProperties.Any(p => p.Name == InjectionInfoMembers.CrmPriorityField))
{
injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.CrmPriorityField)
.Value = security.InputFilter(txtCrmPriority.Text.Trim(), PortalSecurity.FilterFlag.NoMarkup);
}
else
{
injection.CustomProperties.Add(new CustomPropertyInfo()
{
Name = InjectionInfoMembers.CrmPriorityField,
Value = security.InputFilter(txtCrmPriority.Text.Trim(), PortalSecurity.FilterFlag.NoMarkup)
});
}
if (injection.CustomProperties.Any(p => p.Name == InjectionInfoMembers.LastUpdatedByField))
{
// update the existing auditing fields
injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.LastUpdatedByField)
.Value = UserInfo.UserID.ToString();
injection.CustomProperties.FirstOrDefault(p => p.Name == InjectionInfoMembers.LastUpdatedDateField)
.Value = DateTime.UtcNow.ToString();
}
else
{
// adding new audting fields
injection.CustomProperties.Add(new CustomPropertyInfo()
{
Name = InjectionInfoMembers.LastUpdatedByField,
Value = UserInfo.UserID.ToString()
});
injection.CustomProperties.Add(new CustomPropertyInfo()
{
Name = InjectionInfoMembers.LastUpdatedDateField,
Value = DateTime.UtcNow.ToString()
});
}
}
private int ParsePriotityLevel(PortalSecurity security)
{
var priorityInput = security.InputFilter(txtCrmPriority.Text.Trim(), PortalSecurity.FilterFlag.NoMarkup);
var priorityLevel = InjectionController.GetCrmPriority(priorityInput);
return (priorityLevel > Null.NullInteger) ? priorityLevel : Null.NullInteger;
}
#endregion
#region User Interface
private void ToggleType()
{
divInject.Visible = radType.SelectedIndex == 1;
radInject.Enabled = radType.SelectedIndex == 1;
cvContent.Enabled = radType.SelectedIndex == 0;
divAdvanced.Visible = radType.SelectedIndex == 0;
txtContent.Rows = radType.SelectedIndex == 1 ? 10 : 2;
}
private void TogglePanels()
{
pnlAddNew.Visible = (!pnlAddNew.Visible);
pnlManage.Visible = (!pnlManage.Visible);
}
protected bool CommandUpVisible(object InjectionId)
{
if (InjectionId == null) return false;
var ctlModule = new InjectionController();
var oInject = ctlModule.GetInjectionContent(int.Parse(InjectionId.ToString(), NumberStyles.Integer));
return (oInject.OrderShown != 1);
}
protected bool CommandDownVisible(object InjectionId)
{
if (InjectionId == null) return false;
var ctlModule = new InjectionController();
var oInject = ctlModule.GetInjectionContent(int.Parse(InjectionId.ToString(), NumberStyles.Integer));
var collInject = ctlModule.GetInjectionContents(ModuleId);
return (oInject.OrderShown != collInject.Count);
}
protected string GetEnabledImage(object EnabledText)
{
if (EnabledText != null && string.Equals(EnabledText.ToString(), c_True))
{
return EnabledImage;
}
else
{
return DisabledImage;
}
}
protected string GetEnabledImageAltText(object EnabledText)
{
if (EnabledText != null && string.Equals(EnabledText, c_True))
{
return EnabledAltText;
}
else
{
return DisabledAltText;
}
}
protected string GetInjectionTypeForDisplay(object InjectionId)
{
if (InjectionId == null) return string.Empty;
var ctl = new InjectionController();
var injection = ctl.GetInjectionContent(int.Parse(InjectionId.ToString(), NumberStyles.Integer));
var injectionType = InjectionController.GetInjectionType(injection);
if (injectionType == InjectionType.HtmlBottom || injectionType == InjectionType.HtmlTop)
{
return GetLocalizedString(injectionType.ToString());
}
else
{
var injectionProvider = InjectionController.GetCrmProvider(injection);
if (string.IsNullOrEmpty(injectionProvider))
{
return string.Concat(GetLocalizedString(injectionType.ToString()),
GetLocalizedString(InjectionController.GetCrmProviderDefault(injectionType)));
}
else
{
return string.Concat(GetLocalizedString(injectionType.ToString()),
GetLocalizedString(injectionProvider));
}
}
}
#endregion
}
}
| |
using System;
using Csla;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERLevel;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A09_Region_Child (editable child object).<br/>
/// This is a generated base class of <see cref="A09_Region_Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="A08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class A09_Region_Child : BusinessBase<A09_Region_Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int region_ID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Region Child Name");
/// <summary>
/// Gets or sets the Region Child Name.
/// </summary>
/// <value>The Region Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A09_Region_Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="A09_Region_Child"/> object.</returns>
internal static A09_Region_Child NewA09_Region_Child()
{
return DataPortal.CreateChild<A09_Region_Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="A09_Region_Child"/> object from the given A09_Region_ChildDto.
/// </summary>
/// <param name="data">The <see cref="A09_Region_ChildDto"/>.</param>
/// <returns>A reference to the fetched <see cref="A09_Region_Child"/> object.</returns>
internal static A09_Region_Child GetA09_Region_Child(A09_Region_ChildDto data)
{
A09_Region_Child obj = new A09_Region_Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A09_Region_Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A09_Region_Child()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="A09_Region_Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="A09_Region_Child"/> object from the given <see cref="A09_Region_ChildDto"/>.
/// </summary>
/// <param name="data">The A09_Region_ChildDto to use.</param>
private void Fetch(A09_Region_ChildDto data)
{
// Value properties
LoadProperty(Region_Child_NameProperty, data.Region_Child_Name);
// parent properties
region_ID1 = data.Parent_Region_ID;
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="A09_Region_Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(A08_Region parent)
{
var dto = new A09_Region_ChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IA09_Region_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="A09_Region_Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(A08_Region parent)
{
if (!IsDirty)
return;
var dto = new A09_Region_ChildDto();
dto.Parent_Region_ID = parent.Region_ID;
dto.Region_Child_Name = Region_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IA09_Region_ChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="A09_Region_Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(A08_Region parent)
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IA09_Region_ChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
using Shouldly;
using StructureMap.Configuration.DSL;
using StructureMap.Graph;
using StructureMap.Graph.Scanning;
using StructureMap.Testing.DocumentationExamples;
using StructureMap.Testing.ExeWidget;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
using StructureMap.Testing.Widget5;
using StructureMap.TypeRules;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Xunit;
namespace StructureMap.Testing.Graph
{
public class TestingRegistry : Registry
{
public static bool WasUsed;
public TestingRegistry()
{
WasUsed = true;
For<Rule>().Use(new ColorRule("Green"));
}
public static void Reset()
{
WasUsed = false;
}
}
public class AssemblyScannerTesterFixture
{
public AssemblyScannerTesterFixture()
{
var binFolder = Path.GetDirectoryName(GetType().GetAssembly().Location);
AssemblyScanningFolder = Path.Combine(binFolder, "DynamicallyLoaded");
if (!Directory.Exists(AssemblyScanningFolder)) Directory.CreateDirectory(AssemblyScanningFolder);
var assembly1 = typeof(RedGreenRegistry).GetAssembly().Location;
var assembly2 = typeof(IWorker).GetAssembly().Location;
var assembly3 = typeof(IDefinedInExe).GetAssembly().Location;
File.Copy(assembly1, Path.Combine(AssemblyScanningFolder, Path.GetFileName(assembly1)), true);
File.Copy(assembly2, Path.Combine(AssemblyScanningFolder, Path.GetFileName(assembly2)), true);
File.Copy(assembly3, Path.Combine(AssemblyScanningFolder, Path.GetFileName(assembly3)), true);
}
public string AssemblyScanningFolder { get; private set; }
}
public class AssemblyScannerTester : IClassFixture<AssemblyScannerTesterFixture>
{
public AssemblyScannerTester(AssemblyScannerTesterFixture assemblyScannerTesterFixture)
{
TestingRegistry.Reset();
theGraph = null;
assemblyScanningFolder = assemblyScannerTesterFixture.AssemblyScanningFolder;
}
private PluginGraph theGraph;
private string assemblyScanningFolder;
private void Scan(Action<IAssemblyScanner> action)
{
var registry = new Registry();
registry.Scan(scan =>
{
action(scan);
scan.ExcludeNamespaceContainingType<ScanningRegistry>();
scan.Convention<FakeConvention>();
});
var builder = new PluginGraphBuilder();
builder.Add(registry);
theGraph = builder.Build();
}
public class FakeConvention : IRegistrationConvention
{
public void ScanTypes(TypeSet types, Registry registry)
{
types.FindTypes(TypeClassification.Interfaces).Each(type => registry.For(type));
}
}
private void shouldHaveFamily<T>()
{
theGraph.Families.Has(typeof(T)).ShouldBeTrue();
}
private void shouldNotHaveFamily<T>()
{
theGraph.Families.Has(typeof(T)).ShouldBeFalse();
}
private void shouldHaveFamilyWithSameName<T>()
{
// The Types may not be "Equal" if their assemblies were loaded in different load contexts (.LoadFrom)
// so we will consider them equal if their names match.
theGraph.Families.Any(family => family.PluginType.FullName == typeof(T).FullName).ShouldBeTrue();
}
private void shouldNotHaveFamilyWithSameName<T>()
{
theGraph.Families.Any(family => family.PluginType.FullName == typeof(T).FullName).ShouldBeFalse();
}
[Fact]
public void is_in_namespace()
{
GetType().IsInNamespace("blah").ShouldBeFalse();
GetType().IsInNamespace("Struct").ShouldBeFalse();
GetType().IsInNamespace("StructureMap").ShouldBeTrue();
GetType().IsInNamespace("StructureMap.Test").ShouldBeFalse();
GetType().IsInNamespace("StructureMap.Testing").ShouldBeTrue();
GetType().IsInNamespace("StructureMap.Testing.Graph").ShouldBeTrue();
GetType().IsInNamespace("StructureMap.Testing.Graphics").ShouldBeFalse();
GetType().IsInNamespace("StructureMap.Testing.Graph.Something").ShouldBeFalse();
var _person = new
{
ID = 1,
FirstName = "Michael",
LastName = "Sync"
};
_person.GetType().IsInNamespace("foo").ShouldBeFalse();
}
[Fact]
public void class_outside_namespace_doesnt_match_any_namespace_check()
{
typeof(class_outside_namespace).IsInNamespace("blah").ShouldBeFalse();
typeof(class_outside_namespace).IsInNamespace("StructureMap").ShouldBeFalse();
}
#if NET451
// SAMPLE: scan-filesystem
[Fact]
public void scan_all_assemblies_in_a_folder()
{
Scan(x => x.AssembliesFromPath(assemblyScanningFolder));
shouldHaveFamilyWithSameName<IInterfaceInWidget5>();
shouldHaveFamilyWithSameName<IWorker>();
shouldNotHaveFamilyWithSameName<IDefinedInExe>();
}
[Fact]
public void scan_all_assemblies_in_application_base_directory()
{
Scan(x => x.AssembliesFromApplicationBaseDirectory());
shouldHaveFamilyWithSameName<IInterfaceInWidget5>();
shouldHaveFamilyWithSameName<IWorker>();
shouldNotHaveFamilyWithSameName<IDefinedInExe>();
}
// ENDSAMPLE
// SAMPLE: scan-filesystem-for-exe
[Fact]
public void scan_all_assemblies_in_a_folder_including_exe()
{
Scan(x => x.AssembliesAndExecutablesFromPath(assemblyScanningFolder));
shouldHaveFamilyWithSameName<IInterfaceInWidget5>();
shouldHaveFamilyWithSameName<IWorker>();
shouldHaveFamilyWithSameName<IDefinedInExe>();
}
[Fact]
public void scan_all_assemblies_in_application_base_directory_including_exe()
{
Scan(x => x.AssembliesAndExecutablesFromApplicationBaseDirectory());
shouldHaveFamilyWithSameName<IInterfaceInWidget5>();
shouldHaveFamilyWithSameName<IWorker>();
shouldHaveFamilyWithSameName<IDefinedInExe>();
}
// ENDSAMPLE
// SAMPLE: scan-calling-assembly
[Fact]
public void scan_but_ignore_registries_by_default()
{
Scan(x => { x.TheCallingAssembly(); });
TestingRegistry.WasUsed.ShouldBeFalse();
}
// ENDSAMPLE
[Fact]
public void scan_specific_assemblies_in_a_folder()
{
var assemblyToSpecificallyExclude = typeof(IWorker).GetAssembly().GetName().Name;
Scan(
x =>
x.AssembliesFromPath(assemblyScanningFolder,
asm => asm.GetName().Name != assemblyToSpecificallyExclude));
shouldHaveFamilyWithSameName<IInterfaceInWidget5>();
shouldNotHaveFamilyWithSameName<IWorker>();
}
[Fact]
public void scan_specific_assemblies_in_application_base_directory()
{
var assemblyToSpecificallyExclude = typeof(IWorker).GetAssembly().GetName().Name;
Scan(
x =>
x.AssembliesFromPath(assemblyScanningFolder,
asm => asm.GetName().Name != assemblyToSpecificallyExclude));
shouldHaveFamilyWithSameName<IInterfaceInWidget5>();
shouldNotHaveFamilyWithSameName<IWorker>();
}
#endif
// SAMPLE: scan-for-registries
[Fact]
public void Search_for_registries_when_explicitly_told()
{
Scan(x =>
{
x.TheCallingAssembly();
x.LookForRegistries();
});
TestingRegistry.WasUsed.ShouldBeTrue();
}
// ENDSAMPLE
[Fact]
public void use_a_dual_exclude()
{
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.Exclude(type => type == typeof(ITypeThatHasAttributeButIsNotInRegistry));
x.Exclude(type => type == typeof(IInterfaceInWidget5));
});
shouldNotHaveFamily<IInterfaceInWidget5>();
shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
[Fact]
public void use_a_dual_exclude2()
{
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.Exclude(type => type == typeof(ITypeThatHasAttributeButIsNotInRegistry));
x.Exclude(type => type == GetType());
});
shouldHaveFamily<IInterfaceInWidget5>();
shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
[Fact]
public void use_a_single_exclude()
{
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.Exclude(type => type == typeof(ITypeThatHasAttributeButIsNotInRegistry));
});
shouldHaveFamily<IInterfaceInWidget5>();
shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
// SAMPLE: scan-exclusions
[Fact]
public void use_a_single_exclude_of_type()
{
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.ExcludeType<ITypeThatHasAttributeButIsNotInRegistry>();
});
shouldHaveFamily<IInterfaceInWidget5>();
shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
[Fact]
public void use_a_single_exclude2()
{
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.ExcludeNamespace("StructureMap.Testing.Widget5");
});
shouldNotHaveFamily<IInterfaceInWidget5>();
shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
[Fact]
public void use_a_single_exclude3()
{
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.ExcludeNamespaceContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
});
shouldNotHaveFamily<IInterfaceInWidget5>();
shouldNotHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
// ENDSAMPLE
[Fact]
public void Use_a_single_include_predicate()
{
Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); });
shouldHaveFamily<IInterfaceInWidget5>();
shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.Include(type => type == typeof(ITypeThatHasAttributeButIsNotInRegistry));
});
shouldNotHaveFamily<IInterfaceInWidget5>();
shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
[Fact]
public void Use_a_single_include_predicate_2()
{
Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); });
shouldHaveFamily<IInterfaceInWidget5>();
shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.IncludeNamespace(typeof(ITypeThatHasAttributeButIsNotInRegistry).Namespace);
});
shouldHaveFamily<IInterfaceInWidget5>();
shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
[Fact]
public void Use_a_single_include_predicate_3()
{
Scan(x => { x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>(); });
shouldHaveFamily<IInterfaceInWidget5>();
shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.IncludeNamespaceContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
});
shouldHaveFamily<IInterfaceInWidget5>();
shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
[Fact]
public void use_two_predicates_for_includes()
{
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.Include(type => type == typeof(ITypeThatHasAttributeButIsNotInRegistry));
x.Include(type => type == typeof(IInterfaceInWidget5));
});
shouldHaveFamily<IInterfaceInWidget5>();
shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
[Fact]
public void use_two_predicates_for_includes2()
{
Scan(x =>
{
x.AssemblyContainingType<ITypeThatHasAttributeButIsNotInRegistry>();
x.Include(type => type == typeof(ITypeThatHasAttributeButIsNotInRegistry));
x.Include(type => type == GetType());
});
shouldNotHaveFamily<IInterfaceInWidget5>();
shouldHaveFamily<ITypeThatHasAttributeButIsNotInRegistry>();
}
}
public interface IController
{
}
public class AddressController : IController
{
}
public class SiteController : IController
{
}
public class when_attaching_types_with_naming_pattern
{
public when_attaching_types_with_naming_pattern()
{
container = new Container(x =>
{
x.Scan(o =>
{
o.TheCallingAssembly();
o.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", ""));
});
});
}
private IContainer container;
[Fact]
public void can_find_objects_later_by_name()
{
container.GetInstance<IController>("Address")
.ShouldBeOfType<AddressController>();
container.GetInstance<IController>("Site")
.ShouldBeOfType<SiteController>();
}
}
}
public class class_outside_namespace
{
}
| |
//------------------------------------------------------------------------------
// <copyright file="StateWorkerRequest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* StateHttpWorkerRequest
*
* Copyright (c) 1998-1999, Microsoft Corporation
*
*/
namespace System.Web.SessionState {
using System.Text;
using System.Configuration.Assemblies;
using System.Runtime.InteropServices;
using System.Collections;
using System.Web;
using System.Web.Util;
using System.Globalization;
class StateHttpWorkerRequest : HttpWorkerRequest {
/* long enough to hold the string representation of an IPv4 or IPv6 address; keep in [....] with tracker.cxx */
private const int ADDRESS_LENGTH_MAX = 64;
IntPtr _tracker;
string _uri;
UnsafeNativeMethods.StateProtocolExclusive _exclusive;
int _extraFlags;
int _timeout;
int _lockCookie;
bool _lockCookieExists;
int _contentLength;
byte[] _content;
UnsafeNativeMethods.StateProtocolVerb _methodIndex;
string _method;
string _remoteAddress;
int _remotePort;
string _localAddress;
int _localPort;
StringBuilder _status;
int _statusCode;
StringBuilder _headers;
IntPtr _unmanagedState;
bool _sent;
internal StateHttpWorkerRequest(
IntPtr tracker,
UnsafeNativeMethods.StateProtocolVerb methodIndex,
string uri,
UnsafeNativeMethods.StateProtocolExclusive exclusive,
int extraFlags,
int timeout,
int lockCookieExists,
int lockCookie,
int contentLength,
IntPtr content
) {
_tracker = tracker;
_methodIndex = methodIndex;
switch (_methodIndex) {
case UnsafeNativeMethods.StateProtocolVerb.GET:
_method = "GET";
break;
case UnsafeNativeMethods.StateProtocolVerb.PUT:
_method = "PUT";
break;
case UnsafeNativeMethods.StateProtocolVerb.HEAD:
_method = "HEAD";
break;
case UnsafeNativeMethods.StateProtocolVerb.DELETE:
_method = "DELETE";
break;
default:
Debug.Assert(false, "Shouldn't get here!");
break;
}
_uri = uri;
// Handle the ASP1.1 case which prepends an extra / to the URI
if (_uri.StartsWith("//", StringComparison.Ordinal)) {
_uri = _uri.Substring(1);
}
_exclusive = exclusive;
_extraFlags = extraFlags;
_timeout = timeout;
_lockCookie = lockCookie;
_lockCookieExists = lockCookieExists != 0;
_contentLength = contentLength;
if (contentLength != 0) {
Debug.Assert(_contentLength == IntPtr.Size);
// Need to convert 'content', which is a ptr to native StateItem,
// into a byte array because that's what GetPreloadedEntityBody
// must return, and GetPreloadedEntityBody is what the pipeline uses
// to read the body of the request, which in our case is just a pointer
// to a native StateItem object.
#if WIN64
ulong p = (ulong) content;
_content = new byte[8]
{
(byte) ((p & 0x00000000000000ff)),
(byte) ((p & 0x000000000000ff00) >> 8),
(byte) ((p & 0x0000000000ff0000) >> 16),
(byte) ((p & 0x00000000ff000000) >> 24),
(byte) ((p & 0x000000ff00000000) >> 32),
(byte) ((p & 0x0000ff0000000000) >> 40),
(byte) ((p & 0x00ff000000000000) >> 48),
(byte) ((p & 0xff00000000000000) >> 56),
};
#else
uint p = (uint) content;
_content = new byte[4]
{
(byte) ((p & 0x000000ff)),
(byte) ((p & 0x0000ff00) >> 8),
(byte) ((p & 0x00ff0000) >> 16),
(byte) ((p & 0xff000000) >> 24),
};
#endif
}
_status = new StringBuilder(256);
_headers = new StringBuilder(256);
}
public override string GetUriPath() {
return HttpUtility.UrlDecode(_uri);
}
// The file path is used as the path for configuration.
// This path should always be null, in order to retrieve
// the machine configuration.
public override string GetFilePath() {
return null;
}
public override string GetQueryString() {
return null;
}
public override string GetRawUrl() {
return _uri;
}
public override string GetHttpVerbName() {
return _method;
}
public override string GetHttpVersion() {
return "HTTP/1.0";
}
public override string GetRemoteAddress() {
StringBuilder buf;
if (_remoteAddress == null) {
buf = new StringBuilder(ADDRESS_LENGTH_MAX);
UnsafeNativeMethods.STWNDGetRemoteAddress(_tracker, buf);
_remoteAddress = buf.ToString();
}
return _remoteAddress;
}
public override int GetRemotePort() {
if (_remotePort == 0) {
_remotePort = UnsafeNativeMethods.STWNDGetRemotePort(_tracker);
}
return _remotePort;
}
public override string GetLocalAddress() {
StringBuilder buf;
if (_localAddress == null) {
buf = new StringBuilder(ADDRESS_LENGTH_MAX);
UnsafeNativeMethods.STWNDGetLocalAddress(_tracker, buf);
_localAddress = buf.ToString();
}
return _localAddress;
}
public override int GetLocalPort() {
if (_localPort == 0) {
_localPort = UnsafeNativeMethods.STWNDGetLocalPort(_tracker);
}
return _localPort;
}
public override byte[] GetPreloadedEntityBody() {
return _content;
}
public override bool IsEntireEntityBodyIsPreloaded() {
/* Request is always preloaded */
return true;
}
public override string MapPath(string virtualPath) {
/*
* Physical and virtual are identical to state server.
*/
return virtualPath;
}
public override int ReadEntityBody(byte[] buffer, int size) {
/* pretend everything is preloaded */
return 0;
}
public override long GetBytesRead() {
/* State web doesn't support partial reads */
throw new NotSupportedException(SR.GetString(SR.Not_supported));
}
public override string GetKnownRequestHeader(int index) {
string s = null;
switch (index) {
/* special case important ones */
case HeaderContentLength:
s = (_contentLength).ToString(CultureInfo.InvariantCulture);
break;
}
return s;
}
public override string GetUnknownRequestHeader(string name) {
string s = null;
if (name.Equals(StateHeaders.EXCLUSIVE_NAME)) {
switch (_exclusive) {
case UnsafeNativeMethods.StateProtocolExclusive.ACQUIRE:
s = StateHeaders.EXCLUSIVE_VALUE_ACQUIRE;
break;
case UnsafeNativeMethods.StateProtocolExclusive.RELEASE:
s = StateHeaders.EXCLUSIVE_VALUE_RELEASE;
break;
}
}
else if (name.Equals(StateHeaders.TIMEOUT_NAME)) {
if (_timeout != -1) {
s = (_timeout).ToString(CultureInfo.InvariantCulture);
}
}
else if (name.Equals(StateHeaders.LOCKCOOKIE_NAME)) {
if (_lockCookieExists) {
s = (_lockCookie).ToString(CultureInfo.InvariantCulture);
}
}
else if (name.Equals(StateHeaders.EXTRAFLAGS_NAME)) {
if (_extraFlags != -1) {
s = (_extraFlags).ToString(CultureInfo.InvariantCulture);
}
}
return s;
}
public override string[][] GetUnknownRequestHeaders() {
string [][] ret;
int c, i;
c = 0;
if (_exclusive != (UnsafeNativeMethods.StateProtocolExclusive) (-1)) {
c++;
}
if (_extraFlags != -1) {
c++;
}
if (_timeout != -1) {
c++;
}
if (_lockCookieExists) {
c++;
}
if (c == 0)
return null;
ret = new string[c][];
i = 0;
if (_exclusive != (UnsafeNativeMethods.StateProtocolExclusive) (-1)) {
ret[0] = new string[2];
ret[0][0] = StateHeaders.EXCLUSIVE_NAME;
if (_exclusive == UnsafeNativeMethods.StateProtocolExclusive.ACQUIRE) {
ret[0][1] = StateHeaders.EXCLUSIVE_VALUE_ACQUIRE;
}
else {
Debug.Assert(_exclusive == UnsafeNativeMethods.StateProtocolExclusive.RELEASE, "_exclusive == UnsafeNativeMethods.StateProtocolExclusive.RELEASE");
ret[0][1] = StateHeaders.EXCLUSIVE_VALUE_RELEASE;
}
i++;
}
if (_timeout != -1) {
ret[i] = new string[2];
ret[i][0] = StateHeaders.TIMEOUT_NAME;
ret[i][1] = (_timeout).ToString(CultureInfo.InvariantCulture);
i++;
}
if (_lockCookieExists) {
ret[i] = new string[2];
ret[i][0] = StateHeaders.LOCKCOOKIE_NAME;
ret[i][1] = (_lockCookie).ToString(CultureInfo.InvariantCulture);
i++;
}
if (_extraFlags != -1) {
ret[i] = new string[2];
ret[i][0] = StateHeaders.EXTRAFLAGS_NAME;
ret[i][1] = (_extraFlags).ToString(CultureInfo.InvariantCulture);
i++;
}
return ret;
}
public override void SendStatus(int statusCode, string statusDescription) {
Debug.Assert(!_sent);
_statusCode = statusCode;
_status.Append((statusCode).ToString(CultureInfo.InvariantCulture) + " " + statusDescription + "\r\n");
}
public override void SendKnownResponseHeader(int index, string value) {
Debug.Assert(!_sent);
_headers.Append(GetKnownResponseHeaderName(index));
_headers.Append(": ");
_headers.Append(value);
_headers.Append("\r\n");
}
public override void SendUnknownResponseHeader(string name, string value) {
Debug.Assert(!_sent);
_headers.Append(name);
_headers.Append(": ");
_headers.Append(value);
_headers.Append("\r\n");
}
public override void SendCalculatedContentLength(int contentLength) {
Debug.Assert(!_sent);
/*
* Do nothing - we append the content-length in STWNDSendResponse.
*/
}
public override bool HeadersSent() {
return _sent;
}
public override bool IsClientConnected() {
return UnsafeNativeMethods.STWNDIsClientConnected(_tracker);
}
public override void CloseConnection() {
UnsafeNativeMethods.STWNDCloseConnection(_tracker);
}
private void SendResponse() {
if (!_sent) {
_sent = true;
UnsafeNativeMethods.STWNDSendResponse(
_tracker,
_status,
_status.Length,
_headers,
_headers.Length,
_unmanagedState);
}
}
public override void SendResponseFromMemory(byte[] data, int length) {
/*
* The only content besides error message text is the pointer
* to the state item in unmanaged memory.
*/
if (_statusCode == 200) {
Debug.Assert(_unmanagedState == IntPtr.Zero, "_unmanagedState == 0");
Debug.Assert(length == IntPtr.Size, "length == IntPtr.Size");
Debug.Assert(_methodIndex == UnsafeNativeMethods.StateProtocolVerb.GET, "verb == GET");
Debug.Assert(_exclusive != UnsafeNativeMethods.StateProtocolExclusive.RELEASE,
"correct exclusive method");
if (IntPtr.Size == 4) {
_unmanagedState = (IntPtr)
(((int)data[0]) |
((int)data[1] << 8) |
((int)data[2] << 16) |
((int)data[3] << 24));
}
else {
_unmanagedState = (IntPtr)
(((long)data[0]) |
((long)data[1] << 8) |
((long)data[2] << 16) |
((long)data[3] << 24) |
((long)data[4] << 32) |
((long)data[5] << 40) |
((long)data[6] << 48) |
((long)data[7] << 56));
}
Debug.Assert(_unmanagedState != IntPtr.Zero, "_unmanagedState != 0");
}
SendResponse();
}
public override void SendResponseFromFile(string filename, long offset, long length) {
/* Not needed by state application */
throw new NotSupportedException(SR.GetString(SR.Not_supported));
}
public override void SendResponseFromFile(IntPtr handle, long offset, long length) {
/* Not needed by state application */
throw new NotSupportedException(SR.GetString(SR.Not_supported));
}
public override void FlushResponse(bool finalFlush) {
SendResponse();
}
public override void EndOfRequest() {
SendResponse();
UnsafeNativeMethods.STWNDEndOfRequest(_tracker);
}
}
}
| |
using AllReady.Areas.Admin.Controllers;
using AllReady.Areas.Admin.Features.CampaignManagerInvites;
using AllReady.Areas.Admin.Features.Notifications;
using AllReady.Areas.Admin.ViewModels.ManagerInvite;
using AllReady.Features.Campaigns;
using AllReady.Models;
using AllReady.UnitTest.Extensions;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Moq;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Xunit;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class CampaignManagerInviteControllerTests
{
private const int campaignId = 100;
private const int eventId = 200;
private const int inviteId = 300;
#region Send GET Tests
[Fact]
public async Task SendSendsCampaignByCampaignIdQueryWithCorrectCampaignId()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
await sut.Send(campaignId);
// Assert
mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignManagerInviteQuery>(c => c.CampaignId == campaignId)));
}
[Fact]
public async Task SendReturnsNotFoundResult_WhenNoCampaignMatchesId()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteQuery>())).ReturnsAsync((CampaignManagerInviteViewModel)null);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
IActionResult result = await sut.Send(campaignId);
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async Task SendReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteQuery>())).ReturnsAsync(new CampaignManagerInviteViewModel() { CampaignId = campaignId });
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserNotAnOrgAdmin();
// Act
IActionResult result = await sut.Send(campaignId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task SendReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new CampaignManagerInviteViewModel() { CampaignId = campaignId, OrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteQuery>())).ReturnsAsync(campaign);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "2");
// Act
IActionResult result = await sut.Send(campaignId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task SendReturnsSendView_WhenUserIsOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new CampaignManagerInviteViewModel() { CampaignId = campaignId, OrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteQuery>())).ReturnsAsync(campaign);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
// Act
IActionResult result = await sut.Send(campaignId);
// Assert
Assert.IsType<ViewResult>(result);
ViewResult view = result as ViewResult;
Assert.Equal("Send", view.ViewName);
}
[Fact]
public async Task SendPassesCorrectViewModelToView()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new CampaignManagerInviteViewModel() { CampaignId = campaignId, OrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteQuery>())).ReturnsAsync(campaign);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
// Act
IActionResult result = await sut.Send(campaignId);
// Assert
ViewResult view = result as ViewResult;
var model = Assert.IsType<CampaignManagerInviteViewModel>(view.ViewData.Model);
Assert.Equal(campaignId, model.CampaignId);
}
#endregion
#region Send POST Tests
[Fact]
public async Task SendReturnsBadRequestResult_WhenViewModelIsNull()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
IActionResult result = await sut.Send(campaignId, null);
// Assert
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenViewModelIsNull()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
IActionResult result = await sut.Send(campaignId, null);
// Assert
mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never);
}
[Fact]
public async Task SendReturnsSendView_WhenModelStateIsNotValid()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.ModelState.AddModelError("Error", "Message");
// Act
var result = await sut.Send(campaignId, new CampaignManagerInviteViewModel());
// Assert
var view = Assert.IsType<ViewResult>(result);
Assert.Equal("Send", view.ViewName);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenModelStateIsNotValid()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.ModelState.AddModelError("Error", "Message");
// Act
var result = await sut.Send(campaignId, new CampaignManagerInviteViewModel());
// Assert
mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never);
}
[Fact]
public async Task SendPostReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new Campaign() { ManagingOrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserNotAnOrgAdmin();
var invite = new CampaignManagerInviteViewModel();
// Act
IActionResult result = await sut.Send(campaignId, invite);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenUserIsNotOrgAdmin()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new Campaign() { ManagingOrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserNotAnOrgAdmin();
var invite = new CampaignManagerInviteViewModel();
// Act
IActionResult result = await sut.Send(campaignId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never);
}
[Fact]
public async Task SendPostReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new Campaign() { ManagingOrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "2");
var invite = new CampaignManagerInviteViewModel();
// Act
IActionResult result = await sut.Send(campaignId, invite);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenUserIsNotOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new Campaign() { ManagingOrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "2");
var invite = new CampaignManagerInviteViewModel();
// Act
IActionResult result = await sut.Send(campaignId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.IsAny<CreateCampaignManagerInviteCommand>()), Times.Never);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenAnInviteAlreadyExistsForInviteeEmailAddress()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new Campaign() { ManagingOrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign);
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<UserHasCampaignManagerInviteQuery>())).ReturnsAsync(true);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
var invite = new CampaignManagerInviteViewModel
{
CampaignId = 1,
InviteeEmailAddress = "[email protected]",
CustomMessage = "test message"
};
// Act
IActionResult result = await sut.Send(invite.CampaignId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.Is<CreateCampaignManagerInviteCommand>(c => c.Invite == invite)), Times.Never);
}
[Fact]
public async Task SendShouldNotCreateInvite_WhenUserIsAllreadyManagerForEvent()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new Campaign() { ManagingOrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign);
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<UserHasCampaignManagerInviteQuery>())).ReturnsAsync(false);
var mockUserManger = UserManagerMockHelper.CreateUserManagerMock();
mockUserManger.Setup(mock => mock.FindByEmailAsync(It.Is<string>(e => e == "[email protected]"))).ReturnsAsync(new ApplicationUser
{
ManagedCampaigns = new List<CampaignManager> { new CampaignManager() { CampaignId = 1 } },
});
var sut = new CampaignManagerInviteController(mockMediator.Object, mockUserManger.Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
var invite = new CampaignManagerInviteViewModel
{
CampaignId = 1,
InviteeEmailAddress = "[email protected]",
CustomMessage = "test message"
};
// Act
IActionResult result = await sut.Send(invite.CampaignId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.Is<CreateCampaignManagerInviteCommand>(c => c.Invite == invite)), Times.Never);
}
[Fact]
public async Task SendShouldCreateInvite_WhenUserIsOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new Campaign() { ManagingOrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignByCampaignIdQuery>())).ReturnsAsync(campaign);
var userManager = UserManagerMockHelper.CreateUserManagerMock();
userManager.Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(new ApplicationUser());
var urlHelper = new Mock<IUrlHelper>();
urlHelper.Setup(x => x.Action(It.IsAny<UrlActionContext>())).Returns(It.IsAny<string>());
var sut = new CampaignManagerInviteController(mockMediator.Object, userManager.Object) { Url = urlHelper.Object };
sut.MakeUserAnOrgAdmin(organizationId: "1");
var invite = new CampaignManagerInviteViewModel
{
CampaignId = 1,
InviteeEmailAddress = "[email protected]",
CustomMessage = "test message"
};
// Act
IActionResult result = await sut.Send(campaignId, invite);
// Assert
mockMediator.Verify(x => x.SendAsync(It.Is<CreateCampaignManagerInviteCommand>(c => c.Invite == invite)), Times.Once);
}
#endregion
#region Details Tests
[Fact]
public async Task DetailsSendsCampaignManagerInviteDetailQueryWithCorrectInviteId()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
await sut.Details(inviteId);
// Assert
mockMediator.Verify(mock => mock.SendAsync(It.Is<CampaignManagerInviteDetailQuery>(c => c.CampaignManagerInviteId == inviteId)));
}
[Fact]
public async Task DetailsReturnsNotFoundResult_WhenNoInviteMatchesId()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async Task DetailsReturnsUnauthorizedResult_WhenUserIsNotOrgAdmin()
{
// Arrange
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteDetailQuery>()))
.ReturnsAsync(new CampaignManagerInviteDetailsViewModel { Id = inviteId });
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserNotAnOrgAdmin();
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task DetailsReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var invite = new CampaignManagerInviteDetailsViewModel() { Id = inviteId, OrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteDetailQuery>())).ReturnsAsync(invite);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "2");
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task DetailsReturnsView_WhenUserIsOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var invite = new CampaignManagerInviteDetailsViewModel() { Id = inviteId, OrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteDetailQuery>())).ReturnsAsync(invite);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
Assert.IsType<ViewResult>(result);
}
[Fact]
public async Task DetailsPassesCorrectViewModelToView()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var invite = new CampaignManagerInviteDetailsViewModel() { Id = inviteId, OrganizationId = 1 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteDetailQuery>())).ReturnsAsync(invite);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin(organizationId: "1");
// Act
IActionResult result = await sut.Details(inviteId);
// Assert
ViewResult view = result as ViewResult;
var model = Assert.IsType<CampaignManagerInviteDetailsViewModel>(view.ViewData.Model);
Assert.Equal(inviteId, model.Id);
}
#endregion
#region CancelInvice tests
[Fact]
public async Task CancelReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new CampaignManagerInviteDetailsViewModel() { CampaignId = campaignId, OrganizationId = 1, Id = 5};
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteDetailQuery>())).ReturnsAsync(campaign);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserNotAnOrgAdmin();
// Act
var result = await sut.Cancel(5);
// Assert
Assert.IsType<UnauthorizedResult>(result);
}
[Fact]
public async Task CancelReturnsNotFoundResult_WhenInviteIsMissing()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin("1");
// Act
var result = await sut.Cancel(5);
// Assert
Assert.IsType<NotFoundResult>(result);
}
[Fact]
public async Task CancelReturnsRedirectResult_WhenInviteIsOk()
{
// Arrange
var mockMediator = new Mock<IMediator>();
var campaign = new CampaignManagerInviteDetailsViewModel() { CampaignId = campaignId, OrganizationId = 1, Id = 5 };
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignManagerInviteDetailQuery>())).ReturnsAsync(campaign);
var sut = new CampaignManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);
sut.MakeUserAnOrgAdmin("1");
// Act
var result = await sut.Cancel(5);
// Assert
Assert.IsType<RedirectToActionResult>(result);
}
#endregion
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace ParquetSharp.Filter
{
using ParquetSharp.Column;
using ParquetSharp.External;
/**
* ColumnPredicates class provides checks for column values. Factory methods
* are provided for standard predicates which wrap the job of getting the
* correct value from the column.
*/
public class ColumnPredicates
{
public interface Predicate
{
bool apply(ColumnReader input);
}
public interface PredicateFunction<T>
{
bool functionToApply(T input);
}
/* provide the following to avoid boxing primitives */
public interface IntegerPredicateFunction
{
bool functionToApply(int input);
}
public interface LongPredicateFunction
{
bool functionToApply(long input);
}
public interface FloatPredicateFunction
{
bool functionToApply(float input);
}
public interface DoublePredicateFunction
{
bool functionToApply(double input);
}
public interface BooleanPredicateFunction
{
bool functionToApply(bool input);
}
public static Predicate equalTo(string target)
{
Preconditions.checkNotNull(target, "target");
return new StringEqualsPredicate(target);
}
class StringEqualsPredicate : Predicate
{
private readonly string target;
public StringEqualsPredicate(string target)
{
this.target = target;
}
public bool apply(ColumnReader input)
{
return target.Equals(input.getBinary().toStringUsingUTF8());
}
}
public static Predicate applyFunctionToString(PredicateFunction<string> fn)
{
return new StringFunctionPredicate(fn);
}
class StringFunctionPredicate : Predicate
{
private readonly PredicateFunction<string> fn;
public StringFunctionPredicate(PredicateFunction<string> fn)
{
this.fn = fn;
}
public bool apply(ColumnReader input)
{
return fn.functionToApply(input.getBinary().toStringUsingUTF8());
}
}
public static Predicate equalTo(int target)
{
return new IntEqualsPredicate(target);
}
class IntEqualsPredicate : Predicate
{
private readonly int target;
public IntEqualsPredicate(int target)
{
this.target = target;
}
public bool apply(ColumnReader input)
{
return input.getInteger() == target;
}
}
public static Predicate applyFunctionToInteger(IntegerPredicateFunction fn)
{
return new IntFunctionPredicate(fn);
}
class IntFunctionPredicate : Predicate
{
private readonly IntegerPredicateFunction fn;
public IntFunctionPredicate(IntegerPredicateFunction fn)
{
this.fn = fn;
}
public bool apply(ColumnReader input)
{
return fn.functionToApply(input.getInteger());
}
}
public static Predicate equalTo(long target)
{
return new LongEqualsPredicate(target);
}
class LongEqualsPredicate : Predicate
{
private readonly long target;
public LongEqualsPredicate(long target)
{
this.target = target;
}
public bool apply(ColumnReader input)
{
return input.getLong() == target;
}
}
public static Predicate applyFunctionToLong(LongPredicateFunction fn)
{
return new LongFunctionPredicate(fn);
}
class LongFunctionPredicate : Predicate
{
private readonly LongPredicateFunction fn;
public LongFunctionPredicate(LongPredicateFunction fn)
{
this.fn = fn;
}
public bool apply(ColumnReader input)
{
return fn.functionToApply(input.getLong());
}
}
public static Predicate equalTo(float target)
{
return new FloatEqualsPredicate(target);
}
class FloatEqualsPredicate : Predicate
{
private readonly float target;
public FloatEqualsPredicate(float target)
{
this.target = target;
}
public bool apply(ColumnReader input)
{
return input.getFloat() == target;
}
}
public static Predicate applyFunctionToFloat(FloatPredicateFunction fn)
{
return new FloatFunctionPredicate(fn);
}
class FloatFunctionPredicate : Predicate
{
private readonly FloatPredicateFunction fn;
public FloatFunctionPredicate(FloatPredicateFunction fn)
{
this.fn = fn;
}
public bool apply(ColumnReader input)
{
return fn.functionToApply(input.getFloat());
}
}
public static Predicate equalTo(double target)
{
return new DoubleEqualsPredicate(target);
}
class DoubleEqualsPredicate : Predicate
{
private readonly double target;
public DoubleEqualsPredicate(double target)
{
this.target = target;
}
public bool apply(ColumnReader input)
{
return input.getDouble() == target;
}
}
public static Predicate applyFunctionToDouble(DoublePredicateFunction fn)
{
return new DoubleFunctionPredicate(fn);
}
class DoubleFunctionPredicate : Predicate
{
private readonly DoublePredicateFunction fn;
public DoubleFunctionPredicate(DoublePredicateFunction fn)
{
this.fn = fn;
}
public bool apply(ColumnReader input)
{
return fn.functionToApply(input.getDouble());
}
}
public static Predicate equalTo(bool target)
{
return new BoolEqualsPredicate(target);
}
class BoolEqualsPredicate : Predicate
{
private readonly bool target;
public BoolEqualsPredicate(bool target)
{
this.target = target;
}
public bool apply(ColumnReader input)
{
return input.getBoolean() == target;
}
}
public static Predicate applyFunctionToBoolean(BooleanPredicateFunction fn)
{
return new BoolFunctionPredicate(fn);
}
class BoolFunctionPredicate : Predicate
{
private readonly BooleanPredicateFunction fn;
public BoolFunctionPredicate(BooleanPredicateFunction fn)
{
this.fn = fn;
}
public bool apply(ColumnReader input)
{
return fn.functionToApply(input.getBoolean());
}
}
#if false
public static <E : Enum> Predicate equalTo(E target) {
Preconditions.checkNotNull(target,"target");
string targetAsString = target.name();
return new Predicate() {
@Override
public bool apply(ColumnReader input) {
return targetAsString.equals(input.getBinary().toStringUsingUTF8());
}
};
}
public static Predicate applyFunctionToBinary (PredicateFunction<Binary> fn) {
return new Predicate() {
@Override
public bool apply(ColumnReader input) {
return fn.functionToApply(input.getBinary());
}
};
}
#endif
}
}
| |
//
// 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.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.ServiceBus;
using Microsoft.WindowsAzure.Management.ServiceBus.Models;
namespace Microsoft.WindowsAzure.Management.ServiceBus
{
/// <summary>
/// The Service Bus Management API includes operations for managing Service
/// Bus notification hubs.
/// </summary>
internal partial class NotificationHubOperations : IServiceOperations<ServiceBusManagementClient>, INotificationHubOperations
{
/// <summary>
/// Initializes a new instance of the NotificationHubOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal NotificationHubOperations(ServiceBusManagementClient client)
{
this._client = client;
}
private ServiceBusManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ServiceBus.ServiceBusManagementClient.
/// </summary>
public ServiceBusManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Deletes a notification hub associated with a namespace.
/// </summary>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// Required. The notification hub name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string namespaceName, string notificationHubName, CancellationToken cancellationToken)
{
// Validate
if (namespaceName == null)
{
throw new ArgumentNullException("namespaceName");
}
if (notificationHubName == null)
{
throw new ArgumentNullException("notificationHubName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("notificationHubName", notificationHubName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/servicebus/namespaces/";
url = url + Uri.EscapeDataString(namespaceName);
url = url + "/NotificationHubs/";
url = url + Uri.EscapeDataString(notificationHubName);
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.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-08-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// Required. The notification hub name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<ServiceBusNotificationHubResponse> GetAsync(string namespaceName, string notificationHubName, CancellationToken cancellationToken)
{
// Validate
if (namespaceName == null)
{
throw new ArgumentNullException("namespaceName");
}
if (notificationHubName == null)
{
throw new ArgumentNullException("notificationHubName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("notificationHubName", notificationHubName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/servicebus/namespaces/";
url = url + Uri.EscapeDataString(namespaceName);
url = url + "/NotificationHubs/";
url = url + Uri.EscapeDataString(notificationHubName);
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("x-ms-version", "2013-08-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServiceBusNotificationHubResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServiceBusNotificationHubResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement entryElement = responseDoc.Element(XName.Get("entry", "http://www.w3.org/2005/Atom"));
if (entryElement != null)
{
XElement titleElement = entryElement.Element(XName.Get("title", "http://www.w3.org/2005/Atom"));
if (titleElement != null)
{
}
XElement contentElement = entryElement.Element(XName.Get("content", "http://www.w3.org/2005/Atom"));
if (contentElement != null)
{
XElement notificationHubDescriptionElement = contentElement.Element(XName.Get("NotificationHubDescription", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (notificationHubDescriptionElement != null)
{
ServiceBusNotificationHub notificationHubDescriptionInstance = new ServiceBusNotificationHub();
result.NotificationHub = notificationHubDescriptionInstance;
XElement registrationTtlElement = notificationHubDescriptionElement.Element(XName.Get("RegistrationTtl", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (registrationTtlElement != null)
{
string registrationTtlInstance = registrationTtlElement.Value;
notificationHubDescriptionInstance.RegistrationTtl = registrationTtlInstance;
}
XElement authorizationRulesSequenceElement = notificationHubDescriptionElement.Element(XName.Get("AuthorizationRules", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (authorizationRulesSequenceElement != null)
{
foreach (XElement authorizationRulesElement in authorizationRulesSequenceElement.Elements(XName.Get("AuthorizationRule", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")))
{
ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
notificationHubDescriptionInstance.AuthorizationRules.Add(authorizationRuleInstance);
XElement claimTypeElement = authorizationRulesElement.Element(XName.Get("ClaimType", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (claimTypeElement != null)
{
string claimTypeInstance = claimTypeElement.Value;
authorizationRuleInstance.ClaimType = claimTypeInstance;
}
XElement claimValueElement = authorizationRulesElement.Element(XName.Get("ClaimValue", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (claimValueElement != null)
{
string claimValueInstance = claimValueElement.Value;
authorizationRuleInstance.ClaimValue = claimValueInstance;
}
XElement rightsSequenceElement = authorizationRulesElement.Element(XName.Get("Rights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (rightsSequenceElement != null)
{
foreach (XElement rightsElement in rightsSequenceElement.Elements(XName.Get("AccessRights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")))
{
authorizationRuleInstance.Rights.Add(((AccessRight)Enum.Parse(typeof(AccessRight), rightsElement.Value, true)));
}
}
XElement createdTimeElement = authorizationRulesElement.Element(XName.Get("CreatedTime", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (createdTimeElement != null)
{
DateTime createdTimeInstance = DateTime.Parse(createdTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
authorizationRuleInstance.CreatedTime = createdTimeInstance;
}
XElement keyNameElement = authorizationRulesElement.Element(XName.Get("KeyName", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (keyNameElement != null)
{
string keyNameInstance = keyNameElement.Value;
authorizationRuleInstance.KeyName = keyNameInstance;
}
XElement modifiedTimeElement = authorizationRulesElement.Element(XName.Get("ModifiedTime", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (modifiedTimeElement != null)
{
DateTime modifiedTimeInstance = DateTime.Parse(modifiedTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
authorizationRuleInstance.ModifiedTime = modifiedTimeInstance;
}
XElement primaryKeyElement = authorizationRulesElement.Element(XName.Get("PrimaryKey", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (primaryKeyElement != null)
{
string primaryKeyInstance = primaryKeyElement.Value;
authorizationRuleInstance.PrimaryKey = primaryKeyInstance;
}
XElement secondaryKeyElement = authorizationRulesElement.Element(XName.Get("SecondaryKey", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (secondaryKeyElement != null)
{
string secondaryKeyInstance = secondaryKeyElement.Value;
authorizationRuleInstance.SecondaryKey = secondaryKeyInstance;
}
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// Required. The notification hub name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The set of connection details for a service bus entity.
/// </returns>
public async Task<ServiceBusConnectionDetailsResponse> GetConnectionDetailsAsync(string namespaceName, string notificationHubName, CancellationToken cancellationToken)
{
// Validate
if (namespaceName == null)
{
throw new ArgumentNullException("namespaceName");
}
if (notificationHubName == null)
{
throw new ArgumentNullException("notificationHubName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("namespaceName", namespaceName);
tracingParameters.Add("notificationHubName", notificationHubName);
TracingAdapter.Enter(invocationId, this, "GetConnectionDetailsAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/servicebus/namespaces/";
url = url + Uri.EscapeDataString(namespaceName);
url = url + "/NotificationHubs/";
url = url + Uri.EscapeDataString(notificationHubName);
url = url + "/ConnectionDetails";
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("x-ms-version", "2013-08-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServiceBusConnectionDetailsResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServiceBusConnectionDetailsResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement feedElement = responseDoc.Element(XName.Get("feed", "http://www.w3.org/2005/Atom"));
if (feedElement != null)
{
if (feedElement != null)
{
foreach (XElement entriesElement in feedElement.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")))
{
ServiceBusConnectionDetail entryInstance = new ServiceBusConnectionDetail();
result.ConnectionDetails.Add(entryInstance);
XElement contentElement = entriesElement.Element(XName.Get("content", "http://www.w3.org/2005/Atom"));
if (contentElement != null)
{
XElement connectionDetailElement = contentElement.Element(XName.Get("ConnectionDetail", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (connectionDetailElement != null)
{
XElement keyNameElement = connectionDetailElement.Element(XName.Get("KeyName", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (keyNameElement != null)
{
string keyNameInstance = keyNameElement.Value;
entryInstance.KeyName = keyNameInstance;
}
XElement connectionStringElement = connectionDetailElement.Element(XName.Get("ConnectionString", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (connectionStringElement != null)
{
string connectionStringInstance = connectionStringElement.Value;
entryInstance.ConnectionString = connectionStringInstance;
}
XElement authorizationTypeElement = connectionDetailElement.Element(XName.Get("AuthorizationType", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (authorizationTypeElement != null)
{
string authorizationTypeInstance = authorizationTypeElement.Value;
entryInstance.AuthorizationType = authorizationTypeInstance;
}
XElement rightsSequenceElement = connectionDetailElement.Element(XName.Get("Rights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (rightsSequenceElement != null)
{
foreach (XElement rightsElement in rightsSequenceElement.Elements(XName.Get("AccessRights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")))
{
entryInstance.Rights.Add(((AccessRight)Enum.Parse(typeof(AccessRight), rightsElement.Value, true)));
}
}
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='namespaceName'>
/// Required. The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<ServiceBusNotificationHubsResponse> ListAsync(string namespaceName, CancellationToken cancellationToken)
{
// Validate
if (namespaceName == null)
{
throw new ArgumentNullException("namespaceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("namespaceName", namespaceName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/servicebus/namespaces/";
url = url + Uri.EscapeDataString(namespaceName);
url = url + "/NotificationHubs";
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("x-ms-version", "2013-08-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ServiceBusNotificationHubsResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServiceBusNotificationHubsResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement feedElement = responseDoc.Element(XName.Get("feed", "http://www.w3.org/2005/Atom"));
if (feedElement != null)
{
if (feedElement != null)
{
foreach (XElement entriesElement in feedElement.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")))
{
ServiceBusNotificationHub entryInstance = new ServiceBusNotificationHub();
result.NotificationHubs.Add(entryInstance);
XElement titleElement = entriesElement.Element(XName.Get("title", "http://www.w3.org/2005/Atom"));
if (titleElement != null)
{
string titleInstance = titleElement.Value;
entryInstance.Name = titleInstance;
}
XElement contentElement = entriesElement.Element(XName.Get("content", "http://www.w3.org/2005/Atom"));
if (contentElement != null)
{
XElement notificationHubDescriptionElement = contentElement.Element(XName.Get("NotificationHubDescription", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (notificationHubDescriptionElement != null)
{
XElement registrationTtlElement = notificationHubDescriptionElement.Element(XName.Get("RegistrationTtl", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (registrationTtlElement != null)
{
string registrationTtlInstance = registrationTtlElement.Value;
entryInstance.RegistrationTtl = registrationTtlInstance;
}
XElement authorizationRulesSequenceElement = notificationHubDescriptionElement.Element(XName.Get("AuthorizationRules", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (authorizationRulesSequenceElement != null)
{
foreach (XElement authorizationRulesElement in authorizationRulesSequenceElement.Elements(XName.Get("AuthorizationRule", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")))
{
ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
entryInstance.AuthorizationRules.Add(authorizationRuleInstance);
XElement claimTypeElement = authorizationRulesElement.Element(XName.Get("ClaimType", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (claimTypeElement != null)
{
string claimTypeInstance = claimTypeElement.Value;
authorizationRuleInstance.ClaimType = claimTypeInstance;
}
XElement claimValueElement = authorizationRulesElement.Element(XName.Get("ClaimValue", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (claimValueElement != null)
{
string claimValueInstance = claimValueElement.Value;
authorizationRuleInstance.ClaimValue = claimValueInstance;
}
XElement rightsSequenceElement = authorizationRulesElement.Element(XName.Get("Rights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (rightsSequenceElement != null)
{
foreach (XElement rightsElement in rightsSequenceElement.Elements(XName.Get("AccessRights", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect")))
{
authorizationRuleInstance.Rights.Add(((AccessRight)Enum.Parse(typeof(AccessRight), rightsElement.Value, true)));
}
}
XElement createdTimeElement = authorizationRulesElement.Element(XName.Get("CreatedTime", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (createdTimeElement != null)
{
DateTime createdTimeInstance = DateTime.Parse(createdTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
authorizationRuleInstance.CreatedTime = createdTimeInstance;
}
XElement keyNameElement = authorizationRulesElement.Element(XName.Get("KeyName", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (keyNameElement != null)
{
string keyNameInstance = keyNameElement.Value;
authorizationRuleInstance.KeyName = keyNameInstance;
}
XElement modifiedTimeElement = authorizationRulesElement.Element(XName.Get("ModifiedTime", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (modifiedTimeElement != null)
{
DateTime modifiedTimeInstance = DateTime.Parse(modifiedTimeElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime();
authorizationRuleInstance.ModifiedTime = modifiedTimeInstance;
}
XElement primaryKeyElement = authorizationRulesElement.Element(XName.Get("PrimaryKey", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (primaryKeyElement != null)
{
string primaryKeyInstance = primaryKeyElement.Value;
authorizationRuleInstance.PrimaryKey = primaryKeyInstance;
}
XElement secondaryKeyElement = authorizationRulesElement.Element(XName.Get("SecondaryKey", "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect"));
if (secondaryKeyElement != null)
{
string secondaryKeyInstance = secondaryKeyElement.Value;
authorizationRuleInstance.SecondaryKey = secondaryKeyInstance;
}
}
}
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
#region Apache Licensed
/*
Copyright 2013 Daniel Cazzulino
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Kzu.NuGetReferences.Properties
{
using System;
using System.Globalization;
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
static partial class ResourceNames
{
/// <summary>
/// Resource name for a localized string similar to:
/// "(Executing Command)"
/// </summary>
public const string ExecutingCommand = "ExecutingCommand";
/// <summary>
/// Resource name for a localized string similar to:
/// "Failed to load NuGet Package Manager. Please contact support."
/// </summary>
public const string FailedToLoadNuGetPackage = "FailedToLoadNuGetPackage";
/// <summary>
/// Resource name for a localized string similar to:
/// "Your currently installed version of NuGet Package Manager is version {installedVersion}, but the {productName} extension was tested with version {buildVersion}. Some functionality may not work as expected."
/// </summary>
public const string IncompatibleNuGet = "IncompatibleNuGet";
/// <summary>
/// Resource name for a localized string similar to:
/// "(Initializing NuGet Console)"
/// </summary>
public const string InitializingConsole = "InitializingConsole";
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class PackageInfo
{
/// <summary>
/// Resource name for a localized string similar to:
/// "General"
/// </summary>
public const string Category = "PackageInfo_Category";
/// <summary>
/// Resource name for a localized string similar to:
/// "NuGet Package"
/// </summary>
public const string DisplayName = "PackageInfo_DisplayName";
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Id
{
/// <summary>
/// Resource name for a localized string similar to:
/// "Package identifier."
/// </summary>
public const string Description = "PackageInfo_Id_Description";
/// <summary>
/// Resource name for a localized string similar to:
/// "Id"
/// </summary>
public const string DisplayName = "PackageInfo_Id_DisplayName";
}
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Version
{
/// <summary>
/// Resource name for a localized string similar to:
/// "Package version."
/// </summary>
public const string Description = "PackageInfo_Version_Description";
/// <summary>
/// Resource name for a localized string similar to:
/// "Version"
/// </summary>
public const string DisplayName = "PackageInfo_Version_DisplayName";
}
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Title
{
/// <summary>
/// Resource name for a localized string similar to:
/// "Package title."
/// </summary>
public const string Description = "PackageInfo_Title_Description";
/// <summary>
/// Resource name for a localized string similar to:
/// "Title"
/// </summary>
public const string DisplayName = "PackageInfo_Title_DisplayName";
}
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Authors
{
/// <summary>
/// Resource name for a localized string similar to:
/// "Package authors."
/// </summary>
public const string Description = "PackageInfo_Authors_Description";
/// <summary>
/// Resource name for a localized string similar to:
/// "Authors"
/// </summary>
public const string DisplayName = "PackageInfo_Authors_DisplayName";
}
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class InstallPath
{
/// <summary>
/// Resource name for a localized string similar to:
/// "Package installation location."
/// </summary>
public const string Description = "PackageInfo_InstallPath_Description";
/// <summary>
/// Resource name for a localized string similar to:
/// "Install Path"
/// </summary>
public const string DisplayName = "PackageInfo_InstallPath_DisplayName";
}
}
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Uninstall
{
/// <summary>
/// Resource name for a localized string similar to:
/// "Uninstall"
/// </summary>
public const string Text = "Uninstall_Text";
}
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Update
{
/// <summary>
/// Resource name for a localized string similar to:
/// "Update"
/// </summary>
public const string Text = "Update_Text";
}
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Package
{
/// <summary>
/// Resource name for a localized string similar to:
/// "Installing DevStore version {version} from {vsixPath}."
/// </summary>
public const string DevStoreInstalling = "Package_DevStoreInstalling";
/// <summary>
/// Resource name for a localized string similar to:
/// "DevStore is currently not installed."
/// </summary>
public const string DevStoreNotInstalled = "Package_DevStoreNotInstalled";
/// <summary>
/// Resource name for a localized string similar to:
/// "Installed DevStore version is {oldVersion}. Upgrading to {newVersion}."
/// </summary>
public const string DevStoreOldVersion = "Package_DevStoreOldVersion";
/// <summary>
/// Resource name for a localized string similar to:
/// "Latest version of DevStore will be activated on your next Visual Studio restart."
/// </summary>
public const string DevStoreRestartNeeded = "Package_DevStoreRestartNeeded";
/// <summary>
/// Resource name for a localized string similar to:
/// "Could not find DevStore installer at {vsixPath}. Please reinstall {product}."
/// </summary>
public const string DevStoreVsixNotFound = "Package_DevStoreVsixNotFound";
/// <summary>
/// Resource name for a localized string similar to:
/// "Verifying current version of DevStore"
/// </summary>
public const string VerifyingDevStore = "Package_VerifyingDevStore";
}
/// <summary>
/// Provides access to string resources.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("TextTemplate", "1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Reinstall
{
/// <summary>
/// Resource name for a localized string similar to:
/// "Reinstall"
/// </summary>
public const string Text = "Reinstall_Text";
}
}
}
| |
using Apache.NMS.Util;
using System;
using System.Collections.Generic;
using Lucene.Net.Documents;
using Lucene.Net.Search;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using NUnit.Framework;
using System.IO;
using BinaryDocValuesField = BinaryDocValuesField;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using NumericDocValuesField = NumericDocValuesField;
using SortedDocValuesField = SortedDocValuesField;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestDocValuesWithThreads : LuceneTestCase
{
[Test]
public virtual void Test()
{
Directory dir = NewDirectory();
IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
IList<long?> numbers = new List<long?>();
IList<BytesRef> binary = new List<BytesRef>();
IList<BytesRef> sorted = new List<BytesRef>();
int numDocs = AtLeast(100);
for (int i = 0; i < numDocs; i++)
{
Document d = new Document();
long number = Random().NextLong();
d.Add(new NumericDocValuesField("number", number));
BytesRef bytes = new BytesRef(TestUtil.RandomRealisticUnicodeString(Random()));
d.Add(new BinaryDocValuesField("bytes", bytes));
binary.Add(bytes);
bytes = new BytesRef(TestUtil.RandomRealisticUnicodeString(Random()));
d.Add(new SortedDocValuesField("sorted", bytes));
sorted.Add(bytes);
w.AddDocument(d);
numbers.Add(number);
}
w.ForceMerge(1);
IndexReader r = w.Reader;
w.Dispose();
Assert.AreEqual(1, r.Leaves.Count);
AtomicReader ar = (AtomicReader)r.Leaves[0].Reader;
int numThreads = TestUtil.NextInt(Random(), 2, 5);
IList<ThreadClass> threads = new List<ThreadClass>();
CountDownLatch startingGun = new CountDownLatch(1);
for (int t = 0; t < numThreads; t++)
{
Random threadRandom = new Random(Random().Next());
ThreadClass thread = new ThreadAnonymousInnerClassHelper(this, numbers, binary, sorted, numDocs, ar, startingGun, threadRandom);
thread.Start();
threads.Add(thread);
}
startingGun.countDown();
foreach (ThreadClass thread in threads)
{
thread.Join();
}
r.Dispose();
dir.Dispose();
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly TestDocValuesWithThreads OuterInstance;
private IList<long?> Numbers;
private IList<BytesRef> Binary;
private IList<BytesRef> Sorted;
private int NumDocs;
private AtomicReader Ar;
private CountDownLatch StartingGun;
private Random ThreadRandom;
public ThreadAnonymousInnerClassHelper(TestDocValuesWithThreads outerInstance, IList<long?> numbers, IList<BytesRef> binary, IList<BytesRef> sorted, int numDocs, AtomicReader ar, CountDownLatch startingGun, Random threadRandom)
{
this.OuterInstance = outerInstance;
this.Numbers = numbers;
this.Binary = binary;
this.Sorted = sorted;
this.NumDocs = numDocs;
this.Ar = ar;
this.StartingGun = startingGun;
this.ThreadRandom = threadRandom;
}
public override void Run()
{
try
{
//NumericDocValues ndv = ar.GetNumericDocValues("number");
FieldCache.Longs ndv = FieldCache.DEFAULT.GetLongs(Ar, "number", false);
//BinaryDocValues bdv = ar.GetBinaryDocValues("bytes");
BinaryDocValues bdv = FieldCache.DEFAULT.GetTerms(Ar, "bytes", false);
SortedDocValues sdv = FieldCache.DEFAULT.GetTermsIndex(Ar, "sorted");
StartingGun.@await();
int iters = AtLeast(1000);
BytesRef scratch = new BytesRef();
BytesRef scratch2 = new BytesRef();
for (int iter = 0; iter < iters; iter++)
{
int docID = ThreadRandom.Next(NumDocs);
switch (ThreadRandom.Next(6))
{
case 0:
Assert.AreEqual((long)(sbyte)Numbers[docID], FieldCache.DEFAULT.GetBytes(Ar, "number", false).Get(docID));
break;
case 1:
Assert.AreEqual((long)(short)Numbers[docID], FieldCache.DEFAULT.GetShorts(Ar, "number", false).Get(docID));
break;
case 2:
Assert.AreEqual((long)(int)Numbers[docID], FieldCache.DEFAULT.GetInts(Ar, "number", false).Get(docID));
break;
case 3:
Assert.AreEqual((long)Numbers[docID], FieldCache.DEFAULT.GetLongs(Ar, "number", false).Get(docID));
break;
case 4:
Assert.AreEqual(Number.IntBitsToFloat((int)Numbers[docID]), FieldCache.DEFAULT.GetFloats(Ar, "number", false).Get(docID), 0.0f);
break;
case 5:
Assert.AreEqual(BitConverter.Int64BitsToDouble((long)Numbers[docID]), FieldCache.DEFAULT.GetDoubles(Ar, "number", false).Get(docID), 0.0);
break;
}
bdv.Get(docID, scratch);
Assert.AreEqual(Binary[docID], scratch);
// Cannot share a single scratch against two "sources":
sdv.Get(docID, scratch2);
Assert.AreEqual(Sorted[docID], scratch2);
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
}
}
[Test]
public virtual void Test2()
{
Random random = Random();
int NUM_DOCS = AtLeast(100);
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random, dir);
bool allowDups = random.NextBoolean();
HashSet<string> seen = new HashSet<string>();
if (VERBOSE)
{
Console.WriteLine("TEST: NUM_DOCS=" + NUM_DOCS + " allowDups=" + allowDups);
}
int numDocs = 0;
IList<BytesRef> docValues = new List<BytesRef>();
// TODO: deletions
while (numDocs < NUM_DOCS)
{
string s;
if (random.NextBoolean())
{
s = TestUtil.RandomSimpleString(random);
}
else
{
s = TestUtil.RandomUnicodeString(random);
}
BytesRef br = new BytesRef(s);
if (!allowDups)
{
if (seen.Contains(s))
{
continue;
}
seen.Add(s);
}
if (VERBOSE)
{
Console.WriteLine(" " + numDocs + ": s=" + s);
}
Document doc = new Document();
doc.Add(new SortedDocValuesField("stringdv", br));
doc.Add(new NumericDocValuesField("id", numDocs));
docValues.Add(br);
writer.AddDocument(doc);
numDocs++;
if (random.Next(40) == 17)
{
// force flush
writer.Reader.Dispose();
}
}
writer.ForceMerge(1);
DirectoryReader r = writer.Reader;
writer.Dispose();
AtomicReader sr = GetOnlySegmentReader(r);
long END_TIME = Environment.TickCount + (TEST_NIGHTLY ? 30 : 1);
int NUM_THREADS = TestUtil.NextInt(Random(), 1, 10);
ThreadClass[] threads = new ThreadClass[NUM_THREADS];
for (int thread = 0; thread < NUM_THREADS; thread++)
{
threads[thread] = new ThreadAnonymousInnerClassHelper2(random, docValues, sr, END_TIME);
threads[thread].Start();
}
foreach (ThreadClass thread in threads)
{
thread.Join();
}
r.Dispose();
dir.Dispose();
}
private class ThreadAnonymousInnerClassHelper2 : ThreadClass
{
private Random Random;
private IList<BytesRef> DocValues;
private AtomicReader Sr;
private long END_TIME;
public ThreadAnonymousInnerClassHelper2(Random random, IList<BytesRef> docValues, AtomicReader sr, long END_TIME)
{
this.Random = random;
this.DocValues = docValues;
this.Sr = sr;
this.END_TIME = END_TIME;
}
public override void Run()
{
Random random = Random();
SortedDocValues stringDVDirect;
NumericDocValues docIDToID;
try
{
stringDVDirect = Sr.GetSortedDocValues("stringdv");
docIDToID = Sr.GetNumericDocValues("id");
Assert.IsNotNull(stringDVDirect);
}
catch (IOException ioe)
{
throw new Exception(ioe.Message, ioe);
}
while (Environment.TickCount < END_TIME)
{
SortedDocValues source;
source = stringDVDirect;
BytesRef scratch = new BytesRef();
for (int iter = 0; iter < 100; iter++)
{
int docID = random.Next(Sr.MaxDoc);
source.Get(docID, scratch);
Assert.AreEqual(DocValues[(int)docIDToID.Get(docID)], scratch);
}
}
}
}
}
}
| |
/*
* daap-sharp
* Copyright (C) 2005 James Willcox <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
namespace Daap {
public delegate void TrackHandler (object o, TrackArgs args);
public class TrackArgs : EventArgs {
private Track track;
public Track Track {
get { return track; }
}
public TrackArgs (Track track) {
this.track = track;
}
}
public delegate void PlaylistHandler (object o, PlaylistArgs args);
public class PlaylistArgs : EventArgs {
private Playlist pl;
public Playlist Playlist {
get { return pl; }
}
public PlaylistArgs (Playlist pl) {
this.pl = pl;
}
}
public class Database : ICloneable {
private const int ChunkLength = 8192;
private const string TrackQuery = "meta=dmap.itemid,dmap.itemname,dmap.itemkind,dmap.persistentid," +
"daap.songalbum,daap.songgrouping,daap.songartist,daap.songbitrate," +
"daap.songbeatsperminute,daap.songcomment,daap.songcodectype," +
"daap.songcodecsubtype,daap.songcompilation,daap.songcomposer," +
"daap.songdateadded,daap.songdatemodified,daap.songdisccount," +
"daap.songdiscnumber,daap.songdisabled,daap.songeqpreset," +
"daap.songformat,daap.songgenre,daap.songdescription," +
"daap.songsamplerate,daap.songsize,daap.songstarttime," +
"daap.songstoptime,daap.songtime,daap.songtrackcount," +
"daap.songtracknumber,daap.songuserrating,daap.songyear," +
"daap.songdatakind,daap.songdataurl,com.apple.itunes.norm-volume," +
"com.apple.itunes.itms-songid,com.apple.itunes.itms-artistid," +
"com.apple.itunes.itms-playlistid,com.apple.itunes.itms-composerid," +
"com.apple.itunes.itms-genreid";
private static int nextid = 1;
private Client client;
private int id;
private long persistentId;
private string name;
private List<Track> tracks = new List<Track> ();
private List<Playlist> playlists = new List<Playlist> ();
private Playlist basePlaylist = new Playlist ();
private int nextTrackId = 1;
public event TrackHandler TrackAdded;
public event TrackHandler TrackRemoved;
public event PlaylistHandler PlaylistAdded;
public event PlaylistHandler PlaylistRemoved;
public int Id {
get { return id; }
}
public string Name {
get { return name; }
set {
name = value;
basePlaylist.Name = value;
}
}
public IList<Track> Tracks {
get {
return new ReadOnlyCollection<Track> (tracks);
}
}
public int TrackCount {
get { return tracks.Count; }
}
public Track TrackAt(int index)
{
return tracks[index] as Track;
}
public IList<Playlist> Playlists {
get {
return new ReadOnlyCollection<Playlist> (playlists);
}
}
internal Client Client {
get { return client; }
}
private Database ()
{
this.id = nextid++;
}
public Database (string name) : this ()
{
this.Name = name;
}
internal Database (Client client, ContentNode dbNode) : this ()
{
this.client = client;
Parse (dbNode);
}
private void Parse (ContentNode dbNode) {
foreach (ContentNode item in (ContentNode[]) dbNode.Value) {
switch (item.Name) {
case "dmap.itemid":
id = (int) item.Value;
break;
case "dmap.persistentid":
persistentId = (long) item.Value;
break;
case "dmap.itemname":
name = (string) item.Value;
break;
default:
break;
}
}
}
public Track LookupTrackById (int id) {
foreach (Track track in tracks) {
if (track.Id == id)
return track;
}
return null;
}
public Playlist LookupPlaylistById (int id) {
if (id == basePlaylist.Id)
return basePlaylist;
foreach (Playlist pl in playlists) {
if (pl.Id == id)
return pl;
}
return null;
}
internal ContentNode ToTracksNode (string[] fields, int[] deletedIds) {
List <ContentNode> trackNodes = new List <ContentNode> ();
foreach (Track track in tracks) {
trackNodes.Add (track.ToNode (fields));
}
List <ContentNode> deletedNodes = null;
if (deletedIds.Length > 0) {
deletedNodes = new List <ContentNode> ();
foreach (int id in deletedIds) {
deletedNodes.Add (new ContentNode ("dmap.itemid", id));
}
}
List <ContentNode> children = new List <ContentNode> ();
children.Add (new ContentNode ("dmap.status", 200));
children.Add (new ContentNode ("dmap.updatetype", deletedNodes == null ? (byte) 0 : (byte) 1));
children.Add (new ContentNode ("dmap.specifiedtotalcount", tracks.Count));
children.Add (new ContentNode ("dmap.returnedcount", tracks.Count));
children.Add (new ContentNode ("dmap.listing", trackNodes));
if (deletedNodes != null) {
children.Add (new ContentNode ("dmap.deletedidlisting", deletedNodes));
}
return new ContentNode ("daap.databasesongs", children);
}
internal ContentNode ToPlaylistsNode () {
List <ContentNode> nodes = new List <ContentNode> ();
nodes.Add (basePlaylist.ToNode (true));
foreach (Playlist pl in playlists) {
nodes.Add (pl.ToNode (false));
}
return new ContentNode ("daap.databaseplaylists",
new ContentNode ("dmap.status", 200),
new ContentNode ("dmap.updatetype", (byte) 0),
new ContentNode ("dmap.specifiedtotalcount", nodes.Count),
new ContentNode ("dmap.returnedcount", nodes.Count),
new ContentNode ("dmap.listing", nodes));
}
internal ContentNode ToDatabaseNode () {
return new ContentNode ("dmap.listingitem",
new ContentNode ("dmap.itemid", id),
new ContentNode ("dmap.persistentid", (long) id),
new ContentNode ("dmap.itemname", name),
new ContentNode ("dmap.itemcount", tracks.Count),
new ContentNode ("dmap.containercount", playlists.Count + 1));
}
public void Clear () {
if (client != null)
throw new InvalidOperationException ("cannot clear client databases");
ClearPlaylists ();
ClearTracks ();
}
private void ClearPlaylists () {
foreach (Playlist pl in new List<Playlist> (playlists)) {
RemovePlaylist (pl);
}
}
private void ClearTracks () {
foreach (Track track in new List<Track> (tracks)) {
RemoveTrack (track);
}
}
private bool IsUpdateResponse (ContentNode node) {
return node.Name == "dmap.updateresponse";
}
private void RefreshPlaylists (string revquery) {
byte[] playlistsData;
try {
playlistsData = client.Fetcher.Fetch (String.Format ("/databases/{0}/containers", id), revquery);
} catch (WebException) {
return;
}
ContentNode playlistsNode = ContentParser.Parse (client.Bag, playlistsData);
if (IsUpdateResponse (playlistsNode))
return;
// handle playlist additions/changes
List <int> plids = new List <int> ();
foreach (ContentNode playlistNode in (ContentNode[]) playlistsNode.GetChild ("dmap.listing").Value) {
Playlist pl = Playlist.FromNode (playlistNode);
if (pl != null) {
plids.Add (pl.Id);
Playlist existing = LookupPlaylistById (pl.Id);
if (existing == null) {
AddPlaylist (pl);
} else {
existing.Update (pl);
}
}
}
// delete playlists that no longer exist
foreach (Playlist pl in new List<Playlist> (playlists)) {
if (!plids.Contains (pl.Id)) {
RemovePlaylist (pl);
}
}
plids = null;
// add/remove tracks in the playlists
foreach (Playlist pl in playlists) {
byte [] playlistTracksData = client.Fetcher.Fetch (String.Format (
"/databases/{0}/containers/{1}/items", id, pl.Id), String.Format ("meta=dmap.itemid,dmap.containeritemid&{0}", revquery)
);
ContentNode playlistTracksNode = ContentParser.Parse (client.Bag, playlistTracksData);
if (IsUpdateResponse (playlistTracksNode))
return;
if ((byte) playlistTracksNode.GetChild ("dmap.updatetype").Value == 1) {
// handle playlist track deletions
ContentNode deleteList = playlistTracksNode.GetChild ("dmap.deletedidlisting");
if (deleteList != null) {
foreach (ContentNode deleted in (ContentNode[]) deleteList.Value) {
int index = pl.LookupIndexByContainerId ((int) deleted.Value);
if (index < 0)
continue;
pl.RemoveAt (index);
}
}
}
// add new tracks, or reorder existing ones
int plindex = 0;
foreach (ContentNode plTrackNode in (ContentNode[]) playlistTracksNode.GetChild ("dmap.listing").Value) {
Track pltrack = null;
int containerId = 0;
Track.FromPlaylistNode (this, plTrackNode, out pltrack, out containerId);
if (pl[plindex] != null && pl.GetContainerId (plindex) != containerId) {
pl.RemoveAt (plindex);
pl.InsertTrack (plindex, pltrack, containerId);
} else if (pl[plindex] == null) {
pl.InsertTrack (plindex, pltrack, containerId);
}
plindex++;
}
}
}
private void RefreshTracks (string revquery) {
byte[] tracksData = client.Fetcher.Fetch (String.Format ("/databases/{0}/items", id),
TrackQuery + "&" + revquery);
ContentNode tracksNode = ContentParser.Parse (client.Bag, tracksData);
if (IsUpdateResponse (tracksNode))
return;
// handle track additions/changes
foreach (ContentNode trackNode in (ContentNode[]) tracksNode.GetChild ("dmap.listing").Value) {
Track track = Track.FromNode (trackNode);
Track existing = LookupTrackById (track.Id);
if (existing == null)
AddTrack (track);
else
existing.Update (track);
}
if ((byte) tracksNode.GetChild ("dmap.updatetype").Value == 1) {
// handle track deletions
ContentNode deleteList = tracksNode.GetChild ("dmap.deletedidlisting");
if (deleteList != null) {
foreach (ContentNode deleted in (ContentNode[]) deleteList.Value) {
Track track = LookupTrackById ((int) deleted.Value);
if (track != null)
RemoveTrack (track);
}
}
}
}
internal void Refresh (int newrev) {
if (client == null)
throw new InvalidOperationException ("cannot refresh server databases");
string revquery = null;
if (client.Revision != Client.InitialRevision)
revquery = String.Format ("revision-number={0}&delta={1}", newrev, newrev - client.Revision);
RefreshTracks (revquery);
RefreshPlaylists (revquery);
}
private HttpWebResponse FetchTrack (int track_id, string format, long offset)
{
return client.Fetcher.FetchFile (String.Format ("/databases/{0}/items/{1}.{2}", id, track_id, format), offset);
}
public Stream StreamTrack (Track track, out long length)
{
return StreamTrack (track, -1, out length);
}
public Stream StreamTrack (Track track, long offset, out long length)
{
return StreamTrack (track.Id, track.Format, offset, out length);
}
public Stream StreamTrack (int track_id, string track_format, out long length)
{
return StreamTrack (track_id, track_format, -1, out length);
}
public Stream StreamTrack (int track_id, string track_format, long offset, out long length)
{
HttpWebResponse response = FetchTrack (track_id, track_format, offset);
length = response.ContentLength;
return response.GetResponseStream ();
}
public IEnumerable<double> DownloadTrack (int track_id, string track_format, string dest) {
BinaryWriter writer = new BinaryWriter (File.Open (dest, FileMode.Create));
try {
long len, pos = 0, i = 0;
using (BinaryReader reader = new BinaryReader (StreamTrack (track_id, track_format, out len))) {
int count = 0;
byte [] buf = new byte[ChunkLength];
do {
count = reader.Read (buf, 0, ChunkLength);
pos += count;
writer.Write (buf, 0, count);
// Roughly every 40KB yield an updated percent-done double
if (i++ % 5 == 0) {
yield return (double)pos / (double)len;
}
} while (count != 0);
}
} finally {
writer.Close ();
}
}
public void AddTrack (Track track) {
if (track.Id == 0)
track.SetId (nextTrackId++);
tracks.Add (track);
basePlaylist.AddTrack (track);
if (TrackAdded != null)
TrackAdded (this, new TrackArgs (track));
}
public void RemoveTrack (Track track) {
tracks.Remove (track);
basePlaylist.RemoveTrack (track);
foreach (Playlist pl in playlists) {
pl.RemoveTrack (track);
}
if (TrackRemoved != null)
TrackRemoved (this, new TrackArgs (track));
}
public void AddPlaylist (Playlist pl) {
playlists.Add (pl);
if (PlaylistAdded != null)
PlaylistAdded (this, new PlaylistArgs (pl));
}
public void RemovePlaylist (Playlist pl) {
playlists.Remove (pl);
if (PlaylistRemoved != null)
PlaylistRemoved (this, new PlaylistArgs (pl));
}
private Playlist ClonePlaylist (Database db, Playlist pl) {
Playlist clonePl = new Playlist (pl.Name);
clonePl.Id = pl.Id;
IList<Track> pltracks = pl.Tracks;
for (int i = 0; i < pltracks.Count; i++) {
clonePl.AddTrack (db.LookupTrackById (pltracks[i].Id), pl.GetContainerId (i));
}
return clonePl;
}
public object Clone () {
Database db = new Database (this.name);
db.id = id;
db.persistentId = persistentId;
List<Track> cloneTracks = new List<Track> ();
foreach (Track track in tracks) {
cloneTracks.Add ((Track) track.Clone ());
}
db.tracks = cloneTracks;
List<Playlist> clonePlaylists = new List<Playlist> ();
foreach (Playlist pl in playlists) {
clonePlaylists.Add (ClonePlaylist (db, pl));
}
db.playlists = clonePlaylists;
db.basePlaylist = ClonePlaylist (db, basePlaylist);
return db;
}
}
}
| |
// 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.ServiceBus
{
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>
/// TopicsOperations operations.
/// </summary>
public partial interface ITopicsOperations
{
/// <summary>
/// Lists all the topics in a namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<TopicResource>>> ListAllWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates a topic in the specified namespace
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Topic Resource.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<TopicResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, TopicCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a topic from the specified namespace and resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The topics name.
/// </param>
/// <param name='topicName'>
/// The topics name.
/// </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 namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the description for the specified topic
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<TopicResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorization rules for a topic.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The topic name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates an authorizatioRule for the specified topic.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='authorizationRuleName'>
/// Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns the specified authorizationRule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a topic authorizationRule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='authorizationRuleName'>
/// AuthorizationRule Name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Primary and Secondary ConnectionStrings to the topic
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Regenerates Primary or Secondary ConnectionStrings to the topic
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate Auth Rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string authorizationRuleName, RegenerateKeysParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists all the topics in a namespace.
/// </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<TopicResource>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Authorization rules for a topic.
/// </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<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
//
// 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.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.TrafficManager;
using Microsoft.Azure.Management.TrafficManager.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.TrafficManager
{
/// <summary>
/// Operations for managing Traffic Manager endpoints.
/// </summary>
internal partial class EndpointOperations : IServiceOperations<TrafficManagerManagementClient>, IEndpointOperations
{
/// <summary>
/// Initializes a new instance of the EndpointOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal EndpointOperations(TrafficManagerManagementClient client)
{
this._client = client;
}
private TrafficManagerManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.TrafficManager.TrafficManagerManagementClient.
/// </summary>
public TrafficManagerManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the Traffic
/// Manager endpoint to be created or updated.
/// </param>
/// <param name='profileName'>
/// Required. The name of the Traffic Manager endpoint to be created or
/// updated.
/// </param>
/// <param name='endpointType'>
/// Required. The type of the Traffic Manager endpoint to be created or
/// updated.
/// </param>
/// <param name='endpointName'>
/// Required. The name of the Traffic Manager endpoint to be created or
/// updated.
/// </param>
/// <param name='parameters'>
/// Required. The Traffic Manager endpoint parameters supplied to the
/// CreateOrUpdate operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response to a Traffic Manager endpoint 'CreateOrUpdate'
/// operation.
/// </returns>
public async Task<EndpointCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, EndpointCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (profileName == null)
{
throw new ArgumentNullException("profileName");
}
if (endpointType == null)
{
throw new ArgumentNullException("endpointType");
}
if (endpointName == null)
{
throw new ArgumentNullException("endpointName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Endpoint == null)
{
throw new ArgumentNullException("parameters.Endpoint");
}
// 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("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", 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/";
url = url + "Microsoft.Network";
url = url + "/trafficmanagerprofiles/";
url = url + Uri.EscapeDataString(profileName);
url = url + "/";
url = url + Uri.EscapeDataString(endpointType);
url = url + "/";
url = url + Uri.EscapeDataString(endpointName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-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.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject endpointCreateOrUpdateParametersValue = new JObject();
requestDoc = endpointCreateOrUpdateParametersValue;
if (parameters.Endpoint.Id != null)
{
endpointCreateOrUpdateParametersValue["id"] = parameters.Endpoint.Id;
}
if (parameters.Endpoint.Name != null)
{
endpointCreateOrUpdateParametersValue["name"] = parameters.Endpoint.Name;
}
if (parameters.Endpoint.Type != null)
{
endpointCreateOrUpdateParametersValue["type"] = parameters.Endpoint.Type;
}
if (parameters.Endpoint.Properties != null)
{
JObject propertiesValue = new JObject();
endpointCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Endpoint.Properties.TargetResourceId != null)
{
propertiesValue["targetResourceId"] = parameters.Endpoint.Properties.TargetResourceId;
}
if (parameters.Endpoint.Properties.Target != null)
{
propertiesValue["target"] = parameters.Endpoint.Properties.Target;
}
if (parameters.Endpoint.Properties.EndpointStatus != null)
{
propertiesValue["endpointStatus"] = parameters.Endpoint.Properties.EndpointStatus;
}
if (parameters.Endpoint.Properties.Weight != null)
{
propertiesValue["weight"] = parameters.Endpoint.Properties.Weight.Value;
}
if (parameters.Endpoint.Properties.Priority != null)
{
propertiesValue["priority"] = parameters.Endpoint.Properties.Priority.Value;
}
if (parameters.Endpoint.Properties.EndpointLocation != null)
{
propertiesValue["endpointLocation"] = parameters.Endpoint.Properties.EndpointLocation;
}
if (parameters.Endpoint.Properties.EndpointMonitorStatus != null)
{
propertiesValue["endpointMonitorStatus"] = parameters.Endpoint.Properties.EndpointMonitorStatus;
}
if (parameters.Endpoint.Properties.MinChildEndpoints != null)
{
propertiesValue["minChildEndpoints"] = parameters.Endpoint.Properties.MinChildEndpoints.Value;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// 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.BadRequest)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EndpointCreateOrUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EndpointCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Endpoint endpointInstance = new Endpoint();
result.Endpoint = endpointInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
endpointInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
endpointInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
endpointInstance.Type = typeInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
EndpointProperties propertiesInstance = new EndpointProperties();
endpointInstance.Properties = propertiesInstance;
JToken targetResourceIdValue = propertiesValue2["targetResourceId"];
if (targetResourceIdValue != null && targetResourceIdValue.Type != JTokenType.Null)
{
string targetResourceIdInstance = ((string)targetResourceIdValue);
propertiesInstance.TargetResourceId = targetResourceIdInstance;
}
JToken targetValue = propertiesValue2["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
propertiesInstance.Target = targetInstance;
}
JToken endpointStatusValue = propertiesValue2["endpointStatus"];
if (endpointStatusValue != null && endpointStatusValue.Type != JTokenType.Null)
{
string endpointStatusInstance = ((string)endpointStatusValue);
propertiesInstance.EndpointStatus = endpointStatusInstance;
}
JToken weightValue = propertiesValue2["weight"];
if (weightValue != null && weightValue.Type != JTokenType.Null)
{
uint weightInstance = ((uint)weightValue);
propertiesInstance.Weight = weightInstance;
}
JToken priorityValue = propertiesValue2["priority"];
if (priorityValue != null && priorityValue.Type != JTokenType.Null)
{
uint priorityInstance = ((uint)priorityValue);
propertiesInstance.Priority = priorityInstance;
}
JToken endpointLocationValue = propertiesValue2["endpointLocation"];
if (endpointLocationValue != null && endpointLocationValue.Type != JTokenType.Null)
{
string endpointLocationInstance = ((string)endpointLocationValue);
propertiesInstance.EndpointLocation = endpointLocationInstance;
}
JToken endpointMonitorStatusValue = propertiesValue2["endpointMonitorStatus"];
if (endpointMonitorStatusValue != null && endpointMonitorStatusValue.Type != JTokenType.Null)
{
string endpointMonitorStatusInstance = ((string)endpointMonitorStatusValue);
propertiesInstance.EndpointMonitorStatus = endpointMonitorStatusInstance;
}
JToken minChildEndpointsValue = propertiesValue2["minChildEndpoints"];
if (minChildEndpointsValue != null && minChildEndpointsValue.Type != JTokenType.Null)
{
uint minChildEndpointsInstance = ((uint)minChildEndpointsValue);
propertiesInstance.MinChildEndpoints = minChildEndpointsInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the Traffic
/// Manager endpoint to be deleted.
/// </param>
/// <param name='profileName'>
/// Required. The name of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointType'>
/// Required. The type of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointName'>
/// Required. The name of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (profileName == null)
{
throw new ArgumentNullException("profileName");
}
if (endpointType == null)
{
throw new ArgumentNullException("endpointType");
}
if (endpointName == null)
{
throw new ArgumentNullException("endpointName");
}
// 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("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", 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/";
url = url + "Microsoft.Network";
url = url + "/trafficmanagerprofiles/";
url = url + Uri.EscapeDataString(profileName);
url = url + "/";
url = url + Uri.EscapeDataString(endpointType);
url = url + "/";
url = url + Uri.EscapeDataString(endpointName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-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.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// 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.BadRequest)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the Traffic
/// Manager endpoint.
/// </param>
/// <param name='profileName'>
/// Required. The name of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointType'>
/// Required. The type of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointName'>
/// Required. The name of the Traffic Manager endpoint.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response to a Traffic Manager endpoint 'Get' operation.
/// </returns>
public async Task<EndpointGetResponse> GetAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (profileName == null)
{
throw new ArgumentNullException("profileName");
}
if (endpointType == null)
{
throw new ArgumentNullException("endpointType");
}
if (endpointName == null)
{
throw new ArgumentNullException("endpointName");
}
// 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("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
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/";
url = url + "Microsoft.Network";
url = url + "/trafficmanagerprofiles/";
url = url + Uri.EscapeDataString(profileName);
url = url + "/";
url = url + Uri.EscapeDataString(endpointType);
url = url + "/";
url = url + Uri.EscapeDataString(endpointName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-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
// 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.BadRequest)
{
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
EndpointGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EndpointGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Endpoint endpointInstance = new Endpoint();
result.Endpoint = endpointInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
endpointInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
endpointInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
endpointInstance.Type = typeInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
EndpointProperties propertiesInstance = new EndpointProperties();
endpointInstance.Properties = propertiesInstance;
JToken targetResourceIdValue = propertiesValue["targetResourceId"];
if (targetResourceIdValue != null && targetResourceIdValue.Type != JTokenType.Null)
{
string targetResourceIdInstance = ((string)targetResourceIdValue);
propertiesInstance.TargetResourceId = targetResourceIdInstance;
}
JToken targetValue = propertiesValue["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
propertiesInstance.Target = targetInstance;
}
JToken endpointStatusValue = propertiesValue["endpointStatus"];
if (endpointStatusValue != null && endpointStatusValue.Type != JTokenType.Null)
{
string endpointStatusInstance = ((string)endpointStatusValue);
propertiesInstance.EndpointStatus = endpointStatusInstance;
}
JToken weightValue = propertiesValue["weight"];
if (weightValue != null && weightValue.Type != JTokenType.Null)
{
uint weightInstance = ((uint)weightValue);
propertiesInstance.Weight = weightInstance;
}
JToken priorityValue = propertiesValue["priority"];
if (priorityValue != null && priorityValue.Type != JTokenType.Null)
{
uint priorityInstance = ((uint)priorityValue);
propertiesInstance.Priority = priorityInstance;
}
JToken endpointLocationValue = propertiesValue["endpointLocation"];
if (endpointLocationValue != null && endpointLocationValue.Type != JTokenType.Null)
{
string endpointLocationInstance = ((string)endpointLocationValue);
propertiesInstance.EndpointLocation = endpointLocationInstance;
}
JToken endpointMonitorStatusValue = propertiesValue["endpointMonitorStatus"];
if (endpointMonitorStatusValue != null && endpointMonitorStatusValue.Type != JTokenType.Null)
{
string endpointMonitorStatusInstance = ((string)endpointMonitorStatusValue);
propertiesInstance.EndpointMonitorStatus = endpointMonitorStatusInstance;
}
JToken minChildEndpointsValue = propertiesValue["minChildEndpoints"];
if (minChildEndpointsValue != null && minChildEndpointsValue.Type != JTokenType.Null)
{
uint minChildEndpointsInstance = ((uint)minChildEndpointsValue);
propertiesInstance.MinChildEndpoints = minChildEndpointsInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group containing the Traffic
/// Manager endpoint to be created or updated.
/// </param>
/// <param name='profileName'>
/// Required. The name of the Traffic Manager endpoint to be created or
/// updated.
/// </param>
/// <param name='endpointType'>
/// Required. The type of the Traffic Manager endpoint to be created or
/// updated.
/// </param>
/// <param name='endpointName'>
/// Required. The name of the Traffic Manager endpoint to be created or
/// updated.
/// </param>
/// <param name='parameters'>
/// Required. The Traffic Manager endpoint parameters supplied to the
/// Update operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response to a Traffic Manager endpoint 'CreateOrUpdate'
/// operation.
/// </returns>
public async Task<EndpointUpdateResponse> UpdateAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, EndpointUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (profileName == null)
{
throw new ArgumentNullException("profileName");
}
if (endpointType == null)
{
throw new ArgumentNullException("endpointType");
}
if (endpointName == null)
{
throw new ArgumentNullException("endpointName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Endpoint == null)
{
throw new ArgumentNullException("parameters.Endpoint");
}
// 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("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", 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/";
url = url + "Microsoft.Network";
url = url + "/trafficmanagerprofiles/";
url = url + Uri.EscapeDataString(profileName);
url = url + "/";
url = url + Uri.EscapeDataString(endpointType);
url = url + "/";
url = url + Uri.EscapeDataString(endpointName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-11-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 = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject endpointUpdateParametersValue = new JObject();
requestDoc = endpointUpdateParametersValue;
if (parameters.Endpoint.Id != null)
{
endpointUpdateParametersValue["id"] = parameters.Endpoint.Id;
}
if (parameters.Endpoint.Name != null)
{
endpointUpdateParametersValue["name"] = parameters.Endpoint.Name;
}
if (parameters.Endpoint.Type != null)
{
endpointUpdateParametersValue["type"] = parameters.Endpoint.Type;
}
if (parameters.Endpoint.Properties != null)
{
JObject propertiesValue = new JObject();
endpointUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Endpoint.Properties.TargetResourceId != null)
{
propertiesValue["targetResourceId"] = parameters.Endpoint.Properties.TargetResourceId;
}
if (parameters.Endpoint.Properties.Target != null)
{
propertiesValue["target"] = parameters.Endpoint.Properties.Target;
}
if (parameters.Endpoint.Properties.EndpointStatus != null)
{
propertiesValue["endpointStatus"] = parameters.Endpoint.Properties.EndpointStatus;
}
if (parameters.Endpoint.Properties.Weight != null)
{
propertiesValue["weight"] = parameters.Endpoint.Properties.Weight.Value;
}
if (parameters.Endpoint.Properties.Priority != null)
{
propertiesValue["priority"] = parameters.Endpoint.Properties.Priority.Value;
}
if (parameters.Endpoint.Properties.EndpointLocation != null)
{
propertiesValue["endpointLocation"] = parameters.Endpoint.Properties.EndpointLocation;
}
if (parameters.Endpoint.Properties.EndpointMonitorStatus != null)
{
propertiesValue["endpointMonitorStatus"] = parameters.Endpoint.Properties.EndpointMonitorStatus;
}
if (parameters.Endpoint.Properties.MinChildEndpoints != null)
{
propertiesValue["minChildEndpoints"] = parameters.Endpoint.Properties.MinChildEndpoints.Value;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// 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.BadRequest)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
EndpointUpdateResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EndpointUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Endpoint endpointInstance = new Endpoint();
result.Endpoint = endpointInstance;
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
endpointInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
endpointInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
endpointInstance.Type = typeInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
EndpointProperties propertiesInstance = new EndpointProperties();
endpointInstance.Properties = propertiesInstance;
JToken targetResourceIdValue = propertiesValue2["targetResourceId"];
if (targetResourceIdValue != null && targetResourceIdValue.Type != JTokenType.Null)
{
string targetResourceIdInstance = ((string)targetResourceIdValue);
propertiesInstance.TargetResourceId = targetResourceIdInstance;
}
JToken targetValue = propertiesValue2["target"];
if (targetValue != null && targetValue.Type != JTokenType.Null)
{
string targetInstance = ((string)targetValue);
propertiesInstance.Target = targetInstance;
}
JToken endpointStatusValue = propertiesValue2["endpointStatus"];
if (endpointStatusValue != null && endpointStatusValue.Type != JTokenType.Null)
{
string endpointStatusInstance = ((string)endpointStatusValue);
propertiesInstance.EndpointStatus = endpointStatusInstance;
}
JToken weightValue = propertiesValue2["weight"];
if (weightValue != null && weightValue.Type != JTokenType.Null)
{
uint weightInstance = ((uint)weightValue);
propertiesInstance.Weight = weightInstance;
}
JToken priorityValue = propertiesValue2["priority"];
if (priorityValue != null && priorityValue.Type != JTokenType.Null)
{
uint priorityInstance = ((uint)priorityValue);
propertiesInstance.Priority = priorityInstance;
}
JToken endpointLocationValue = propertiesValue2["endpointLocation"];
if (endpointLocationValue != null && endpointLocationValue.Type != JTokenType.Null)
{
string endpointLocationInstance = ((string)endpointLocationValue);
propertiesInstance.EndpointLocation = endpointLocationInstance;
}
JToken endpointMonitorStatusValue = propertiesValue2["endpointMonitorStatus"];
if (endpointMonitorStatusValue != null && endpointMonitorStatusValue.Type != JTokenType.Null)
{
string endpointMonitorStatusInstance = ((string)endpointMonitorStatusValue);
propertiesInstance.EndpointMonitorStatus = endpointMonitorStatusInstance;
}
JToken minChildEndpointsValue = propertiesValue2["minChildEndpoints"];
if (minChildEndpointsValue != null && minChildEndpointsValue.Type != JTokenType.Null)
{
uint minChildEndpointsInstance = ((uint)minChildEndpointsValue);
propertiesInstance.MinChildEndpoints = minChildEndpointsInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data{
/// <summary>
/// Strongly-typed collection for the VOrganisationStation class.
/// </summary>
[Serializable]
public partial class VOrganisationStationCollection : ReadOnlyList<VOrganisationStation, VOrganisationStationCollection>
{
public VOrganisationStationCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vOrganisationStation view.
/// </summary>
[Serializable]
public partial class VOrganisationStation : ReadOnlyRecord<VOrganisationStation>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("vOrganisationStation", TableType.View, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "ID";
colvarId.DataType = DbType.Guid;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = false;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = false;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarOrganisationID = new TableSchema.TableColumn(schema);
colvarOrganisationID.ColumnName = "OrganisationID";
colvarOrganisationID.DataType = DbType.Guid;
colvarOrganisationID.MaxLength = 0;
colvarOrganisationID.AutoIncrement = false;
colvarOrganisationID.IsNullable = false;
colvarOrganisationID.IsPrimaryKey = false;
colvarOrganisationID.IsForeignKey = false;
colvarOrganisationID.IsReadOnly = false;
schema.Columns.Add(colvarOrganisationID);
TableSchema.TableColumn colvarStationID = new TableSchema.TableColumn(schema);
colvarStationID.ColumnName = "StationID";
colvarStationID.DataType = DbType.Guid;
colvarStationID.MaxLength = 0;
colvarStationID.AutoIncrement = false;
colvarStationID.IsNullable = false;
colvarStationID.IsPrimaryKey = false;
colvarStationID.IsForeignKey = false;
colvarStationID.IsReadOnly = false;
schema.Columns.Add(colvarStationID);
TableSchema.TableColumn colvarOrganisationRoleID = new TableSchema.TableColumn(schema);
colvarOrganisationRoleID.ColumnName = "OrganisationRoleID";
colvarOrganisationRoleID.DataType = DbType.Guid;
colvarOrganisationRoleID.MaxLength = 0;
colvarOrganisationRoleID.AutoIncrement = false;
colvarOrganisationRoleID.IsNullable = false;
colvarOrganisationRoleID.IsPrimaryKey = false;
colvarOrganisationRoleID.IsForeignKey = false;
colvarOrganisationRoleID.IsReadOnly = false;
schema.Columns.Add(colvarOrganisationRoleID);
TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema);
colvarStartDate.ColumnName = "StartDate";
colvarStartDate.DataType = DbType.Date;
colvarStartDate.MaxLength = 0;
colvarStartDate.AutoIncrement = false;
colvarStartDate.IsNullable = true;
colvarStartDate.IsPrimaryKey = false;
colvarStartDate.IsForeignKey = false;
colvarStartDate.IsReadOnly = false;
schema.Columns.Add(colvarStartDate);
TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema);
colvarEndDate.ColumnName = "EndDate";
colvarEndDate.DataType = DbType.Date;
colvarEndDate.MaxLength = 0;
colvarEndDate.AutoIncrement = false;
colvarEndDate.IsNullable = true;
colvarEndDate.IsPrimaryKey = false;
colvarEndDate.IsForeignKey = false;
colvarEndDate.IsReadOnly = false;
schema.Columns.Add(colvarEndDate);
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = false;
colvarUserId.IsReadOnly = false;
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema);
colvarAddedAt.ColumnName = "AddedAt";
colvarAddedAt.DataType = DbType.DateTime;
colvarAddedAt.MaxLength = 0;
colvarAddedAt.AutoIncrement = false;
colvarAddedAt.IsNullable = true;
colvarAddedAt.IsPrimaryKey = false;
colvarAddedAt.IsForeignKey = false;
colvarAddedAt.IsReadOnly = false;
schema.Columns.Add(colvarAddedAt);
TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema);
colvarUpdatedAt.ColumnName = "UpdatedAt";
colvarUpdatedAt.DataType = DbType.DateTime;
colvarUpdatedAt.MaxLength = 0;
colvarUpdatedAt.AutoIncrement = false;
colvarUpdatedAt.IsNullable = true;
colvarUpdatedAt.IsPrimaryKey = false;
colvarUpdatedAt.IsForeignKey = false;
colvarUpdatedAt.IsReadOnly = false;
schema.Columns.Add(colvarUpdatedAt);
TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema);
colvarRowVersion.ColumnName = "RowVersion";
colvarRowVersion.DataType = DbType.Binary;
colvarRowVersion.MaxLength = 0;
colvarRowVersion.AutoIncrement = false;
colvarRowVersion.IsNullable = false;
colvarRowVersion.IsPrimaryKey = false;
colvarRowVersion.IsForeignKey = false;
colvarRowVersion.IsReadOnly = true;
schema.Columns.Add(colvarRowVersion);
TableSchema.TableColumn colvarOrganisationCode = new TableSchema.TableColumn(schema);
colvarOrganisationCode.ColumnName = "OrganisationCode";
colvarOrganisationCode.DataType = DbType.AnsiString;
colvarOrganisationCode.MaxLength = 50;
colvarOrganisationCode.AutoIncrement = false;
colvarOrganisationCode.IsNullable = false;
colvarOrganisationCode.IsPrimaryKey = false;
colvarOrganisationCode.IsForeignKey = false;
colvarOrganisationCode.IsReadOnly = false;
schema.Columns.Add(colvarOrganisationCode);
TableSchema.TableColumn colvarOrganisationName = new TableSchema.TableColumn(schema);
colvarOrganisationName.ColumnName = "OrganisationName";
colvarOrganisationName.DataType = DbType.AnsiString;
colvarOrganisationName.MaxLength = 150;
colvarOrganisationName.AutoIncrement = false;
colvarOrganisationName.IsNullable = false;
colvarOrganisationName.IsPrimaryKey = false;
colvarOrganisationName.IsForeignKey = false;
colvarOrganisationName.IsReadOnly = false;
schema.Columns.Add(colvarOrganisationName);
TableSchema.TableColumn colvarStationCode = new TableSchema.TableColumn(schema);
colvarStationCode.ColumnName = "StationCode";
colvarStationCode.DataType = DbType.AnsiString;
colvarStationCode.MaxLength = 50;
colvarStationCode.AutoIncrement = false;
colvarStationCode.IsNullable = false;
colvarStationCode.IsPrimaryKey = false;
colvarStationCode.IsForeignKey = false;
colvarStationCode.IsReadOnly = false;
schema.Columns.Add(colvarStationCode);
TableSchema.TableColumn colvarStationName = new TableSchema.TableColumn(schema);
colvarStationName.ColumnName = "StationName";
colvarStationName.DataType = DbType.AnsiString;
colvarStationName.MaxLength = 150;
colvarStationName.AutoIncrement = false;
colvarStationName.IsNullable = false;
colvarStationName.IsPrimaryKey = false;
colvarStationName.IsForeignKey = false;
colvarStationName.IsReadOnly = false;
schema.Columns.Add(colvarStationName);
TableSchema.TableColumn colvarOrganisationRoleCode = new TableSchema.TableColumn(schema);
colvarOrganisationRoleCode.ColumnName = "OrganisationRoleCode";
colvarOrganisationRoleCode.DataType = DbType.AnsiString;
colvarOrganisationRoleCode.MaxLength = 50;
colvarOrganisationRoleCode.AutoIncrement = false;
colvarOrganisationRoleCode.IsNullable = false;
colvarOrganisationRoleCode.IsPrimaryKey = false;
colvarOrganisationRoleCode.IsForeignKey = false;
colvarOrganisationRoleCode.IsReadOnly = false;
schema.Columns.Add(colvarOrganisationRoleCode);
TableSchema.TableColumn colvarOrganisationRoleName = new TableSchema.TableColumn(schema);
colvarOrganisationRoleName.ColumnName = "OrganisationRoleName";
colvarOrganisationRoleName.DataType = DbType.AnsiString;
colvarOrganisationRoleName.MaxLength = 150;
colvarOrganisationRoleName.AutoIncrement = false;
colvarOrganisationRoleName.IsNullable = false;
colvarOrganisationRoleName.IsPrimaryKey = false;
colvarOrganisationRoleName.IsForeignKey = false;
colvarOrganisationRoleName.IsReadOnly = false;
schema.Columns.Add(colvarOrganisationRoleName);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("vOrganisationStation",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VOrganisationStation()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VOrganisationStation(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VOrganisationStation(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VOrganisationStation(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public Guid Id
{
get
{
return GetColumnValue<Guid>("ID");
}
set
{
SetColumnValue("ID", value);
}
}
[XmlAttribute("OrganisationID")]
[Bindable(true)]
public Guid OrganisationID
{
get
{
return GetColumnValue<Guid>("OrganisationID");
}
set
{
SetColumnValue("OrganisationID", value);
}
}
[XmlAttribute("StationID")]
[Bindable(true)]
public Guid StationID
{
get
{
return GetColumnValue<Guid>("StationID");
}
set
{
SetColumnValue("StationID", value);
}
}
[XmlAttribute("OrganisationRoleID")]
[Bindable(true)]
public Guid OrganisationRoleID
{
get
{
return GetColumnValue<Guid>("OrganisationRoleID");
}
set
{
SetColumnValue("OrganisationRoleID", value);
}
}
[XmlAttribute("StartDate")]
[Bindable(true)]
public DateTime? StartDate
{
get
{
return GetColumnValue<DateTime?>("StartDate");
}
set
{
SetColumnValue("StartDate", value);
}
}
[XmlAttribute("EndDate")]
[Bindable(true)]
public DateTime? EndDate
{
get
{
return GetColumnValue<DateTime?>("EndDate");
}
set
{
SetColumnValue("EndDate", value);
}
}
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get
{
return GetColumnValue<Guid>("UserId");
}
set
{
SetColumnValue("UserId", value);
}
}
[XmlAttribute("AddedAt")]
[Bindable(true)]
public DateTime? AddedAt
{
get
{
return GetColumnValue<DateTime?>("AddedAt");
}
set
{
SetColumnValue("AddedAt", value);
}
}
[XmlAttribute("UpdatedAt")]
[Bindable(true)]
public DateTime? UpdatedAt
{
get
{
return GetColumnValue<DateTime?>("UpdatedAt");
}
set
{
SetColumnValue("UpdatedAt", value);
}
}
[XmlAttribute("RowVersion")]
[Bindable(true)]
public byte[] RowVersion
{
get
{
return GetColumnValue<byte[]>("RowVersion");
}
set
{
SetColumnValue("RowVersion", value);
}
}
[XmlAttribute("OrganisationCode")]
[Bindable(true)]
public string OrganisationCode
{
get
{
return GetColumnValue<string>("OrganisationCode");
}
set
{
SetColumnValue("OrganisationCode", value);
}
}
[XmlAttribute("OrganisationName")]
[Bindable(true)]
public string OrganisationName
{
get
{
return GetColumnValue<string>("OrganisationName");
}
set
{
SetColumnValue("OrganisationName", value);
}
}
[XmlAttribute("StationCode")]
[Bindable(true)]
public string StationCode
{
get
{
return GetColumnValue<string>("StationCode");
}
set
{
SetColumnValue("StationCode", value);
}
}
[XmlAttribute("StationName")]
[Bindable(true)]
public string StationName
{
get
{
return GetColumnValue<string>("StationName");
}
set
{
SetColumnValue("StationName", value);
}
}
[XmlAttribute("OrganisationRoleCode")]
[Bindable(true)]
public string OrganisationRoleCode
{
get
{
return GetColumnValue<string>("OrganisationRoleCode");
}
set
{
SetColumnValue("OrganisationRoleCode", value);
}
}
[XmlAttribute("OrganisationRoleName")]
[Bindable(true)]
public string OrganisationRoleName
{
get
{
return GetColumnValue<string>("OrganisationRoleName");
}
set
{
SetColumnValue("OrganisationRoleName", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"ID";
public static string OrganisationID = @"OrganisationID";
public static string StationID = @"StationID";
public static string OrganisationRoleID = @"OrganisationRoleID";
public static string StartDate = @"StartDate";
public static string EndDate = @"EndDate";
public static string UserId = @"UserId";
public static string AddedAt = @"AddedAt";
public static string UpdatedAt = @"UpdatedAt";
public static string RowVersion = @"RowVersion";
public static string OrganisationCode = @"OrganisationCode";
public static string OrganisationName = @"OrganisationName";
public static string StationCode = @"StationCode";
public static string StationName = @"StationName";
public static string OrganisationRoleCode = @"OrganisationRoleCode";
public static string OrganisationRoleName = @"OrganisationRoleName";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Reflection;
namespace XSharp.MacroCompiler
{
using Syntax;
internal partial class Binder
{
internal BinaryOperatorSymbol BindBinaryLogicOperation(BinaryExpr expr, BinaryOperatorKind kind)
{
return BindBinaryOperation(expr, kind, Options.Binding | BindOptions.Logic);
}
internal BinaryOperatorSymbol BindBinaryOperation(BinaryExpr expr, BinaryOperatorKind kind)
{
return BindBinaryOperation(expr, kind, Options.Binding);
}
internal static BinaryOperatorSymbol BindBinaryOperation(BinaryExpr expr, BinaryOperatorKind kind, BindOptions options)
{
if (options.HasFlag(BindOptions.Logic))
{
Convert(ref expr.Left, Compilation.Get(NativeType.Boolean), options);
Convert(ref expr.Right, Compilation.Get(NativeType.Boolean), options);
}
var res = BinaryOperation(kind, ref expr.Left, ref expr.Right, options);
if (res != null)
return res;
throw BinaryOperationError(expr, kind, options);
}
internal static BinaryOperatorSymbol BinaryOperation(BinaryOperatorKind kind, ref Expr left, ref Expr right, BindOptions options)
{
// When one or both of the datatypes is Usual or Object then convert to Usual and let
// the operators in the Usual type handle the binary operation
if (left.Datatype.IsUsualOrObject() || right.Datatype.IsUsualOrObject())
{
Convert(ref left, Compilation.Get(NativeType.Usual), options);
Convert(ref right, Compilation.Get(NativeType.Usual), options);
}
var sym = BinaryOperatorEasyOut.ClassifyOperation(kind, left.Datatype, right.Datatype);
if (options.HasFlag(BindOptions.AllowInexactComparisons) && sym != null)
{
switch (sym.Kind)
{
case BinaryOperatorKind.EqString:
case BinaryOperatorKind.EqStringObject:
case BinaryOperatorKind.EqObjectString:
case BinaryOperatorKind.NeqString:
case BinaryOperatorKind.NeqStringObject:
case BinaryOperatorKind.NeqObjectString:
sym = null;
break;
}
}
if (sym != null)
{
Convert(ref left, sym.TypeOfOp, options);
Convert(ref right, sym.TypeOfOp, options);
return sym;
}
// User-defined operators
{
var op = UserDefinedBinaryOperator(kind, ref left, ref right, options);
if (op != null)
return op;
}
// Symbol/string operations
{
var op = SymbolAndStringBinaryOperator(kind, ref left, ref right, options);
if (op != null)
return op;
}
// Dynamic with usual
if (options.HasFlag(BindOptions.AllowDynamic))
{
var op = DynamicBinaryOperator(kind, ref left, ref right, options);
if (op != null)
return op;
}
// Emun operations
{
var op = EnumBinaryOperator(kind, ref left, ref right, options);
if (op != null)
return op;
}
return null;
}
internal static BinaryOperatorSymbol UserDefinedBinaryOperator(BinaryOperatorKind kind, ref Expr left, ref Expr right, BindOptions options)
{
MethodSymbol mop = null;
ConversionSymbol lconv = null;
ConversionSymbol rconv = null;
bool hasUsual = left.Datatype.NativeType == NativeType.Usual || right.Datatype.NativeType == NativeType.Usual;
if (options.HasFlag(BindOptions.AllowInexactComparisons))
{
bool hasString = left.Datatype.NativeType == NativeType.String || right.Datatype.NativeType == NativeType.String;
bool hasUsuals = left.Datatype.NativeType == NativeType.Usual || right.Datatype.NativeType == NativeType.Usual;
bool bothStrings = left.Datatype.NativeType == NativeType.String && right.Datatype.NativeType == NativeType.String;
switch (kind)
{
case BinaryOperatorKind.Equal:
if (bothStrings)
ResolveBinaryOperator(left, right, Compilation.Get(WellKnownMembers.XSharp_RT_Functions___StringEquals), ref mop, ref lconv, ref rconv, options);
else if (hasString || hasUsuals)
ResolveBinaryOperator(left, right, Compilation.Get(NativeType.Usual).Lookup(OperatorNames.__UsualInExactEquals), ref mop, ref lconv, ref rconv, options);
break;
case BinaryOperatorKind.NotEqual:
if (bothStrings)
ResolveBinaryOperator(left, right, Compilation.Get(WellKnownMembers.XSharp_RT_Functions___StringNotEquals), ref mop, ref lconv, ref rconv, options);
else if (hasString)
ResolveBinaryOperator(left, right, Compilation.Get(NativeType.Usual).Lookup(OperatorNames.__UsualInExactNotEquals), ref mop, ref lconv, ref rconv, options);
break;
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
if (bothStrings)
ResolveBinaryOperator(left, right, Compilation.Get(WellKnownMembers.XSharp_RT_Functions___StringCompare), ref mop, ref lconv, ref rconv, options);
break;
}
}
else
{
switch (kind)
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThanOrEqual:
if (left.Datatype.NativeType == NativeType.String && right.Datatype.NativeType == NativeType.String)
ResolveBinaryOperator(left, right, Compilation.Get(WellKnownMembers.System_String_CompareOrdinal), ref mop, ref lconv, ref rconv, options);
break;
}
}
if (mop == null)
{
var name = BinaryOperatorSymbol.OperatorName(kind);
if (name != null)
{
ResolveBinaryOperator(left, right, left.Datatype.Lookup(name), ref mop, ref lconv, ref rconv, options | BindOptions.Special);
ResolveBinaryOperator(left, right, right.Datatype.Lookup(name), ref mop, ref lconv, ref rconv, options | BindOptions.Special);
}
}
if (mop == null && kind == BinaryOperatorKind.Exponent)
{
ResolveBinaryOperator(left, right, Compilation.Get(WellKnownMembers.XSharp_RT_Functions_POW), ref mop, ref lconv, ref rconv, options);
if (hasUsual)
{
ResolveBinaryOperator(left, right, left.Datatype.Lookup(OperatorNames.__UsualExponent), ref mop, ref lconv, ref rconv, options);
ResolveBinaryOperator(left, right, right.Datatype.Lookup(OperatorNames.__UsualExponent), ref mop, ref lconv, ref rconv, options);
}
}
if (mop != null)
{
var op = BinaryOperatorSymbol.Create(kind, mop, lconv, rconv);
ApplyBinaryOperator(ref left, ref right, op);
return op;
}
return null;
}
internal static void ResolveBinaryOperator(Expr left, Expr right, Symbol ops,
ref MethodSymbol op, ref ConversionSymbol lconv, ref ConversionSymbol rconv, BindOptions options)
{
if (ops is MethodSymbol)
{
if (CheckBinaryOperator(left, right, (MethodSymbol)ops, ref lconv, ref rconv, options))
op = (MethodSymbol)ops;
}
else if ((ops as SymbolList)?.SymbolTypes.HasFlag(MemberTypes.Method) == true)
{
foreach (MethodSymbol m in ((SymbolList)ops).Symbols)
if (m != null)
{
if (CheckBinaryOperator(left, right, m, ref lconv, ref rconv, options))
op = m;
}
}
}
internal static bool CheckBinaryOperator(Expr left, Expr right, MethodSymbol m,
ref ConversionSymbol lconv, ref ConversionSymbol rconv, BindOptions options)
{
var method = m.Method;
if (!m.Method.IsStatic || (options.HasFlag(BindOptions.Special) && !m.Method.IsSpecialName))
return false;
var parameters = method.GetParameters();
if (parameters.Length != 2)
return false;
var ltype = FindType(parameters[0].ParameterType);
var rtype = FindType(parameters[1].ParameterType);
if (TypesMatch(ltype, left.Datatype) && TypesMatch(rtype, right.Datatype))
{
lconv = ConversionSymbol.Create(ConversionKind.Identity);
rconv = ConversionSymbol.Create(ConversionKind.Identity);
return true;
}
var _lconv = Conversion(left, ltype, options);
var _rconv = Conversion(right, rtype, options);
if (_lconv.IsImplicit && _rconv.IsImplicit)
{
if (lconv == null && rconv == null)
{
lconv = _lconv;
rconv = _rconv;
return true;
}
var cost = lconv?.Cost + rconv?.Cost;
var _cost = _lconv.Cost + _rconv.Cost;
if (_cost < cost)
{
lconv = _lconv;
rconv = _rconv;
return true;
}
}
return false;
}
static void ApplyBinaryOperator(ref Expr left, ref Expr right, BinaryOperatorSymbol op)
{
if (op is BinaryOperatorSymbolWithMethod)
{
var mop = (BinaryOperatorSymbolWithMethod)op;
var parameters = mop.Method.Method.GetParameters();
var lconv = mop.ConvLeft;
if (lconv != null && lconv.Kind != ConversionKind.Identity)
Convert(ref left, FindType(parameters[0].ParameterType), lconv);
var rconv = mop.ConvRight;
if (rconv != null && rconv.Kind != ConversionKind.Identity)
Convert(ref right, FindType(parameters[1].ParameterType), rconv);
}
}
internal static BinaryOperatorSymbol SymbolAndStringBinaryOperator(BinaryOperatorKind kind, ref Expr left, ref Expr right, BindOptions options)
{
if (kind == BinaryOperatorKind.Addition)
{
var l = left;
var r = right;
if (left.Datatype.NativeType == NativeType.Symbol)
Convert(ref l, Compilation.Get(NativeType.String), options);
if (right.Datatype.NativeType == NativeType.Symbol)
Convert(ref r, Compilation.Get(NativeType.String), options);
var sym = BinaryOperatorEasyOut.ClassifyOperation(kind, l.Datatype, r.Datatype);
if (sym != null)
{
left = l;
right = r;
Convert(ref left, sym.TypeOfOp, options);
Convert(ref right, sym.TypeOfOp, options);
return sym;
}
}
return null;
}
static BinaryOperatorSymbol DynamicBinaryOperator(BinaryOperatorKind kind, ref Expr left, ref Expr right, BindOptions options)
{
var l = left;
var r = right;
if (l.Datatype.NativeType == NativeType.Object)
Convert(ref l, Compilation.Get(NativeType.Usual), options);
if (r.Datatype.NativeType == NativeType.Object)
Convert(ref r, Compilation.Get(NativeType.Usual), options);
var op = UserDefinedBinaryOperator(kind, ref l, ref r, options);
if (op != null)
{
left = l;
right = r;
}
return op;
}
static BinaryOperatorSymbol EnumBinaryOperator(BinaryOperatorKind kind, ref Expr left, ref Expr right, BindOptions options)
{
var l = left;
var r = right;
TypeSymbol dt;
if (l.Datatype.IsEnum)
{
if (r.Datatype.IsEnum && !TypesMatch(l.Datatype,r.Datatype))
return null;
dt = l.Datatype;
}
else if (r.Datatype.IsEnum)
{
dt = r.Datatype;
}
else
return null;
Convert(ref l, dt.EnumUnderlyingType, options);
Convert(ref r, dt.EnumUnderlyingType, options);
var op = BinaryOperation(kind, ref l, ref r, options);
if (op != null)
{
left = l;
right = r;
if (kind == BinaryOperatorKind.Addition || kind == BinaryOperatorKind.Subtraction || kind == BinaryOperatorKind.Or ||
kind == BinaryOperatorKind.And || kind == BinaryOperatorKind.Xor)
return op.AsEnum(dt) ?? op;
else
return op;
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Tests;
using ServiceStack.Text.Tests.JsonTests;
namespace ServiceStack.Text.Tests.Support
{
[Ignore]
[TestFixture]
public class BenchmarkTests
: PerfTestBase
{
[Test]
public void Test_string_parsing()
{
const int stringSampleSize = 1024 * 10;
var testString = CreateRandomString(stringSampleSize);
var copyTo = new char[stringSampleSize];
CompareMultipleRuns(
"As char array",
() => {
var asChars = testString.ToCharArray();
for (var i = 0; i < stringSampleSize; i++)
{
copyTo[i] = asChars[i];
}
},
"As string",
() => {
for (var i = 0; i < stringSampleSize; i++)
{
copyTo[i] = testString[i];
}
});
}
public string CreateRandomString(int size)
{
var randString = new char[size];
for (var i = 0; i < size; i++)
{
randString[i] = (char)((i % 10) + '0');
}
return new string(randString);
}
static readonly char[] EscapeChars = new char[]
{
'"', '\n', '\r', '\t', '"', '\\', '\f', '\b',
};
public static readonly char[] JsvEscapeChars = new[]
{
'"', ',', '{', '}', '[', ']',
};
private const int LengthFromLargestChar = '\\' + 1;
private static readonly bool[] HasEscapeChars = new bool[LengthFromLargestChar];
[Test]
public void PrintEscapeChars()
{
JsvEscapeChars.ToList().OrderBy(x => (int)x).ForEach(x => Console.WriteLine(x + ": " + (int)x));
}
[Test]
public void MeasureIndexOfEscapeChars()
{
foreach (var escapeChar in EscapeChars)
{
HasEscapeChars[escapeChar] = true;
}
var value = CreateRandomString(100);
var len = value.Length;
var hasEscapeChars = false;
CompareMultipleRuns(
"With bool flags",
() => {
for (var i = 0; i < len; i++)
{
var c = value[i];
if (c >= LengthFromLargestChar || !HasEscapeChars[c]) continue;
hasEscapeChars = true;
break;
}
},
"With IndexOfAny",
() => {
hasEscapeChars = value.IndexOfAny(EscapeChars) != -1;
});
Console.WriteLine(hasEscapeChars);
}
public class RuntimeType<T>
{
private static Type type = typeof(T);
internal static bool TestVarType()
{
return type == typeof(byte) || type == typeof(byte?)
|| type == typeof(short) || type == typeof(short?)
|| type == typeof(ushort) || type == typeof(ushort?)
|| type == typeof(int) || type == typeof(int?)
|| type == typeof(uint) || type == typeof(uint?)
|| type == typeof(long) || type == typeof(long?)
|| type == typeof(ulong) || type == typeof(ulong?)
|| type == typeof(bool) || type == typeof(bool?)
|| type != typeof(DateTime)
|| type != typeof(DateTime?)
|| type != typeof(Guid)
|| type != typeof(Guid?)
|| type != typeof(float) || type != typeof(float?)
|| type != typeof(double) || type != typeof(double?)
|| type != typeof(decimal) || type != typeof(decimal?);
}
internal static bool TestGenericType()
{
return typeof(T) == typeof(byte) || typeof(T) == typeof(byte?)
|| typeof(T) == typeof(short) || typeof(T) == typeof(short?)
|| typeof(T) == typeof(ushort) || typeof(T) == typeof(ushort?)
|| typeof(T) == typeof(int) || typeof(T) == typeof(int?)
|| typeof(T) == typeof(uint) || typeof(T) == typeof(uint?)
|| typeof(T) == typeof(long) || typeof(T) == typeof(long?)
|| typeof(T) == typeof(ulong) || typeof(T) == typeof(ulong?)
|| typeof(T) == typeof(bool) || typeof(T) == typeof(bool?)
|| typeof(T) != typeof(DateTime)
|| typeof(T) != typeof(DateTime?)
|| typeof(T) != typeof(Guid)
|| typeof(T) != typeof(Guid?)
|| typeof(T) != typeof(float) || typeof(T) != typeof(float?)
|| typeof(T) != typeof(double) || typeof(T) != typeof(double?)
|| typeof(T) != typeof(decimal) || typeof(T) != typeof(decimal?);
}
}
[Test]
public void TestVarOrGenericType()
{
var matchingTypesCount = 0;
CompareMultipleRuns(
"With var type",
() => {
if (RuntimeType<BenchmarkTests>.TestVarType())
{
matchingTypesCount++;
}
},
"With generic type",
() => {
if (RuntimeType<BenchmarkTests>.TestGenericType())
{
matchingTypesCount++;
}
});
Console.WriteLine(matchingTypesCount);
}
[Test]
public void Test_for_list_enumeration()
{
List<Cat> list = 20.Times(x => new Cat { Name = "Cat" });
var results = 0;
var listLength = list.Count;
CompareMultipleRuns(
"With foreach",
() => {
foreach (var cat in list)
{
results++;
}
},
"With for",
() => {
for (var i = 0; i < listLength; i++)
{
var cat = list[i];
results++;
}
});
Console.WriteLine(results);
}
[Test]
public void Test_for_Ilist_enumeration()
{
IList<Cat> list = 20.Times(x => new Cat { Name = "Cat" });
var results = 0;
var listLength = list.Count;
CompareMultipleRuns(
"With foreach",
() => {
foreach (var cat in list)
{
results++;
}
},
"With for",
() => {
for (var i = 0; i < listLength; i++)
{
var cat = list[i];
results++;
}
});
Console.WriteLine(results);
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
using Skybound.VisualTips.Rendering;
using Skybound.Windows.Forms;
namespace Skybound.VisualTips
{
internal class VisualTipWindow : System.Windows.Forms.Form
{
private struct BLENDFUNCTION
{
public byte bytAlphaFormat;
public byte bytBlendFlags;
public byte bytBlendOp;
public byte bytSourceConstantAlpha;
}
private struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
X = x;
Y = y;
}
}
private struct SIZE
{
public int CX;
public int CY;
public SIZE(int cx, int cy)
{
CX = cx;
CY = cy;
}
}
private const byte AC_SRC_ALPHA = 1;
private const byte AC_SRC_OVER = 0;
private const int SW_HIDE = 0;
private const int SW_NORMAL = 1;
private const int SW_SHOW = 5;
private const int SW_SHOWNOACTIVATE = 4;
private const int ULW_ALPHA = 2;
private const int ULW_COLORKEY = 1;
private const int ULW_OPAQUE = 4;
private Skybound.VisualTips.VisualTip _DisplayedTip;
private bool _IsDisplayed;
private Skybound.VisualTips.VisualTipDisplayOptions _Options;
private Skybound.Windows.Forms.Animator Animator;
private Skybound.Windows.Forms.BufferedGraphics Buffer;
private System.IntPtr HLayeredWindowBitmap;
private System.Drawing.Size LayeredWindowSize;
private Skybound.VisualTips.VisualTipProvider Provider;
private double StartingOpacity;
public Skybound.VisualTips.VisualTip DisplayedTip
{
get
{
if (!IsDisplayed)
return null;
return _DisplayedTip;
}
}
public bool IsDisplayed
{
get
{
return _IsDisplayed;
}
}
private bool IsLayeredWindow
{
get
{
return Skybound.VisualTips.Rendering.VisualTipRenderer.LayeredWindowsSupported;
}
}
public Skybound.VisualTips.VisualTipDisplayOptions Options
{
get
{
return _Options;
}
}
protected override System.Windows.Forms.CreateParams CreateParams
{
get
{
System.Windows.Forms.CreateParams createParams = base.CreateParams;
if (IsLayeredWindow)
createParams.ExStyle |= 524288;
return createParams;
}
}
public VisualTipWindow()
{
Buffer = new Skybound.Windows.Forms.BufferedGraphics();
SetStyle(System.Windows.Forms.ControlStyles.UserPaint | System.Windows.Forms.ControlStyles.AllPaintingInWmPaint | System.Windows.Forms.ControlStyles.DoubleBuffer, true);
StartPosition = System.Windows.Forms.FormStartPosition.Manual;
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
ShowInTaskbar = false;
Animator = new Skybound.Windows.Forms.Animator(Skybound.Windows.Forms.Motion.Decelerate, 200);
Animator.NextFrame += new System.EventHandler(Animator_NextFrame);
Animator.SynchronizingObject = this;
}
private void Animator_NextFrame(object sender, System.EventArgs e)
{
if (Animator.IsComplete)
{
Skybound.VisualTips.VisualTipWindow.ShowWindow(Handle, 0);
return;
}
UpdateAlphaMask((byte)((1.0 - Animator.Value) * (StartingOpacity * 255.0)));
}
private void DestroyLayeredWindowBitmap()
{
if (HLayeredWindowBitmap != System.IntPtr.Zero)
{
Skybound.VisualTips.VisualTipWindow.DeleteObject(HLayeredWindowBitmap);
HLayeredWindowBitmap = System.IntPtr.Zero;
LayeredWindowSize = System.Drawing.Size.Empty;
}
}
public void Display(Skybound.VisualTips.VisualTipProvider provider, Skybound.VisualTips.VisualTip tip, System.Drawing.Rectangle toolArea, Skybound.VisualTips.VisualTipDisplayOptions options)
{
Provider = provider;
_DisplayedTip = tip;
_Options = options;
RightToLeft = tip.RightToLeft;
Skybound.VisualTips.Rendering.VisualTipLayout visualTipLayout = provider.Renderer.CreateLayout(tip);
Size = visualTipLayout.GetSize();
Location = GetBestLocation(toolArea, Size, options);
toolArea.Location = toolArea.Location - (new System.Drawing.Size(Location));
tip.SetRelativeToolArea(toolArea);
if (IsLayeredWindow)
{
Animator.Stop();
using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(Width, Height))
using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
{
provider.Renderer.Draw(new System.Windows.Forms.PaintEventArgs(graphics, new System.Drawing.Rectangle(0, 0, Width, Height)), tip, visualTipLayout);
SetAlphaMask(bitmap, (byte)(Provider.Opacity * 255.0));
}
}
DisplayAnimate();
if (!IsLayeredWindow)
{
System.Drawing.Rectangle rectangle = visualTipLayout.WindowBounds;
Width = rectangle.Width;
Region = Provider.Renderer.CreateMaskRegion(tip, visualTipLayout);
}
}
private void DisplayAnimate()
{
Skybound.VisualTips.VisualTipWindow.SetWindowPos(Handle, new System.IntPtr(-1), 0, 0, 0, 0, 83);
_IsDisplayed = true;
Opacity = 1.0;
}
private System.Drawing.Point GetBestLocation(System.Drawing.Rectangle toolArea, System.Drawing.Size tipSize, Skybound.VisualTips.VisualTipDisplayOptions options)
{
System.Drawing.Rectangle rectangle1 = System.Windows.Forms.Screen.GetBounds(toolArea);
bool flag1 = RightToLeft == System.Windows.Forms.RightToLeft.No;
System.Drawing.Rectangle rectangle2 = new System.Drawing.Rectangle(toolArea.Location, tipSize);
bool flag2 = (options & Skybound.VisualTips.VisualTipDisplayOptions.PositionMask) == Skybound.VisualTips.VisualTipDisplayOptions.PositionLeft;
bool flag3 = (options & Skybound.VisualTips.VisualTipDisplayOptions.PositionMask) == Skybound.VisualTips.VisualTipDisplayOptions.PositionMask;
bool flag4 = flag2 || ((options & Skybound.VisualTips.VisualTipDisplayOptions.PositionMask) == Skybound.VisualTips.VisualTipDisplayOptions.PositionRight);
if (flag4)
{
if (flag1 && !flag2)
{
if (((toolArea.Right + tipSize.Width) > rectangle1.Right) && ((toolArea.Left - tipSize.Width) >= rectangle1.X))
rectangle2.X -= tipSize.Width;
else
rectangle2.X += toolArea.Width;
}
else if (((toolArea.Left - tipSize.Width) < rectangle1.X) && ((toolArea.Right + tipSize.Width) <= rectangle1.Right))
{
rectangle2.X += toolArea.Width;
}
else
{
rectangle2.X -= tipSize.Width;
}
}
else
{
if (!flag1)
rectangle2.X -= tipSize.Width - toolArea.Width;
if (flag3)
{
if (((toolArea.Y - tipSize.Height) < rectangle1.Y) && ((toolArea.Bottom + tipSize.Height) <= rectangle1.Bottom))
rectangle2.Y += toolArea.Height;
else
rectangle2.Y -= tipSize.Height;
}
else if (((toolArea.Bottom + tipSize.Height) > rectangle1.Bottom) && ((toolArea.Y - tipSize.Height) >= rectangle1.Y))
{
rectangle2.Y -= tipSize.Height;
}
else
{
rectangle2.Y += toolArea.Height;
}
}
if (rectangle2.Right > rectangle1.Right)
rectangle2.X = rectangle1.Right - rectangle2.Width;
if (rectangle2.X < rectangle1.X)
rectangle2.X = rectangle1.X;
if (rectangle2.Bottom > rectangle1.Bottom)
rectangle2.Y = rectangle1.Bottom - rectangle2.Height;
if (rectangle2.Y < rectangle1.Y)
rectangle2.Y = rectangle1.Y;
return rectangle2.Location;
}
private void SetAlphaMask(System.Drawing.Bitmap bitmap, byte opacity)
{
DestroyLayeredWindowBitmap();
HLayeredWindowBitmap = bitmap.GetHbitmap(System.Drawing.Color.FromArgb(0));
LayeredWindowSize = bitmap.Size;
UpdateAlphaMask(opacity);
}
public void SetToolArea(System.Drawing.Rectangle toolArea, Skybound.VisualTips.VisualTipDisplayOptions options)
{
Location = GetBestLocation(toolArea, Size, options);
_Options = options;
}
public void Undisplay()
{
if (IsDisplayed)
{
_IsDisplayed = false;
_DisplayedTip = null;
if ((IsLayeredWindow && (Provider.Animation == Skybound.VisualTips.VisualTipAnimation.Enabled)) || ((Provider.Animation == Skybound.VisualTips.VisualTipAnimation.SystemDefault) && Skybound.VisualTips.SystemParameters.ToolTipAnimation))
{
StartingOpacity = Provider.Opacity;
Animator.Start();
}
else
{
Skybound.VisualTips.VisualTipWindow.ShowWindow(Handle, 0);
}
Provider.OnUndisplay(this);
}
}
private void UpdateAlphaMask(byte opacity)
{
Skybound.VisualTips.VisualTipWindow.BLENDFUNCTION blendfunction;
Skybound.VisualTips.VisualTipWindow.POINT point2;
System.IntPtr intPtr1 = Skybound.VisualTips.VisualTipWindow.GetDC(System.IntPtr.Zero);
System.IntPtr intPtr2 = Skybound.VisualTips.VisualTipWindow.CreateCompatibleDC(intPtr1);
System.IntPtr intPtr3 = System.IntPtr.Zero;
try
{
intPtr3 = Skybound.VisualTips.VisualTipWindow.SelectObject(intPtr2, HLayeredWindowBitmap);
Skybound.VisualTips.VisualTipWindow.POINT point1 = new Skybound.VisualTips.VisualTipWindow.POINT(Left, Top);
Skybound.VisualTips.VisualTipWindow.SIZE size = new Skybound.VisualTips.VisualTipWindow.SIZE(LayeredWindowSize.Width, LayeredWindowSize.Height);
point2 = new Skybound.VisualTips.VisualTipWindow.POINT();
blendfunction = new Skybound.VisualTips.VisualTipWindow.BLENDFUNCTION();
blendfunction.bytBlendOp = 0;
blendfunction.bytBlendFlags = 0;
blendfunction.bytSourceConstantAlpha = opacity;
blendfunction.bytAlphaFormat = 1;
Skybound.VisualTips.VisualTipWindow.UpdateLayeredWindow(Handle, intPtr1, ref point1, ref size, intPtr2, ref point2, 0, ref blendfunction, 2);
}
finally
{
Skybound.VisualTips.VisualTipWindow.ReleaseDC(System.IntPtr.Zero, intPtr1);
Skybound.VisualTips.VisualTipWindow.SelectObject(intPtr2, intPtr3);
Skybound.VisualTips.VisualTipWindow.DeleteDC(intPtr2);
}
}
protected override void Dispose(bool disposing)
{
DestroyLayeredWindowBitmap();
base.Dispose(disposing);
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
if (!IsLayeredWindow)
{
Buffer.SetTarget(e.Graphics, ClientRectangle);
Provider.Renderer.Draw(new System.Windows.Forms.PaintEventArgs(Buffer.Graphics, e.ClipRectangle), DisplayedTip, null);
Buffer.Render();
}
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == 33)
{
Undisplay();
m.Result = new System.IntPtr(4);
return;
}
base.WndProc(ref m);
}
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("gdi32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern System.IntPtr CreateCompatibleDC(System.IntPtr hdc);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("gdi32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern int DeleteDC(System.IntPtr hdc);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("gdi32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern int DeleteObject(System.IntPtr hObject);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern System.IntPtr GetDC(System.IntPtr hwnd);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern int ReleaseDC(System.IntPtr hwnd, System.IntPtr hdc);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("gdi32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern System.IntPtr SelectObject(System.IntPtr hdc, System.IntPtr hObject);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern int SetWindowPos(System.IntPtr hwnd, System.IntPtr hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern int ShowWindow(System.IntPtr hwnd, int nCmdShow);
[System.Runtime.InteropServices.PreserveSig]
[System.Runtime.InteropServices.DllImport("user32", CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern System.IntPtr UpdateLayeredWindow(System.IntPtr hwnd, System.IntPtr hdcDst, ref Skybound.VisualTips.VisualTipWindow.POINT pptDst, ref Skybound.VisualTips.VisualTipWindow.SIZE psize, System.IntPtr hdcSrc, ref Skybound.VisualTips.VisualTipWindow.POINT pprSrc, int crKey, ref Skybound.VisualTips.VisualTipWindow.BLENDFUNCTION pblend, int dwFlags);
} // class VisualTipWindow
}
| |
/* **********************************************************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH *
* Web: http://www.hypermediasystems.de *
* This file is part of hmssp *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
************************************************************************************************************ */
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection;
using Newtonsoft.Json;
namespace HMS.SP{
/// <summary>
/// <para>https://msdn.microsoft.com/en-us/library/office/jj245565.aspx#properties</para>
/// </summary>
public class ListTemplate : SPBase{
[JsonProperty("__HMSError")]
public HMS.Util.__HMSError __HMSError_ { set; get; }
[JsonProperty("__status")]
public SP.__status __status_ { set; get; }
[JsonProperty("__deferred")]
public SP.__deferred __deferred_ { set; get; }
[JsonProperty("__metadata")]
public SP.__metadata __metadata_ { set; get; }
public Dictionary<string, string> __rest;
/// <summary>
/// <para>Gets a value that specifies whether new list folders can be added to a list created from the list template.(s. https://msdn.microsoft.com/en-us/library/office/jj245481.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("AllowsFolderCreation")]
public Boolean AllowsFolderCreation_ { set; get; }
// undefined class SP.BaseType : Object { }
/// <summary>
/// <para>Gets a value that specifies the base type of the list template.(s. https://msdn.microsoft.com/en-us/library/office/jj246055.aspx)[SP.BaseType]</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("BaseType")]
public Object BaseType_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the description of the list template.(s. https://msdn.microsoft.com/en-us/library/office/jj246343.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Description")]
public String Description_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the description of the list template.(s. https://msdn.microsoft.com/en-us/library/office/jj246343.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("DescriptionResource")]
public SP.__deferred DescriptionResource_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the feature identifier of the feature that contains the list schema for the list template.(s. https://msdn.microsoft.com/en-us/library/office/jj246861.aspx) [SP.Guid]</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("FeatureId")]
public Guid FeatureId_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies whether the list template is hidden from the user interface for creating new lists.(s. https://msdn.microsoft.com/en-us/library/office/jj246068.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Hidden")]
public Boolean Hidden_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the URL for the icon of the list template.(s. https://msdn.microsoft.com/en-us/library/office/jj245413.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("ImageUrl")]
public String ImageUrl_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the identifier for the list template.(s. https://msdn.microsoft.com/en-us/library/office/jj244864.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("InternalName")]
public String InternalName_ { set; get; }
/// <summary>
/// <para>Specifies whether the list template is user created.(s. https://msdn.microsoft.com/en-us/library/office/jj246619.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("IsCustomTemplate")]
public Boolean IsCustomTemplate_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the list server template.(s. https://msdn.microsoft.com/en-us/library/office/jj244836.aspx) [Number]</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("ListTemplateTypeKind")]
public Int32 ListTemplateTypeKind_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the display name of the list template.(s. https://msdn.microsoft.com/en-us/library/office/jj247011.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Name")]
public String Name_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies whether the list template can be used to create only one list in a site collection, and that the list template is hidden from the user interface for creating new lists.(s. https://msdn.microsoft.com/en-us/library/office/jj245427.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("OnQuickLaunch")]
public Boolean OnQuickLaunch_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies whether the list template can be used to create only one list in a site collection, and that the list template is hidden from the user interface for creating new lists.(s. https://msdn.microsoft.com/en-us/library/office/jj245040.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Unique")]
public Boolean Unique_ { set; get; }
/// <summary>
/// <para> Endpoints </para>
/// </summary>
static string[] endpoints = {
};
public ListTemplate(ExpandoObject expObj)
{
try
{
var use_EO = ((dynamic)expObj).entry.content.properties;
HMS.SP.SPUtil.expando2obj(use_EO, this, typeof(ListTemplate));
}
catch (Exception ex)
{
}
}
// used by Newtonsoft.JSON
public ListTemplate()
{
}
public ListTemplate(string json)
{
if( json == String.Empty )
return;
dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
dynamic refObj = jobject;
if (jobject.d != null)
refObj = jobject.d;
string errInfo = "";
if (refObj.results != null)
{
if (refObj.results.Count > 1)
errInfo = "Result is Collection, only 1. entry displayed.";
refObj = refObj.results[0];
}
List<string> usedFields = new List<string>();
usedFields.Add("__HMSError");
HMS.SP.SPUtil.dyn_ValueSet("__HMSError", refObj, this);
usedFields.Add("__deferred");
this.__deferred_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.__deferred));
usedFields.Add("__metadata");
this.__metadata_ = new SP.__metadata(HMS.SP.SPUtil.dyn_toString(refObj.__metadata));
usedFields.Add("AllowsFolderCreation");
HMS.SP.SPUtil.dyn_ValueSet("AllowsFolderCreation", refObj, this);
usedFields.Add("BaseType");
HMS.SP.SPUtil.dyn_ValueSet("BaseType", refObj, this);
usedFields.Add("Description");
HMS.SP.SPUtil.dyn_ValueSet("Description", refObj, this);
usedFields.Add("DescriptionResource");
this.DescriptionResource_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.DescriptionResource));
usedFields.Add("FeatureId");
HMS.SP.SPUtil.dyn_ValueSet("FeatureId", refObj, this);
usedFields.Add("Hidden");
HMS.SP.SPUtil.dyn_ValueSet("Hidden", refObj, this);
usedFields.Add("ImageUrl");
HMS.SP.SPUtil.dyn_ValueSet("ImageUrl", refObj, this);
usedFields.Add("InternalName");
HMS.SP.SPUtil.dyn_ValueSet("InternalName", refObj, this);
usedFields.Add("IsCustomTemplate");
HMS.SP.SPUtil.dyn_ValueSet("IsCustomTemplate", refObj, this);
usedFields.Add("ListTemplateTypeKind");
HMS.SP.SPUtil.dyn_ValueSet("ListTemplateTypeKind", refObj, this);
usedFields.Add("Name");
HMS.SP.SPUtil.dyn_ValueSet("Name", refObj, this);
usedFields.Add("OnQuickLaunch");
HMS.SP.SPUtil.dyn_ValueSet("OnQuickLaunch", refObj, this);
usedFields.Add("Unique");
HMS.SP.SPUtil.dyn_ValueSet("Unique", refObj, this);
this.__rest = new Dictionary<string, string>();
var dyn = ((Newtonsoft.Json.Linq.JContainer)refObj).First;
while (dyn != null)
{
string Name = ((Newtonsoft.Json.Linq.JProperty)dyn).Name;
string Value = ((Newtonsoft.Json.Linq.JProperty)dyn).Value.ToString();
if ( !usedFields.Contains( Name ))
this.__rest.Add( Name, Value);
dyn = dyn.Next;
}
if( errInfo != "")
this.__HMSError_.info = errInfo;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.IndicesDeleteWarmer1
{
public partial class IndicesDeleteWarmer1YamlTests
{
public class IndicesDeleteWarmer1AllPathOptionsYamlBase : YamlTestsBase
{
public IndicesDeleteWarmer1AllPathOptionsYamlBase() : base()
{
//do indices.create
_body = new {
warmers= new {
test_warmer1= new {
source= new {
query= new {
match_all= new {}
}
}
},
test_warmer2= new {
source= new {
query= new {
match_all= new {}
}
}
}
}
};
this.Do(()=> _client.IndicesCreate("test_index1", _body));
//do indices.create
_body = new {
warmers= new {
test_warmer1= new {
source= new {
query= new {
match_all= new {}
}
}
},
test_warmer2= new {
source= new {
query= new {
match_all= new {}
}
}
}
}
};
this.Do(()=> _client.IndicesCreate("test_index2", _body));
//do indices.create
_body = new {
warmers= new {
test_warmer1= new {
source= new {
query= new {
match_all= new {}
}
}
},
test_warmer2= new {
source= new {
query= new {
match_all= new {}
}
}
}
}
};
this.Do(()=> _client.IndicesCreate("foo", _body));
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class CheckDeleteWithAllIndex3Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase
{
[Test]
public void CheckDeleteWithAllIndex3Test()
{
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("_all", "test_warmer1"));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmerForAll());
//match _response.test_index1.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {});
//match _response.test_index2.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {});
//match _response.foo.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class CheckDeleteWithIndex4Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase
{
[Test]
public void CheckDeleteWithIndex4Test()
{
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("*", "test_warmer1"));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmerForAll());
//match _response.test_index1.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {});
//match _response.test_index2.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {});
//match _response.foo.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class CheckDeleteWithIndexList5Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase
{
[Test]
public void CheckDeleteWithIndexList5Test()
{
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("test_index1,test_index2", "test_warmer1"));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1"));
//match _response.foo.warmers.test_warmer1.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {});
//is_false _response.test_index1;
this.IsFalse(_response.test_index1);
//is_false _response.test_index2;
this.IsFalse(_response.test_index2);
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2"));
//match _response.test_index1.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {});
//match _response.test_index2.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {});
//match _response.foo.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class CheckDeleteWithPrefixIndex6Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase
{
[Test]
public void CheckDeleteWithPrefixIndex6Test()
{
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("test_*", "test_warmer1"));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1"));
//match _response.foo.warmers.test_warmer1.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {});
//is_false _response.test_index1;
this.IsFalse(_response.test_index1);
//is_false _response.test_index2;
this.IsFalse(_response.test_index2);
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2"));
//match _response.test_index1.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {});
//match _response.test_index2.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {});
//match _response.foo.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class CheckDeleteWithIndexListAndWarmers7Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase
{
[Test]
public void CheckDeleteWithIndexListAndWarmers7Test()
{
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("test_index1,test_index2", "*"));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1"));
//match _response.foo.warmers.test_warmer1.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {});
//is_false _response.test_index1;
this.IsFalse(_response.test_index1);
//is_false _response.test_index2;
this.IsFalse(_response.test_index2);
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2"));
//match _response.foo.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {});
//is_false _response.test_index1;
this.IsFalse(_response.test_index1);
//is_false _response.test_index2;
this.IsFalse(_response.test_index2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class CheckDeleteWithIndexListAndAllWarmers8Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase
{
[Test]
public void CheckDeleteWithIndexListAndAllWarmers8Test()
{
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("test_index1,test_index2", "_all"));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1"));
//match _response.foo.warmers.test_warmer1.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {});
//is_false _response.test_index1;
this.IsFalse(_response.test_index1);
//is_false _response.test_index2;
this.IsFalse(_response.test_index2);
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2"));
//match _response.foo.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {});
//is_false _response.test_index1;
this.IsFalse(_response.test_index1);
//is_false _response.test_index2;
this.IsFalse(_response.test_index2);
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class CheckDeleteWithIndexListAndWildcardWarmers9Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase
{
[Test]
public void CheckDeleteWithIndexListAndWildcardWarmers9Test()
{
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("test_index1,test_index2", "*1"));
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1"));
//match _response.foo.warmers.test_warmer1.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {});
//is_false _response.test_index1;
this.IsFalse(_response.test_index1);
//is_false _response.test_index2;
this.IsFalse(_response.test_index2);
//do indices.get_warmer
this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2"));
//match _response.test_index1.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {});
//match _response.test_index2.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {});
//match _response.foo.warmers.test_warmer2.source.query.match_all:
this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {});
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class Check404OnNoMatchingTestWarmer10Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase
{
[Test]
public void Check404OnNoMatchingTestWarmer10Test()
{
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("*", "non_existent"), shouldCatch: @"missing");
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("non_existent", "test_warmer1"), shouldCatch: @"missing");
}
}
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class CheckDeleteWithBlankIndexAndBlankTestWarmer11Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase
{
[Test]
public void CheckDeleteWithBlankIndexAndBlankTestWarmer11Test()
{
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("", "test_warmer1"), shouldCatch: @"param");
//do indices.delete_warmer
this.Do(()=> _client.IndicesDeleteWarmer("test_index1", ""), shouldCatch: @"param");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
** Purpose: Defines the settings that the loader uses to find assemblies in an
** AppDomain
**
**
=============================================================================*/
namespace System
{
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using Path = System.IO.Path;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
internal sealed class AppDomainSetup
{
internal enum LoaderInformation
{
// If you add a new value, add the corresponding property
// to AppDomain.GetData() and SetData()'s switch statements,
// as well as fusionsetup.h.
ApplicationBaseValue = 0, // LOADER_APPLICATION_BASE
ConfigurationFileValue = 1, // LOADER_CONFIGURATION_BASE
DynamicBaseValue = 2, // LOADER_DYNAMIC_BASE
DevPathValue = 3, // LOADER_DEVPATH
ApplicationNameValue = 4, // LOADER_APPLICATION_NAME
PrivateBinPathValue = 5, // LOADER_PRIVATE_PATH
PrivateBinPathProbeValue = 6, // LOADER_PRIVATE_BIN_PATH_PROBE
ShadowCopyDirectoriesValue = 7, // LOADER_SHADOW_COPY_DIRECTORIES
ShadowCopyFilesValue = 8, // LOADER_SHADOW_COPY_FILES
CachePathValue = 9, // LOADER_CACHE_PATH
LicenseFileValue = 10, // LOADER_LICENSE_FILE
DisallowPublisherPolicyValue = 11, // LOADER_DISALLOW_PUBLISHER_POLICY
DisallowCodeDownloadValue = 12, // LOADER_DISALLOW_CODE_DOWNLOAD
DisallowBindingRedirectsValue = 13, // LOADER_DISALLOW_BINDING_REDIRECTS
DisallowAppBaseProbingValue = 14, // LOADER_DISALLOW_APPBASE_PROBING
ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES
LoaderMaximum = 18 // LOADER_MAXIMUM
}
// Constants from fusionsetup.h.
private const string LOADER_OPTIMIZATION = "LOADER_OPTIMIZATION";
private const string ACTAG_APP_BASE_URL = "APPBASE";
// This class has an unmanaged representation so be aware you will need to make edits in vm\object.h if you change the order
// of these fields or add new ones.
private string[] _Entries;
#pragma warning disable 169
private String _AppBase; // for compat with v1.1
#pragma warning restore 169
// A collection of strings used to indicate which breaking changes shouldn't be applied
// to an AppDomain. We only use the keys, the values are ignored.
[OptionalField(VersionAdded = 4)]
private Dictionary<string, object> _CompatFlags;
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private String _TargetFrameworkName;
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private bool _CheckedForTargetFrameworkName;
#if FEATURE_RANDOMIZED_STRING_HASHING
[OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
private bool _UseRandomizedStringHashing;
#endif
internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData)
{
string[] mine = Value;
if (copy != null)
{
string[] other = copy.Value;
int mineSize = _Entries.Length;
int otherSize = other.Length;
int size = (otherSize < mineSize) ? otherSize : mineSize;
for (int i = 0; i < size; i++)
mine[i] = other[i];
if (size < mineSize)
{
// This case can happen when the copy is a deserialized version of
// an AppDomainSetup object serialized by Everett.
for (int i = size; i < mineSize; i++)
mine[i] = null;
}
if (copy._CompatFlags != null)
{
SetCompatibilitySwitches(copy._CompatFlags.Keys);
}
_TargetFrameworkName = copy._TargetFrameworkName;
#if FEATURE_RANDOMIZED_STRING_HASHING
_UseRandomizedStringHashing = copy._UseRandomizedStringHashing;
#endif
}
}
public AppDomainSetup()
{
}
internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false)
{
char[] sep = { '\\', '/' };
int i = imageLocation.LastIndexOfAny(sep);
if (i == -1)
{
ApplicationName = imageLocation;
}
else
{
ApplicationName = imageLocation.Substring(i + 1);
string appBase = imageLocation.Substring(0, i + 1);
if (imageLocationAlreadyNormalized)
Value[(int)LoaderInformation.ApplicationBaseValue] = appBase;
else
ApplicationBase = appBase;
}
}
internal string[] Value
{
get
{
if (_Entries == null)
_Entries = new String[(int)LoaderInformation.LoaderMaximum];
return _Entries;
}
}
public String ApplicationBase
{
[Pure]
get
{
return Value[(int)LoaderInformation.ApplicationBaseValue];
}
set
{
Value[(int)LoaderInformation.ApplicationBaseValue] = (value == null || value.Length == 0)?null:Path.GetFullPath(value);
}
}
// only needed by AppDomain.Setup(). Not really needed by users.
internal Dictionary<string, object> GetCompatibilityFlags()
{
return _CompatFlags;
}
public void SetCompatibilitySwitches(IEnumerable<String> switches)
{
#if FEATURE_RANDOMIZED_STRING_HASHING
_UseRandomizedStringHashing = false;
#endif
if (switches != null)
{
_CompatFlags = new Dictionary<string, object>();
foreach (String str in switches)
{
#if FEATURE_RANDOMIZED_STRING_HASHING
if (StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str))
{
_UseRandomizedStringHashing = true;
}
#endif
_CompatFlags.Add(str, null);
}
}
else
{
_CompatFlags = null;
}
}
// A target Framework moniker, in a format parsible by the FrameworkName class.
public String TargetFrameworkName
{
get
{
return _TargetFrameworkName;
}
set
{
_TargetFrameworkName = value;
}
}
public String ApplicationName
{
get
{
return Value[(int)LoaderInformation.ApplicationNameValue];
}
set
{
Value[(int)LoaderInformation.ApplicationNameValue] = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NPoco;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Core.Notifications;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Scoping;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Infrastructure.Persistence.Dtos;
using Umbraco.Cms.Infrastructure.Persistence.Factories;
using Umbraco.Cms.Infrastructure.Persistence.Querying;
using Umbraco.Extensions;
using static Umbraco.Cms.Core.Persistence.SqlExtensionsStatics;
namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement
{
/// <summary>
/// Represents a repository for doing CRUD operations for <see cref="IMember" />
/// </summary>
public class MemberRepository : ContentRepositoryBase<int, IMember, MemberRepository>, IMemberRepository
{
private readonly IJsonSerializer _jsonSerializer;
private readonly IRepositoryCachePolicy<IMember, string> _memberByUsernameCachePolicy;
private readonly IMemberGroupRepository _memberGroupRepository;
private readonly IMemberTypeRepository _memberTypeRepository;
private readonly MemberPasswordConfigurationSettings _passwordConfiguration;
private readonly IPasswordHasher _passwordHasher;
private readonly ITagRepository _tagRepository;
private bool _passwordConfigInitialized;
private string _passwordConfigJson;
public MemberRepository(
IScopeAccessor scopeAccessor,
AppCaches cache,
ILogger<MemberRepository> logger,
IMemberTypeRepository memberTypeRepository,
IMemberGroupRepository memberGroupRepository,
ITagRepository tagRepository,
ILanguageRepository languageRepository,
IRelationRepository relationRepository,
IRelationTypeRepository relationTypeRepository,
IPasswordHasher passwordHasher,
PropertyEditorCollection propertyEditors,
DataValueReferenceFactoryCollection dataValueReferenceFactories,
IDataTypeService dataTypeService,
IJsonSerializer serializer,
IEventAggregator eventAggregator,
IOptions<MemberPasswordConfigurationSettings> passwordConfiguration)
: base(scopeAccessor, cache, logger, languageRepository, relationRepository, relationTypeRepository,
propertyEditors, dataValueReferenceFactories, dataTypeService, eventAggregator)
{
_memberTypeRepository =
memberTypeRepository ?? throw new ArgumentNullException(nameof(memberTypeRepository));
_tagRepository = tagRepository ?? throw new ArgumentNullException(nameof(tagRepository));
_passwordHasher = passwordHasher;
_jsonSerializer = serializer;
_memberGroupRepository = memberGroupRepository;
_passwordConfiguration = passwordConfiguration.Value;
_memberByUsernameCachePolicy =
new DefaultRepositoryCachePolicy<IMember, string>(GlobalIsolatedCache, ScopeAccessor, DefaultOptions);
}
/// <summary>
/// Returns a serialized dictionary of the password configuration that is stored against the member in the database
/// </summary>
private string DefaultPasswordConfigJson
{
get
{
if (_passwordConfigInitialized)
{
return _passwordConfigJson;
}
var passwordConfig = new PersistedPasswordSettings
{
HashAlgorithm = _passwordConfiguration.HashAlgorithmType
};
_passwordConfigJson = passwordConfig == null ? null : _jsonSerializer.Serialize(passwordConfig);
_passwordConfigInitialized = true;
return _passwordConfigJson;
}
}
protected override MemberRepository This => this;
public override int RecycleBinId => throw new NotSupportedException();
public IEnumerable<IMember> FindMembersInRole(string roleName, string usernameToMatch,
StringPropertyMatchType matchType = StringPropertyMatchType.StartsWith)
{
//get the group id
IQuery<IMemberGroup> grpQry = Query<IMemberGroup>().Where(group => group.Name.Equals(roleName));
IMemberGroup memberGroup = _memberGroupRepository.Get(grpQry).FirstOrDefault();
if (memberGroup == null)
{
return Enumerable.Empty<IMember>();
}
// get the members by username
IQuery<IMember> query = Query<IMember>();
switch (matchType)
{
case StringPropertyMatchType.Exact:
query.Where(member => member.Username.Equals(usernameToMatch));
break;
case StringPropertyMatchType.Contains:
query.Where(member => member.Username.Contains(usernameToMatch));
break;
case StringPropertyMatchType.StartsWith:
query.Where(member => member.Username.StartsWith(usernameToMatch));
break;
case StringPropertyMatchType.EndsWith:
query.Where(member => member.Username.EndsWith(usernameToMatch));
break;
case StringPropertyMatchType.Wildcard:
query.Where(member => member.Username.SqlWildcard(usernameToMatch, TextColumnType.NVarchar));
break;
default:
throw new ArgumentOutOfRangeException(nameof(matchType));
}
IMember[] matchedMembers = Get(query).ToArray();
var membersInGroup = new List<IMember>();
//then we need to filter the matched members that are in the role
foreach (IEnumerable<int> group in matchedMembers.Select(x => x.Id)
.InGroupsOf(Constants.Sql.MaxParameterCount))
{
Sql<ISqlContext> sql = Sql().SelectAll().From<Member2MemberGroupDto>()
.Where<Member2MemberGroupDto>(dto => dto.MemberGroup == memberGroup.Id)
.WhereIn<Member2MemberGroupDto>(dto => dto.Member, group);
var memberIdsInGroup = Database.Fetch<Member2MemberGroupDto>(sql)
.Select(x => x.Member).ToArray();
membersInGroup.AddRange(matchedMembers.Where(x => memberIdsInGroup.Contains(x.Id)));
}
return membersInGroup;
}
/// <summary>
/// Get all members in a specific group
/// </summary>
/// <param name="groupName"></param>
/// <returns></returns>
public IEnumerable<IMember> GetByMemberGroup(string groupName)
{
IQuery<IMemberGroup> grpQry = Query<IMemberGroup>().Where(group => group.Name.Equals(groupName));
IMemberGroup memberGroup = _memberGroupRepository.Get(grpQry).FirstOrDefault();
if (memberGroup == null)
{
return Enumerable.Empty<IMember>();
}
Sql<ISqlContext> subQuery = Sql().Select("Member").From<Member2MemberGroupDto>()
.Where<Member2MemberGroupDto>(dto => dto.MemberGroup == memberGroup.Id);
Sql<ISqlContext> sql = GetBaseQuery(false)
// TODO: An inner join would be better, though I've read that the query optimizer will always turn a
// subquery with an IN clause into an inner join anyways.
.Append("WHERE umbracoNode.id IN (" + subQuery.SQL + ")", subQuery.Arguments)
.OrderByDescending<ContentVersionDto>(x => x.VersionDate)
.OrderBy<NodeDto>(x => x.SortOrder);
return MapDtosToContent(Database.Fetch<MemberDto>(sql));
}
public bool Exists(string username)
{
Sql<ISqlContext> sql = Sql()
.SelectCount()
.From<MemberDto>()
.Where<MemberDto>(x => x.LoginName == username);
return Database.ExecuteScalar<int>(sql) > 0;
}
public int GetCountByQuery(IQuery<IMember> query)
{
Sql<ISqlContext> sqlWithProps = GetNodeIdQueryWithPropertyData();
var translator = new SqlTranslator<IMember>(sqlWithProps, query);
Sql<ISqlContext> sql = translator.Translate();
//get the COUNT base query
Sql<ISqlContext> fullSql = GetBaseQuery(true)
.Append(new Sql("WHERE umbracoNode.id IN (" + sql.SQL + ")", sql.Arguments));
return Database.ExecuteScalar<int>(fullSql);
}
/// <inheritdoc />
public void SetLastLogin(string username, DateTime date)
{
// Important - these queries are designed to execute without an exclusive WriteLock taken in our distributed lock
// table. However due to the data that we are updating which relies on version data we cannot update this data
// without taking some locks, otherwise we'll end up with strange situations because when a member is updated, that operation
// deletes and re-inserts all property data. So if there are concurrent transactions, one deleting and re-inserting and another trying
// to update there can be problems. This is only an issue for cmsPropertyData, not umbracoContentVersion because that table just
// maintains a single row and it isn't deleted/re-inserted.
// So the important part here is the ForUpdate() call on the select to fetch the property data to update.
// Update the cms property value for the member
SqlTemplate sqlSelectTemplateProperty = SqlContext.Templates.Get(
"Umbraco.Core.MemberRepository.SetLastLogin1", s => s
.Select<PropertyDataDto>(x => x.Id)
.From<PropertyDataDto>()
.InnerJoin<PropertyTypeDto>()
.On<PropertyTypeDto, PropertyDataDto>((l, r) => l.Id == r.PropertyTypeId)
.InnerJoin<ContentVersionDto>()
.On<ContentVersionDto, PropertyDataDto>((l, r) => l.Id == r.VersionId)
.InnerJoin<NodeDto>().On<NodeDto, ContentVersionDto>((l, r) => l.NodeId == r.NodeId)
.InnerJoin<MemberDto>().On<MemberDto, NodeDto>((l, r) => l.NodeId == r.NodeId)
.Where<NodeDto>(x => x.NodeObjectType == SqlTemplate.Arg<Guid>("nodeObjectType"))
.Where<PropertyTypeDto>(x => x.Alias == SqlTemplate.Arg<string>("propertyTypeAlias"))
.Where<MemberDto>(x => x.LoginName == SqlTemplate.Arg<string>("username"))
.ForUpdate());
Sql<ISqlContext> sqlSelectProperty = sqlSelectTemplateProperty.Sql(Constants.ObjectTypes.Member,
Constants.Conventions.Member.LastLoginDate, username);
Sql<ISqlContext> update = Sql()
.Update<PropertyDataDto>(u => u
.Set(x => x.DateValue, date))
.WhereIn<PropertyDataDto>(x => x.Id, sqlSelectProperty);
Database.Execute(update);
// Update the umbracoContentVersion value for the member
SqlTemplate sqlSelectTemplateVersion = SqlContext.Templates.Get(
"Umbraco.Core.MemberRepository.SetLastLogin2", s => s
.Select<ContentVersionDto>(x => x.Id)
.From<ContentVersionDto>()
.InnerJoin<NodeDto>().On<NodeDto, ContentVersionDto>((l, r) => l.NodeId == r.NodeId)
.InnerJoin<MemberDto>().On<MemberDto, NodeDto>((l, r) => l.NodeId == r.NodeId)
.Where<NodeDto>(x => x.NodeObjectType == SqlTemplate.Arg<Guid>("nodeObjectType"))
.Where<MemberDto>(x => x.LoginName == SqlTemplate.Arg<string>("username")));
Sql<ISqlContext> sqlSelectVersion = sqlSelectTemplateVersion.Sql(Constants.ObjectTypes.Member, username);
Database.Execute(Sql()
.Update<ContentVersionDto>(u => u
.Set(x => x.VersionDate, date))
.WhereIn<ContentVersionDto>(x => x.Id, sqlSelectVersion));
}
/// <summary>
/// Gets paged member results.
/// </summary>
public override IEnumerable<IMember> GetPage(IQuery<IMember> query,
long pageIndex, int pageSize, out long totalRecords,
IQuery<IMember> filter,
Ordering ordering)
{
Sql<ISqlContext> filterSql = null;
if (filter != null)
{
filterSql = Sql();
foreach (Tuple<string, object[]> clause in filter.GetWhereClauses())
{
filterSql = filterSql.Append($"AND ({clause.Item1})", clause.Item2);
}
}
return GetPage<MemberDto>(query, pageIndex, pageSize, out totalRecords,
x => MapDtosToContent(x),
filterSql,
ordering);
}
public IMember GetByUsername(string username) =>
_memberByUsernameCachePolicy.Get(username, PerformGetByUsername, PerformGetAllByUsername);
public int[] GetMemberIds(string[] usernames)
{
Guid memberObjectType = Constants.ObjectTypes.Member;
Sql<ISqlContext> memberSql = Sql()
.Select("umbracoNode.id")
.From<NodeDto>()
.InnerJoin<MemberDto>()
.On<NodeDto, MemberDto>(dto => dto.NodeId, dto => dto.NodeId)
.Where<NodeDto>(x => x.NodeObjectType == memberObjectType)
.Where("cmsMember.LoginName in (@usernames)", new
{
/*usernames =*/
usernames
});
return Database.Fetch<int>(memberSql).ToArray();
}
protected override string ApplySystemOrdering(ref Sql<ISqlContext> sql, Ordering ordering)
{
if (ordering.OrderBy.InvariantEquals("email"))
{
return SqlSyntax.GetFieldName<MemberDto>(x => x.Email);
}
if (ordering.OrderBy.InvariantEquals("loginName"))
{
return SqlSyntax.GetFieldName<MemberDto>(x => x.LoginName);
}
if (ordering.OrderBy.InvariantEquals("userName"))
{
return SqlSyntax.GetFieldName<MemberDto>(x => x.LoginName);
}
if (ordering.OrderBy.InvariantEquals("updateDate"))
{
return SqlSyntax.GetFieldName<ContentVersionDto>(x => x.VersionDate);
}
if (ordering.OrderBy.InvariantEquals("createDate"))
{
return SqlSyntax.GetFieldName<NodeDto>(x => x.CreateDate);
}
if (ordering.OrderBy.InvariantEquals("contentTypeAlias"))
{
return SqlSyntax.GetFieldName<ContentTypeDto>(x => x.Alias);
}
return base.ApplySystemOrdering(ref sql, ordering);
}
private IEnumerable<IMember> MapDtosToContent(List<MemberDto> dtos, bool withCache = false)
{
var temps = new List<TempContent<Member>>();
var contentTypes = new Dictionary<int, IMemberType>();
var content = new Member[dtos.Count];
for (var i = 0; i < dtos.Count; i++)
{
MemberDto dto = dtos[i];
if (withCache)
{
// if the cache contains the (proper version of the) item, use it
IMember cached =
IsolatedCache.GetCacheItem<IMember>(RepositoryCacheKeys.GetKey<IMember, int>(dto.NodeId));
if (cached != null && cached.VersionId == dto.ContentVersionDto.Id)
{
content[i] = (Member)cached;
continue;
}
}
// else, need to build it
// get the content type - the repository is full cache *but* still deep-clones
// whatever comes out of it, so use our own local index here to avoid this
var contentTypeId = dto.ContentDto.ContentTypeId;
if (contentTypes.TryGetValue(contentTypeId, out IMemberType contentType) == false)
{
contentTypes[contentTypeId] = contentType = _memberTypeRepository.Get(contentTypeId);
}
Member c = content[i] = ContentBaseFactory.BuildEntity(dto, contentType);
// need properties
var versionId = dto.ContentVersionDto.Id;
temps.Add(new TempContent<Member>(dto.NodeId, versionId, 0, contentType, c));
}
// load all properties for all documents from database in 1 query - indexed by version id
IDictionary<int, PropertyCollection> properties = GetPropertyCollections(temps);
// assign properties
foreach (TempContent<Member> temp in temps)
{
temp.Content.Properties = properties[temp.VersionId];
// reset dirty initial properties (U4-1946)
temp.Content.ResetDirtyProperties(false);
}
return content;
}
private IMember MapDtoToContent(MemberDto dto)
{
IMemberType memberType = _memberTypeRepository.Get(dto.ContentDto.ContentTypeId);
Member member = ContentBaseFactory.BuildEntity(dto, memberType);
// get properties - indexed by version id
var versionId = dto.ContentVersionDto.Id;
var temp = new TempContent<Member>(dto.ContentDto.NodeId, versionId, 0, memberType);
IDictionary<int, PropertyCollection> properties =
GetPropertyCollections(new List<TempContent<Member>> { temp });
member.Properties = properties[versionId];
// reset dirty initial properties (U4-1946)
member.ResetDirtyProperties(false);
return member;
}
private IMember PerformGetByUsername(string username)
{
IQuery<IMember> query = Query<IMember>().Where(x => x.Username.Equals(username));
return PerformGetByQuery(query).FirstOrDefault();
}
private IEnumerable<IMember> PerformGetAllByUsername(params string[] usernames)
{
IQuery<IMember> query = Query<IMember>().WhereIn(x => x.Username, usernames);
return PerformGetByQuery(query);
}
#region Repository Base
protected override Guid NodeObjectTypeId => Constants.ObjectTypes.Member;
protected override IMember PerformGet(int id)
{
Sql<ISqlContext> sql = GetBaseQuery(QueryType.Single)
.Where<NodeDto>(x => x.NodeId == id)
.SelectTop(1);
MemberDto dto = Database.Fetch<MemberDto>(sql).FirstOrDefault();
return dto == null
? null
: MapDtoToContent(dto);
}
protected override IEnumerable<IMember> PerformGetAll(params int[] ids)
{
Sql<ISqlContext> sql = GetBaseQuery(QueryType.Many);
if (ids.Any())
{
sql.WhereIn<NodeDto>(x => x.NodeId, ids);
}
return MapDtosToContent(Database.Fetch<MemberDto>(sql));
}
protected override IEnumerable<IMember> PerformGetByQuery(IQuery<IMember> query)
{
Sql<ISqlContext> baseQuery = GetBaseQuery(false);
// TODO: why is this different from content/media?!
// check if the query is based on properties or not
IEnumerable<Tuple<string, object[]>> wheres = query.GetWhereClauses();
//this is a pretty rudimentary check but will work, we just need to know if this query requires property
// level queries
if (wheres.Any(x => x.Item1.Contains("cmsPropertyType")))
{
Sql<ISqlContext> sqlWithProps = GetNodeIdQueryWithPropertyData();
var translator = new SqlTranslator<IMember>(sqlWithProps, query);
Sql<ISqlContext> sql = translator.Translate();
baseQuery.Append("WHERE umbracoNode.id IN (" + sql.SQL + ")", sql.Arguments)
.OrderBy<NodeDto>(x => x.SortOrder);
return MapDtosToContent(Database.Fetch<MemberDto>(baseQuery));
}
else
{
var translator = new SqlTranslator<IMember>(baseQuery, query);
Sql<ISqlContext> sql = translator.Translate()
.OrderBy<NodeDto>(x => x.SortOrder);
return MapDtosToContent(Database.Fetch<MemberDto>(sql));
}
}
protected override Sql<ISqlContext> GetBaseQuery(QueryType queryType) => GetBaseQuery(queryType, true);
protected virtual Sql<ISqlContext> GetBaseQuery(QueryType queryType, bool current)
{
Sql<ISqlContext> sql = SqlContext.Sql();
switch (queryType) // TODO: pretend we still need these queries for now
{
case QueryType.Count:
sql = sql.SelectCount();
break;
case QueryType.Ids:
sql = sql.Select<MemberDto>(x => x.NodeId);
break;
case QueryType.Single:
case QueryType.Many:
sql = sql.Select<MemberDto>(r =>
r.Select(x => x.ContentVersionDto)
.Select(x => x.ContentDto, r1 =>
r1.Select(x => x.NodeDto)))
// ContentRepositoryBase expects a variantName field to order by name
// so get it here, though for members it's just the plain node name
.AndSelect<NodeDto>(x => Alias(x.Text, "variantName"));
break;
}
sql
.From<MemberDto>()
.InnerJoin<ContentDto>().On<MemberDto, ContentDto>(left => left.NodeId, right => right.NodeId)
.InnerJoin<NodeDto>().On<ContentDto, NodeDto>(left => left.NodeId, right => right.NodeId)
.InnerJoin<ContentVersionDto>()
.On<ContentDto, ContentVersionDto>(left => left.NodeId, right => right.NodeId)
// joining the type so we can do a query against the member type - not sure if this adds much overhead or not?
// the execution plan says it doesn't so we'll go with that and in that case, it might be worth joining the content
// types by default on the document and media repos so we can query by content type there too.
.InnerJoin<ContentTypeDto>()
.On<ContentDto, ContentTypeDto>(left => left.ContentTypeId, right => right.NodeId);
sql.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
if (current)
{
sql.Where<ContentVersionDto>(x => x.Current); // always get the current version
}
return sql;
}
// TODO: move that one up to Versionable! or better: kill it!
protected override Sql<ISqlContext> GetBaseQuery(bool isCount) =>
GetBaseQuery(isCount ? QueryType.Count : QueryType.Single);
protected override string GetBaseWhereClause() // TODO: can we kill / refactor this?
=>
"umbracoNode.id = @id";
// TODO: document/understand that one
protected Sql<ISqlContext> GetNodeIdQueryWithPropertyData() =>
Sql()
.Select("DISTINCT(umbracoNode.id)")
.From<NodeDto>()
.InnerJoin<ContentDto>().On<NodeDto, ContentDto>((left, right) => left.NodeId == right.NodeId)
.InnerJoin<ContentTypeDto>()
.On<ContentDto, ContentTypeDto>((left, right) => left.ContentTypeId == right.NodeId)
.InnerJoin<ContentVersionDto>()
.On<NodeDto, ContentVersionDto>((left, right) => left.NodeId == right.NodeId)
.InnerJoin<MemberDto>().On<ContentDto, MemberDto>((left, right) => left.NodeId == right.NodeId)
.LeftJoin<PropertyTypeDto>()
.On<ContentDto, PropertyTypeDto>(left => left.ContentTypeId, right => right.ContentTypeId)
.LeftJoin<DataTypeDto>()
.On<PropertyTypeDto, DataTypeDto>(left => left.DataTypeId, right => right.NodeId)
.LeftJoin<PropertyDataDto>().On(x => x
.Where<PropertyDataDto, PropertyTypeDto>((left, right) => left.PropertyTypeId == right.Id)
.Where<PropertyDataDto, ContentVersionDto>((left, right) => left.VersionId == right.Id))
.Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
protected override IEnumerable<string> GetDeleteClauses()
{
var list = new List<string>
{
"DELETE FROM umbracoUser2NodeNotify WHERE nodeId = @id",
"DELETE FROM umbracoUserGroup2Node WHERE nodeId = @id",
"DELETE FROM umbracoUserGroup2NodePermission WHERE nodeId = @id",
"DELETE FROM umbracoRelation WHERE parentId = @id",
"DELETE FROM umbracoRelation WHERE childId = @id",
"DELETE FROM cmsTagRelationship WHERE nodeId = @id",
"DELETE FROM " + Constants.DatabaseSchema.Tables.PropertyData +
" WHERE versionId IN (SELECT id FROM " + Constants.DatabaseSchema.Tables.ContentVersion +
" WHERE nodeId = @id)",
"DELETE FROM cmsMember2MemberGroup WHERE Member = @id",
"DELETE FROM cmsMember WHERE nodeId = @id",
"DELETE FROM " + Constants.DatabaseSchema.Tables.ContentVersion + " WHERE nodeId = @id",
"DELETE FROM " + Constants.DatabaseSchema.Tables.Content + " WHERE nodeId = @id",
"DELETE FROM umbracoNode WHERE id = @id"
};
return list;
}
#endregion
#region Versions
public override IEnumerable<IMember> GetAllVersions(int nodeId)
{
Sql<ISqlContext> sql = GetBaseQuery(QueryType.Many, false)
.Where<NodeDto>(x => x.NodeId == nodeId)
.OrderByDescending<ContentVersionDto>(x => x.Current)
.AndByDescending<ContentVersionDto>(x => x.VersionDate);
return MapDtosToContent(Database.Fetch<MemberDto>(sql), true);
}
public override IMember GetVersion(int versionId)
{
Sql<ISqlContext> sql = GetBaseQuery(QueryType.Single)
.Where<ContentVersionDto>(x => x.Id == versionId);
MemberDto dto = Database.Fetch<MemberDto>(sql).FirstOrDefault();
return dto == null ? null : MapDtoToContent(dto);
}
protected override void PerformDeleteVersion(int id, int versionId)
{
Database.Delete<PropertyDataDto>("WHERE versionId = @VersionId", new { versionId });
Database.Delete<ContentVersionDto>("WHERE versionId = @VersionId", new { versionId });
}
#endregion
#region Persist
protected override void PersistNewItem(IMember entity)
{
entity.AddingEntity();
// ensure security stamp if missing
if (entity.SecurityStamp.IsNullOrWhiteSpace())
{
entity.SecurityStamp = Guid.NewGuid().ToString();
}
// ensure that strings don't contain characters that are invalid in xml
// TODO: do we really want to keep doing this here?
entity.SanitizeEntityPropertiesForXmlStorage();
// create the dto
MemberDto memberDto = ContentBaseFactory.BuildDto(entity);
// check if we have a user config else use the default
memberDto.PasswordConfig = entity.PasswordConfiguration ?? DefaultPasswordConfigJson;
// derive path and level from parent
NodeDto parent = GetParentNodeDto(entity.ParentId);
var level = parent.Level + 1;
// get sort order
var sortOrder = GetNewChildSortOrder(entity.ParentId, 0);
// persist the node dto
NodeDto nodeDto = memberDto.ContentDto.NodeDto;
nodeDto.Path = parent.Path;
nodeDto.Level = Convert.ToInt16(level);
nodeDto.SortOrder = sortOrder;
// see if there's a reserved identifier for this unique id
// and then either update or insert the node dto
var id = GetReservedId(nodeDto.UniqueId);
if (id > 0)
{
nodeDto.NodeId = id;
nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
nodeDto.ValidatePathWithException();
Database.Update(nodeDto);
}
else
{
Database.Insert(nodeDto);
// update path, now that we have an id
nodeDto.Path = string.Concat(parent.Path, ",", nodeDto.NodeId);
nodeDto.ValidatePathWithException();
Database.Update(nodeDto);
}
// update entity
entity.Id = nodeDto.NodeId;
entity.Path = nodeDto.Path;
entity.SortOrder = sortOrder;
entity.Level = level;
// persist the content dto
ContentDto contentDto = memberDto.ContentDto;
contentDto.NodeId = nodeDto.NodeId;
Database.Insert(contentDto);
// persist the content version dto
// assumes a new version id and version date (modified date) has been set
ContentVersionDto contentVersionDto = memberDto.ContentVersionDto;
contentVersionDto.NodeId = nodeDto.NodeId;
contentVersionDto.Current = true;
Database.Insert(contentVersionDto);
entity.VersionId = contentVersionDto.Id;
// persist the member dto
memberDto.NodeId = nodeDto.NodeId;
// if the password is empty, generate one with the special prefix
// this will hash the guid with a salt so should be nicely random
if (entity.RawPasswordValue.IsNullOrWhiteSpace())
{
memberDto.Password = Constants.Security.EmptyPasswordPrefix +
_passwordHasher.HashPassword(Guid.NewGuid().ToString("N"));
entity.RawPasswordValue = memberDto.Password;
}
Database.Insert(memberDto);
// persist the property data
InsertPropertyValues(entity, 0, out _, out _);
SetEntityTags(entity, _tagRepository, _jsonSerializer);
PersistRelations(entity);
OnUowRefreshedEntity(new MemberRefreshNotification(entity, new EventMessages()));
entity.ResetDirtyProperties();
}
protected override void PersistUpdatedItem(IMember entity)
{
// update
entity.UpdatingEntity();
// ensure security stamp if missing
if (entity.SecurityStamp.IsNullOrWhiteSpace())
{
entity.SecurityStamp = Guid.NewGuid().ToString();
}
// ensure that strings don't contain characters that are invalid in xml
// TODO: do we really want to keep doing this here?
entity.SanitizeEntityPropertiesForXmlStorage();
// if parent has changed, get path, level and sort order
if (entity.IsPropertyDirty("ParentId"))
{
NodeDto parent = GetParentNodeDto(entity.ParentId);
entity.Path = string.Concat(parent.Path, ",", entity.Id);
entity.Level = parent.Level + 1;
entity.SortOrder = GetNewChildSortOrder(entity.ParentId, 0);
}
// create the dto
MemberDto memberDto = ContentBaseFactory.BuildDto(entity);
// update the node dto
NodeDto nodeDto = memberDto.ContentDto.NodeDto;
Database.Update(nodeDto);
// update the content dto
Database.Update(memberDto.ContentDto);
// update the content version dto
Database.Update(memberDto.ContentVersionDto);
// update the member dto
// but only the changed columns, 'cos we cannot update password if empty
var changedCols = new List<string>();
if (entity.IsPropertyDirty("SecurityStamp"))
{
changedCols.Add("securityStampToken");
}
if (entity.IsPropertyDirty("Email"))
{
changedCols.Add("Email");
}
if (entity.IsPropertyDirty("Username"))
{
changedCols.Add("LoginName");
}
// this can occur from an upgrade
if (memberDto.PasswordConfig.IsNullOrWhiteSpace())
{
memberDto.PasswordConfig = DefaultPasswordConfigJson;
changedCols.Add("passwordConfig");
}else if (memberDto.PasswordConfig == Constants.Security.UnknownPasswordConfigJson)
{
changedCols.Add("passwordConfig");
}
// do NOT update the password if it has not changed or if it is null or empty
if (entity.IsPropertyDirty("RawPasswordValue") && !string.IsNullOrWhiteSpace(entity.RawPasswordValue))
{
changedCols.Add("Password");
// If the security stamp hasn't already updated we need to force it
if (entity.IsPropertyDirty("SecurityStamp") == false)
{
memberDto.SecurityStampToken = entity.SecurityStamp = Guid.NewGuid().ToString();
changedCols.Add("securityStampToken");
}
// check if we have a user config else use the default
memberDto.PasswordConfig = entity.PasswordConfiguration ?? DefaultPasswordConfigJson;
changedCols.Add("passwordConfig");
}
// If userlogin or the email has changed then need to reset security stamp
if (changedCols.Contains("Email") || changedCols.Contains("LoginName"))
{
memberDto.EmailConfirmedDate = null;
changedCols.Add("emailConfirmedDate");
// If the security stamp hasn't already updated we need to force it
if (entity.IsPropertyDirty("SecurityStamp") == false)
{
memberDto.SecurityStampToken = entity.SecurityStamp = Guid.NewGuid().ToString();
changedCols.Add("securityStampToken");
}
}
if (changedCols.Count > 0)
{
Database.Update(memberDto, changedCols);
}
ReplacePropertyValues(entity, entity.VersionId, 0, out _, out _);
SetEntityTags(entity, _tagRepository, _jsonSerializer);
PersistRelations(entity);
OnUowRefreshedEntity(new MemberRefreshNotification(entity, new EventMessages()));
entity.ResetDirtyProperties();
}
#endregion
}
}
| |
using EmpMan.Common.Enums;
using EmpMan.Model.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace EmpMan.Data.Infrastructure
{
public abstract class RepositoryBase<T> : IRepository<T> where T : class
{
#region Properties
private EmpManDbContext dataContext;
private readonly IDbSet<T> dbSet;
protected IDbFactory DbFactory
{
get;
private set;
}
protected EmpManDbContext DbContext
{
get { return dataContext ?? (dataContext = DbFactory.Init()); }
}
#endregion Properties
protected RepositoryBase(IDbFactory dbFactory)
{
DbFactory = dbFactory;
dbSet = DbContext.Set<T>();
}
#region Implementation
public virtual T Add(T entity)
{
return dbSet.Add(entity);
}
public virtual void Update(T entity)
{
dbSet.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual T Delete(T entity)
{
return dbSet.Remove(entity);
}
public virtual T Delete(int id)
{
var entity = dbSet.Find(id);
return dbSet.Remove(entity);
}
public virtual void DeleteMulti(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = dbSet.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
dbSet.Remove(obj);
}
public virtual T GetSingleById(int id)
{
return dbSet.Find(id);
}
public virtual T GetSingleByKey(object[] key)
{
return dbSet.Find(key);
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where, string includes)
{
return dbSet.Where(where).ToList();
}
public virtual int Count(Expression<Func<T, bool>> where)
{
return dbSet.Count(where);
}
//http://www.itworld.com/article/2700950/development/a-generic-repository-for--net-entity-framework-6-with-async-operations.html
public async Task<IEnumerable<T>> GetAllAsync()
{
return await dataContext.Set<T>().ToListAsync();
}
public IEnumerable<T> GetAll(string[] includes = null)
{
//HANDLE INCLUDES FOR ASSOCIATED OBJECTS IF APPLICABLE
if (includes != null && includes.Count() > 0)
{
var query = dataContext.Set<T>().Include(includes.First());
foreach (var include in includes.Skip(1))
query = query.Include(include);
return query.AsQueryable();
}
return dataContext.Set<T>().AsQueryable();
}
public IEnumerable<T> GetAllNoTracking(string[] includes = null)
{
//HANDLE INCLUDES FOR ASSOCIATED OBJECTS IF APPLICABLE
if (includes != null && includes.Count() > 0)
{
var query = dataContext.Set<T>().AsNoTracking<T>().Include(includes.First());
foreach (var include in includes.Skip(1))
query = query.Include(include);
return query.AsQueryable();
}
return dataContext.Set<T>().AsQueryable();
}
public T GetSingleByCondition(Expression<Func<T, bool>> expression, string[] includes = null)
{
if (includes != null && includes.Count() > 0)
{
var query = dataContext.Set<T>().Include(includes.First());
foreach (var include in includes.Skip(1))
query = query.Include(include);
return query.FirstOrDefault(expression);
}
return dataContext.Set<T>().FirstOrDefault(expression);
}
/// <summary>
/// Thay doi trang thai approved cua du lieu
/// </summary>
/// <param name="where"></param>
public void ChangeApprovedStatusMulti(Expression<Func<T, bool>> where, string userName, ApprovedStatusEnum approvedStatus)
{
IEnumerable<T> objects = dbSet.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
{
//-----------table doanh thu-----------
if (obj is Revenue )
{
//data doanh thu
Revenue tmp = obj as Revenue;
tmp.ApprovedBy = userName;
tmp.ApprovedStatus = (int)approvedStatus;
tmp.ApprovedDate = DateTime.Now;
Update(tmp as T);
}
//-----------table phong van-----------
if (obj is RecruitmentInterview)
{
//data doanh thu
RecruitmentInterview tmp = obj as RecruitmentInterview;
tmp.ApprovedBy = userName;
tmp.ApprovedStatus = (int)approvedStatus;
tmp.ApprovedDate = DateTime.Now;
Update(tmp as T);
}
//-----------table XXX-----------
//-----------table XXX-----------
//-----------table XXX-----------
//cap nhat du lieu cho entity
}
}
public virtual void UpdateEntity(T entityToUpdate)
{
var entry = this.dataContext.Entry(entityToUpdate);
var key = this.GetPrimaryKey(entry);
if (entry.State == EntityState.Detached)
{
var currentEntry = this.dbSet.Find(key);
if (currentEntry != null)
{
var attachedEntry = this.dataContext.Entry(currentEntry);
attachedEntry.CurrentValues.SetValues(entityToUpdate);
}
else
{
this.dbSet.Attach(entityToUpdate);
entry.State = EntityState.Modified;
}
}
}
//get key cua table
private int GetPrimaryKey(DbEntityEntry entry)
{
var myObject = entry.Entity;
var property =
myObject.GetType()
.GetProperties()
.FirstOrDefault(prop => Attribute.IsDefined(prop, typeof(KeyAttribute)));
return (int)property.GetValue(myObject, null);
}
/// <summary>
/// Thay doi trang thai approved cua du lieu dua vao ID cua table
/// </summary>
/// <param name="where"></param>
public void ChangeApprovedStatusById(int id, string userName, ApprovedStatusEnum approvedStatus)
{
}
public virtual IEnumerable<T> GetMulti(Expression<Func<T, bool>> predicate, string[] includes = null)
{
//HANDLE INCLUDES FOR ASSOCIATED OBJECTS IF APPLICABLE
if (includes != null && includes.Count() > 0)
{
var query = dataContext.Set<T>().Include(includes.First());
foreach (var include in includes.Skip(1))
query = query.Include(include);
return query.Where<T>(predicate).AsQueryable<T>();
}
return dataContext.Set<T>().Where<T>(predicate).AsQueryable<T>();
}
public virtual IEnumerable<T> GetMultiNoTracking(Expression<Func<T, bool>> predicate, string[] includes = null)
{
//HANDLE INCLUDES FOR ASSOCIATED OBJECTS IF APPLICABLE
if (includes != null && includes.Count() > 0)
{
var query = dataContext.Set<T>().AsNoTracking<T>().Include(includes.First());
foreach (var include in includes.Skip(1))
query = query.Include(include);
return query.Where<T>(predicate).AsQueryable<T>();
}
return dataContext.Set<T>().Where<T>(predicate).AsQueryable<T>();
}
public virtual IEnumerable<T> GetMultiPaging(Expression<Func<T, bool>> predicate, out int total, int index = 0, int size = 20, string[] includes = null)
{
int skipCount = index * size;
IQueryable<T> _resetSet;
//HANDLE INCLUDES FOR ASSOCIATED OBJECTS IF APPLICABLE
if (includes != null && includes.Count() > 0)
{
var query = dataContext.Set<T>().Include(includes.First());
foreach (var include in includes.Skip(1))
query = query.Include(include);
_resetSet = predicate != null ? query.Where<T>(predicate).AsQueryable() : query.AsQueryable();
}
else
{
_resetSet = predicate != null ? dataContext.Set<T>().Where<T>(predicate).AsQueryable() : dataContext.Set<T>().AsQueryable();
}
_resetSet = skipCount == 0 ? _resetSet.Take(size) : _resetSet.Skip(skipCount).Take(size);
total = _resetSet.Count();
return _resetSet.AsQueryable();
}
public virtual IEnumerable<T> GetMultiPagingNoTracking(Expression<Func<T, bool>> predicate, out int total, int index = 0, int size = 20, string[] includes = null)
{
int skipCount = index * size;
IQueryable<T> _resetSet;
//HANDLE INCLUDES FOR ASSOCIATED OBJECTS IF APPLICABLE
if (includes != null && includes.Count() > 0)
{
var query = dataContext.Set<T>().AsNoTracking<T>().Include(includes.First());
foreach (var include in includes.Skip(1))
query = query.Include(include);
_resetSet = predicate != null ? query.Where<T>(predicate).AsQueryable() : query.AsQueryable();
}
else
{
_resetSet = predicate != null ? dataContext.Set<T>().Where<T>(predicate).AsQueryable() : dataContext.Set<T>().AsQueryable();
}
_resetSet = skipCount == 0 ? _resetSet.Take(size) : _resetSet.Skip(skipCount).Take(size);
total = _resetSet.Count();
return _resetSet.AsQueryable();
}
public bool CheckContains(Expression<Func<T, bool>> predicate)
{
return dataContext.Set<T>().Count<T>(predicate) > 0;
}
#endregion Implementation
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public readonly ref struct ReadOnlySpan<T>
{
public static ReadOnlySpan<T> Empty { get { throw null; } }
public ReadOnlySpan(T[] array) { throw null;}
public ReadOnlySpan(T[] array, int start, int length) { throw null;}
public unsafe ReadOnlySpan(void* pointer, int length) { throw null;}
public bool IsEmpty { get { throw null; } }
public T this[int index] { get { throw null; }}
public int Length { get { throw null; } }
public void CopyTo(Span<T> destination) { }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) { throw null; }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference() { throw null; }
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
[System.ObsoleteAttribute("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ObsoleteAttribute("GetHashCode() on ReadOnlySpan will always throw an exception.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
#pragma warning restore 0809
public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { throw null; }
public static implicit operator ReadOnlySpan<T> (T[] array) { throw null; }
public static implicit operator ReadOnlySpan<T> (ArraySegment<T> arraySegment) { throw null; }
public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { throw null; }
public ReadOnlySpan<T> Slice(int start) { throw null; }
public ReadOnlySpan<T> Slice(int start, int length) { throw null; }
public T[] ToArray() { throw null; }
public bool TryCopyTo(Span<T> destination) { throw null; }
}
public readonly ref struct Span<T>
{
public static Span<T> Empty { get { throw null; } }
public Span(T[] array) { throw null;}
public Span(T[] array, int start, int length) { throw null;}
public unsafe Span(void* pointer, int length) { throw null;}
public bool IsEmpty { get { throw null; } }
public ref T this[int index] { get { throw null; } }
public int Length { get { throw null; } }
public void Clear() { }
public void Fill(T value) { }
public void CopyTo(Span<T> destination) { }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length) { throw null; }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference() { throw null; }
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
[System.ObsoleteAttribute("Equals() on Span will always throw an exception. Use == instead.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ObsoleteAttribute("GetHashCode() on Span will always throw an exception.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
#pragma warning restore 0809
public static bool operator ==(Span<T> left, Span<T> right) { throw null; }
public static implicit operator Span<T> (T[] array) { throw null; }
public static implicit operator Span<T> (ArraySegment<T> arraySegment) { throw null; }
public static implicit operator ReadOnlySpan<T> (Span<T> span) { throw null; }
public static bool operator !=(Span<T> left, Span<T> right) { throw null; }
public Span<T> Slice(int start) { throw null; }
public Span<T> Slice(int start, int length) { throw null; }
public T[] ToArray() { throw null; }
public bool TryCopyTo(Span<T> destination) { throw null; }
}
public static class SpanExtensions
{
public static int IndexOf<T>(this Span<T> span, T value) where T:struct, IEquatable<T> { throw null; }
public static int IndexOf<T>(this Span<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { throw null; }
public static int IndexOf(this Span<byte> span, byte value) { throw null; }
public static int IndexOf(this Span<byte> span, ReadOnlySpan<byte> value) { throw null; }
public static int IndexOfAny(this Span<byte> span, byte value0, byte value1) { throw null; }
public static int IndexOfAny(this Span<byte> span, byte value0, byte value1, byte value2) { throw null; }
public static int IndexOfAny(this Span<byte> span, ReadOnlySpan<byte> values) { throw null; }
public static bool SequenceEqual<T>(this Span<T> first, ReadOnlySpan<T> second) where T:struct, IEquatable<T> { throw null; }
public static bool SequenceEqual(this Span<byte> first, ReadOnlySpan<byte> second) { throw null; }
public static bool StartsWith<T>(this Span<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { throw null; }
public static bool StartsWith(this Span<byte> span, ReadOnlySpan<byte> value) { throw null; }
public static Span<byte> AsBytes<T>(this Span<T> source) where T : struct { throw null; }
public static Span<TTo> NonPortableCast<TFrom, TTo>(this Span<TFrom> source) where TFrom : struct where TTo : struct { throw null; }
public static ReadOnlySpan<char> AsReadOnlySpan(this string text) { throw null; }
public static Span<T> AsSpan<T>(this T[] array) { throw null; }
public static Span<T> AsSpan<T>(this ArraySegment<T> arraySegment) { throw null; }
public static ReadOnlySpan<T> AsReadOnlySpan<T>(this T[] array) { throw null; }
public static ReadOnlySpan<T> AsReadOnlySpan<T>(this ArraySegment<T> arraySegment) { throw null; }
public static void CopyTo<T>(this T[] array, Span<T> destination) { throw null; }
public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : struct, IEquatable<T> { throw null; }
public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { throw null; }
public static int IndexOf(this ReadOnlySpan<byte> span, byte value) { throw null; }
public static int IndexOf(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> value) { throw null; }
public static int IndexOfAny(this ReadOnlySpan<byte> span, byte value0, byte value1) { throw null; }
public static int IndexOfAny(this ReadOnlySpan<byte> span, byte value0, byte value1, byte value2) { throw null; }
public static int IndexOfAny(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> values) { throw null; }
public static bool SequenceEqual<T>(this ReadOnlySpan<T> first, ReadOnlySpan<T> second) where T : struct, IEquatable<T> { throw null; }
public static bool SequenceEqual(this ReadOnlySpan<byte> first, ReadOnlySpan<byte> second) { throw null; }
public static bool StartsWith<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : struct, IEquatable<T> { throw null; }
public static bool StartsWith(this ReadOnlySpan<byte> span, ReadOnlySpan<byte> value) { throw null; }
public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source) where T : struct { throw null; }
public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source) where TFrom : struct where TTo : struct { throw null; }
}
public readonly struct ReadOnlyMemory<T>
{
public static ReadOnlyMemory<T> Empty { get { throw null; } }
public ReadOnlyMemory(T[] array) { throw null;}
public ReadOnlyMemory(T[] array, int start, int length) { throw null;}
public bool IsEmpty { get { throw null; } }
public int Length { get { throw null; } }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
public bool Equals(ReadOnlyMemory<T> other) { throw null; }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static implicit operator ReadOnlyMemory<T>(T[] array) { throw null; }
public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) { throw null; }
public ReadOnlyMemory<T> Slice(int start) { throw null; }
public ReadOnlyMemory<T> Slice(int start, int length) { throw null; }
public ReadOnlySpan<T> Span { get { throw null; } }
public unsafe Buffers.MemoryHandle Retain(bool pin = false) { throw null; }
public T[] ToArray() { throw null; }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public bool DangerousTryGetArray(out ArraySegment<T> arraySegment) { throw null; }
}
public readonly struct Memory<T>
{
public static Memory<T> Empty { get { throw null; } }
public Memory(T[] array) { throw null;}
public Memory(T[] array, int start, int length) { throw null;}
public bool IsEmpty { get { throw null; } }
public int Length { get { throw null; } }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
public bool Equals(Memory<T> other) { throw null; }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static implicit operator Memory<T>(T[] array) { throw null; }
public static implicit operator Memory<T>(ArraySegment<T> arraySegment) { throw null; }
public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { throw null; }
public Memory<T> Slice(int start) { throw null; }
public Memory<T> Slice(int start, int length) { throw null; }
public Span<T> Span { get { throw null; } }
public unsafe Buffers.MemoryHandle Retain(bool pin = false) { throw null; }
public T[] ToArray() { throw null; }
public bool TryGetArray(out ArraySegment<T> arraySegment) { throw null; }
}
}
namespace System.Buffers
{
public unsafe struct MemoryHandle : IDisposable
{
public MemoryHandle(IRetainable owner, void* pointer = null, System.Runtime.InteropServices.GCHandle handle = default(System.Runtime.InteropServices.GCHandle)) { throw null; }
public void* Pointer { get { throw null; } }
public bool HasPointer { get { throw null; } }
public void Dispose() { throw null; }
}
public interface IRetainable
{
bool Release();
void Retain();
}
public abstract class OwnedMemory<T> : IDisposable, IRetainable
{
public Memory<T> Memory { get { throw null; } }
public abstract bool IsDisposed { get; }
protected abstract bool IsRetained { get; }
public abstract int Length { get; }
public abstract Span<T> Span { get; }
public void Dispose() { throw null; }
protected abstract void Dispose(bool disposing);
public abstract MemoryHandle Pin();
public abstract bool Release();
public abstract void Retain();
protected internal abstract bool TryGetArray(out ArraySegment<T> arraySegment);
}
}
namespace System.Buffers.Binary
{
public static class BinaryPrimitives
{
public static sbyte ReverseEndianness(sbyte value) { throw null; }
public static byte ReverseEndianness(byte value) { throw null; }
public static short ReverseEndianness(short value) { throw null; }
public static ushort ReverseEndianness(ushort value) { throw null; }
public static int ReverseEndianness(int value) { throw null; }
public static uint ReverseEndianness(uint value) { throw null; }
public static long ReverseEndianness(long value) { throw null; }
public static ulong ReverseEndianness(ulong value) { throw null; }
public static T ReadMachineEndian<T>(ReadOnlySpan<byte> buffer) where T : struct { throw null; }
public static bool TryReadMachineEndian<T>(ReadOnlySpan<byte> buffer, out T value) where T : struct { throw null; }
public static short ReadInt16LittleEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static int ReadInt32LittleEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static long ReadInt64LittleEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static ushort ReadUInt16LittleEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static uint ReadUInt32LittleEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static ulong ReadUInt64LittleEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static bool TryReadInt16LittleEndian(ReadOnlySpan<byte> buffer, out short value) { throw null; }
public static bool TryReadInt32LittleEndian(ReadOnlySpan<byte> buffer, out int value) { throw null; }
public static bool TryReadInt64LittleEndian(ReadOnlySpan<byte> buffer, out long value) { throw null; }
public static bool TryReadUInt16LittleEndian(ReadOnlySpan<byte> buffer, out ushort value) { throw null; }
public static bool TryReadUInt32LittleEndian(ReadOnlySpan<byte> buffer, out uint value) { throw null; }
public static bool TryReadUInt64LittleEndian(ReadOnlySpan<byte> buffer, out ulong value) { throw null; }
public static short ReadInt16BigEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static int ReadInt32BigEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static long ReadInt64BigEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static ushort ReadUInt16BigEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static uint ReadUInt32BigEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static ulong ReadUInt64BigEndian(ReadOnlySpan<byte> buffer) { throw null; }
public static bool TryReadInt16BigEndian(ReadOnlySpan<byte> buffer, out short value) { throw null; }
public static bool TryReadInt32BigEndian(ReadOnlySpan<byte> buffer, out int value) { throw null; }
public static bool TryReadInt64BigEndian(ReadOnlySpan<byte> buffer, out long value) { throw null; }
public static bool TryReadUInt16BigEndian(ReadOnlySpan<byte> buffer, out ushort value) { throw null; }
public static bool TryReadUInt32BigEndian(ReadOnlySpan<byte> buffer, out uint value) { throw null; }
public static bool TryReadUInt64BigEndian(ReadOnlySpan<byte> buffer, out ulong value) { throw null; }
public static void WriteMachineEndian<T>(Span<byte> buffer, ref T value) where T : struct { throw null; }
public static bool TryWriteMachineEndian<T>(Span<byte> buffer, ref T value) where T : struct { throw null; }
public static void WriteInt16LittleEndian(Span<byte> buffer, short value) { throw null; }
public static void WriteInt32LittleEndian(Span<byte> buffer, int value) { throw null; }
public static void WriteInt64LittleEndian(Span<byte> buffer, long value) { throw null; }
public static void WriteUInt16LittleEndian(Span<byte> buffer, ushort value) { throw null; }
public static void WriteUInt32LittleEndian(Span<byte> buffer, uint value) { throw null; }
public static void WriteUInt64LittleEndian(Span<byte> buffer, ulong value) { throw null; }
public static bool TryWriteInt16LittleEndian(Span<byte> buffer, short value) { throw null; }
public static bool TryWriteInt32LittleEndian(Span<byte> buffer, int value) { throw null; }
public static bool TryWriteInt64LittleEndian(Span<byte> buffer, long value) { throw null; }
public static bool TryWriteUInt16LittleEndian(Span<byte> buffer, ushort value) { throw null; }
public static bool TryWriteUInt32LittleEndian(Span<byte> buffer, uint value) { throw null; }
public static bool TryWriteUInt64LittleEndian(Span<byte> buffer, ulong value) { throw null; }
public static void WriteInt16BigEndian(Span<byte> buffer, short value) { throw null; }
public static void WriteInt32BigEndian(Span<byte> buffer, int value) { throw null; }
public static void WriteInt64BigEndian(Span<byte> buffer, long value) { throw null; }
public static void WriteUInt16BigEndian(Span<byte> buffer, ushort value) { throw null; }
public static void WriteUInt32BigEndian(Span<byte> buffer, uint value) { throw null; }
public static void WriteUInt64BigEndian(Span<byte> buffer, ulong value) { throw null; }
public static bool TryWriteInt16BigEndian(Span<byte> buffer, short value) { throw null; }
public static bool TryWriteInt32BigEndian(Span<byte> buffer, int value) { throw null; }
public static bool TryWriteInt64BigEndian(Span<byte> buffer, long value) { throw null; }
public static bool TryWriteUInt16BigEndian(Span<byte> buffer, ushort value) { throw null; }
public static bool TryWriteUInt32BigEndian(Span<byte> buffer, uint value) { throw null; }
public static bool TryWriteUInt64BigEndian(Span<byte> buffer, ulong value) { throw null; }
}
}
| |
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using ServiceStack.Common.Utils;
using ServiceStack.ServiceInterface.ServiceModel;
namespace ServiceStack.ServiceClient.Web
{
/// <summary>
/// Adds the singleton instance of <see cref="CookieManagerMessageInspector"/> to an endpoint on the client.
/// </summary>
/// <remarks>
/// Based on http://megakemp.wordpress.com/2009/02/06/managing-shared-cookies-in-wcf/
/// </remarks>
public class CookieManagerEndpointBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
return;
}
/// <summary>
/// Adds the singleton of the <see cref="ClientIdentityMessageInspector"/> class to the client endpoint's message inspectors.
/// </summary>
/// <param name="endpoint">The endpoint that is to be customized.</param>
/// <param name="clientRuntime">The client runtime to be customized.</param>
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
var cm = CookieManagerMessageInspector.Instance;
cm.Uri = endpoint.ListenUri.AbsoluteUri;
clientRuntime.MessageInspectors.Add(cm);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
return;
}
public void Validate(ServiceEndpoint endpoint)
{
return;
}
}
/// <summary>
/// Maintains a copy of the cookies contained in the incoming HTTP response received from any service
/// and appends it to all outgoing HTTP requests.
/// </summary>
/// <remarks>
/// This class effectively allows to send any received HTTP cookies to different services,
/// reproducing the same functionality available in ASMX Web Services proxies with the <see cref="System.Net.CookieContainer"/> class.
/// Based on http://megakemp.wordpress.com/2009/02/06/managing-shared-cookies-in-wcf/
/// </remarks>
public class CookieManagerMessageInspector : IClientMessageInspector
{
private static CookieManagerMessageInspector instance;
private CookieContainer cookieContainer;
public string Uri { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ClientIdentityMessageInspector"/> class.
/// </summary>
public CookieManagerMessageInspector()
{
cookieContainer = new CookieContainer();
Uri = "http://tempuri.org";
}
public CookieManagerMessageInspector(string uri)
{
cookieContainer = new CookieContainer();
Uri = uri;
}
/// <summary>
/// Gets the singleton <see cref="ClientIdentityMessageInspector" /> instance.
/// </summary>
public static CookieManagerMessageInspector Instance
{
get
{
if (instance == null)
{
instance = new CookieManagerMessageInspector();
}
return instance;
}
}
/// <summary>
/// Inspects a message after a reply message is received but prior to passing it back to the client application.
/// </summary>
/// <param name="reply">The message to be transformed into types and handed back to the client application.</param>
/// <param name="correlationState">Correlation state data.</param>
public void AfterReceiveReply(ref Message reply, object correlationState)
{
HttpResponseMessageProperty httpResponse =
reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
if (httpResponse != null)
{
string cookie = httpResponse.Headers[HttpResponseHeader.SetCookie];
if (!string.IsNullOrEmpty(cookie))
{
cookieContainer.SetCookies(new System.Uri(Uri), cookie);
}
}
}
/// <summary>
/// Inspects a message before a request message is sent to a service.
/// </summary>
/// <param name="request">The message to be sent to the service.</param>
/// <param name="channel">The client object channel.</param>
/// <returns>
/// <strong>Null</strong> since no message correlation is used.
/// </returns>
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
HttpRequestMessageProperty httpRequest;
// The HTTP request object is made available in the outgoing message only when
// the Visual Studio Debugger is attacched to the running process
if (!request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
{
request.Properties.Add(HttpRequestMessageProperty.Name, new HttpRequestMessageProperty());
}
httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieContainer.GetCookieHeader(new System.Uri(Uri)));
return null;
}
}
public abstract class WcfServiceClient : IWcfServiceClient
{
const string XPATH_SOAP_FAULT = "/s:Fault";
const string XPATH_SOAP_FAULT_REASON = "/s:Fault/s:Reason";
const string NAMESPACE_SOAP = "http://www.w3.org/2003/05/soap-envelope";
const string NAMESPACE_SOAP_ALIAS = "s";
public string Uri { get; set; }
public abstract void SetProxy(Uri proxyAddress);
protected abstract MessageVersion MessageVersion { get; }
protected abstract Binding Binding { get; }
/// <summary>
/// Specifies if cookies should be stored
/// </summary>
// CCB Custom
public bool StoreCookies { get; set; }
public WcfServiceClient()
{
// CCB Custom
this.StoreCookies = true;
}
private static XmlNamespaceManager GetNamespaceManager(XmlDocument doc)
{
var nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace(NAMESPACE_SOAP_ALIAS, NAMESPACE_SOAP);
return nsmgr;
}
private static Exception CreateException(Exception e, XmlReader reader)
{
var doc = new XmlDocument();
doc.Load(reader);
var node = doc.SelectSingleNode(XPATH_SOAP_FAULT, GetNamespaceManager(doc));
if (node != null)
{
string errMsg = null;
var nodeReason = doc.SelectSingleNode(XPATH_SOAP_FAULT_REASON, GetNamespaceManager(doc));
if (nodeReason != null)
{
errMsg = nodeReason.FirstChild.InnerXml;
}
return new Exception(string.Format("SOAP FAULT '{0}': {1}", errMsg, node.InnerXml), e);
}
return e;
}
private ServiceEndpoint SyncReply
{
get
{
var contract = new ContractDescription("ServiceStack.ServiceClient.Web.ISyncReply", "http://services.servicestack.net/");
var addr = new EndpointAddress(Uri);
var endpoint = new ServiceEndpoint(contract, Binding, addr);
return endpoint;
}
}
public Message Send(object request)
{
return Send(request, request.GetType().Name);
}
public Message Send(object request, string action)
{
return Send(Message.CreateMessage(MessageVersion, action, request));
}
public Message Send(XmlReader reader, string action)
{
return Send(Message.CreateMessage(MessageVersion, action, reader));
}
public Message Send(Message message)
{
using (var client = new GenericProxy<ISyncReply>(SyncReply))
{
// CCB Custom...add behavior to propagate cookies across SOAP method calls
if (StoreCookies)
client.ChannelFactory.Endpoint.Behaviors.Add(new CookieManagerEndpointBehavior());
var response = client.Proxy.Send(message);
return response;
}
}
public static T GetBody<T>(Message message)
{
var buffer = message.CreateBufferedCopy(int.MaxValue);
try
{
return buffer.CreateMessage().GetBody<T>();
}
catch (Exception ex)
{
throw CreateException(ex, buffer.CreateMessage().GetReaderAtBodyContents());
}
}
public T Send<T>(object request)
{
try
{
var responseMsg = Send(request);
var response = responseMsg.GetBody<T>();
var responseStatus = GetResponseStatus(response);
if (responseStatus != null && !string.IsNullOrEmpty(responseStatus.ErrorCode))
{
throw new WebServiceException(responseStatus.Message, null) {
StatusCode = 500,
ResponseDto = response,
StatusDescription = responseStatus.Message,
};
}
return response;
}
catch (WebServiceException webEx)
{
throw;
}
catch (Exception ex)
{
var webEx = ex as WebException ?? ex.InnerException as WebException;
if (webEx == null)
{
throw new WebServiceException(ex.Message, ex) {
StatusCode = 500,
};
}
var httpEx = webEx.Response as HttpWebResponse;
throw new WebServiceException(webEx.Message, webEx) {
StatusCode = httpEx != null ? (int)httpEx.StatusCode : 500
};
}
}
public ResponseStatus GetResponseStatus(object response)
{
if (response == null)
return null;
var hasResponseStatus = response as IHasResponseStatus;
if (hasResponseStatus != null)
return hasResponseStatus.ResponseStatus;
var propertyInfo = response.GetType().GetProperty("ResponseStatus");
if (propertyInfo == null)
return null;
return ReflectionUtils.GetProperty(response, propertyInfo) as ResponseStatus;
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, string mimeType)
{
throw new NotImplementedException();
}
public TResponse PostFile<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, string mimeType)
{
throw new NotImplementedException();
}
public void SendOneWay(object request)
{
SendOneWay(request, request.GetType().Name);
}
public void SendOneWay(string relativeOrAbsoluteUrl, object request)
{
SendOneWay(Message.CreateMessage(MessageVersion, relativeOrAbsoluteUrl, request));
}
public void SendOneWay(object request, string action)
{
SendOneWay(Message.CreateMessage(MessageVersion, action, request));
}
public void SendOneWay(XmlReader reader, string action)
{
SendOneWay(Message.CreateMessage(MessageVersion, action, reader));
}
public void SendOneWay(Message message)
{
using (var client = new GenericProxy<IOneWay>(SyncReply))
{
client.Proxy.SendOneWay(message);
}
}
public void SendAsync<TResponse>(object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void SetCredentials(string userName, string password)
{
throw new NotImplementedException();
}
public void GetAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void DeleteAsync<TResponse>(string relativeOrAbsoluteUrl, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PostAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void PutAsync<TResponse>(string relativeOrAbsoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError)
{
throw new NotImplementedException();
}
public void Dispose()
{
}
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload, object request)
{
throw new NotImplementedException();
}
public TResponse PostFileWithRequest<TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload, string fileName, object request)
{
throw new NotImplementedException();
}
}
}
#endif
| |
/*
* Copyright (c) 2009 Jim Radford http://www.jimradford.com
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Web;
using SuperPutty.Data;
using SuperPutty.Utils;
using SuperPutty.Gui;
using log4net;
namespace SuperPutty
{
public partial class dlgEditSession : Form
{
private static readonly ILog Log = LogManager.GetLogger(typeof(dlgEditSession));
public delegate bool SessionNameValidationHandler(string name, out string error);
private SessionData Session;
private String OldHostname;
private bool isInitialized = false;
private ImageListPopup imgPopup = null;
public dlgEditSession(SessionData session, ImageList iconList)
{
Session = session;
InitializeComponent();
// get putty saved settings from the registry to populate
// the dropdown
PopulatePuttySettings();
if (!String.IsNullOrEmpty(Session.SessionName))
{
this.Text = "Edit session: " + session.SessionName;
this.textBoxSessionName.Text = Session.SessionName;
this.textBoxHostname.Text = Session.Host;
this.textBoxPort.Text = Session.Port.ToString();
this.textBoxExtraArgs.Text = Session.ExtraArgs;
this.textBoxUsername.Text = Session.Username;
this.textBoxPassword.Text = Session.Password;
switch (Session.Proto)
{
case ConnectionProtocol.Raw:
radioButtonRaw.Checked = true;
break;
case ConnectionProtocol.Rlogin:
radioButtonRlogin.Checked = true;
break;
case ConnectionProtocol.Serial:
radioButtonSerial.Checked = true;
break;
case ConnectionProtocol.SSH:
radioButtonSSH.Checked = true;
break;
case ConnectionProtocol.Telnet:
radioButtonTelnet.Checked = true;
break;
case ConnectionProtocol.Cygterm:
radioButtonCygterm.Checked = true;
break;
case ConnectionProtocol.Mintty:
radioButtonMintty.Checked = true;
break;
default:
radioButtonSSH.Checked = true;
break;
}
foreach(String settings in this.comboBoxPuttyProfile.Items){
if (settings == session.PuttySession)
{
this.comboBoxPuttyProfile.SelectedItem = settings;
break;
}
}
this.buttonSave.Enabled = true;
}
else
{
this.Text = "Create new session";
radioButtonSSH.Checked = true;
this.buttonSave.Enabled = false;
}
// Setup icon chooser
this.buttonImageSelect.ImageList = iconList;
this.buttonImageSelect.ImageKey = string.IsNullOrEmpty(Session.ImageKey)
? SessionTreeview.ImageKeySession
: Session.ImageKey;
this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey);
this.isInitialized = true;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.BeginInvoke(new MethodInvoker(delegate { this.textBoxSessionName.Focus(); }));
}
private void PopulatePuttySettings()
{
foreach (String sessionName in PuttyDataHelper.GetSessionNames())
{
comboBoxPuttyProfile.Items.Add(sessionName);
}
comboBoxPuttyProfile.SelectedItem = PuttyDataHelper.SessionDefaultSettings;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
private void buttonSave_Click(object sender, EventArgs e)
{
Session.SessionName = textBoxSessionName.Text.Trim();
Session.PuttySession = comboBoxPuttyProfile.Text.Trim();
Session.Host = textBoxHostname.Text.Trim();
Session.ExtraArgs = textBoxExtraArgs.Text.Trim();
Session.Port = int.Parse(textBoxPort.Text.Trim());
Session.Username = textBoxUsername.Text.Trim();
Session.Password = textBoxPassword.Text.Trim();
Session.SessionId = SessionData.CombineSessionIds(SessionData.GetSessionParentId(Session.SessionId), Session.SessionName);
Session.ImageKey = buttonImageSelect.ImageKey;
for (int i = 0; i < groupBox1.Controls.Count; i++)
{
RadioButton rb = (RadioButton)groupBox1.Controls[i];
if (rb.Checked)
{
Session.Proto = (ConnectionProtocol)rb.Tag;
}
}
DialogResult = DialogResult.OK;
}
/// <summary>
/// Special UI handling for cygterm or mintty sessions
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButtonCygterm_CheckedChanged(object sender, EventArgs e)
{
string host = this.textBoxHostname.Text;
bool isLocalShell = this.radioButtonCygterm.Checked || this.radioButtonMintty.Checked;
this.textBoxPort.Enabled = !isLocalShell;
this.textBoxExtraArgs.Enabled = !isLocalShell;
this.textBoxUsername.Enabled = !isLocalShell;
this.textBoxPassword.Enabled = !isLocalShell;
if (isLocalShell)
{
if (String.IsNullOrEmpty(host) || !host.StartsWith(CygtermStartInfo.LocalHost))
{
OldHostname = this.textBoxHostname.Text;
this.textBoxHostname.Text = CygtermStartInfo.LocalHost;
}
}
}
private void radioButtonRaw_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonRaw.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
}
}
private void radioButtonTelnet_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonTelnet.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
this.textBoxPort.Text = "23";
}
}
private void radioButtonRlogin_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonRlogin.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
this.textBoxPort.Text = "513";
}
}
private void radioButtonSSH_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonSSH.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
this.textBoxPort.Text = "22";
}
}
public static int GetDefaultPort(ConnectionProtocol protocol)
{
int port = 22;
switch (protocol)
{
case ConnectionProtocol.Raw:
break;
case ConnectionProtocol.Rlogin:
port = 513;
break;
case ConnectionProtocol.Serial:
break;
case ConnectionProtocol.Telnet:
port = 23;
break;
}
return port;
}
#region Icon
private void buttonImageSelect_Click(object sender, EventArgs e)
{
if (this.imgPopup == null)
{
int n = buttonImageSelect.ImageList.Images.Count;
int x = (int) Math.Floor(Math.Sqrt(n)) + 1;
int cols = x;
int rows = x;
imgPopup = new ImageListPopup();
imgPopup.BackgroundColor = Color.FromArgb(241, 241, 241);
imgPopup.BackgroundOverColor = Color.FromArgb(102, 154, 204);
imgPopup.Init(this.buttonImageSelect.ImageList, 8, 8, cols, rows);
imgPopup.ItemClick += new ImageListPopupEventHandler(this.OnItemClicked);
}
Point pt = PointToScreen(new Point(buttonImageSelect.Left, buttonImageSelect.Bottom));
imgPopup.Show(pt.X + 2, pt.Y);
}
private void OnItemClicked(object sender, ImageListPopupEventArgs e)
{
if (imgPopup == sender)
{
buttonImageSelect.ImageKey = e.SelectedItem;
this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey);
}
}
#endregion
#region Validation Logic
public SessionNameValidationHandler SessionNameValidator { get; set; }
private void textBoxSessionName_Validating(object sender, CancelEventArgs e)
{
if (this.SessionNameValidator != null)
{
string error;
if (!this.SessionNameValidator(this.textBoxSessionName.Text, out error))
{
e.Cancel = true;
this.SetError(this.textBoxSessionName, error ?? "Invalid Session Name");
}
}
}
private void textBoxSessionName_Validated(object sender, EventArgs e)
{
this.SetError(this.textBoxSessionName, String.Empty);
}
private void textBoxPort_Validating(object sender, CancelEventArgs e)
{
int val;
if (!Int32.TryParse(this.textBoxPort.Text, out val))
{
e.Cancel = true;
this.SetError(this.textBoxPort, "Invalid Port");
}
}
private void textBoxPort_Validated(object sender, EventArgs e)
{
this.SetError(this.textBoxPort, String.Empty);
}
private void textBoxHostname_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrEmpty((string)this.comboBoxPuttyProfile.SelectedItem) &&
string.IsNullOrEmpty(this.textBoxHostname.Text.Trim()))
{
if (sender == this.textBoxHostname)
{
this.SetError(this.textBoxHostname, "A host name must be specified if a Putty Session Profile is not selected");
}
else if (sender == this.comboBoxPuttyProfile)
{
this.SetError(this.comboBoxPuttyProfile, "A Putty Session Profile must be selected if a Host Name is not provided");
}
}
else
{
this.SetError(this.textBoxHostname, String.Empty);
this.SetError(this.comboBoxPuttyProfile, String.Empty);
}
}
private void comboBoxPuttyProfile_Validating(object sender, CancelEventArgs e)
{
this.textBoxHostname_Validating(sender, e);
}
private void comboBoxPuttyProfile_SelectedIndexChanged(object sender, EventArgs e)
{
this.ValidateChildren(ValidationConstraints.ImmediateChildren);
}
void SetError(Control control, string error)
{
this.errorProvider.SetError(control, error);
this.EnableDisableSaveButton();
}
void EnableDisableSaveButton()
{
this.buttonSave.Enabled = (
this.errorProvider.GetError(this.textBoxSessionName) == String.Empty &&
this.errorProvider.GetError(this.textBoxHostname) == String.Empty &&
this.errorProvider.GetError(this.textBoxPort) == String.Empty &&
this.errorProvider.GetError(this.comboBoxPuttyProfile) == String.Empty);
}
#endregion
}
}
| |
//
// 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.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation usages. (see
/// http://aka.ms/azureautomationsdk/usageoperations for more information)
/// </summary>
internal partial class UsageOperations : IServiceOperations<AutomationManagementClient>, IUsageOperations
{
/// <summary>
/// Initializes a new instance of the UsageOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal UsageOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Retrieve the usage for the account id. (see
/// http://aka.ms/azureautomationsdk/usageoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get usage operation.
/// </returns>
public async Task<UsageListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// 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("automationAccount", automationAccount);
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 + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/usages";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
UsageListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new UsageListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Usage usageInstance = new Usage();
result.Usage.Add(usageInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
usageInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
UsageCounterName nameInstance = new UsageCounterName();
usageInstance.Name = nameInstance;
JToken valueValue2 = nameValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
nameInstance.Value = valueInstance;
}
JToken localizedValueValue = nameValue["localizedValue"];
if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
{
string localizedValueInstance = ((string)localizedValueValue);
nameInstance.LocalizedValue = localizedValueInstance;
}
}
JToken unitValue = valueValue["unit"];
if (unitValue != null && unitValue.Type != JTokenType.Null)
{
string unitInstance = ((string)unitValue);
usageInstance.Unit = unitInstance;
}
JToken currentValueValue = valueValue["currentValue"];
if (currentValueValue != null && currentValueValue.Type != JTokenType.Null)
{
double currentValueInstance = ((double)currentValueValue);
usageInstance.CurrentValue = currentValueInstance;
}
JToken limitValue = valueValue["limit"];
if (limitValue != null && limitValue.Type != JTokenType.Null)
{
long limitInstance = ((long)limitValue);
usageInstance.Limit = limitInstance;
}
JToken throttleStatusValue = valueValue["throttleStatus"];
if (throttleStatusValue != null && throttleStatusValue.Type != JTokenType.Null)
{
string throttleStatusInstance = ((string)throttleStatusValue);
usageInstance.ThrottleStatus = throttleStatusInstance;
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// 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 Internal.NativeCrypto;
namespace System.Security.Cryptography
{
public sealed class CspKeyContainerInfo
{
private readonly CspParameters _parameters;
private readonly bool _randomKeyContainer;
//Public Constructor will call internal constructor.
public CspKeyContainerInfo(CspParameters parameters)
: this(parameters, false)
{
}
/// <summary>
///Internal constructor for creating the CspKeyContainerInfo object
/// </summary>
/// <param name="parameters">CSP parameters</param>
/// <param name="randomKeyContainer">Is it ranndom container</param>
internal CspKeyContainerInfo(CspParameters parameters, bool randomKeyContainer)
{
_parameters = new CspParameters(parameters);
if (_parameters.KeyNumber == -1)
{
if (_parameters.ProviderType == (int)CapiHelper.ProviderType.PROV_RSA_FULL ||
_parameters.ProviderType == (int)CapiHelper.ProviderType.PROV_RSA_AES)
{
_parameters.KeyNumber = (int)KeyNumber.Exchange;
}
else if (_parameters.ProviderType == (int)CapiHelper.ProviderType.PROV_DSS_DH)
{
_parameters.KeyNumber = (int)KeyNumber.Signature;
}
}
_randomKeyContainer = randomKeyContainer;
}
/// <summary>
/// Check the key is accessible
/// </summary>
public bool Accessible
{
get
{
object retVal = ReadKeyParameterSilent(Constants.CLR_ACCESSIBLE, throwOnNotFound: false);
if (retVal == null)
{
// The key wasn't found, so consider it to be not accessible.
return false;
}
return (bool)retVal;
}
}
/// <summary>
/// Check the key is exportable
/// </summary>
public bool Exportable
{
get
{
// Assume hardware keys are not exportable.
if (HardwareDevice)
{
return false;
}
return (bool)ReadKeyParameterSilent(Constants.CLR_EXPORTABLE);
}
}
/// <summary>
/// Check if device with key is HW device
/// </summary>
public bool HardwareDevice
{
get
{
return (bool)ReadDeviceParameterVerifyContext(Constants.CLR_HARDWARE);
}
}
/// <summary>
/// Get Key container Name
/// </summary>
public string KeyContainerName
{
get
{
return _parameters.KeyContainerName;
}
}
/// <summary>
/// Get the key number
/// </summary>
public KeyNumber KeyNumber
{
get
{
return (KeyNumber)_parameters.KeyNumber;
}
}
/// <summary>
/// Check if machine key store is in flag or not
/// </summary>
public bool MachineKeyStore
{
get
{
return CapiHelper.IsFlagBitSet((uint)_parameters.Flags, (uint)CspProviderFlags.UseMachineKeyStore);
}
}
/// <summary>
/// Check if key is protected
/// </summary>
public bool Protected
{
get
{
// Assume hardware keys are protected.
if (HardwareDevice)
{
return true;
}
return (bool)ReadKeyParameterSilent(Constants.CLR_PROTECTED);
}
}
/// <summary>
/// Gets the provider name
/// </summary>
public string ProviderName
{
get
{
return _parameters.ProviderName;
}
}
/// <summary>
/// Gets the provider type
/// </summary>
public int ProviderType
{
get
{
return _parameters.ProviderType;
}
}
/// <summary>
/// Check if key container is randomly generated
/// </summary>
public bool RandomlyGenerated
{
get
{
return _randomKeyContainer;
}
}
/// <summary>
/// Check if container is removable
/// </summary>
public bool Removable
{
get
{
return (bool)ReadDeviceParameterVerifyContext(Constants.CLR_REMOVABLE);
}
}
/// <summary>
/// Get the container name
/// </summary>
public string UniqueKeyContainerName
{
get
{
return (string)ReadKeyParameterSilent(Constants.CLR_UNIQUE_CONTAINER);
}
}
/// <summary>
/// Read a parameter from the current key using CRYPT_SILENT, to avoid any potential UI prompts.
/// </summary>
private object ReadKeyParameterSilent(int keyParam, bool throwOnNotFound=true)
{
const uint SilentFlags = (uint)CapiHelper.CryptAcquireContextFlags.CRYPT_SILENT;
SafeProvHandle safeProvHandle;
int hr = CapiHelper.OpenCSP(_parameters, SilentFlags, out safeProvHandle);
using (safeProvHandle)
{
if (hr != CapiHelper.S_OK)
{
if (throwOnNotFound)
{
throw new CryptographicException(SR.Format(SR.Cryptography_CSP_NotFound, "Error"));
}
return null;
}
object retVal = CapiHelper.GetProviderParameter(safeProvHandle, _parameters.KeyNumber, keyParam);
return retVal;
}
}
/// <summary>
/// Read a parameter using VERIFY_CONTEXT to read from the device being targeted by _parameters
/// </summary>
private object ReadDeviceParameterVerifyContext(int keyParam)
{
CspParameters parameters = new CspParameters(_parameters);
// We're asking questions of the device container, the only flag that makes sense is Machine vs User.
parameters.Flags &= CspProviderFlags.UseMachineKeyStore;
// In order to ask about the device, instead of a key, we need to ensure that no key is named.
parameters.KeyContainerName = null;
const uint OpenDeviceFlags = (uint)CapiHelper.CryptAcquireContextFlags.CRYPT_VERIFYCONTEXT;
SafeProvHandle safeProvHandle;
int hr = CapiHelper.OpenCSP(parameters, OpenDeviceFlags, out safeProvHandle);
using (safeProvHandle)
{
if (hr != CapiHelper.S_OK)
{
throw new CryptographicException(SR.Format(SR.Cryptography_CSP_NotFound, "Error"));
}
object retVal = CapiHelper.GetProviderParameter(safeProvHandle, parameters.KeyNumber, keyParam);
return retVal;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//#define DEBUGSTACK
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Research.DataStructures;
using StackTemp = System.Int32;
namespace Microsoft.Research.CodeAnalysis
{
using SubroutineContext = FList<Microsoft.Research.DataStructures.STuple<CFGBlock, CFGBlock, string>>;
using SubroutineEdge = Microsoft.Research.DataStructures.STuple<CFGBlock, CFGBlock, string>;
using System.Diagnostics.Contracts;
/// <summary>
/// Turns any type T that is Equatable into a flat abstract domain
/// </summary>
/// <typeparam name="T">Elements in the domain besides Top and Bottom</typeparam>
public struct FlatDomain<T> : IEquatable<FlatDomain<T>>, IAbstractValue<FlatDomain<T>>
where T : IEquatable<T>
{
/// <summary>
/// Make sure that Top = 0 so default(FlatDomain) is Top
/// </summary>
private enum State { Top = 0, Bottom, Normal }
private FlatDomain(State state)
{
this.state = state;
this.Value = default(T);
}
public FlatDomain(T/*!*/ value)
{
this.Value = value;
state = State.Normal;
}
private readonly State state;
public readonly T Value;
public static readonly FlatDomain<T> BottomValue = new FlatDomain<T>(State.Bottom); // Thread-safe if T is thread-safe
public static readonly FlatDomain<T> TopValue = new FlatDomain<T>(State.Top); // Thread-safe if T is thread-safe
public static implicit operator FlatDomain<T>(T/*!*/ value) { return new FlatDomain<T>(value); }
public bool IsNormal { get { return state == State.Normal; } }
#region IAbstractValue<LiftedDomain<T>> Members
public FlatDomain<T> Top
{
get { return FlatDomain<T>.TopValue; }
}
public FlatDomain<T> Bottom
{
get { return FlatDomain<T>.BottomValue; }
}
public bool IsTop
{
get
{
return state == State.Top;
}
}
public bool IsBottom
{
get
{
return state == State.Bottom;
}
}
public FlatDomain<T> ImmutableVersion()
{
return this;
}
public FlatDomain<T> Clone()
{
return this;
}
public FlatDomain<T> Join(FlatDomain<T> newState, out bool weaker, bool widen)
{
if (this.IsTop) { weaker = false; return this; }
if (newState.IsTop) { weaker = !this.IsTop; return newState; }
if (this.IsBottom) { weaker = !newState.IsBottom; return newState; }
if (newState.IsBottom) { weaker = false; return this; }
if (this.Value.Equals(newState.Value)) { weaker = false; return newState; }
weaker = true;
return TopValue;
}
public FlatDomain<T> Meet(FlatDomain<T> that)
{
if (this.IsTop) return that;
if (that.IsTop) return this;
if (this.IsBottom) return this;
if (that.IsBottom) return that;
if (this.Value.Equals(that.Value)) return that;
return BottomValue;
}
public void Dump(TextWriter tw)
{
if (this.IsTop) { tw.WriteLine("Top"); }
else if (this.IsBottom) { tw.WriteLine("Bot"); }
else
{
tw.WriteLine("<{0}>", Value);
}
}
public bool LessEqual(FlatDomain<T> that)
{
if (that.IsTop) return true;
if (this.IsBottom) return true;
if (this.IsTop) return false;
if (that.IsBottom) return false;
return this.Value.Equals(that.Value);
}
#endregion
public override string ToString()
{
if (this.IsTop) { return ("Top"); }
else if (this.IsBottom) { return ("Bot"); }
else
{
// invariant IsNormal => Value != null
//^ assume Value != null;
return Value.ToString();
}
}
#region IEquatable<LiftedDomain<T>> Members
//^ [StateIndependent]
public bool Equals(FlatDomain<T> other)
{
return state == other.state && (!this.IsNormal || this.Value.Equals(other.Value));
}
#endregion
}
public struct EnvironmentDomain<Key, Val> : IAbstractValue<EnvironmentDomain<Key, Val>>
where Val : IAbstractValue<Val>
{
#if false //unused?
public static bool Debug;
#endif
private readonly IFunctionalMap<Key, Val>/*?*/ map;
public EnvironmentDomain(IFunctionalMap<Key, Val>/*?*/ value)
{
map = value;
}
[ThreadStatic] // Current implementation: (only) depends on the analysis driver used
private static Converter<Key/*!*/, int> KeyNumber;
public static EnvironmentDomain<Key, Val> TopValue(Converter<Key/*!*/, int> keyNumber)
{
if (KeyNumber == null) { KeyNumber = keyNumber; }
return new EnvironmentDomain<Key, Val>(FunctionalIntKeyMap<Key, Val>.Empty(keyNumber));
}
public EnvironmentDomain<Key, Val> Add(Key key, Val val)
{
if (map == null)
{
throw new InvalidOperationException();
}
return new EnvironmentDomain<Key, Val>(map.Add(key, val));
}
public EnvironmentDomain<Key, Val> Remove(Key key)
{
if (map == null)
{
throw new InvalidOperationException();
}
return new EnvironmentDomain<Key, Val>(map.Remove(key));
}
public bool Contains(Key/*!*/ key)
{
if (map == null)
{
throw new InvalidOperationException();
}
return map.Contains(key);
}
public Val/*?*/ this[Key/*!*/ key] { get { if (map == null) return default(Val); return map[key]; } }
public IEnumerable<Key/*!*/> Keys { get { return map.Keys; } }
public static readonly EnvironmentDomain<Key, Val> BottomValue = new EnvironmentDomain<Key, Val>(null); // Thread-safe
#region IAbstractValue<EnvironmentDomain<Key,Val>> Members
public EnvironmentDomain<Key, Val> Top
{
get
{
return EnvironmentDomain<Key, Val>.TopValue(KeyNumber);
}
}
public EnvironmentDomain<Key, Val> Bottom
{
get { return new EnvironmentDomain<Key, Val>(null); }
}
public bool IsTop
{
get
{
return map != null && map.Count == 0;
}
}
public bool IsBottom
{
get
{
return map == null;
}
}
public EnvironmentDomain<Key, Val> ImmutableVersion()
{
return this;
}
public EnvironmentDomain<Key, Val> Clone()
{
return this;
}
public EnvironmentDomain<Key, Val> Join(EnvironmentDomain<Key, Val> newState, out bool weaker, bool widen)
{
if (map == newState.map) { weaker = false; return this; }
bool resultWeaker = false;
if (this.IsTop) { weaker = false; return this; }
if (newState.IsTop) { weaker = !this.IsTop; return newState; }
if (this.IsBottom) { weaker = !newState.IsBottom; return newState; }
if (newState.IsBottom) { weaker = false; return this; }
// compare pointwise
IFunctionalMap<Key, Val> smaller;
IFunctionalMap<Key, Val> larger;
if (map.Count < newState.map.Count)
{
smaller = map;
larger = newState.map;
}
else
{
smaller = newState.map;
larger = map;
}
IFunctionalMap<Key, Val> result = smaller;
foreach (Key k in smaller.Keys)
{
if (!larger.Contains(k))
{
result = result.Remove(k);
}
else
{
bool joinWeaker;
Val join = smaller[k].Join(larger[k], out joinWeaker, widen);
if (joinWeaker)
{
resultWeaker = true;
if (join.IsTop)
{
result = result.Remove(k);
}
else
{
result = result.Add(k, join);
}
}
}
}
weaker = resultWeaker || (result.Count < map.Count);
return new EnvironmentDomain<Key, Val>(result);
}
public EnvironmentDomain<Key, Val> Meet(EnvironmentDomain<Key, Val> that)
{
if (map == that.map) { return this; }
if (this.IsTop) return that;
if (that.IsTop) return this;
if (this.IsBottom) return this;
if (that.IsBottom) return that;
Contract.Assume(map != null);
// compare pointwise
IFunctionalMap<Key, Val> smaller;
IFunctionalMap<Key, Val> larger;
if (map.Count < that.map.Count)
{
smaller = map;
larger = that.map;
}
else
{
smaller = that.map;
larger = map;
}
IFunctionalMap<Key, Val> result = larger;
foreach (Key k in smaller.Keys)
{
if (larger.Contains(k))
{
// must meet the values
Val meet = smaller[k].Meet(larger[k]);
result = result.Add(k, meet);
}
else
{
// just add the value to the result
result = result.Add(k, smaller[k]);
}
}
return new EnvironmentDomain<Key, Val>(result);
}
public void Dump(TextWriter tw)
{
Contract.Assume(tw != null);
if (this.IsTop) { tw.WriteLine("Top"); }
else if (this.IsBottom) { tw.WriteLine("Bot"); }
else
{
map.Visit(delegate (Key/*!*/ k, Val v) { tw.WriteLine("{0} -> {1}", k.ToString(), v.ToString()); return VisitStatus.ContinueVisit; });
}
}
#endregion
public override string ToString()
{
if (this.IsTop) { return ("Top"); }
else if (this.IsBottom) { return ("Bot"); }
else
{
StringBuilder sb = new StringBuilder();
map.Visit(delegate (Key/*!*/ k, Val v) { sb.AppendFormat("({0}->{1}),", k.ToString(), v.ToString()); return VisitStatus.ContinueVisit; });
return sb.ToString();
}
}
public EnvironmentDomain<Key, Val> Empty()
{
return new EnvironmentDomain<Key, Val>(map.EmptyMap);
}
#region IAbstractValue<EnvironmentDomain<Key,Val>> Members
public bool LessEqual(EnvironmentDomain<Key, Val> that)
{
if (that.IsTop) return true;
if (this.IsBottom) return true;
if (this.IsTop) return false;
if (that.IsBottom) return false;
if (map.Count < that.map.Count) return false;
// pointwise
foreach (Key k in that.map.Keys)
{
if (!map.Contains(k) || !map[k].LessEqual(that.map[k])) return false;
}
return true;
}
#endregion
}
public struct SetDomain<T> : IAbstractValue<SetDomain<T>>
where T : IEquatable<T>
{
#region Privates
// null represents bottom
private readonly IFunctionalSet<T>/*?*/ set;
#endregion
public SetDomain(IFunctionalSet<T>/*?*/ value)
{
set = value;
}
public SetDomain(Converter<T, int> keyNumber)
{
set = FunctionalSet<T>.Empty(keyNumber);
}
public static readonly SetDomain<T> TopValue = new SetDomain<T>(Microsoft.Research.DataStructures.FunctionalSet<T>.Empty()); // Thread-safe
public static readonly SetDomain<T> BottomValue = new SetDomain<T>((IFunctionalSet<T>)null); // Thread-safe
public SetDomain<T> Add(T elem)
{
if (set == null)
{
throw new InvalidOperationException("The set is null");
}
return new SetDomain<T>(set.Add(elem));
}
public SetDomain<T> Remove(T elem)
{
if (set == null)
{
throw new InvalidOperationException("The set is null");
}
return new SetDomain<T>(set.Remove(elem));
}
public bool Contains(T elem)
{
if (set == null)
{
throw new InvalidOperationException("The set is null");
}
return set.Contains(elem);
}
public IEnumerable<T> Elements
{
get
{
if (set == null)
{
throw new InvalidOperationException("The set is null");
}
return set.Elements;
}
}
public override string ToString()
{
if (IsBottom) { return "Bot"; }
if (IsTop) { return ("Top"); }
Contract.Assert(set != null);
StringBuilder sb = new StringBuilder();
set.Visit(delegate (T/*!*/ elem) { sb.AppendFormat("{0},", elem.ToString()); });
return sb.ToString();
}
#region IAbstractValue<SetDomain<T>> Members
public SetDomain<T> Top
{
get { return TopValue; }
}
public SetDomain<T> Bottom
{
get { return BottomValue; }
}
public bool IsTop
{
get { return set != null && set.Count == 0; }
}
public bool IsBottom
{
get
{
Contract.Ensures(Contract.Result<bool>() == (set == null));
return set == null;
}
}
public SetDomain<T> ImmutableVersion()
{
// pure
return this;
}
public SetDomain<T> Clone()
{
// pure
return this;
}
/// <summary>
/// Implemented as Intersection
/// </summary>
[ContractVerification(false)]
public SetDomain<T> Join(SetDomain<T> newState, out bool weaker, bool widen)
{
if (set == newState.set) { weaker = false; return this; }
if (this.IsBottom) { weaker = !newState.IsBottom; return newState; }
if (newState.IsBottom || this.IsTop) { weaker = false; return this; }
if (newState.IsTop) { weaker = !this.IsTop; return newState; }
Contract.Assert(set != null);
IFunctionalSet<T> result = set.Intersect(newState.set);
weaker = result.Count < set.Count;
return new SetDomain<T>(result);
}
/// <summary>
/// Implemented as Union
/// </summary>
[ContractVerification(false)]
public SetDomain<T> Meet(SetDomain<T> that)
{
if (set == that.set) { return this; }
if (this.IsBottom || that.IsTop) { return this; }
if (that.IsBottom || this.IsTop) { return that; }
Contract.Assert(set != null);
IFunctionalSet<T> result = set.Union(that.set);
return new SetDomain<T>(result);
}
public bool LessEqual(SetDomain<T> that)
{
if (this.IsBottom) return true;
if (that.IsBottom) return false;
Contract.Assert(set != null);
return that.set.Contained(set);
}
public void Dump(TextWriter tw)
{
if (this.IsBottom) { tw.WriteLine("Bot"); return; }
if (this.IsTop) { tw.WriteLine("Top"); return; }
Contract.Assert(set != null);
set.Dump(tw);
}
#endregion
}
}
| |
using System;
using ChainUtils.BouncyCastle.Utilities;
namespace ChainUtils.BouncyCastle.Crypto.Digests
{
/**
* implementation of RipeMD see,
* http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html
*/
public class RipeMD160Digest
: GeneralDigest
{
private const int DigestLength = 20;
private int H0, H1, H2, H3, H4; // IV's
private int[] X = new int[16];
private int xOff;
/**
* Standard constructor
*/
public RipeMD160Digest()
{
Reset();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public RipeMD160Digest(RipeMD160Digest t) : base(t)
{
CopyIn(t);
}
private void CopyIn(RipeMD160Digest t)
{
base.CopyIn(t);
H0 = t.H0;
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get { return "RIPEMD160"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8)
| ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24);
if (xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (int)(bitLength & 0xffffffff);
X[15] = (int)((ulong) bitLength >> 32);
}
private void UnpackWord(
int word,
byte[] outBytes,
int outOff)
{
outBytes[outOff] = (byte)word;
outBytes[outOff + 1] = (byte)((uint) word >> 8);
outBytes[outOff + 2] = (byte)((uint) word >> 16);
outBytes[outOff + 3] = (byte)((uint) word >> 24);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
UnpackWord(H0, output, outOff);
UnpackWord(H1, output, outOff + 4);
UnpackWord(H2, output, outOff + 8);
UnpackWord(H3, output, outOff + 12);
UnpackWord(H4, output, outOff + 16);
Reset();
return DigestLength;
}
/**
* reset the chaining variables to the IV values.
*/
public override void Reset()
{
base.Reset();
H0 = unchecked((int) 0x67452301);
H1 = unchecked((int) 0xefcdab89);
H2 = unchecked((int) 0x98badcfe);
H3 = unchecked((int) 0x10325476);
H4 = unchecked((int) 0xc3d2e1f0);
xOff = 0;
for (var i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
/*
* rotate int x left n bits.
*/
private int RL(
int x,
int n)
{
return (x << n) | (int) ((uint) x >> (32 - n));
}
/*
* f1,f2,f3,f4,f5 are the basic RipeMD160 functions.
*/
/*
* rounds 0-15
*/
private int F1(
int x,
int y,
int z)
{
return x ^ y ^ z;
}
/*
* rounds 16-31
*/
private int F2(
int x,
int y,
int z)
{
return (x & y) | (~x & z);
}
/*
* rounds 32-47
*/
private int F3(
int x,
int y,
int z)
{
return (x | ~y) ^ z;
}
/*
* rounds 48-63
*/
private int F4(
int x,
int y,
int z)
{
return (x & z) | (y & ~z);
}
/*
* rounds 64-79
*/
private int F5(
int x,
int y,
int z)
{
return x ^ (y | ~z);
}
internal override void ProcessBlock()
{
int a, aa;
int b, bb;
int c, cc;
int d, dd;
int e, ee;
a = aa = H0;
b = bb = H1;
c = cc = H2;
d = dd = H3;
e = ee = H4;
//
// Rounds 1 - 16
//
// left
a = RL(a + F1(b,c,d) + X[ 0], 11) + e; c = RL(c, 10);
e = RL(e + F1(a,b,c) + X[ 1], 14) + d; b = RL(b, 10);
d = RL(d + F1(e,a,b) + X[ 2], 15) + c; a = RL(a, 10);
c = RL(c + F1(d,e,a) + X[ 3], 12) + b; e = RL(e, 10);
b = RL(b + F1(c,d,e) + X[ 4], 5) + a; d = RL(d, 10);
a = RL(a + F1(b,c,d) + X[ 5], 8) + e; c = RL(c, 10);
e = RL(e + F1(a,b,c) + X[ 6], 7) + d; b = RL(b, 10);
d = RL(d + F1(e,a,b) + X[ 7], 9) + c; a = RL(a, 10);
c = RL(c + F1(d,e,a) + X[ 8], 11) + b; e = RL(e, 10);
b = RL(b + F1(c,d,e) + X[ 9], 13) + a; d = RL(d, 10);
a = RL(a + F1(b,c,d) + X[10], 14) + e; c = RL(c, 10);
e = RL(e + F1(a,b,c) + X[11], 15) + d; b = RL(b, 10);
d = RL(d + F1(e,a,b) + X[12], 6) + c; a = RL(a, 10);
c = RL(c + F1(d,e,a) + X[13], 7) + b; e = RL(e, 10);
b = RL(b + F1(c,d,e) + X[14], 9) + a; d = RL(d, 10);
a = RL(a + F1(b,c,d) + X[15], 8) + e; c = RL(c, 10);
// right
aa = RL(aa + F5(bb,cc,dd) + X[ 5] + unchecked((int) 0x50a28be6), 8) + ee; cc = RL(cc, 10);
ee = RL(ee + F5(aa,bb,cc) + X[14] + unchecked((int) 0x50a28be6), 9) + dd; bb = RL(bb, 10);
dd = RL(dd + F5(ee,aa,bb) + X[ 7] + unchecked((int) 0x50a28be6), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F5(dd,ee,aa) + X[ 0] + unchecked((int) 0x50a28be6), 11) + bb; ee = RL(ee, 10);
bb = RL(bb + F5(cc,dd,ee) + X[ 9] + unchecked((int) 0x50a28be6), 13) + aa; dd = RL(dd, 10);
aa = RL(aa + F5(bb,cc,dd) + X[ 2] + unchecked((int) 0x50a28be6), 15) + ee; cc = RL(cc, 10);
ee = RL(ee + F5(aa,bb,cc) + X[11] + unchecked((int) 0x50a28be6), 15) + dd; bb = RL(bb, 10);
dd = RL(dd + F5(ee,aa,bb) + X[ 4] + unchecked((int) 0x50a28be6), 5) + cc; aa = RL(aa, 10);
cc = RL(cc + F5(dd,ee,aa) + X[13] + unchecked((int) 0x50a28be6), 7) + bb; ee = RL(ee, 10);
bb = RL(bb + F5(cc,dd,ee) + X[ 6] + unchecked((int) 0x50a28be6), 7) + aa; dd = RL(dd, 10);
aa = RL(aa + F5(bb,cc,dd) + X[15] + unchecked((int) 0x50a28be6), 8) + ee; cc = RL(cc, 10);
ee = RL(ee + F5(aa,bb,cc) + X[ 8] + unchecked((int) 0x50a28be6), 11) + dd; bb = RL(bb, 10);
dd = RL(dd + F5(ee,aa,bb) + X[ 1] + unchecked((int) 0x50a28be6), 14) + cc; aa = RL(aa, 10);
cc = RL(cc + F5(dd,ee,aa) + X[10] + unchecked((int) 0x50a28be6), 14) + bb; ee = RL(ee, 10);
bb = RL(bb + F5(cc,dd,ee) + X[ 3] + unchecked((int) 0x50a28be6), 12) + aa; dd = RL(dd, 10);
aa = RL(aa + F5(bb,cc,dd) + X[12] + unchecked((int) 0x50a28be6), 6) + ee; cc = RL(cc, 10);
//
// Rounds 16-31
//
// left
e = RL(e + F2(a,b,c) + X[ 7] + unchecked((int) 0x5a827999), 7) + d; b = RL(b, 10);
d = RL(d + F2(e,a,b) + X[ 4] + unchecked((int) 0x5a827999), 6) + c; a = RL(a, 10);
c = RL(c + F2(d,e,a) + X[13] + unchecked((int) 0x5a827999), 8) + b; e = RL(e, 10);
b = RL(b + F2(c,d,e) + X[ 1] + unchecked((int) 0x5a827999), 13) + a; d = RL(d, 10);
a = RL(a + F2(b,c,d) + X[10] + unchecked((int) 0x5a827999), 11) + e; c = RL(c, 10);
e = RL(e + F2(a,b,c) + X[ 6] + unchecked((int) 0x5a827999), 9) + d; b = RL(b, 10);
d = RL(d + F2(e,a,b) + X[15] + unchecked((int) 0x5a827999), 7) + c; a = RL(a, 10);
c = RL(c + F2(d,e,a) + X[ 3] + unchecked((int) 0x5a827999), 15) + b; e = RL(e, 10);
b = RL(b + F2(c,d,e) + X[12] + unchecked((int) 0x5a827999), 7) + a; d = RL(d, 10);
a = RL(a + F2(b,c,d) + X[ 0] + unchecked((int) 0x5a827999), 12) + e; c = RL(c, 10);
e = RL(e + F2(a,b,c) + X[ 9] + unchecked((int) 0x5a827999), 15) + d; b = RL(b, 10);
d = RL(d + F2(e,a,b) + X[ 5] + unchecked((int) 0x5a827999), 9) + c; a = RL(a, 10);
c = RL(c + F2(d,e,a) + X[ 2] + unchecked((int) 0x5a827999), 11) + b; e = RL(e, 10);
b = RL(b + F2(c,d,e) + X[14] + unchecked((int) 0x5a827999), 7) + a; d = RL(d, 10);
a = RL(a + F2(b,c,d) + X[11] + unchecked((int) 0x5a827999), 13) + e; c = RL(c, 10);
e = RL(e + F2(a,b,c) + X[ 8] + unchecked((int) 0x5a827999), 12) + d; b = RL(b, 10);
// right
ee = RL(ee + F4(aa,bb,cc) + X[ 6] + unchecked((int) 0x5c4dd124), 9) + dd; bb = RL(bb, 10);
dd = RL(dd + F4(ee,aa,bb) + X[11] + unchecked((int) 0x5c4dd124), 13) + cc; aa = RL(aa, 10);
cc = RL(cc + F4(dd,ee,aa) + X[ 3] + unchecked((int) 0x5c4dd124), 15) + bb; ee = RL(ee, 10);
bb = RL(bb + F4(cc,dd,ee) + X[ 7] + unchecked((int) 0x5c4dd124), 7) + aa; dd = RL(dd, 10);
aa = RL(aa + F4(bb,cc,dd) + X[ 0] + unchecked((int) 0x5c4dd124), 12) + ee; cc = RL(cc, 10);
ee = RL(ee + F4(aa,bb,cc) + X[13] + unchecked((int) 0x5c4dd124), 8) + dd; bb = RL(bb, 10);
dd = RL(dd + F4(ee,aa,bb) + X[ 5] + unchecked((int) 0x5c4dd124), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F4(dd,ee,aa) + X[10] + unchecked((int) 0x5c4dd124), 11) + bb; ee = RL(ee, 10);
bb = RL(bb + F4(cc,dd,ee) + X[14] + unchecked((int) 0x5c4dd124), 7) + aa; dd = RL(dd, 10);
aa = RL(aa + F4(bb,cc,dd) + X[15] + unchecked((int) 0x5c4dd124), 7) + ee; cc = RL(cc, 10);
ee = RL(ee + F4(aa,bb,cc) + X[ 8] + unchecked((int) 0x5c4dd124), 12) + dd; bb = RL(bb, 10);
dd = RL(dd + F4(ee,aa,bb) + X[12] + unchecked((int) 0x5c4dd124), 7) + cc; aa = RL(aa, 10);
cc = RL(cc + F4(dd,ee,aa) + X[ 4] + unchecked((int) 0x5c4dd124), 6) + bb; ee = RL(ee, 10);
bb = RL(bb + F4(cc,dd,ee) + X[ 9] + unchecked((int) 0x5c4dd124), 15) + aa; dd = RL(dd, 10);
aa = RL(aa + F4(bb,cc,dd) + X[ 1] + unchecked((int) 0x5c4dd124), 13) + ee; cc = RL(cc, 10);
ee = RL(ee + F4(aa,bb,cc) + X[ 2] + unchecked((int) 0x5c4dd124), 11) + dd; bb = RL(bb, 10);
//
// Rounds 32-47
//
// left
d = RL(d + F3(e,a,b) + X[ 3] + unchecked((int) 0x6ed9eba1), 11) + c; a = RL(a, 10);
c = RL(c + F3(d,e,a) + X[10] + unchecked((int) 0x6ed9eba1), 13) + b; e = RL(e, 10);
b = RL(b + F3(c,d,e) + X[14] + unchecked((int) 0x6ed9eba1), 6) + a; d = RL(d, 10);
a = RL(a + F3(b,c,d) + X[ 4] + unchecked((int) 0x6ed9eba1), 7) + e; c = RL(c, 10);
e = RL(e + F3(a,b,c) + X[ 9] + unchecked((int) 0x6ed9eba1), 14) + d; b = RL(b, 10);
d = RL(d + F3(e,a,b) + X[15] + unchecked((int) 0x6ed9eba1), 9) + c; a = RL(a, 10);
c = RL(c + F3(d,e,a) + X[ 8] + unchecked((int) 0x6ed9eba1), 13) + b; e = RL(e, 10);
b = RL(b + F3(c,d,e) + X[ 1] + unchecked((int) 0x6ed9eba1), 15) + a; d = RL(d, 10);
a = RL(a + F3(b,c,d) + X[ 2] + unchecked((int) 0x6ed9eba1), 14) + e; c = RL(c, 10);
e = RL(e + F3(a,b,c) + X[ 7] + unchecked((int) 0x6ed9eba1), 8) + d; b = RL(b, 10);
d = RL(d + F3(e,a,b) + X[ 0] + unchecked((int) 0x6ed9eba1), 13) + c; a = RL(a, 10);
c = RL(c + F3(d,e,a) + X[ 6] + unchecked((int) 0x6ed9eba1), 6) + b; e = RL(e, 10);
b = RL(b + F3(c,d,e) + X[13] + unchecked((int) 0x6ed9eba1), 5) + a; d = RL(d, 10);
a = RL(a + F3(b,c,d) + X[11] + unchecked((int) 0x6ed9eba1), 12) + e; c = RL(c, 10);
e = RL(e + F3(a,b,c) + X[ 5] + unchecked((int) 0x6ed9eba1), 7) + d; b = RL(b, 10);
d = RL(d + F3(e,a,b) + X[12] + unchecked((int) 0x6ed9eba1), 5) + c; a = RL(a, 10);
// right
dd = RL(dd + F3(ee,aa,bb) + X[15] + unchecked((int) 0x6d703ef3), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F3(dd,ee,aa) + X[ 5] + unchecked((int) 0x6d703ef3), 7) + bb; ee = RL(ee, 10);
bb = RL(bb + F3(cc,dd,ee) + X[ 1] + unchecked((int) 0x6d703ef3), 15) + aa; dd = RL(dd, 10);
aa = RL(aa + F3(bb,cc,dd) + X[ 3] + unchecked((int) 0x6d703ef3), 11) + ee; cc = RL(cc, 10);
ee = RL(ee + F3(aa,bb,cc) + X[ 7] + unchecked((int) 0x6d703ef3), 8) + dd; bb = RL(bb, 10);
dd = RL(dd + F3(ee,aa,bb) + X[14] + unchecked((int) 0x6d703ef3), 6) + cc; aa = RL(aa, 10);
cc = RL(cc + F3(dd,ee,aa) + X[ 6] + unchecked((int) 0x6d703ef3), 6) + bb; ee = RL(ee, 10);
bb = RL(bb + F3(cc,dd,ee) + X[ 9] + unchecked((int) 0x6d703ef3), 14) + aa; dd = RL(dd, 10);
aa = RL(aa + F3(bb,cc,dd) + X[11] + unchecked((int) 0x6d703ef3), 12) + ee; cc = RL(cc, 10);
ee = RL(ee + F3(aa,bb,cc) + X[ 8] + unchecked((int) 0x6d703ef3), 13) + dd; bb = RL(bb, 10);
dd = RL(dd + F3(ee,aa,bb) + X[12] + unchecked((int) 0x6d703ef3), 5) + cc; aa = RL(aa, 10);
cc = RL(cc + F3(dd,ee,aa) + X[ 2] + unchecked((int) 0x6d703ef3), 14) + bb; ee = RL(ee, 10);
bb = RL(bb + F3(cc,dd,ee) + X[10] + unchecked((int) 0x6d703ef3), 13) + aa; dd = RL(dd, 10);
aa = RL(aa + F3(bb,cc,dd) + X[ 0] + unchecked((int) 0x6d703ef3), 13) + ee; cc = RL(cc, 10);
ee = RL(ee + F3(aa,bb,cc) + X[ 4] + unchecked((int) 0x6d703ef3), 7) + dd; bb = RL(bb, 10);
dd = RL(dd + F3(ee,aa,bb) + X[13] + unchecked((int) 0x6d703ef3), 5) + cc; aa = RL(aa, 10);
//
// Rounds 48-63
//
// left
c = RL(c + F4(d,e,a) + X[ 1] + unchecked((int) 0x8f1bbcdc), 11) + b; e = RL(e, 10);
b = RL(b + F4(c,d,e) + X[ 9] + unchecked((int) 0x8f1bbcdc), 12) + a; d = RL(d, 10);
a = RL(a + F4(b,c,d) + X[11] + unchecked((int) 0x8f1bbcdc), 14) + e; c = RL(c, 10);
e = RL(e + F4(a,b,c) + X[10] + unchecked((int) 0x8f1bbcdc), 15) + d; b = RL(b, 10);
d = RL(d + F4(e,a,b) + X[ 0] + unchecked((int) 0x8f1bbcdc), 14) + c; a = RL(a, 10);
c = RL(c + F4(d,e,a) + X[ 8] + unchecked((int) 0x8f1bbcdc), 15) + b; e = RL(e, 10);
b = RL(b + F4(c,d,e) + X[12] + unchecked((int) 0x8f1bbcdc), 9) + a; d = RL(d, 10);
a = RL(a + F4(b,c,d) + X[ 4] + unchecked((int) 0x8f1bbcdc), 8) + e; c = RL(c, 10);
e = RL(e + F4(a,b,c) + X[13] + unchecked((int) 0x8f1bbcdc), 9) + d; b = RL(b, 10);
d = RL(d + F4(e,a,b) + X[ 3] + unchecked((int) 0x8f1bbcdc), 14) + c; a = RL(a, 10);
c = RL(c + F4(d,e,a) + X[ 7] + unchecked((int) 0x8f1bbcdc), 5) + b; e = RL(e, 10);
b = RL(b + F4(c,d,e) + X[15] + unchecked((int) 0x8f1bbcdc), 6) + a; d = RL(d, 10);
a = RL(a + F4(b,c,d) + X[14] + unchecked((int) 0x8f1bbcdc), 8) + e; c = RL(c, 10);
e = RL(e + F4(a,b,c) + X[ 5] + unchecked((int) 0x8f1bbcdc), 6) + d; b = RL(b, 10);
d = RL(d + F4(e,a,b) + X[ 6] + unchecked((int) 0x8f1bbcdc), 5) + c; a = RL(a, 10);
c = RL(c + F4(d,e,a) + X[ 2] + unchecked((int) 0x8f1bbcdc), 12) + b; e = RL(e, 10);
// right
cc = RL(cc + F2(dd,ee,aa) + X[ 8] + unchecked((int) 0x7a6d76e9), 15) + bb; ee = RL(ee, 10);
bb = RL(bb + F2(cc,dd,ee) + X[ 6] + unchecked((int) 0x7a6d76e9), 5) + aa; dd = RL(dd, 10);
aa = RL(aa + F2(bb,cc,dd) + X[ 4] + unchecked((int) 0x7a6d76e9), 8) + ee; cc = RL(cc, 10);
ee = RL(ee + F2(aa,bb,cc) + X[ 1] + unchecked((int) 0x7a6d76e9), 11) + dd; bb = RL(bb, 10);
dd = RL(dd + F2(ee,aa,bb) + X[ 3] + unchecked((int) 0x7a6d76e9), 14) + cc; aa = RL(aa, 10);
cc = RL(cc + F2(dd,ee,aa) + X[11] + unchecked((int) 0x7a6d76e9), 14) + bb; ee = RL(ee, 10);
bb = RL(bb + F2(cc,dd,ee) + X[15] + unchecked((int) 0x7a6d76e9), 6) + aa; dd = RL(dd, 10);
aa = RL(aa + F2(bb,cc,dd) + X[ 0] + unchecked((int) 0x7a6d76e9), 14) + ee; cc = RL(cc, 10);
ee = RL(ee + F2(aa,bb,cc) + X[ 5] + unchecked((int) 0x7a6d76e9), 6) + dd; bb = RL(bb, 10);
dd = RL(dd + F2(ee,aa,bb) + X[12] + unchecked((int) 0x7a6d76e9), 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F2(dd,ee,aa) + X[ 2] + unchecked((int) 0x7a6d76e9), 12) + bb; ee = RL(ee, 10);
bb = RL(bb + F2(cc,dd,ee) + X[13] + unchecked((int) 0x7a6d76e9), 9) + aa; dd = RL(dd, 10);
aa = RL(aa + F2(bb,cc,dd) + X[ 9] + unchecked((int) 0x7a6d76e9), 12) + ee; cc = RL(cc, 10);
ee = RL(ee + F2(aa,bb,cc) + X[ 7] + unchecked((int) 0x7a6d76e9), 5) + dd; bb = RL(bb, 10);
dd = RL(dd + F2(ee,aa,bb) + X[10] + unchecked((int) 0x7a6d76e9), 15) + cc; aa = RL(aa, 10);
cc = RL(cc + F2(dd,ee,aa) + X[14] + unchecked((int) 0x7a6d76e9), 8) + bb; ee = RL(ee, 10);
//
// Rounds 64-79
//
// left
b = RL(b + F5(c,d,e) + X[ 4] + unchecked((int) 0xa953fd4e), 9) + a; d = RL(d, 10);
a = RL(a + F5(b,c,d) + X[ 0] + unchecked((int) 0xa953fd4e), 15) + e; c = RL(c, 10);
e = RL(e + F5(a,b,c) + X[ 5] + unchecked((int) 0xa953fd4e), 5) + d; b = RL(b, 10);
d = RL(d + F5(e,a,b) + X[ 9] + unchecked((int) 0xa953fd4e), 11) + c; a = RL(a, 10);
c = RL(c + F5(d,e,a) + X[ 7] + unchecked((int) 0xa953fd4e), 6) + b; e = RL(e, 10);
b = RL(b + F5(c,d,e) + X[12] + unchecked((int) 0xa953fd4e), 8) + a; d = RL(d, 10);
a = RL(a + F5(b,c,d) + X[ 2] + unchecked((int) 0xa953fd4e), 13) + e; c = RL(c, 10);
e = RL(e + F5(a,b,c) + X[10] + unchecked((int) 0xa953fd4e), 12) + d; b = RL(b, 10);
d = RL(d + F5(e,a,b) + X[14] + unchecked((int) 0xa953fd4e), 5) + c; a = RL(a, 10);
c = RL(c + F5(d,e,a) + X[ 1] + unchecked((int) 0xa953fd4e), 12) + b; e = RL(e, 10);
b = RL(b + F5(c,d,e) + X[ 3] + unchecked((int) 0xa953fd4e), 13) + a; d = RL(d, 10);
a = RL(a + F5(b,c,d) + X[ 8] + unchecked((int) 0xa953fd4e), 14) + e; c = RL(c, 10);
e = RL(e + F5(a,b,c) + X[11] + unchecked((int) 0xa953fd4e), 11) + d; b = RL(b, 10);
d = RL(d + F5(e,a,b) + X[ 6] + unchecked((int) 0xa953fd4e), 8) + c; a = RL(a, 10);
c = RL(c + F5(d,e,a) + X[15] + unchecked((int) 0xa953fd4e), 5) + b; e = RL(e, 10);
b = RL(b + F5(c,d,e) + X[13] + unchecked((int) 0xa953fd4e), 6) + a; d = RL(d, 10);
// right
bb = RL(bb + F1(cc,dd,ee) + X[12], 8) + aa; dd = RL(dd, 10);
aa = RL(aa + F1(bb,cc,dd) + X[15], 5) + ee; cc = RL(cc, 10);
ee = RL(ee + F1(aa,bb,cc) + X[10], 12) + dd; bb = RL(bb, 10);
dd = RL(dd + F1(ee,aa,bb) + X[ 4], 9) + cc; aa = RL(aa, 10);
cc = RL(cc + F1(dd,ee,aa) + X[ 1], 12) + bb; ee = RL(ee, 10);
bb = RL(bb + F1(cc,dd,ee) + X[ 5], 5) + aa; dd = RL(dd, 10);
aa = RL(aa + F1(bb,cc,dd) + X[ 8], 14) + ee; cc = RL(cc, 10);
ee = RL(ee + F1(aa,bb,cc) + X[ 7], 6) + dd; bb = RL(bb, 10);
dd = RL(dd + F1(ee,aa,bb) + X[ 6], 8) + cc; aa = RL(aa, 10);
cc = RL(cc + F1(dd,ee,aa) + X[ 2], 13) + bb; ee = RL(ee, 10);
bb = RL(bb + F1(cc,dd,ee) + X[13], 6) + aa; dd = RL(dd, 10);
aa = RL(aa + F1(bb,cc,dd) + X[14], 5) + ee; cc = RL(cc, 10);
ee = RL(ee + F1(aa,bb,cc) + X[ 0], 15) + dd; bb = RL(bb, 10);
dd = RL(dd + F1(ee,aa,bb) + X[ 3], 13) + cc; aa = RL(aa, 10);
cc = RL(cc + F1(dd,ee,aa) + X[ 9], 11) + bb; ee = RL(ee, 10);
bb = RL(bb + F1(cc,dd,ee) + X[11], 11) + aa; dd = RL(dd, 10);
dd += c + H1;
H1 = H2 + d + ee;
H2 = H3 + e + aa;
H3 = H4 + a + bb;
H4 = H0 + b + cc;
H0 = dd;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
for (var i = 0; i != X.Length; i++)
{
X[i] = 0;
}
}
public override IMemoable Copy()
{
return new RipeMD160Digest(this);
}
public override void Reset(IMemoable other)
{
var d = (RipeMD160Digest)other;
CopyIn(d);
}
}
}
| |
using System;
using JetBrains.Annotations;
using JetBrains.Diagnostics;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Caches;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Impl.Resolve.Filters;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Resolve;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Resolve.Filters;
using JetBrains.ReSharper.Psi.Impl.Shared.References;
using JetBrains.ReSharper.Psi.Impl.Shared.Util;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.Resolve
{
public class UnityObjectTypeOrNamespaceReference :
QualifiableReferenceWithinElement<ICSharpLiteralExpression, ITokenNode>,
IReferenceQualifier, ICompletableReference
{
private readonly ISymbolCache mySymbolCache;
private readonly bool myIsFinalPart;
private readonly ForwardedTypesFilter myForwardedTypesFilter;
private readonly ExpectedObjectTypeFilter myExpectedObjectTypeFilter;
public UnityObjectTypeOrNamespaceReference(ICSharpLiteralExpression owner, [CanBeNull] IQualifier qualifier,
ITokenNode token, TreeTextRange rangeWithin,
ExpectedObjectTypeReferenceKind kind, ISymbolCache symbolCache,
bool isFinalPart)
: base(owner, qualifier, token, rangeWithin)
{
mySymbolCache = symbolCache;
myIsFinalPart = isFinalPart;
myForwardedTypesFilter = new ForwardedTypesFilter(symbolCache);
myExpectedObjectTypeFilter = new ExpectedObjectTypeFilter(kind, mustBeClass: isFinalPart);
}
public override Staticness GetStaticness() => Staticness.Any;
// Qualifier is either null or a namespace. No type element
public override ITypeElement GetQualifierTypeElement() => null;
protected override IReference BindToInternal(IDeclaredElement declaredElement, ISubstitution substitution)
{
// Fix up name
if (declaredElement.ShortName != GetName())
{
var newReference = ReferenceWithinElementUtil<ITokenNode>.SetText(this, declaredElement.ShortName,
(node, buffer) =>
{
// The new name is substituted into the existing text, which includes quotes
var unquotedStringValue = buffer.GetText(TextRange.FromLength(1, buffer.Length - 2));
return CSharpElementFactory.GetInstance(node)
.CreateStringLiteralExpression(unquotedStringValue)
.Literal;
});
return newReference.BindTo(declaredElement);
}
// Fix up qualification (e.g. move namespace)
if (declaredElement is ITypeElement newType && !newType.Equals(Resolve().DeclaredElement))
{
var oldRange = new TreeTextRange(TreeOffset.Zero, new TreeOffset(myOwner.GetTextLength()));
ReferenceWithinElementUtil<ITokenNode>.SetText(myOwner.Literal, oldRange,
newType.GetClrName().FullName, (node, buffer) =>
{
// We're replacing the whole text and don't provide quotes in the new string
var unquotedStringValue = buffer.GetText();
return CSharpElementFactory.GetInstance(node)
.CreateStringLiteralExpression(unquotedStringValue)
.Literal;
}, myOwner);
var newReference = myOwner.FindReference<UnityObjectTypeOrNamespaceReference>(r => r.myIsFinalPart);
Assertion.AssertNotNull(newReference, "newReference != null");
return newReference;
}
return this;
}
public override ResolveResultWithInfo GetResolveResult(ISymbolTable symbolTable, string referenceName)
{
var result = base.GetResolveResult(symbolTable, referenceName);
if (result.ResolveErrorType == ResolveErrorType.NOT_RESOLVED)
{
// It's not necessarily an error that we can't resolve. It might be that GetComponent (or whatever) is
// being used as part of a modular architecture
return new ResolveResultWithInfo(result.Result, UnityResolveErrorType.UNRESOLVED_COMPONENT_OR_SCRIPTABLE_OBJECT);
}
return result;
}
public override ISymbolTable GetReferenceSymbolTable(bool useReferenceName)
{
if (myQualifier == null && myIsFinalPart)
{
var name = GetName();
var symbolScope = mySymbolCache.GetSymbolScope(LibrarySymbolScope.FULL, true);
var declaredElements = symbolScope.GetElementsByShortName(name);
var symbolTable = ResolveUtil.CreateSymbolTable(declaredElements, 0);
// GetElementsByShortName is case insensitive, so filter by exact name, which is case sensitive.
// Then filter out any forwarded types. Unity has a lot of these, with types forwarded from
// UnityEngine.dll to UnityEngine.*Module.dll
// Note that filtering here means that filtered values are not treated as candidates and the errors
// are not shown. Use GetSymbolFilters for that
return symbolTable.Filter(new ExactNameFilter(name), myForwardedTypesFilter);
}
// Use the global namespace if there's no qualifier. The base implementation would create a scope based on
// local using statements
if (myQualifier == null)
{
var symbolTable = GetGlobalNamespaceSymbolTable();
return useReferenceName ? symbolTable.Filter(new ExactNameFilter(GetName())) : symbolTable;
}
return base.GetReferenceSymbolTable(useReferenceName);
}
public override ISymbolTable GetCompletionSymbolTable()
{
// this.GetReferenceSymbolTable for an unqualified reference will try to resolve a type based on short
// name. This is no good for completion. Use the default base behaviour, to show namespaces and types
// based on the qualifier
var symbolTable = myQualifier == null
? GetGlobalNamespaceSymbolTable()
: base.GetReferenceSymbolTable(false);
return symbolTable.Filter(GetCompletionFilters());
}
private ISymbolTable GetGlobalNamespaceSymbolTable()
{
var module = myOwner.GetPsiModule();
var globalNamespace = mySymbolCache.GetSymbolScope(module, true, CaseSensitive).GlobalNamespace;
return ResolveUtil.GetSymbolTableByNamespace(globalNamespace, module, true);
}
// I(Reference)Qualifier.GetSymbolTable - returns the symbol table of items available from the resolved
// reference, when being used as a qualifier. Not used to resolve this reference, but can be used to resolve
// another reference, when this instance is used as a qualifier. E.g. if this reference is a namespace,
// return all applicable items available in the namespace.
// Contrast with IReference.GetReferenceSymbolTable, which returns the symbol table used to resolve a
// reference. For a qualified reference, this will call GetQualifier.GetSymbolTable(mode). If there is no
// qualifier, it gets a symbol table based on current scope
public ISymbolTable GetSymbolTable(SymbolTableMode mode, IReference reference, bool useReferenceName)
{
if(!(Resolve().DeclaredElement is INamespace @namespace))
return EmptySymbolTable.INSTANCE;
var module = myOwner.GetPsiModule();
var symbolTable = ResolveUtil.GetSymbolTableByNamespace(@namespace, module, true);
return useReferenceName ? symbolTable.Filter(new ExactNameFilter(reference.GetName())) : symbolTable;
}
public ISymbolTable GetSymbolTable(SymbolTableMode mode)
{
return GetSymbolTable(mode, this, true);
}
// We have a number of symbol filters and it can be confusing to know when they're used and what the default
// implementations are. For QualifiableReferenceWithinElement:
// * GetSymbolFilters - used for resolve. Default is to call GetSmartSymbolFilters and add ExactNameFilter
// Typically, items filtered here are treated as candidates, and errors are used. Anything filtered in
// GetReferenceSymbolTable is lost, and errors are ignored
// * GetSmartSymbolFilters - used to filter the reference symbol table in GetSmartCompletionTable (but GSCT
// is not a common interface method, so only used/implemented by certain languages if we add an interface)
// Default is to return GetCompletionFilters
// * GetCompletionFilters - used by base.GetCompletionTable(), which is only called if this reference adds
// ICompletableReference. Default is an empty list
public override ISymbolFilter[] GetSymbolFilters()
{
return new ISymbolFilter[]
{
new DeclaredElementTypeFilter(ResolveErrorType.TYPE_EXPECTED, CLRDeclaredElementType.NAMESPACE,
CLRDeclaredElementType.CLASS),
myExpectedObjectTypeFilter,
IsNonGenericFilter.INSTANCE
};
}
protected override ISymbolFilter[] GetCompletionFilters()
{
// Complete types and namespaces, no matter where we are. If we're at the end of the string, the user
// might be trying to complete a type in the namespace from the current qualifier, or might be trying to
// add another namespace. If we're in the middle of the string, they might be changing their mind, and
// adding a new (qualified) type, so adding either type or namespace (the text to the right will fail to
// resolve)
return new[]
{
CSharpTypeOrNamespaceFilter.INSTANCE,
TypeElementMustBeClassFilter.INSTANCE,
new GlobalUnityEditorTypeFilter(),
IsPublicFilter.INSTANCE
};
}
public QualifierKind GetKind()
{
return Resolve().DeclaredElement is INamespace ? QualifierKind.NAMESPACE : QualifierKind.NONE;
}
public bool Resolved => Resolve().DeclaredElement != null;
private class GlobalUnityEditorTypeFilter : SimpleSymbolFilter
{
public override ResolveErrorType ErrorType => ResolveErrorType.IGNORABLE;
public override bool Accepts(IDeclaredElement declaredElement, ISubstitution substitution)
{
var typeElement = declaredElement as ITypeElement;
if (typeElement == null)
return true;
// Filter out the obsolete AssetModificationProcessor type in the global namespace from UnityEditor.dll
if (declaredElement.ShortName == "AssetModificationProcessor")
return !typeElement.Module.Name.StartsWith("UnityEditor");
if (declaredElement.ShortName == "TMPro_SDFMaterialEditor")
{
// This is copied into Libraries, so don't rely on case (UnityEditor.dll comes from the install dir)
return !typeElement.Module.Name.Equals("Unity.TextMeshPro.Editor",
StringComparison.OrdinalIgnoreCase);
}
return true;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="QueryCacheManager.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//------------------------------------------------------------------------------
namespace System.Data.Common.QueryCache
{
using System;
using System.Collections.Generic;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;
using System.Data.Objects.Internal;
using System.Diagnostics;
using System.Threading;
using System.Data.Common.Internal.Materialization;
/// <summary>
/// Provides Query Execution Plan Caching Service
/// </summary>
/// <remarks>
/// Thread safe.
/// Dispose <b>must</b> be called as there is no finalizer for this class
/// </remarks>
internal class QueryCacheManager : IDisposable
{
#region Constants/Default values for configuration parameters
/// <summary>
/// Default Soft maximum number of entries in the cache
/// Default value: 1000
/// </summary>
const int DefaultMaxNumberOfEntries = 1000;
/// <summary>
/// Default high mark for starting sweeping process
/// default value: 80% of MaxNumberOfEntries
/// </summary>
const float DefaultHighMarkPercentageFactor = 0.8f; // 80% of MaxLimit
/// <summary>
/// Recycler timer period
/// </summary>
const int DefaultRecyclerPeriodInMilliseconds = 60 * 1000;
#endregion
#region Fields
/// <summary>
/// cache lock object
/// </summary>
private readonly object _cacheDataLock = new object();
/// <summary>
/// cache data
/// </summary>
private readonly Dictionary<QueryCacheKey, QueryCacheEntry> _cacheData = new Dictionary<QueryCacheKey, QueryCacheEntry>(32);
/// <summary>
/// soft maximum number of entries in the cache
/// </summary>
private readonly int _maxNumberOfEntries;
/// <summary>
/// high mark of the number of entries to trigger the sweeping process
/// </summary>
private readonly int _sweepingTriggerHighMark;
/// <summary>
/// Eviction timer
/// </summary>
private readonly EvictionTimer _evictionTimer;
#endregion
#region Construction and Initialization
/// <summary>
/// Constructs a new Query Cache Manager instance, with default values for all 'configurable' parameters.
/// </summary>
/// <returns>A new instance of <see cref="QueryCacheManager"/> configured with default entry count, load factor and recycle period</returns>
internal static QueryCacheManager Create()
{
return new QueryCacheManager(DefaultMaxNumberOfEntries, DefaultHighMarkPercentageFactor, DefaultRecyclerPeriodInMilliseconds);
}
/// <summary>
/// Cache Constructor
/// </summary>
/// <param name="maximumSize">
/// Maximum number of entries that the cache should contain.
/// </param>
/// <param name="loadFactor">
/// The number of entries that must be present, as a percentage, before entries should be removed
/// according to the eviction policy.
/// Must be greater than 0 and less than or equal to 1.0
/// </param>
/// <param name="recycleMillis">
/// The interval, in milliseconds, at which the number of entries will be compared to the load factor
/// and eviction carried out if necessary.
/// </param>
private QueryCacheManager(int maximumSize, float loadFactor, int recycleMillis)
{
Debug.Assert(maximumSize > 0, "Maximum size must be greater than zero");
Debug.Assert(loadFactor > 0 && loadFactor <= 1, "Load factor must be greater than 0.0 and less than or equal to 1.0");
Debug.Assert(recycleMillis >= 0, "Recycle period in milliseconds must not be negative");
//
// Load hardcoded defaults
//
this._maxNumberOfEntries = maximumSize;
//
// set sweeping high mark trigger value
//
this._sweepingTriggerHighMark = (int)(_maxNumberOfEntries * loadFactor);
//
// Initialize Recycler
//
this._evictionTimer = new EvictionTimer(this, recycleMillis);
}
#endregion
#region 'External' interface
/// <summary>
/// Adds new entry to the cache using "abstract" cache context and
/// value; returns an existing entry if the key is already in the
/// dictionary.
/// </summary>
/// <param name="inQueryCacheEntry"></param>
/// <param name="outQueryCacheEntry">
/// The existing entry in the dicitionary if already there;
/// inQueryCacheEntry if none was found and inQueryCacheEntry
/// was added instead.
/// </param>
/// <returns>true if the output entry was already found; false if it had to be added.</returns>
internal bool TryLookupAndAdd(QueryCacheEntry inQueryCacheEntry, out QueryCacheEntry outQueryCacheEntry)
{
Debug.Assert(null != inQueryCacheEntry, "qEntry must not be null");
outQueryCacheEntry = null;
lock (_cacheDataLock)
{
if (!_cacheData.TryGetValue(inQueryCacheEntry.QueryCacheKey, out outQueryCacheEntry))
{
//
// add entry to cache data
//
_cacheData.Add(inQueryCacheEntry.QueryCacheKey, inQueryCacheEntry);
if (_cacheData.Count > _sweepingTriggerHighMark)
{
_evictionTimer.Start();
}
return false;
}
else
{
outQueryCacheEntry.QueryCacheKey.UpdateHit();
return true;
}
}
}
/// <summary>
/// Lookup service for a cached value.
/// </summary>
internal bool TryCacheLookup<TK, TE>(TK key, out TE value)
where TK : QueryCacheKey
{
Debug.Assert(null != key, "key must not be null");
value = default(TE);
//
// invoke internal lookup
//
QueryCacheEntry qEntry = null;
bool bHit = TryInternalCacheLookup(key, out qEntry);
//
// if it is a hit, 'extract' the entry strong type cache value
//
if (bHit)
{
value = (TE)qEntry.GetTarget();
}
return bHit;
}
/// <summary>
/// Clears the Cache
/// </summary>
internal void Clear()
{
lock (_cacheDataLock)
{
_cacheData.Clear();
}
}
#endregion
#region Private Members
/// <summary>
/// lookup service
/// </summary>
/// <param name="queryCacheKey"></param>
/// <param name="queryCacheEntry"></param>
/// <returns>true if cache hit, false if cache miss</returns>
private bool TryInternalCacheLookup( QueryCacheKey queryCacheKey, out QueryCacheEntry queryCacheEntry )
{
Debug.Assert(null != queryCacheKey, "queryCacheKey must not be null");
queryCacheEntry = null;
bool bHit = false;
//
// lock the cache for the minimal possible period
//
lock (_cacheDataLock)
{
bHit = _cacheData.TryGetValue(queryCacheKey, out queryCacheEntry);
}
//
// if cache hit
//
if (bHit)
{
//
// update hit mark in cache key
//
queryCacheEntry.QueryCacheKey.UpdateHit();
}
return bHit;
}
/// <summary>
/// Recycler handler. This method is called directly by the eviction timer.
/// It should take no action beyond invoking the <see cref="SweepCache"/> method on the
/// cache manager instance passed as <paramref name="state"/>.
/// </summary>
/// <param name="state">The cache manager instance on which the 'recycle' handler should be invoked</param>
private static void CacheRecyclerHandler(object state)
{
((QueryCacheManager)state).SweepCache();
}
/// <summary>
/// Aging factor
/// </summary>
private static readonly int[] _agingFactor = {1,1,2,4,8,16};
private static readonly int AgingMaxIndex = _agingFactor.Length - 1;
/// <summary>
/// Sweeps the cache removing old unused entries.
/// This method implements the query cache eviction policy.
/// </summary>
private void SweepCache()
{
if (!this._evictionTimer.Suspend())
{
// Return of false from .Suspend means that the manager and timer have been disposed.
return;
}
bool disabledEviction = false;
lock (_cacheDataLock)
{
//
// recycle only if entries exceeds the high mark factor
//
if (_cacheData.Count > _sweepingTriggerHighMark)
{
//
// sweep the cache
//
uint evictedEntriesCount = 0;
List<QueryCacheKey> cacheKeys = new List<QueryCacheKey>(_cacheData.Count);
cacheKeys.AddRange(_cacheData.Keys);
for (int i = 0; i < cacheKeys.Count; i++)
{
//
// if entry was not used in the last time window, then evict the entry
//
if (0 == cacheKeys[i].HitCount)
{
_cacheData.Remove(cacheKeys[i]);
evictedEntriesCount++;
}
//
// otherwise, age the entry in a progressive scheme
//
else
{
int agingIndex = unchecked(cacheKeys[i].AgingIndex + 1);
if (agingIndex > AgingMaxIndex)
{
agingIndex = AgingMaxIndex;
}
cacheKeys[i].AgingIndex = agingIndex;
cacheKeys[i].HitCount = cacheKeys[i].HitCount >> _agingFactor[agingIndex];
}
}
}
else
{
_evictionTimer.Stop();
disabledEviction = true;
}
}
if (!disabledEviction)
{
this._evictionTimer.Resume();
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Dispose instance
/// </summary>
/// <remarks>Dispose <b>must</b> be called as there are no finalizers for this class</remarks>
public void Dispose()
{
// Technically, calling GC.SuppressFinalize is not required because the class does not
// have a finalizer, but it does no harm, protects against the case where a finalizer is added
// in the future, and prevents an FxCop warning.
GC.SuppressFinalize(this);
if (this._evictionTimer.Stop())
{
this.Clear();
}
}
#endregion
/// <summary>
/// Periodically invokes cache cleanup logic on a specified <see cref="QueryCacheManager"/> instance,
/// and allows this periodic callback to be suspended, resumed or stopped in a thread-safe way.
/// </summary>
private sealed class EvictionTimer
{
/// <summary>Used to control multi-threaded accesses to this instance</summary>
private readonly object _sync = new object();
/// <summary>The required interval between invocations of the cache cleanup logic</summary>
private readonly int _period;
/// <summary>The underlying QueryCacheManger that the callback will act on</summary>
private readonly QueryCacheManager _cacheManager;
/// <summary>The underlying <see cref="Timer"/> that implements the periodic callback</summary>
private Timer _timer;
internal EvictionTimer(QueryCacheManager cacheManager, int recyclePeriod)
{
this._cacheManager = cacheManager;
this._period = recyclePeriod;
}
internal void Start()
{
lock (_sync)
{
if (_timer == null)
{
this._timer = new Timer(QueryCacheManager.CacheRecyclerHandler, _cacheManager, _period, _period);
}
}
}
/// <summary>
/// Permanently stops the eviction timer.
/// It will no longer generate periodic callbacks and further calls to <see cref="Suspend"/>, <see cref="Resume"/>, or <see cref="Stop"/>,
/// though thread-safe, will have no effect.
/// </summary>
/// <returns>
/// If this eviction timer has already been stopped (using the <see cref="Stop"/> method), returns <c>false</c>;
/// otherwise, returns <c>true</c> to indicate that the call successfully stopped and cleaned up the underlying timer instance.
/// </returns>
/// <remarks>
/// Thread safe. May be called regardless of the current state of the eviction timer.
/// Once stopped, an eviction timer cannot be restarted with the <see cref="Resume"/> method.
/// </remarks>
internal bool Stop()
{
lock (_sync)
{
if (this._timer != null)
{
this._timer.Dispose();
this._timer = null;
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Pauses the operation of the eviction timer.
/// </summary>
/// <returns>
/// If this eviction timer has already been stopped (using the <see cref="Stop"/> method), returns <c>false</c>;
/// otherwise, returns <c>true</c> to indicate that the call successfully suspended the inderlying <see cref="Timer"/>
/// and no further periodic callbacks will be generated until the <see cref="Resume"/> method is called.
/// </returns>
/// <remarks>
/// Thread-safe. May be called regardless of the current state of the eviction timer.
/// Once suspended, an eviction timer may be resumed or stopped.
/// </remarks>
internal bool Suspend()
{
lock (_sync)
{
if (this._timer != null)
{
this._timer.Change(Timeout.Infinite, Timeout.Infinite);
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// Causes this eviction timer to generate periodic callbacks, provided it has not been permanently stopped (using the <see cref="Stop"/> method).
/// </summary>
/// <remarks>
/// Thread-safe. May be called regardless of the current state of the eviction timer.
/// </remarks>
internal void Resume()
{
lock (_sync)
{
if (this._timer != null)
{
this._timer.Change(this._period, this._period);
}
}
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the GuardiaPracticasClase class.
/// </summary>
[Serializable]
public partial class GuardiaPracticasClaseCollection : ActiveList<GuardiaPracticasClase, GuardiaPracticasClaseCollection>
{
public GuardiaPracticasClaseCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>GuardiaPracticasClaseCollection</returns>
public GuardiaPracticasClaseCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
GuardiaPracticasClase o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Guardia_Practicas_Clases table.
/// </summary>
[Serializable]
public partial class GuardiaPracticasClase : ActiveRecord<GuardiaPracticasClase>, IActiveRecord
{
#region .ctors and Default Settings
public GuardiaPracticasClase()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public GuardiaPracticasClase(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public GuardiaPracticasClase(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public GuardiaPracticasClase(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Guardia_Practicas_Clases", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "id";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = true;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 100;
colvarNombre.AutoIncrement = false;
colvarNombre.IsNullable = false;
colvarNombre.IsPrimaryKey = false;
colvarNombre.IsForeignKey = false;
colvarNombre.IsReadOnly = false;
colvarNombre.DefaultSetting = @"";
colvarNombre.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombre);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("Guardia_Practicas_Clases",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get { return GetColumnValue<int>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("Nombre")]
[Bindable(true)]
public string Nombre
{
get { return GetColumnValue<string>(Columns.Nombre); }
set { SetColumnValue(Columns.Nombre, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varNombre)
{
GuardiaPracticasClase item = new GuardiaPracticasClase();
item.Nombre = varNombre;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varId,string varNombre)
{
GuardiaPracticasClase item = new GuardiaPracticasClase();
item.Id = varId;
item.Nombre = varNombre;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn NombreColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"id";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections;
using UnityEngine;
using Gvr.Internal;
/// Represents the controller's current connection state.
public enum GvrConnectionState {
/// Indicates that the controller is disconnected.
Disconnected,
/// Indicates that the device is scanning for controllers.
Scanning,
/// Indicates that the device is connecting to a controller.
Connecting,
/// Indicates that the device is connected to a controller.
Connected,
/// Indicates that an error has occurred.
Error,
};
/// Main entry point for the GVR Controller API.
///
/// To use this API, add this behavior to a GameObject in your scene, or use the
/// GvrControllerMain prefab. There can only be one object with this behavior on your scene.
///
/// This is a singleton object.
///
/// To access the controller state, simply read the static properties of this class. For example,
/// to know the controller's current orientation, use GvrController.Orientation.
public class GvrController : MonoBehaviour {
private ControllerState controllerState = new ControllerState();
private static GvrController instance;
private static IControllerProvider controllerProvider;
/// If true, enable gyroscope on the controller.
[Tooltip("If enabled, the controller will report gyroscope readings.")]
public bool enableGyro = false;
/// If true, enable accelerometer on the controller.
[Tooltip("If enabled, the controller will report accelerometer readings.")]
public bool enableAccel = false;
public enum EmulatorConnectionMode {
OFF,
USB,
WIFI,
}
/// Indicates how we connect to the controller emulator.
[Tooltip("How to connect to the emulator: USB cable (recommended) or WIFI.")]
public EmulatorConnectionMode emulatorConnectionMode = EmulatorConnectionMode.USB;
/// Returns the controller's current connection state.
public static GvrConnectionState State {
get {
return instance != null ? instance.controllerState.connectionState : GvrConnectionState.Error;
}
}
/// Returns the controller's current orientation in space, as a quaternion.
/// The space in which the orientation is represented is the usual Unity space, with
/// X pointing to the right, Y pointing up and Z pointing forward. Therefore, to make an
/// object in your scene have the same orientation as the controller, simply assign this
/// quaternion to the GameObject's transform.rotation.
public static Quaternion Orientation {
get {
return instance != null ? instance.controllerState.orientation : Quaternion.identity;
}
}
/// Returns the controller's gyroscope reading. The gyroscope indicates the angular
/// about each of its local axes. The controller's axes are: X points to the right,
/// Y points perpendicularly up from the controller's top surface and Z lies
/// along the controller's body, pointing towards the front. The angular speed is given
/// in radians per second, using the right-hand rule (positive means a right-hand rotation
/// about the given axis).
public static Vector3 Gyro {
get {
return instance != null ? instance.controllerState.gyro : Vector3.zero;
}
}
/// Returns the controller's accelerometer reading. The accelerometer indicates the
/// effect of acceleration and gravity in the direction of each of the controller's local
/// axes. The controller's local axes are: X points to the right, Y points perpendicularly
/// up from the controller's top surface and Z lies along the controller's body, pointing
/// towards the front. The acceleration is measured in meters per second squared. Note that
/// gravity is combined with acceleration, so when the controller is resting on a table top,
/// it will measure an acceleration of 9.8 m/s^2 on the Y axis. The accelerometer reading
/// will be zero on all three axes only if the controller is in free fall, or if the user
/// is in a zero gravity environment like a space station.
public static Vector3 Accel {
get {
return instance != null ? instance.controllerState.accel : Vector3.zero;
}
}
/// If true, the user is currently touching the controller's touchpad.
public static bool IsTouching {
get {
return instance != null ? instance.controllerState.isTouching : false;
}
}
/// If true, the user just started touching the touchpad. This is an event flag (it is true
/// for only one frame after the event happens, then reverts to false).
public static bool TouchDown {
get {
return instance != null ? instance.controllerState.touchDown : false;
}
}
/// If true, the user just stopped touching the touchpad. This is an event flag (it is true
/// for only one frame after the event happens, then reverts to false).
public static bool TouchUp {
get {
return instance != null ? instance.controllerState.touchUp : false;
}
}
public static Vector2 TouchPos {
get {
return instance != null ? instance.controllerState.touchPos : Vector2.zero;
}
}
/// If true, the user is currently performing the recentering gesture. Most apps will want
/// to pause the interaction while this remains true.
public static bool Recentering {
get {
return instance != null ? instance.controllerState.recentering : false;
}
}
/// If true, the user just completed the recenter gesture. The controller's orientation is
/// now being reported in the new recentered coordinate system (the controller's orientation
/// when recentering was completed was remapped to mean "forward"). This is an event flag
/// (it is true for only one frame after the event happens, then reverts to false).
/// The headset is recentered together with the controller.
public static bool Recentered {
get {
return instance != null ? instance.controllerState.recentered : false;
}
}
/// If true, the click button (touchpad button) is currently being pressed. This is not
/// an event: it represents the button's state (it remains true while the button is being
/// pressed).
public static bool ClickButton {
get {
return instance != null ? instance.controllerState.clickButtonState : false;
}
}
/// If true, the click button (touchpad button) was just pressed. This is an event flag:
/// it will be true for only one frame after the event happens.
public static bool ClickButtonDown {
get {
return instance != null ? instance.controllerState.clickButtonDown : false;
}
}
/// If true, the click button (touchpad button) was just released. This is an event flag:
/// it will be true for only one frame after the event happens.
public static bool ClickButtonUp {
get {
return instance != null ? instance.controllerState.clickButtonUp : false;
}
}
/// If true, the app button (touchpad button) is currently being pressed. This is not
/// an event: it represents the button's state (it remains true while the button is being
/// pressed).
public static bool AppButton {
get {
return instance != null ? instance.controllerState.appButtonState : false;
}
}
/// If true, the app button was just pressed. This is an event flag: it will be true for
/// only one frame after the event happens.
public static bool AppButtonDown {
get {
return instance != null ? instance.controllerState.appButtonDown : false;
}
}
/// If true, the app button was just released. This is an event flag: it will be true for
/// only one frame after the event happens.
public static bool AppButtonUp {
get {
return instance != null ? instance.controllerState.appButtonUp : false;
}
}
/// If State == GvrConnectionState.Error, this contains details about the error.
public static string ErrorDetails {
get {
if (instance != null) {
return instance.controllerState.connectionState == GvrConnectionState.Error ?
instance.controllerState.errorDetails : "";
} else {
return "GvrController instance not found in scene. It may be missing, or it might "
+ "not have initialized yet.";
}
}
}
void Awake() {
if (instance != null) {
Debug.LogError("More than one GvrController instance was found in your scene. "
+ "Ensure that there is only one GvrController.");
this.enabled = false;
return;
}
instance = this;
if (controllerProvider == null) {
controllerProvider = ControllerProviderFactory.CreateControllerProvider(this);
}
}
void OnDestroy() {
instance = null;
}
private void UpdateController() {
controllerProvider.ReadState(controllerState);
// If the controller was recentered, also recenter the headset.
if (controllerState.recentered) {
GvrViewer sdk = GvrViewer.Instance;
if (sdk) {
sdk.Recenter();
}
}
}
void OnApplicationPause(bool paused) {
Debug.Log("GvrController: application " + (paused ? "paused" : "resumed"));
if (null == controllerProvider) return;
if (paused) {
controllerProvider.OnPause();
} else {
controllerProvider.OnResume();
}
}
void OnEnable() {
StartCoroutine("EndOfFrame");
}
void OnDisable() {
StopCoroutine("EndOfFrame");
}
IEnumerator EndOfFrame() {
while (true) {
// This must be done at the end of the frame to ensure that all GameObjects had a chance
// to read transient controller state (e.g. events, etc) for the current frame before
// it gets reset.
UpdateController();
yield return new WaitForEndOfFrame();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="JsonObjectModel.cs" company="Visual JSON Editor">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>http://visualjsoneditor.codeplex.com/license</license>
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NJsonSchema;
using NJsonSchema.Validation;
namespace VisualJsonEditor.Models
{
/// <summary>Represents a JSON object. </summary>
public class JsonObjectModel : JsonTokenModel
{
/// <summary>Creates a default <see cref="JsonObjectModel"/> from the given schema. </summary>
/// <param name="schema">The <see cref="JsonSchema4"/>. </param>
/// <returns>The <see cref="JsonObjectModel"/>. </returns>
public static JsonObjectModel FromSchema(JsonSchema schema)
{
schema = schema.ActualSchema;
var obj = new JsonObjectModel();
foreach (var property in schema.Properties)
{
var propertySchema = property.Value.ActualSchema;
if (propertySchema.Type.HasFlag(JsonObjectType.Object))
{
if (property.Value.IsRequired)
obj[property.Key] = FromSchema(propertySchema);
else
obj[property.Key] = null;
}
else if (propertySchema.Type.HasFlag(JsonObjectType.Array))
{
if (property.Value.IsRequired)
obj[property.Key] = new ObservableCollection<JsonTokenModel>();
else
obj[property.Key] = null;
}
else
obj[property.Key] = GetDefaultValue(property);
}
obj.Schema = schema;
return obj;
}
/// <summary>Creates a <see cref="JsonObjectModel"/> from the given JSON data and <see cref="JsonSchema4"/>. </summary>
/// <param name="jsonData">The JSON data. </param>
/// <param name="schema">The <see cref="JsonSchema4"/>. </param>
/// <returns>The <see cref="JsonObjectModel"/>. </returns>
public static JsonObjectModel FromJson(string jsonData, JsonSchema schema)
{
var json = JsonConvert.DeserializeObject(jsonData);
return FromJson((JObject)json, schema);
}
/// <summary> Checks the JSON data for a property called "_schema" </summary>
/// <param name="filePath">The JSON document file path. </param>
/// <returns>The path to the schema file if one is defined as a document property. </returns>
public static string GetSchemaProperty(string filePath)
{
JToken schemaToken;
var json = (JObject)JsonConvert.DeserializeObject(File.ReadAllText(filePath, Encoding.UTF8));
if (!json.TryGetValue("$schema", out schemaToken))
return null;
var relativeSchemaPath = ((JValue)schemaToken).Value as string;
relativeSchemaPath = relativeSchemaPath.Replace('/', Path.DirectorySeparatorChar);
return Path.Combine(Path.GetDirectoryName(filePath), relativeSchemaPath);
}
/// <summary>Creates a <see cref="JsonObjectModel"/> from the given <see cref="JObject"/> and <see cref="JsonSchema4"/>. </summary>
/// <param name="obj">The <see cref="JObject"/>. </param>
/// <param name="schema">The <see cref="JsonSchema4"/>. </param>
/// <returns>The <see cref="JsonObjectModel"/>. </returns>
public static JsonObjectModel FromJson(JObject obj, JsonSchema schema)
{
schema = schema.ActualSchema;
var result = new JsonObjectModel();
foreach (var property in schema.Properties)
{
var propertySchema = property.Value.ActualSchema;
if (propertySchema.Type.HasFlag(JsonObjectType.Array))
{
var propertyItemSchema = propertySchema.Item != null ? propertySchema.Item.ActualSchema : null;
if (obj[property.Key] != null)
{
var objects = obj[property.Key].Select(o => o is JObject ?
(JsonTokenModel)FromJson((JObject)o, propertyItemSchema) :
JsonValueModel.FromJson((JValue)o, propertyItemSchema));
var list = new ObservableCollection<JsonTokenModel>(objects);
foreach (var item in list)
item.ParentList = list;
result[property.Key] = list;
}
else
result[property.Key] = null;
}
else if (propertySchema.Type.HasFlag(JsonObjectType.Object) || propertySchema.Type == JsonObjectType.None)
{
var token = obj[property.Key];
if (token is JObject)
result[property.Key] = FromJson((JObject)token, propertySchema);
else
result[property.Key] = null;
}
else
{
JToken value;
if (obj.TryGetValue(property.Key, out value))
result[property.Key] = ((JValue)value).Value;
else
result[property.Key] = GetDefaultValue(property);
}
}
result.Schema = schema;
return result;
}
private static object GetDefaultValue(KeyValuePair<string, JsonSchemaProperty> property)
{
var propertySchema = property.Value.ActualSchema;
if (propertySchema.Default != null)
return propertySchema.Default;
if (propertySchema.Type.HasFlag(JsonObjectType.Boolean))
return false;
if (propertySchema.Type.HasFlag(JsonObjectType.String) && propertySchema.Format == JsonFormatStrings.DateTime)
return new DateTime();
if (propertySchema.Type.HasFlag(JsonObjectType.String) && propertySchema.Format == "date") // TODO: What to do with date/time?
return new DateTime();
if (propertySchema.Type.HasFlag(JsonObjectType.String) && propertySchema.Format == "time")
return new TimeSpan();
if (propertySchema.Type.HasFlag(JsonObjectType.String))
return string.Empty;
return null;
}
/// <summary>Gets the object's properties. </summary>
public IEnumerable<JsonPropertyModel> Properties
{
get
{
var properties = new List<JsonPropertyModel>();
if (Schema.Properties != null)
{
foreach (var propertyInfo in Schema.Properties)
{
var property = new JsonPropertyModel(propertyInfo.Key, this, propertyInfo.Value);
if (property.Value is ObservableCollection<JsonTokenModel>)
{
foreach (var obj in (ObservableCollection<JsonTokenModel>)property.Value)
obj.Schema = propertyInfo.Value.Item != null ? propertyInfo.Value.Item.ActualSchema : null;
}
properties.Add(property);
}
}
return properties;
}
}
/// <summary>Converts the <see cref="JsonTokenModel"/> to a <see cref="JToken"/>. </summary>
/// <returns>The <see cref="JToken"/>. </returns>
public override JToken ToJToken()
{
var obj = new JObject();
foreach (var pair in this)
{
if (pair.Value is ObservableCollection<JsonTokenModel>)
{
var array = (ObservableCollection<JsonTokenModel>)pair.Value;
var jArray = new JArray();
foreach (var item in array)
jArray.Add(item.ToJToken());
obj[pair.Key] = jArray;
}
else if (pair.Value is JsonTokenModel)
obj[pair.Key] = ((JsonTokenModel)pair.Value).ToJToken();
else if (pair.Value != null || Schema.Properties[pair.Key].IsRequired)
obj[pair.Key] = new JValue(pair.Value);
}
return obj;
}
/// <summary>Validates the data of the <see cref="JsonObjectModel"/>. </summary>
/// <returns>The list of validation errors. </returns>
public Task<string> ValidateAsync()
{
return Task.Run(() =>
{
var json = ToJson();
var errors = Schema.Validate(json);
return string.Join("\n", ConvertErrors(errors, string.Empty));
});
}
private static string[] ConvertErrors(IEnumerable<ValidationError> errors, string padding)
{
return errors.Select(error =>
{
var output = new StringBuilder(string.Format("{0}{1}: {2}", padding, error.Path, error.Kind));
if (error is ChildSchemaValidationError)
{
foreach (var childError in ((ChildSchemaValidationError)error).Errors)
{
var schemaTitle = (!string.IsNullOrEmpty(childError.Key.Title) ? childError.Key.Title : "Schema");
output.Append(string.Format("\n{0} {1}:", padding, schemaTitle));
foreach (var x in ConvertErrors(childError.Value, padding + " "))
output.Append(string.Format("\n{0}", x));
}
}
return output.ToString();
}).ToArray();
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using XenAdmin;
using XenAdmin.Core;
using XenAdmin.Network;
namespace XenAPI
{
public partial class SR : IComparable<SR>, IEquatable<SR>
{
/// <summary>
/// The SR types. Note that the names of these enum members correspond exactly to the SR type string as
/// recognised by the server. If you add anything here, check whether it should also be added to
/// SR.CanCreateWithXenCenter. Also add it to XenAPI/FriendlyNames.resx under
/// Label-SR.SRTypes-*. Don't change the lower-casing!
/// </summary>
public enum SRTypes
{
local, ext, lvmoiscsi, iso, nfs, lvm, netapp, udev, lvmofc,
lvmohba, egenera, egeneracd, dummy, unknown, equal, cslg, shm,
iscsi,
ebs, rawhba,
smb, lvmofcoe, gfs2,
nutanix, nutanixiso,
tmpfs
}
public const long DISK_MAX_SIZE = 2 * Util.BINARY_TERA;
public const string Content_Type_ISO = "iso";
public const string SM_Config_Type_CD = "cd";
private const string XenServer_Tools_Label = "XenServer Tools";
public override string ToString()
{
return Name();
}
/// <returns>A friendly name for the SR.</returns>
public override string Name()
{
return I18N("name_label", name_label, true);
}
/// <summary>
/// Get the given SR's home, i.e. the host under which we are going to display it. May return null, if this SR should live
/// at the pool level.
/// </summary>
public Host Home()
{
if (shared || PBDs.Count != 1)
return null;
PBD pbd = Connection.Resolve(PBDs[0]);
if (pbd == null)
return null;
return Connection.Resolve(pbd.host);
}
public string NameWithoutHost()
{
return I18N("name_label", name_label, false);
}
/// <returns>A friendly description for the SR.</returns>
public override string Description()
{
return I18N("name_description", name_description, true);
}
public bool Physical()
{
SRTypes typ = GetSRType(false);
return typ == SRTypes.local || (typ == SRTypes.udev && SMConfigType() == SM_Config_Type_CD);
}
public string SMConfigType()
{
return Get(sm_config, "type");
}
public bool IsToolsSR()
{
return name_label == SR.XenServer_Tools_Label || is_tools_sr;
}
public string FriendlyTypeName()
{
var srType = GetSRType(false);
if (srType == SRTypes.unknown)
{
var sm = SM.GetByType(Connection, type);
if (sm != null &&
Version.TryParse(sm.required_api_version, out var smapiVersion) &&
smapiVersion.CompareTo(new Version(3, 0)) >= 0)
return !string.IsNullOrEmpty(sm.name_label) ? sm.name_label : type;
}
return GetFriendlyTypeName(srType);
}
/// <summary>
/// A friendly (internationalized) name for the SR type.
/// </summary>
public static string GetFriendlyTypeName(SRTypes srType)
{
return FriendlyNameManager.GetFriendlyName(string.Format("Label-SR.SRTypes-{0}", srType.ToString()));
}
/// <summary>
/// Use this instead of type
/// </summary>
public SRTypes GetSRType(bool ignoreCase)
{
try
{
return (SRTypes)Enum.Parse(typeof(SRTypes), type, ignoreCase);
}
catch
{
return SRTypes.unknown;
}
}
public SM GetSM()
{
return SM.GetByType(Connection, GetSRType(true).ToString());
}
private string I18N(string field_name, string field_value, bool with_host)
{
if (!other_config.ContainsKey("i18n-key"))
{
return field_value;
}
string i18n_key = other_config["i18n-key"];
string original_value_key = "i18n-original-value-" + field_name;
string original_value =
other_config.ContainsKey(original_value_key) ? other_config[original_value_key] : "";
if (original_value != field_value)
return field_value;
string hostname = with_host ? GetHostName() : null;
if (hostname == null)
{
string pattern = FriendlyNameManager.GetFriendlyName(string.Format("SR.{0}-{1}", field_name, i18n_key));
return pattern == null ? field_value : pattern;
}
else
{
string pattern = FriendlyNameManager.GetFriendlyName(string.Format("SR.{0}-{1}-host", field_name, i18n_key));
return pattern == null ? field_value : string.Format(pattern, hostname);
}
}
/// <returns>The name of the host to which this SR is attached, or null if the storage is shared
/// or unattached.</returns>
private string GetHostName()
{
if (Connection == null)
return null;
Host host = GetStorageHost();
return host == null ? null : host.Name();
}
/// <returns>The host to which the given SR belongs, or null if the SR is shared or completely disconnected.</returns>
public Host GetStorageHost()
{
if (shared || PBDs.Count != 1)
return null;
PBD pbd = Connection.Resolve(PBDs[0]);
return pbd == null ? null : Connection.Resolve(pbd.host);
}
/// <summary>
/// Iterating through the PBDs, this will return the storage host of the first PBD that is currently_attached.
/// This will return null if there are no PBDs or none of them is currently_attached
/// </summary>
public Host GetFirstAttachedStorageHost()
{
if (PBDs.Count == 0)
return null;
var currentlyAttachedPBDs = PBDs.Select(pbdref => Connection.Resolve(pbdref)).Where(p => p != null && p.currently_attached);
if (currentlyAttachedPBDs.FirstOrDefault() != null)
return currentlyAttachedPBDs.Select(p => Connection.Resolve(p.host)).Where(h => h != null).FirstOrDefault();
return null;
}
/// <summary>
/// Can create with XC, or is citrix storage link gateway. Special case alert!
/// </summary>
public bool CanCreateWithXenCenter()
{
SRTypes type = GetSRType(false);
return type == SRTypes.iso
|| type == SRTypes.lvmoiscsi
|| type == SRTypes.nfs
|| type == SRTypes.equal
|| type == SRTypes.netapp
|| type == SRTypes.lvmohba
|| type == SRTypes.cslg
|| type == SRTypes.smb
|| type == SRTypes.lvmofcoe
|| type == SRTypes.gfs2;
}
public bool IsLocalSR()
{
SRTypes typ = GetSRType(false);
return typ == SRTypes.local
|| typ == SRTypes.ext
|| typ == SRTypes.lvm
|| typ == SRTypes.udev
|| typ == SRTypes.egeneracd
|| typ == SRTypes.dummy;
}
/// <summary>
/// Internal helper function. True if all the PBDs for this SR are currently_attached.
/// </summary>
/// <returns></returns>
private bool AllPBDsAttached()
{
return Connection.ResolveAll(this.PBDs).All(pbd => pbd.currently_attached);
}
/// <summary>
/// Internal helper function. True if any of the PBDs for this SR is currently_attached.
/// </summary>
private bool AnyPBDAttached()
{
return Connection.ResolveAll(this.PBDs).Any(pbd => pbd.currently_attached);
}
/// <summary>
/// Returns true if there are any Running or Suspended VMs attached to VDIs on this SR.
/// </summary>
public bool HasRunningVMs()
{
foreach (VDI vdi in Connection.ResolveAll(VDIs))
{
foreach (VBD vbd in Connection.ResolveAll(vdi.VBDs))
{
VM vm = Connection.Resolve(vbd.VM);
if (vm == null)
continue;
// PR-1223: ignore control domain VM on metadata VDIs, so that the SR can be detached if there are no other running VMs
if (vdi.type == vdi_type.metadata && vm.is_control_domain)
continue;
if (vm.power_state == vm_power_state.Running)
return true;
}
}
return false;
}
public bool HasDriverDomain(out VM vm)
{
foreach (var pbdRef in PBDs)
{
var pbd = Connection.Resolve(pbdRef);
if (pbd != null && pbd.other_config.TryGetValue("storage_driver_domain", out string vmRef))
{
vm = Connection.Resolve(new XenRef<VM>(vmRef));
if (vm != null && !vm.IsControlDomainZero(out _))
return true;
}
}
vm = null;
return false;
}
/// <summary>
/// If host is non-null, return whether this storage can be seen from the given host.
/// If host is null, return whether the storage is shared, with a PBD for each host and at least one PBD plugged.
/// (See CA-36285 for why this is the right test when looking for SRs on which to create a new VM).
/// </summary>
public virtual bool CanBeSeenFrom(Host host)
{
if (host == null)
{
return shared && Connection != null && !IsBroken(false) && AnyPBDAttached();
}
foreach (PBD pbd in host.Connection.ResolveAll(PBDs))
if (pbd.currently_attached && pbd.host.opaque_ref == host.opaque_ref)
return true;
return false;
}
public PBD GetPBDFor(Host host)
{
foreach (PBD pbd in host.Connection.ResolveAll(PBDs))
if (pbd.host.opaque_ref == host.opaque_ref)
return pbd;
return null;
}
/// <summary>
/// True if there is less than 0.5GB free. Always false for dummy and ebs SRs.
/// </summary>
public bool IsFull()
{
SRTypes t = GetSRType(false);
return t != SRTypes.dummy && t != SRTypes.ebs && FreeSpace() < XenAdmin.Util.BINARY_GIGA/2;
}
public virtual long FreeSpace()
{
return physical_size - physical_utilisation;
}
public bool IsDetached()
{
// SR is detached when it has no PBDs or when all its PBDs are unplugged
return !HasPBDs() || !AnyPBDAttached();
}
public bool HasPBDs()
{
// CA-15188: Show SRs with no PBDs on Orlando, as pool-eject bug has been fixed.
// SRs are detached if they have no PBDs
return PBDs.Count > 0;
}
public override bool Show(bool showHiddenVMs)
{
if (name_label.StartsWith(Helpers.GuiTempObjectPrefix))
return false;
SRTypes srType = GetSRType(false);
// CA-15012 - dont show cd drives of type local on miami (if dont get destroyed properly on upgrade)
if (srType == SRTypes.local)
return false;
// Hide Memory SR
if (srType == SRTypes.tmpfs)
return false;
if (showHiddenVMs)
return true;
//CP-2458: hide SRs that were introduced by a DR_task
if (introduced_by != null && introduced_by.opaque_ref != Helper.NullOpaqueRef)
return false;
return !IsHidden();
}
public override bool IsHidden()
{
return BoolKey(other_config, HIDE_FROM_XENCENTER);
}
/// <summary>
/// The SR is broken when it has the wrong number of PBDs, or (optionally) not all the PBDs are attached.
/// </summary>
/// <param name="checkAttached">Whether to check that all the PBDs are attached</param>
/// <returns></returns>
public virtual bool IsBroken(bool checkAttached)
{
if (PBDs == null || PBDs.Count == 0 ||
checkAttached && !AllPBDsAttached())
{
return true;
}
Pool pool = Helpers.GetPoolOfOne(Connection);
if (pool == null || !shared)
{
if (PBDs.Count != 1)
{
// There should be exactly one PBD, since this is a non-shared SR
return true;
}
}
else
{
if (PBDs.Count != Connection.Cache.HostCount)
{
// There isn't a PBD for each host
return true;
}
}
return false;
}
public bool IsBroken()
{
return IsBroken(true);
}
public static bool IsDefaultSr(SR sr)
{
Pool pool = Helpers.GetPoolOfOne(sr.Connection);
return pool != null && pool.default_SR != null && pool.default_SR.opaque_ref == sr.opaque_ref;
}
/// <summary>
/// Whether the underlying SR backend supports VDI_CREATE. Will return true even if the SR is full.
/// </summary>
public virtual bool SupportsVdiCreate()
{
// ISO SRs are deemed not to support VDI create in the GUI, even though the back end
// knows that they do. See CA-40119.
if (content_type == SR.Content_Type_ISO)
return false;
// Memory SRs should not support VDI create in the GUI
if (GetSRType(false) == SR.SRTypes.tmpfs)
return false;
SM sm = SM.GetByType(Connection, type);
return sm != null && -1 != Array.IndexOf(sm.capabilities, "VDI_CREATE");
}
/// <summary>
/// Whether the underlying SR backend supports storage migration. Will return true even if the SR is full.
/// </summary>
/// <returns></returns>
public virtual bool SupportsStorageMigration()
{
// ISO and Memory SRs should not support migration
if (content_type == SR.Content_Type_ISO || GetSRType(false) == SR.SRTypes.tmpfs)
return false;
SM sm = SM.GetByType(Connection, type);
// check if the SM has VDI_SNAPSHOT and VDI_MIRROR capabilities; the VDI_MIRROR capability has only been added in Ely (API Version 2.6)
return sm != null && Array.IndexOf(sm.capabilities, "VDI_SNAPSHOT") != -1 && (Array.IndexOf(sm.capabilities, "VDI_MIRROR") != -1 || !Helpers.ElyOrGreater(Connection));
}
public static List<SRInfo> ParseSRList(List<Probe_result> probeExtResult)
{
List<SRInfo> results = new List<SRInfo>();
foreach (var probeResult in probeExtResult.Where(p => p.sr != null))
{
string uuid = probeResult.sr.uuid;
long size = probeResult.sr.total_space;
string aggr = "";
string name_label = probeResult.sr.name_label;
string name_description = probeResult.sr.name_description;
bool pool_metadata_detected = false;
results.Add(new SRInfo(uuid, size, aggr, name_label, name_description, pool_metadata_detected, probeResult.configuration));
}
return results;
}
public virtual bool VdiCreationCanProceed(long vdiSize)
{
SM sm = GetSM();
bool vdiSizeUnlimited = sm != null && Array.IndexOf(sm.capabilities, "LARGE_VDI") != -1;
if (!vdiSizeUnlimited && vdiSize > DISK_MAX_SIZE)
return false;
bool isThinlyProvisioned = sm != null && Array.IndexOf(sm.capabilities, "THIN_PROVISIONING") != -1;
if (!isThinlyProvisioned && vdiSize > FreeSpace())
return false;
return true;
}
/// <summary>
/// Parses an XML list of SRs (as returned by the SR.probe() call) into a list of SRInfos.
/// </summary>
public static List<SRInfo> ParseSRListXML(string xml)
{
List<SRInfo> results = new List<SRInfo>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
foreach (XmlNode node in doc.GetElementsByTagName("SR"))
{
string uuid = "";
long size = 0;
string aggr = "";
string name_label = "";
string name_description = "";
bool pool_metadata_detected = false;
foreach (XmlNode info in node.ChildNodes)
{
if (info.Name.ToLowerInvariant() == "uuid")
{
uuid = info.InnerText.Trim();
}
else if (info.Name.ToLowerInvariant() == "size")
{
size = long.Parse(info.InnerText.Trim());
}
else if (info.Name.ToLowerInvariant() == "aggregate")
{
aggr = info.InnerText.Trim();
}
else if (info.Name.ToLowerInvariant() == "name_label")
{
name_label = info.InnerText.Trim();
}
else if (info.Name.ToLowerInvariant() == "name_description")
{
name_description = info.InnerText.Trim();
}
else if (info.Name.ToLowerInvariant() == "pool_metadata_detected")
{
bool.TryParse(info.InnerText.Trim(), out pool_metadata_detected);
}
}
results.Add(new SRInfo(uuid, size, aggr, name_label, name_description, pool_metadata_detected));
}
return results;
}
public static List<string> ParseSupportedVersionsListXML(string xml)
{
var supportedVersionsResult = new List<string>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
// If we've got this from an async task result, then it will be wrapped
// in a <value> element. Parse the contents instead.
var nodes = doc.GetElementsByTagName("value");
if (nodes.Count > 0)
{
xml = nodes[0].InnerText;
doc = new XmlDocument();
doc.LoadXml(xml);
}
foreach (XmlNode node in doc.GetElementsByTagName("SupportedVersions"))
{
foreach (XmlNode info in node.ChildNodes)
{
if (info.Name.ToLowerInvariant() == "version")
{
supportedVersionsResult.Add(info.InnerText.Trim());
}
}
}
return supportedVersionsResult;
}
public String GetScsiID()
{
foreach (PBD pbd in Connection.ResolveAll(PBDs))
{
if (!pbd.device_config.ContainsKey("SCSIid"))
continue;
return pbd.device_config["SCSIid"];
}
if (!sm_config.ContainsKey("devserial"))
return null;
String SCSIid = sm_config["devserial"];
if (SCSIid.StartsWith("scsi-"))
SCSIid = SCSIid.Remove(0, 5);
// CA-22352: SCSI IDs on the general panel for a NetApp SR have a trailing comma
SCSIid = SCSIid.TrimEnd(new char[] { ',' });
return SCSIid;
}
/// <summary>
/// New Lun Per VDI mode (cf. LunPerVDI method) using the hba encapsulating type
/// </summary>
public virtual bool HBALunPerVDI()
{
return GetSRType(true) == SRTypes.rawhba;
}
/// <summary>
/// Legacy LunPerVDI mode - for old servers that this was set up on
/// This is no longer an option (2012) for newer servers but we need to keep this
/// </summary>
public bool LunPerVDI()
{
// Look for the mapping from scsi id -> vdi uuid
// in sm-config.
foreach (String key in sm_config.Keys)
if (key.Contains("LUNperVDI") || key.StartsWith("scsi-"))
return true;
return false;
}
private const String MPATH = "mpath";
public Dictionary<VM, Dictionary<VDI, String>> GetMultiPathStatusLunPerVDI()
{
Dictionary<VM, Dictionary<VDI, String>> result =
new Dictionary<VM, Dictionary<VDI, String>>();
if (Connection == null)
return result;
foreach (PBD pbd in Connection.ResolveAll(PBDs))
{
if (!pbd.MultipathActive())
continue;
foreach (KeyValuePair<String, String> kvp in pbd.other_config)
{
if (!kvp.Key.StartsWith(MPATH))
continue;
int current;
int max;
if (!PBD.ParsePathCounts(kvp.Value, out current, out max))
continue;
String scsiIdKey = String.Format("scsi-{0}", kvp.Key.Substring(MPATH.Length + 1));
if (!sm_config.ContainsKey(scsiIdKey))
continue;
String vdiUUID = sm_config[scsiIdKey];
VDI vdi = null;
foreach (VDI candidate in Connection.ResolveAll(VDIs))
{
if (candidate.uuid != vdiUUID)
continue;
vdi = candidate;
break;
}
if (vdi == null)
continue;
foreach (VBD vbd in Connection.ResolveAll(vdi.VBDs))
{
VM vm = Connection.Resolve(vbd.VM);
if (vm == null)
continue;
if (vm.power_state != vm_power_state.Running)
continue;
if (!result.ContainsKey(vm))
result[vm] = new Dictionary<VDI, String>();
result[vm][vdi] = kvp.Value;
}
}
}
return result;
}
public Dictionary<PBD, String> GetMultiPathStatusLunPerSR()
{
Dictionary<PBD, String> result =
new Dictionary<PBD, String>();
if (Connection == null)
return result;
foreach (PBD pbd in Connection.ResolveAll(PBDs))
{
if (!pbd.MultipathActive())
continue;
String status = String.Empty;
foreach (KeyValuePair<String, String> kvp in pbd.other_config)
{
if (!kvp.Key.StartsWith(MPATH))
continue;
status = kvp.Value;
break;
}
int current;
int max;
if (!PBD.ParsePathCounts(status, out current, out max))
continue;
result[pbd] = status;
}
return result;
}
public bool MultipathAOK()
{
if (!MultipathCapable())
return true;
if (LunPerVDI())
{
Dictionary<VM, Dictionary<VDI, String>>
multipathStatus = GetMultiPathStatusLunPerVDI();
foreach (VM vm in multipathStatus.Keys)
foreach (VDI vdi in multipathStatus[vm].Keys)
if (!CheckMultipathString(multipathStatus[vm][vdi]))
return false;
}
else
{
Dictionary<PBD, String> multipathStatus =
GetMultiPathStatusLunPerSR();
foreach (PBD pbd in multipathStatus.Keys)
if (pbd.MultipathActive() && !CheckMultipathString(multipathStatus[pbd]))
return false;
}
return true;
}
public override string NameWithLocation()
{
//return only the Name for local SRs
if (Connection != null && !shared)
{
return Name();
}
return base.NameWithLocation();
}
internal override string LocationString()
{
var home = Home();
return home != null ? home.LocationString() : base.LocationString();
}
private bool CheckMultipathString(String status)
{
int current;
int max;
if (!PBD.ParsePathCounts(status, out current, out max))
return true;
return current >= max;
}
public class SRInfo : IComparable<SRInfo>, IEquatable<SRInfo>
{
public readonly string UUID;
public readonly long Size;
public readonly string Aggr;
public string Name;
public string Description;
public readonly bool PoolMetadataDetected;
public Dictionary<string, string> Configuration;
public SRInfo(string uuid, long size = 0, string aggr = "", string name = "", string description = "",
bool poolMetadataDetected = false, Dictionary<string,string> configuration = null)
{
UUID = uuid;
Size = size;
Aggr = aggr;
Name = name;
Description = description;
PoolMetadataDetected = poolMetadataDetected;
Configuration = configuration;
}
public int CompareTo(SRInfo other)
{
return (this.UUID.CompareTo(other.UUID));
}
public bool Equals(SRInfo other)
{
return this.CompareTo(other) == 0;
}
public override string ToString()
{
return UUID;
}
}
public bool MultipathCapable()
{
SM relatedSm = GetSM();
bool isAnSmCapability = relatedSm != null && relatedSm.MultipathEnabled();
bool isInSmConfig = BoolKey(sm_config, "multipathable");
return isInSmConfig || isAnSmCapability;
}
public string Target()
{
SR sr = Connection.Resolve(new XenRef<SR>(this.opaque_ref));
if (sr == null)
return String.Empty;
foreach (PBD pbd in sr.Connection.ResolveAll(sr.PBDs))
{
SRTypes type = sr.GetSRType(false);
if ((type == SR.SRTypes.netapp || type == SR.SRTypes.lvmoiscsi || type == SR.SRTypes.equal) && pbd.device_config.ContainsKey("target")) // netapp or iscsi
{
return pbd.device_config["target"];
}
else if (type == SR.SRTypes.iso && pbd.device_config.ContainsKey("location")) // cifs or nfs iso
{
String target = Helpers.HostnameFromLocation(pbd.device_config["location"]); // has form //ip_address/path
if (String.IsNullOrEmpty(target))
continue;
return target;
}
else if (type == SR.SRTypes.nfs && pbd.device_config.ContainsKey("server"))
{
return pbd.device_config["server"];
}
}
return String.Empty;
}
/// <summary>
/// The amount of memory used as compared to the available and allocated amounts as a friendly string
/// </summary>
public String SizeString()
{
return string.Format(Messages.SR_SIZE_USED,
Util.DiskSizeString(physical_utilisation),
Util.DiskSizeString(physical_size),
Util.DiskSizeString(virtual_allocation));
}
/// <summary>
/// A friendly string indicating whether the sr is detached/broken/multipath failing/needs upgrade/ok
/// </summary>
public String StatusString()
{
if (!HasPBDs())
return Messages.DETACHED;
if (IsDetached() || IsBroken())
return Messages.GENERAL_SR_STATE_BROKEN;
if (!MultipathAOK())
return Messages.GENERAL_MULTIPATH_FAILURE;
return Messages.GENERAL_STATE_OK;
}
/// <summary>
/// Returns true when there is a pbd containing adapterid else false
/// </summary>
public bool CanRepairAfterUpgradeFromLegacySL()
{
if (type == "cslg")
{
var pbds = Connection.ResolveAll(PBDs);
if (pbds != null)
{
return pbds.Any(pbd => pbd.device_config.ContainsKey("adapterid"));
}
return false;
}
return true;
}
/// <summary>
/// Whether SR supports database replication.
/// </summary>
public static bool SupportsDatabaseReplication(IXenConnection connection, SR sr)
{
try
{
assert_supports_database_replication(connection.Session, sr.opaque_ref);
return true;
}
catch (Failure)
{
return false;
}
}
/// <summary>
/// Is an iSL type or legacy iSl adapter type
/// </summary>
public static bool IsIslOrIslLegacy(SR sr)
{
SRTypes currentType = sr.GetSRType(true);
return currentType == SRTypes.cslg || currentType == SRTypes.equal || currentType == SRTypes.netapp;
}
/// <summary>
/// Whether the underlying SR backend supports SR_TRIM
/// </summary>
public bool SupportsTrim()
{
System.Diagnostics.Trace.Assert(Connection != null, "Connection must not be null");
SM sm = SM.GetByType(Connection, type);
return sm != null && sm.features != null && sm.features.ContainsKey("SR_TRIM");
}
/// <summary>
/// Whether the underlying SR backend supports read caching.
/// </summary>
/// <returns></returns>
public bool SupportsReadCaching()
{
// for Stockholm or greater versions, check if the SM has the VDI_READ_CACHING capability
if (Helpers.StockholmOrGreater(Connection))
{
var sm = SM.GetByType(Connection, type);
return sm?.features != null && sm.features.ContainsKey("VDI_READ_CACHING");
}
// for older versions, use the SR type; read caching is available for NFS, EXT3 and SMB/CIFS SR types
var srType = GetSRType(false);
return srType == SRTypes.nfs || srType == SRTypes.ext || srType == SRTypes.smb;
}
public bool GetReadCachingEnabled()
{
// read caching is enabled when the o_direct key is not defined (or set to false) in other_config
// and is disabled if o_direct=true
return SupportsReadCaching() && !BoolKey(other_config, "o_direct");
}
public void SetReadCachingEnabled(bool value)
{
// to enable read caching, remove the o_direct key; to disable it, set o_direct=true
other_config = SetDictionaryKey(other_config, "o_direct", value ? null : bool.TrueString.ToLower());
}
#region IEquatable<SR> Members
/// <summary>
/// Indicates whether the current object is equal to the specified object. This calls the implementation from XenObject.
/// This implementation is required for ToStringWrapper.
/// </summary>
public bool Equals(SR other)
{
return base.Equals(other);
}
#endregion
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
using System.Data;
using System.Threading;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Stats;
using Alachisoft.NCache.Common.Propagator;
using Alachisoft.NCache.Common.Util;
using Alachisoft.NCache.Common.Logger;
using Alachisoft.NCache.Common.DataStructures.Clustered;
using Alachisoft.NCache.Common.Enum;
using Alachisoft.NCache.Common.Collections;
using Alachisoft.NCache.Common.Caching;
namespace Alachisoft.NCache.Storage
{
#region / --- Store Status --- /
#endregion
/// <summary>
/// This is the base class of all Cache stores. Provides additional optional
/// functions that can be overridden as well as default implementation of the
/// some of the methods in the ICacheStorage interface, wherever possible.
/// Implements ICacheStorage.
/// </summary>
internal class StorageProviderBase : ICacheStorage
{
public const uint KB = 1024;
public const uint MB = KB * KB;
public const uint GB = MB * KB;
private string _cacheContext;
private Boolean _virtualUnlimitedSpace = false;
private ISizableIndex _isizableQueryIndexManager=null;
private ISizableIndex _isizableGroupIndexManager = null;
private ISizableIndex _isizableExpirationIndexManager = null;
private ISizableIndex _isizableEvictionIndexManager = null;
private ISizableIndex _bucketIndexManager = null;
private ISizableIndex _messageStore = null;
/// <summary>
/// The default starting capacity of stores.
/// </summary>
protected readonly int DEFAULT_CAPACITY = 25000;
/// <summary>
/// The default percentage of the extra data which can be accomdated.
/// </summary>
protected readonly double DEFAULT_EXTRA_ACCOMDATION_PERCENTAGE = 0.20f;
/// <summary>
/// Maximam data size, in bytes, that store can hold
/// </summary>
private long _maxSize;
/// <summary>
///Size of data which can be accomdated even after we reach max size.
/// </summary>
private long _extraDataSize = 0;
/// <summary>
/// Maximam number of object in cache
/// </summary>
private long _maxCount;
/// <summary>
/// Size of data, in bytes, stored in cache
/// </summary>
private long _dataSize;
protected long TotalDataSize
{
get
{
long temp=_dataSize;
if (ISizableQueryIndexManager != null)
temp += ISizableQueryIndexManager.IndexInMemorySize;
if (ISizableGroupIndexManager != null)
temp += ISizableGroupIndexManager.IndexInMemorySize;
if (ISizableExpirationIndexManager != null)
temp += ISizableExpirationIndexManager.IndexInMemorySize;
if (ISizableEvictionIndexManager != null)
temp += ISizableEvictionIndexManager.IndexInMemorySize;
if (ISizableBucketIndexManager != null)
temp += ISizableBucketIndexManager.IndexInMemorySize;
if (ISizableMessageStore != null)
temp += ISizableMessageStore.IndexInMemorySize;
return temp;
}
set
{
_dataSize = value;
}
}
/// <summary>
/// Reader, writer lock to be used for synchronization.
/// </summary>
protected ReaderWriterLock _syncObj;
protected bool _reportCacheNearEviction = false;
protected int _evictionReportSize = 0;
protected int _reportInterval = 5;
protected DateTime _lastReportedTime = DateTime.MinValue;
ILogger _ncacheLog;
public ILogger NCacheLog
{
get { return _ncacheLog; }
}
protected IAlertPropagator _alertPropagator;
/// <summary>
/// Default contructor.
/// </summary>
public StorageProviderBase()
: this(0)
{
}
/// <summary>
/// Overloaded constructor. Takes the max objects limit, and the listener as parameters.
/// </summary>
/// <param name="maxLimit">maximum number of objects to contain.</param>
public StorageProviderBase(long maxSize)
{
_syncObj = new ReaderWriterLock();
_maxSize = maxSize;
}
public StorageProviderBase(IDictionary properties, bool evictionEnabled)
: this(properties, evictionEnabled, null, null)
{
}
/// <summary>
/// Overloaded constructor. Takes the properties as a map.
/// </summary>
/// <param name="properties">property collection</param>
public StorageProviderBase(IDictionary properties, bool evictionEnabled, ILogger NCacheLog, IAlertPropagator alertPropagator)
{
Initialize(properties, evictionEnabled);
_ncacheLog = NCacheLog;
_alertPropagator = alertPropagator;
string tmp ;
_evictionReportSize = ServiceConfiguration.CacheSizeThreshold;
if(_evictionReportSize > 0)
_reportCacheNearEviction = true;
_reportInterval = ServiceConfiguration.CacheSizeReportInterval;
}
protected void CheckForStoreNearEviction()
{
//check for updated Properties in service config
_evictionReportSize = ServiceConfiguration.CacheSizeThreshold;
_reportInterval = ServiceConfiguration.CacheSizeReportInterval;
if (_reportCacheNearEviction && !VirtualUnlimitedSpace)
{
if (_lastReportedTime.AddMinutes(_reportInterval) < DateTime.UtcNow)
{
if (_maxSize > 0 && _evictionReportSize > 0)
{
double currentSizeInPerc = ((double)TotalDataSize / (double)_maxSize) * (double)100;
if (currentSizeInPerc >= _evictionReportSize)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(InformCacheNearEviction));
_lastReportedTime = DateTime.UtcNow;
}
}
}
}
}
private void InformCacheNearEviction(object state)
{
try
{
string cacheserver = "NCache";
long currentSizeInPerc = (TotalDataSize / _maxSize) * 100;
if (currentSizeInPerc > 100) currentSizeInPerc = 100;
AppUtil.LogEvent(cacheserver, "Cache '" + _cacheContext + "' has exceeded " + _evictionReportSize + "% of allocated cache size", System.Diagnostics.EventLogEntryType.Warning, EventCategories.Warning, EventID.CacheSizeWarning);
//EMailNotifier : Cache Size Alert Propagation
if (_alertPropagator != null)
{
_alertPropagator.RaiseAlert(EventID.CacheSizeWarning, cacheserver, "Cache '" + _cacheContext + "' has exceeded " + _evictionReportSize + "% of allocated cache size");
}
//-
NCacheLog.CriticalInfo("CacheStore", "cache has exceeded " + _evictionReportSize + "% of allocated cache size");
}
catch (Exception e)
{
}
}
/// <summary>
/// Initialize settings
/// </summary>
/// <param name="properties"></param>
public void Initialize(IDictionary properties, bool evictionEnabled)
{
_syncObj = new ReaderWriterLock();
if (properties == null) return;
if (properties.Contains("max-size"))
{
try
{
_maxSize = ToBytes(Convert.ToInt64(properties["max-size"]));
_maxCount = Convert.ToInt64(properties["max-objects"]);
if (evictionEnabled)
{
//we give user extra cution to add/insert data into the store even
//when you have reached the max limit. But if this limit is also reached
//then we reject the request.
_extraDataSize = (long)(_maxSize * DEFAULT_EXTRA_ACCOMDATION_PERCENTAGE);
}
}
catch (Exception)
{
}
}
}
private long ToBytes(long mbytes)
{
return mbytes * 1024 * 1024;
}
#region / --- IDisposable --- /
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
_syncObj = null;
this.Cleared();
}
#endregion
/// <summary>
/// get or set the maximam size of store, in bytes
/// </summary>
public virtual long MaxSize
{
get { return _maxSize; }
set { _maxSize = value; }
}
/// <summary>
/// get or set the maximam number of objects
/// </summary>
public virtual long MaxCount
{
get { return _maxCount; }
set { _maxCount = value; }
}
/// <summary>
///Gets/Sets the cache context used for the Compact serialization framework.
/// </summary>
public string CacheContext
{
get { return _cacheContext; }
set { _cacheContext = value; }
}
/// <summary>
/// get the synchronization object for this store.
/// </summary>
public ReaderWriterLock Sync
{
get { return _syncObj; }
}
#region / --- ICacheStorage --- /
/// <summary>
/// returns the number of objects contained in the cache.
/// </summary>
public virtual long Count
{
get { return 0; }
}
/// <summary>
/// returns the size of data, in bytes, stored in cache
/// </summary>
public virtual long Size
{
get { return this.TotalDataSize; }
}
public virtual Array Keys
{
get
{
return null;
}
}
/// <summary>
/// Removes all entries from the store.
/// </summary>
public virtual void Clear()
{
}
/// <summary>
/// Determines whether the store contains a specific key.
/// </summary>
/// <param name="key">The key to locate in the store.</param>
/// <returns>true if the store contains an element
/// with the specified key; otherwise, false.</returns>
public virtual bool Contains(object key)
{
return false;
}
/// <summary>
/// Get an object from the store, specified by the passed in key. Must be implemented
/// by cache stores.
/// </summary>
/// <param name="key">key</param>
/// <returns>cache entry.</returns>
public virtual object Get(object key)
{
return null;
}
/// <summary>
/// Get the size of item stored in store
/// </summary>
/// <param name="key">The key whose items size to get</param>
/// <returns>Items size</returns>
public virtual int GetItemSize(object key)
{
return 0;
}
/// <summary>
/// Add the key value pair to the store. Must be implemented by cache stores.
/// </summary>
/// <param name="key">key</param>
/// <param name="item">object</param>
/// <returns>returns the result of operation.</returns>
public virtual StoreAddResult Add(object key, IStorageEntry item, Boolean allowExtendedSize)
{
return StoreAddResult.Failure;
}
/// <summary>
/// Insert the key value pair to the store. Must be implemented by cache stores.
/// </summary>
/// <param name="key">key</param>
/// <param name="item">object</param>
/// <returns>returns the result of operation.</returns>
public virtual StoreInsResult Insert(object key, IStorageEntry item, Boolean allowExtendedSize)
{
return StoreInsResult.Failure;
}
/// <summary>
/// Removes an object from the store, specified by the passed in key. Must be implemented by cache stores.
/// </summary>
/// <param name="key">key</param>
/// <returns>cache entry.</returns>
public virtual object Remove(object key)
{
return null;
}
/// <summary>
/// Returns a .NET IEnumerator interface so that a client should be able
/// to iterate over the elements of the cache store.
/// </summary>
/// <returns>IDictionaryEnumerator enumerator.</returns>
public virtual IDictionaryEnumerator GetEnumerator()
{
return null;
}
/// <summary>
/// Increases/decreases cache size.
/// </summary>
/// <param name="change">Amount of change in cache size.</param>
public virtual void ChangeCacheSize(long change)
{
_dataSize += change;
}
#endregion
/// <summary>
/// Check if store has enough space to add new item
/// </summary>
/// <param name="item">item to be added</param>
/// <returns>true is store has space, else false</returns>
public virtual StoreStatus HasSpace(ISizable item, long keySize , Boolean allowExtendedSize)
{
//Keysize will be included in actual cachesize
if (VirtualUnlimitedSpace)
return StoreStatus.HasSpace;
long maxSize = _maxSize;
if (!allowExtendedSize)
{
maxSize = (long)(_maxSize * .95);
}
long nextSize = TotalDataSize + item.InMemorySize + keySize;
StoreStatus status = StoreStatus.HasSpace;
if (nextSize > maxSize)
{
if (nextSize > (maxSize + _extraDataSize))
status = StoreStatus.HasNotEnoughSpace;
else
status = StoreStatus.NearEviction;
}
return status;
}
/// <summary>
/// Check if store has enough space to add new item
/// </summary>
/// <param name="oldItem">old item</param>
/// <param name="newItem">new item to be inserted</param>
/// <returns>true is store has space, else false</returns>
protected StoreStatus HasSpace(ISizable oldItem, ISizable newItem,long keySize, Boolean allowExtendedSize)
{
if (VirtualUnlimitedSpace)
return StoreStatus.HasSpace;
long maxSize = _maxSize;
if (!allowExtendedSize)
{
maxSize = (long)(_maxSize * .95);
}
long nextSize = TotalDataSize + newItem.InMemorySize - (oldItem == null ? -keySize : oldItem.InMemorySize);
StoreStatus status = StoreStatus.HasSpace;
if (nextSize > maxSize)
{
if (nextSize > (maxSize + _extraDataSize))
return StoreStatus.HasNotEnoughSpace;
return StoreStatus.NearEviction;
}
return status;
}
/// <summary>
/// Increments the data size in cache, after item is Added
/// </summary>
/// <param name="itemSize">item added</param>
protected void Added(IStorageEntry item,long keySize)
{
_dataSize += (item.InMemorySize + keySize);
}
/// <summary>
/// Increments the data size in cache, after item is inserted
/// </summary>
/// <param name="oldItem">old item</param>
/// <param name="newItem">new item to be inserted</param>
protected void Inserted(IStorageEntry oldItem, IStorageEntry newItem, long keySize)
{
if (newItem.Type != EntryType.CacheItem)
{
_dataSize += newItem.InMemorySize - (oldItem == null ? -keySize : oldItem.OldInMemorySize);
newItem.OldInMemorySize = newItem.InMemorySize ;
}
else
{
_dataSize += newItem.InMemorySize - (oldItem == null ? -keySize : oldItem.InMemorySize);
}
}
/// <summary>
/// Decrement the data size in cache, after item is removed
/// </summary>
/// <param name="itemSize">item removed</param>
public void Removed(ISizable item, long keySize,EntryType type)
{
_dataSize -= (item.InMemorySize + keySize);
}
/// <summary>
/// Reset data size when cache is cleared
/// </summary>
protected void Cleared()
{
TotalDataSize = 0;
}
/// <summary>
/// Returns the thread safe synchronized wrapper over cache store.
/// </summary>
/// <param name="storageProvider"></param>
/// <returns></returns>
public static StorageProviderBase Synchronized(StorageProviderBase cacheStorage)
{
return new StorageProviderSyncWrapper(cacheStorage);
}
public ClusteredArrayList GetBucketKeyList(int bucketId)
{
throw new NotImplementedException();
}
public bool VirtualUnlimitedSpace
{
get
{
return _virtualUnlimitedSpace;
}
set
{
_virtualUnlimitedSpace = value;
}
}
public ISizableIndex ISizableQueryIndexManager
{
get
{
return _isizableQueryIndexManager;
}
set
{
_isizableQueryIndexManager = value;
}
}
public ISizableIndex ISizableGroupIndexManager
{
get
{
return _isizableGroupIndexManager;
}
set
{
_isizableGroupIndexManager = value;
}
}
public ISizableIndex ISizableExpirationIndexManager
{
get
{
return _isizableExpirationIndexManager;
}
set
{
_isizableExpirationIndexManager = value;
}
}
public ISizableIndex ISizableEvictionIndexManager
{
get
{
return _isizableEvictionIndexManager;
}
set
{
_isizableEvictionIndexManager = value;
}
}
public ISizableIndex ISizableBucketIndexManager
{
get
{
return _bucketIndexManager;
}
set
{
_bucketIndexManager = value;
}
}
public ISizableIndex ISizableMessageStore
{
get
{
return _messageStore;
}
set
{
_messageStore = value;
}
}
public long IndexInMemorySize
{
get
{
return _dataSize;
}
}
public ISizableIndex ISizableCacheStore
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void CheckIfCacheNearEviction()
{
if (ServiceConfiguration.CacheSizeThreshold > 0) _reportCacheNearEviction = true;
if (_reportCacheNearEviction) CheckForStoreNearEviction();
}
}
}
| |
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;
public partial class Backoffice_Informasi_LABList : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsListRegistrasiLAB";
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["InformasiPasienLAB"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy");
UpdateDataView(true);
}
}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
DataTable myData = new DataTable();
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
if (txtTanggalRegistrasi.Text != "")
{
myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text);
}
myObj.PoliklinikId = 42 ;//LAB
myData = myObj.SelectAllFilter();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("LABAddBaru.aspx?CurrentPage=" + CurrentPage);
}
public void OnAddRJ(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("LABAddRJ.aspx?CurrentPage=" + CurrentPage);
}
public void OnAddRI(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("LABAddRI.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Nama")
dv.RowFilter = " Nama LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRegistrasi")
dv.RowFilter = " NoRegistrasi LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NoRM")
dv.RowFilter = " NoRM LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "NRP")
dv.RowFilter = " NRP LIKE '%" + txtSearch.Text + "%'";
else
dv.RowFilter = "";
BindData(dv);
}
#endregion
#region .Update Link Item Butom
/// <summary>
/// The function is responsible for get link button form.
/// </summary>
/// <param name="szId"></param>
/// <param name="CurrentPage"></param>
/// <returns></returns>
public string GetLinkButton(string RawatJalanId, string StatusRawatJalan, string Nama, string CurrentPage)
{
string szResult = "";
if (Session["InformasiPasienLAB"] != null)
{
szResult += "<a class=\"toolbar\" href=\"LABView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + RawatJalanId + "\" ";
szResult += ">Detil</a>";
}
return szResult;
}
#endregion
protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e)
{
UpdateDataView(true);
}
protected void DataGridList_DeleteCommand(object source, DataGridCommandEventArgs e)
{
string RawatJalanId = DataGridList.DataKeys[e.Item.ItemIndex].ToString();
SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan();
myObj.RawatJalanId = int.Parse(RawatJalanId);
myObj.Delete();
DataGridList.SelectedIndex = -1;
UpdateDataView(true);
}
}
| |
using CSharpGuidelinesAnalyzer.Rules.Naming;
using CSharpGuidelinesAnalyzer.Test.TestDataBuilders;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
namespace CSharpGuidelinesAnalyzer.Test.Specs.Naming
{
public sealed class NamePropertyWithAnAffirmativePhraseSpecs : CSharpGuidelinesAnalysisTestFixture
{
protected override string DiagnosticId => NamePropertyWithAnAffirmativePhraseAnalyzer.DiagnosticId;
[Fact]
internal void When_public_field_type_is_int_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public int some;
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_field_type_is_bool_and_name_starts_with_a_verb_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool isVisible;
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_field_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool [|thisIsVisible|];
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean field 'thisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_field_type_is_nullable_bool_and_name_starts_with_a_verb_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool? isVisible;
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_field_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool? [|thisIsVisible|];
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean field 'thisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_property_type_is_int_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public int Some { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_property_type_is_bool_and_name_starts_with_a_verb_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool IsVisible { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_property_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool [|ThisIsVisible|] { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean property 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_property_type_is_nullable_bool_and_name_starts_with_a_verb_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool? IsVisible { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_property_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool? [|ThisIsVisible|] { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean property 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_inherited_property_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public abstract class B
{
public abstract bool [|ThisIsVisible|] { get; set; }
}
public class C : B
{
public override bool ThisIsVisible { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean property 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void
When_public_inherited_property_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public abstract class B
{
public abstract bool? [|ThisIsVisible|] { get; set; }
}
public class C : B
{
public override bool? ThisIsVisible { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean property 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_implemented_property_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public interface I
{
bool [|ThisIsVisible|] { get; }
}
public class C : I
{
public bool ThisIsVisible { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean property 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void
When_public_implemented_property_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public interface I
{
bool? [|ThisIsVisible|] { get; }
}
public class C : I
{
public bool? ThisIsVisible { get; set; }
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean property 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_method_return_type_is_int_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public int Some()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_method_return_type_is_bool_and_name_starts_with_a_verb_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool IsVisible()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_method_return_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool [|ThisIsVisible|]()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean method 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_operator_return_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public struct C
{
public static bool operator ==(C left, C right)
{
throw new NotImplementedException();
}
public static bool operator !=(C left, C right)
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_method_return_type_is_nullable_bool_and_name_starts_with_a_verb_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool? IsVisible()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_method_return_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public bool? [|ThisIsVisible|]()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean method 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_inherited_method_return_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public abstract class B
{
public abstract bool [|ThisIsVisible|]();
}
public class C : B
{
public override bool ThisIsVisible()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean method 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void
When_public_inherited_method_return_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public abstract class B
{
public abstract bool? [|ThisIsVisible|]();
}
public class C : B
{
public override bool? ThisIsVisible()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean method 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_implemented_method_return_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public interface I
{
bool [|ThisIsVisible|]();
}
public class C : I
{
public bool ThisIsVisible()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean method 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void
When_public_implemented_method_return_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public interface I
{
bool? [|ThisIsVisible|]();
}
public class C : I
{
public bool? ThisIsVisible()
{
throw new NotImplementedException();
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean method 'ThisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_parameter_type_is_int_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public void M(int other)
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_parameter_type_is_bool_and_name_starts_with_a_verb_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public void M(bool isVisible)
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_parameter_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public void M(bool [|thisIsVisible|])
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_parameter_type_is_nullable_bool_and_name_starts_with_a_verb_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public void M(bool? isVisible)
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void When_public_parameter_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public void M(bool? [|thisIsVisible|])
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_inherited_parameter_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public abstract class B
{
public abstract void M(bool [|thisIsVisible|]);
}
public class C : B
{
public override void M(bool thisIsVisible)
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible' should start with a verb");
}
[Fact]
internal void
When_public_inherited_parameter_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public abstract class B
{
public abstract void M(bool? [|thisIsVisible|]);
}
public class C : B
{
public override void M(bool? thisIsVisible)
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible' should start with a verb");
}
[Fact]
internal void When_public_implemented_parameter_type_is_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public interface I
{
void M(bool [|thisIsVisible|]);
}
public class C : I
{
public void M(bool thisIsVisible)
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible' should start with a verb");
}
[Fact]
internal void
When_public_implemented_parameter_type_is_nullable_bool_and_name_does_not_start_with_a_verb_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public interface I
{
void M(bool? [|thisIsVisible|]);
}
public class C : I
{
public void M(bool? thisIsVisible)
{
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible' should start with a verb");
}
[Fact]
internal void When_field_type_is_bool_and_name_does_not_start_with_a_verb_in_public_class_hierarchy_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public class D
{
public bool [|thisIsVisible1|];
protected bool [|thisIsVisible2|];
internal bool [|thisIsVisible3|];
protected internal bool [|thisIsVisible4|];
private protected bool [|thisIsVisible5|];
private bool thisIsVisible6;
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean field 'thisIsVisible1' should start with a verb",
"The name of protected boolean field 'thisIsVisible2' should start with a verb",
"The name of internal boolean field 'thisIsVisible3' should start with a verb",
"The name of protected internal boolean field 'thisIsVisible4' should start with a verb",
"The name of private protected boolean field 'thisIsVisible5' should start with a verb");
}
[Fact]
internal void
When_field_type_is_bool_and_name_does_not_start_with_a_verb_in_protected_class_hierarchy_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
protected class D
{
public bool [|thisIsVisible1|];
protected bool [|thisIsVisible2|];
internal bool [|thisIsVisible3|];
protected internal bool [|thisIsVisible4|];
private protected bool [|thisIsVisible5|];
private bool thisIsVisible6;
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean field 'thisIsVisible1' should start with a verb",
"The name of protected boolean field 'thisIsVisible2' should start with a verb",
"The name of internal boolean field 'thisIsVisible3' should start with a verb",
"The name of protected internal boolean field 'thisIsVisible4' should start with a verb",
"The name of private protected boolean field 'thisIsVisible5' should start with a verb");
}
[Fact]
internal void
When_field_type_is_bool_and_name_does_not_start_with_a_verb_in_internal_class_hierarchy_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
internal class C
{
internal class D
{
public bool [|thisIsVisible1|];
protected bool [|thisIsVisible2|];
internal bool [|thisIsVisible3|];
protected internal bool [|thisIsVisible4|];
private protected bool [|thisIsVisible5|];
private bool thisIsVisible6;
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean field 'thisIsVisible1' should start with a verb",
"The name of protected boolean field 'thisIsVisible2' should start with a verb",
"The name of internal boolean field 'thisIsVisible3' should start with a verb",
"The name of protected internal boolean field 'thisIsVisible4' should start with a verb",
"The name of private protected boolean field 'thisIsVisible5' should start with a verb");
}
[Fact]
internal void
When_field_type_is_bool_and_name_does_not_start_with_a_verb_in_protected_internal_class_hierarchy_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
internal class C
{
protected internal class D
{
public bool [|thisIsVisible1|];
protected bool [|thisIsVisible2|];
internal bool [|thisIsVisible3|];
protected internal bool [|thisIsVisible4|];
private protected bool [|thisIsVisible5|];
private bool thisIsVisible6;
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean field 'thisIsVisible1' should start with a verb",
"The name of protected boolean field 'thisIsVisible2' should start with a verb",
"The name of internal boolean field 'thisIsVisible3' should start with a verb",
"The name of protected internal boolean field 'thisIsVisible4' should start with a verb",
"The name of private protected boolean field 'thisIsVisible5' should start with a verb");
}
[Fact]
internal void When_field_type_is_bool_and_name_does_not_start_with_a_verb_in_private_class_hierarchy_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
private class D
{
public bool thisIsVisible1;
protected bool thisIsVisible2;
internal bool thisIsVisible3;
protected internal bool thisIsVisible4;
private protected bool thisIsVisible5;
private bool thisIsVisible6;
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
[Fact]
internal void
When_parameter_type_is_bool_and_name_does_not_start_with_a_verb_in_public_class_hierarchy_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
public class D
{
public void M1(bool [|thisIsVisible1|])
{
}
protected void M2(bool [|thisIsVisible2|])
{
}
internal void M3(bool [|thisIsVisible3|])
{
}
protected internal void M4(bool [|thisIsVisible4|])
{
}
private protected void M5(bool [|thisIsVisible5|])
{
}
private void M6(bool thisIsVisible6)
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible1' should start with a verb",
"The name of protected boolean parameter 'thisIsVisible2' should start with a verb",
"The name of internal boolean parameter 'thisIsVisible3' should start with a verb",
"The name of protected internal boolean parameter 'thisIsVisible4' should start with a verb",
"The name of private protected boolean parameter 'thisIsVisible5' should start with a verb");
}
[Fact]
internal void
When_parameter_type_is_bool_and_name_does_not_start_with_a_verb_in_protected_class_hierarchy_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
protected class D
{
public void M1(bool [|thisIsVisible1|])
{
}
protected void M2(bool [|thisIsVisible2|])
{
}
internal void M3(bool [|thisIsVisible3|])
{
}
protected internal void M4(bool [|thisIsVisible4|])
{
}
private protected void M5(bool [|thisIsVisible5|])
{
}
private void M6(bool thisIsVisible6)
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible1' should start with a verb",
"The name of protected boolean parameter 'thisIsVisible2' should start with a verb",
"The name of internal boolean parameter 'thisIsVisible3' should start with a verb",
"The name of protected internal boolean parameter 'thisIsVisible4' should start with a verb",
"The name of private protected boolean parameter 'thisIsVisible5' should start with a verb");
}
[Fact]
internal void
When_parameter_type_is_bool_and_name_does_not_start_with_a_verb_in_internal_class_hierarchy_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
internal class C
{
internal class D
{
public void M1(bool [|thisIsVisible1|])
{
}
protected void M2(bool [|thisIsVisible2|])
{
}
internal void M3(bool [|thisIsVisible3|])
{
}
protected internal void M4(bool [|thisIsVisible4|])
{
}
private protected void M5(bool [|thisIsVisible5|])
{
}
private void M6(bool thisIsVisible6)
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible1' should start with a verb",
"The name of protected boolean parameter 'thisIsVisible2' should start with a verb",
"The name of internal boolean parameter 'thisIsVisible3' should start with a verb",
"The name of protected internal boolean parameter 'thisIsVisible4' should start with a verb",
"The name of private protected boolean parameter 'thisIsVisible5' should start with a verb");
}
[Fact]
internal void
When_parameter_type_is_bool_and_name_does_not_start_with_a_verb_in_protected_internal_class_hierarchy_it_must_be_reported()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
internal class C
{
protected internal class D
{
public void M1(bool [|thisIsVisible1|])
{
}
protected void M2(bool [|thisIsVisible2|])
{
}
internal void M3(bool [|thisIsVisible3|])
{
}
protected internal void M4(bool [|thisIsVisible4|])
{
}
private protected void M5(bool [|thisIsVisible5|])
{
}
private void M6(bool thisIsVisible6)
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source,
"The name of public boolean parameter 'thisIsVisible1' should start with a verb",
"The name of protected boolean parameter 'thisIsVisible2' should start with a verb",
"The name of internal boolean parameter 'thisIsVisible3' should start with a verb",
"The name of protected internal boolean parameter 'thisIsVisible4' should start with a verb",
"The name of private protected boolean parameter 'thisIsVisible5' should start with a verb");
}
[Fact]
internal void
When_parameter_type_is_bool_and_name_does_not_start_with_a_verb_in_private_class_hierarchy_it_must_be_skipped()
{
// Arrange
ParsedSourceCode source = new TypeSourceCodeBuilder()
.InGlobalScope(@"
public class C
{
private class D
{
public void M1(bool thisIsVisible1)
{
}
protected void M2(bool thisIsVisible2)
{
}
internal void M3(bool thisIsVisible3)
{
}
protected internal void M4(bool thisIsVisible4)
{
}
private protected void M5(bool thisIsVisible5)
{
}
private void M6(bool thisIsVisible6)
{
}
}
}
")
.Build();
// Act and assert
VerifyGuidelineDiagnostic(source);
}
protected override DiagnosticAnalyzer CreateAnalyzer()
{
return new NamePropertyWithAnAffirmativePhraseAnalyzer();
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnLogPacPap class.
/// </summary>
[Serializable]
public partial class PnLogPacPapCollection : ActiveList<PnLogPacPap, PnLogPacPapCollection>
{
public PnLogPacPapCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnLogPacPapCollection</returns>
public PnLogPacPapCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnLogPacPap o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_log_pac_pap table.
/// </summary>
[Serializable]
public partial class PnLogPacPap : ActiveRecord<PnLogPacPap>, IActiveRecord
{
#region .ctors and Default Settings
public PnLogPacPap()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnLogPacPap(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnLogPacPap(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnLogPacPap(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_log_pac_pap", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdLogPacPap = new TableSchema.TableColumn(schema);
colvarIdLogPacPap.ColumnName = "id_log_pac_pap";
colvarIdLogPacPap.DataType = DbType.Int32;
colvarIdLogPacPap.MaxLength = 0;
colvarIdLogPacPap.AutoIncrement = true;
colvarIdLogPacPap.IsNullable = false;
colvarIdLogPacPap.IsPrimaryKey = true;
colvarIdLogPacPap.IsForeignKey = false;
colvarIdLogPacPap.IsReadOnly = false;
colvarIdLogPacPap.DefaultSetting = @"";
colvarIdLogPacPap.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdLogPacPap);
TableSchema.TableColumn colvarIdPacPap = new TableSchema.TableColumn(schema);
colvarIdPacPap.ColumnName = "id_pac_pap";
colvarIdPacPap.DataType = DbType.Int32;
colvarIdPacPap.MaxLength = 0;
colvarIdPacPap.AutoIncrement = false;
colvarIdPacPap.IsNullable = false;
colvarIdPacPap.IsPrimaryKey = false;
colvarIdPacPap.IsForeignKey = false;
colvarIdPacPap.IsReadOnly = false;
colvarIdPacPap.DefaultSetting = @"";
colvarIdPacPap.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdPacPap);
TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema);
colvarFecha.ColumnName = "fecha";
colvarFecha.DataType = DbType.DateTime;
colvarFecha.MaxLength = 0;
colvarFecha.AutoIncrement = false;
colvarFecha.IsNullable = true;
colvarFecha.IsPrimaryKey = false;
colvarFecha.IsForeignKey = false;
colvarFecha.IsReadOnly = false;
colvarFecha.DefaultSetting = @"";
colvarFecha.ForeignKeyTableName = "";
schema.Columns.Add(colvarFecha);
TableSchema.TableColumn colvarUsuario = new TableSchema.TableColumn(schema);
colvarUsuario.ColumnName = "usuario";
colvarUsuario.DataType = DbType.AnsiString;
colvarUsuario.MaxLength = -1;
colvarUsuario.AutoIncrement = false;
colvarUsuario.IsNullable = true;
colvarUsuario.IsPrimaryKey = false;
colvarUsuario.IsForeignKey = false;
colvarUsuario.IsReadOnly = false;
colvarUsuario.DefaultSetting = @"";
colvarUsuario.ForeignKeyTableName = "";
schema.Columns.Add(colvarUsuario);
TableSchema.TableColumn colvarTipo = new TableSchema.TableColumn(schema);
colvarTipo.ColumnName = "tipo";
colvarTipo.DataType = DbType.AnsiString;
colvarTipo.MaxLength = -1;
colvarTipo.AutoIncrement = false;
colvarTipo.IsNullable = true;
colvarTipo.IsPrimaryKey = false;
colvarTipo.IsForeignKey = false;
colvarTipo.IsReadOnly = false;
colvarTipo.DefaultSetting = @"";
colvarTipo.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipo);
TableSchema.TableColumn colvarForma = new TableSchema.TableColumn(schema);
colvarForma.ColumnName = "forma";
colvarForma.DataType = DbType.AnsiString;
colvarForma.MaxLength = -1;
colvarForma.AutoIncrement = false;
colvarForma.IsNullable = true;
colvarForma.IsPrimaryKey = false;
colvarForma.IsForeignKey = false;
colvarForma.IsReadOnly = false;
colvarForma.DefaultSetting = @"";
colvarForma.ForeignKeyTableName = "";
schema.Columns.Add(colvarForma);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_log_pac_pap",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdLogPacPap")]
[Bindable(true)]
public int IdLogPacPap
{
get { return GetColumnValue<int>(Columns.IdLogPacPap); }
set { SetColumnValue(Columns.IdLogPacPap, value); }
}
[XmlAttribute("IdPacPap")]
[Bindable(true)]
public int IdPacPap
{
get { return GetColumnValue<int>(Columns.IdPacPap); }
set { SetColumnValue(Columns.IdPacPap, value); }
}
[XmlAttribute("Fecha")]
[Bindable(true)]
public DateTime? Fecha
{
get { return GetColumnValue<DateTime?>(Columns.Fecha); }
set { SetColumnValue(Columns.Fecha, value); }
}
[XmlAttribute("Usuario")]
[Bindable(true)]
public string Usuario
{
get { return GetColumnValue<string>(Columns.Usuario); }
set { SetColumnValue(Columns.Usuario, value); }
}
[XmlAttribute("Tipo")]
[Bindable(true)]
public string Tipo
{
get { return GetColumnValue<string>(Columns.Tipo); }
set { SetColumnValue(Columns.Tipo, value); }
}
[XmlAttribute("Forma")]
[Bindable(true)]
public string Forma
{
get { return GetColumnValue<string>(Columns.Forma); }
set { SetColumnValue(Columns.Forma, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdPacPap,DateTime? varFecha,string varUsuario,string varTipo,string varForma)
{
PnLogPacPap item = new PnLogPacPap();
item.IdPacPap = varIdPacPap;
item.Fecha = varFecha;
item.Usuario = varUsuario;
item.Tipo = varTipo;
item.Forma = varForma;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdLogPacPap,int varIdPacPap,DateTime? varFecha,string varUsuario,string varTipo,string varForma)
{
PnLogPacPap item = new PnLogPacPap();
item.IdLogPacPap = varIdLogPacPap;
item.IdPacPap = varIdPacPap;
item.Fecha = varFecha;
item.Usuario = varUsuario;
item.Tipo = varTipo;
item.Forma = varForma;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdLogPacPapColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdPacPapColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn FechaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn UsuarioColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn TipoColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn FormaColumn
{
get { return Schema.Columns[5]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdLogPacPap = @"id_log_pac_pap";
public static string IdPacPap = @"id_pac_pap";
public static string Fecha = @"fecha";
public static string Usuario = @"usuario";
public static string Tipo = @"tipo";
public static string Forma = @"forma";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// <copyright file="MlkBiCgStab.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// 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>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Double.Solvers
{
/// <summary>
/// A Multiple-Lanczos Bi-Conjugate Gradient stabilized iterative matrix solver.
/// </summary>
/// <remarks>
/// <para>
/// The Multiple-Lanczos Bi-Conjugate Gradient stabilized (ML(k)-BiCGStab) solver is an 'improvement'
/// of the standard BiCgStab solver.
/// </para>
/// <para>
/// The algorithm was taken from: <br/>
/// ML(k)BiCGSTAB: A BiCGSTAB variant based on multiple Lanczos starting vectors
/// <br/>
/// Man-chung Yeung and Tony F. Chan
/// <br/>
/// SIAM Journal of Scientific Computing
/// <br/>
/// Volume 21, Number 4, pp. 1263 - 1290
/// </para>
/// <para>
/// The example code below provides an indication of the possible use of the
/// solver.
/// </para>
/// </remarks>
public sealed class MlkBiCgStab : IIterativeSolver<double>
{
/// <summary>
/// The default number of starting vectors.
/// </summary>
const int DefaultNumberOfStartingVectors = 50;
/// <summary>
/// The collection of starting vectors which are used as the basis for the Krylov sub-space.
/// </summary>
IList<Vector<double>> _startingVectors;
/// <summary>
/// The number of starting vectors used by the algorithm
/// </summary>
int _numberOfStartingVectors = DefaultNumberOfStartingVectors;
/// <summary>
/// Gets or sets the number of starting vectors.
/// </summary>
/// <remarks>
/// Must be larger than 1 and smaller than the number of variables in the matrix that
/// for which this solver will be used.
/// </remarks>
public int NumberOfStartingVectors
{
[DebuggerStepThrough]
get
{
return _numberOfStartingVectors;
}
[DebuggerStepThrough]
set
{
if (value <= 1)
{
throw new ArgumentOutOfRangeException("value");
}
_numberOfStartingVectors = value;
}
}
/// <summary>
/// Resets the number of starting vectors to the default value.
/// </summary>
public void ResetNumberOfStartingVectors()
{
_numberOfStartingVectors = DefaultNumberOfStartingVectors;
}
/// <summary>
/// Gets or sets a series of orthonormal vectors which will be used as basis for the
/// Krylov sub-space.
/// </summary>
public IList<Vector<double>> StartingVectors
{
[DebuggerStepThrough]
get
{
return _startingVectors;
}
[DebuggerStepThrough]
set
{
if ((value == null) || (value.Count == 0))
{
_startingVectors = null;
}
else
{
_startingVectors = value;
}
}
}
/// <summary>
/// Gets the number of starting vectors to create
/// </summary>
/// <param name="maximumNumberOfStartingVectors">Maximum number</param>
/// <param name="numberOfVariables">Number of variables</param>
/// <returns>Number of starting vectors to create</returns>
static int NumberOfStartingVectorsToCreate(int maximumNumberOfStartingVectors, int numberOfVariables)
{
// Create no more starting vectors than the size of the problem - 1
return Math.Min(maximumNumberOfStartingVectors, (numberOfVariables - 1));
}
/// <summary>
/// Returns an array of starting vectors.
/// </summary>
/// <param name="maximumNumberOfStartingVectors">The maximum number of starting vectors that should be created.</param>
/// <param name="numberOfVariables">The number of variables.</param>
/// <returns>
/// An array with starting vectors. The array will never be larger than the
/// <paramref name="maximumNumberOfStartingVectors"/> but it may be smaller if
/// the <paramref name="numberOfVariables"/> is smaller than
/// the <paramref name="maximumNumberOfStartingVectors"/>.
/// </returns>
static IList<Vector<double>> CreateStartingVectors(int maximumNumberOfStartingVectors, int numberOfVariables)
{
// Create no more starting vectors than the size of the problem - 1
// Get random values and then orthogonalize them with
// modified Gramm - Schmidt
var count = NumberOfStartingVectorsToCreate(maximumNumberOfStartingVectors, numberOfVariables);
// Get a random set of samples based on the standard normal distribution with
// mean = 0 and sd = 1
var distribution = new Normal();
var matrix = new DenseMatrix(numberOfVariables, count);
for (var i = 0; i < matrix.ColumnCount; i++)
{
var samples = distribution.Samples().Take(matrix.RowCount).ToArray();
// Set the column
matrix.SetColumn(i, samples);
}
// Compute the orthogonalization.
var gs = matrix.GramSchmidt();
var orthogonalMatrix = gs.Q;
// Now transfer this to vectors
var result = new List<Vector<double>>();
for (var i = 0; i < orthogonalMatrix.ColumnCount; i++)
{
result.Add(orthogonalMatrix.Column(i));
// Normalize the result vector
result[i].Multiply(1 / result[i].L2Norm(), result[i]);
}
return result;
}
/// <summary>
/// Create random vecrors array
/// </summary>
/// <param name="arraySize">Number of vectors</param>
/// <param name="vectorSize">Size of each vector</param>
/// <returns>Array of random vectors</returns>
static Vector<double>[] CreateVectorArray(int arraySize, int vectorSize)
{
var result = new Vector<double>[arraySize];
for (var i = 0; i < result.Length; i++)
{
result[i] = new DenseVector(vectorSize);
}
return result;
}
/// <summary>
/// Calculates the true residual of the matrix equation Ax = b according to: residual = b - Ax
/// </summary>
/// <param name="matrix">Source <see cref="Matrix"/>A.</param>
/// <param name="residual">Residual <see cref="Vector"/> data.</param>
/// <param name="x">x <see cref="Vector"/> data.</param>
/// <param name="b">b <see cref="Vector"/> data.</param>
static void CalculateTrueResidual(Matrix<double> matrix, Vector<double> residual, Vector<double> x, Vector<double> b)
{
// -Ax = residual
matrix.Multiply(x, residual);
residual.Multiply(-1, residual);
// residual + b
residual.Add(b, residual);
}
/// <summary>
/// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the
/// solution vector and x is the unknown vector.
/// </summary>
/// <param name="matrix">The coefficient matrix, <c>A</c>.</param>
/// <param name="input">The solution vector, <c>b</c></param>
/// <param name="result">The result vector, <c>x</c></param>
/// <param name="iterator">The iterator to use to control when to stop iterating.</param>
/// <param name="preconditioner">The preconditioner to use for approximations.</param>
public void Solve(Matrix<double> matrix, Vector<double> input, Vector<double> result, Iterator<double> iterator, IPreconditioner<double> preconditioner)
{
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
}
if (result.Count != input.Count)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (input.Count != matrix.RowCount)
{
throw Matrix.DimensionsDontMatch<ArgumentException>(input, matrix);
}
if (iterator == null)
{
iterator = new Iterator<double>();
}
if (preconditioner == null)
{
preconditioner = new UnitPreconditioner<double>();
}
preconditioner.Initialize(matrix);
// Choose an initial guess x_0
// Take x_0 = 0
var xtemp = new DenseVector(input.Count);
// Choose k vectors q_1, q_2, ..., q_k
// Build a new set if:
// a) the stored set doesn't exist (i.e. == null)
// b) Is of an incorrect length (i.e. too long)
// c) The vectors are of an incorrect length (i.e. too long or too short)
var useOld = false;
if (_startingVectors != null)
{
// We don't accept collections with zero starting vectors so ...
if (_startingVectors.Count <= NumberOfStartingVectorsToCreate(_numberOfStartingVectors, input.Count))
{
// Only check the first vector for sizing. If that matches we assume the
// other vectors match too. If they don't the process will crash
if (_startingVectors[0].Count == input.Count)
{
useOld = true;
}
}
}
_startingVectors = useOld ? _startingVectors : CreateStartingVectors(_numberOfStartingVectors, input.Count);
// Store the number of starting vectors. Not really necessary but easier to type :)
var k = _startingVectors.Count;
// r_0 = b - Ax_0
// This is basically a SAXPY so it could be made a lot faster
var residuals = new DenseVector(matrix.RowCount);
CalculateTrueResidual(matrix, residuals, xtemp, input);
// Define the temporary scalars
var c = new double[k];
// Define the temporary vectors
var gtemp = new DenseVector(residuals.Count);
var u = new DenseVector(residuals.Count);
var utemp = new DenseVector(residuals.Count);
var temp = new DenseVector(residuals.Count);
var temp1 = new DenseVector(residuals.Count);
var temp2 = new DenseVector(residuals.Count);
var zd = new DenseVector(residuals.Count);
var zg = new DenseVector(residuals.Count);
var zw = new DenseVector(residuals.Count);
var d = CreateVectorArray(_startingVectors.Count, residuals.Count);
// g_0 = r_0
var g = CreateVectorArray(_startingVectors.Count, residuals.Count);
residuals.CopyTo(g[k - 1]);
var w = CreateVectorArray(_startingVectors.Count, residuals.Count);
// FOR (j = 0, 1, 2 ....)
var iterationNumber = 0;
while (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) == IterationStatus.Continue)
{
// SOLVE M g~_((j-1)k+k) = g_((j-1)k+k)
preconditioner.Approximate(g[k - 1], gtemp);
// w_((j-1)k+k) = A g~_((j-1)k+k)
matrix.Multiply(gtemp, w[k - 1]);
// c_((j-1)k+k) = q^T_1 w_((j-1)k+k)
c[k - 1] = _startingVectors[0].DotProduct(w[k - 1]);
if (c[k - 1].AlmostEqualNumbersBetween(0, 1))
{
throw new NumericalBreakdownException();
}
// alpha_(jk+1) = q^T_1 r_((j-1)k+k) / c_((j-1)k+k)
var alpha = _startingVectors[0].DotProduct(residuals)/c[k - 1];
// u_(jk+1) = r_((j-1)k+k) - alpha_(jk+1) w_((j-1)k+k)
w[k - 1].Multiply(-alpha, temp);
residuals.Add(temp, u);
// SOLVE M u~_(jk+1) = u_(jk+1)
preconditioner.Approximate(u, temp1);
temp1.CopyTo(utemp);
// rho_(j+1) = -u^t_(jk+1) A u~_(jk+1) / ||A u~_(jk+1)||^2
matrix.Multiply(temp1, temp);
var rho = temp.DotProduct(temp);
// If rho is zero then temp is a zero vector and we're probably
// about to have zero residuals (i.e. an exact solution).
// So set rho to 1.0 because in the next step it will turn to zero.
if (rho.AlmostEqualNumbersBetween(0, 1))
{
rho = 1.0;
}
rho = -u.DotProduct(temp)/rho;
// r_(jk+1) = rho_(j+1) A u~_(jk+1) + u_(jk+1)
u.CopyTo(residuals);
// Reuse temp
temp.Multiply(rho, temp);
residuals.Add(temp, temp2);
temp2.CopyTo(residuals);
// x_(jk+1) = x_((j-1)k_k) - rho_(j+1) u~_(jk+1) + alpha_(jk+1) g~_((j-1)k+k)
utemp.Multiply(-rho, temp);
xtemp.Add(temp, temp2);
temp2.CopyTo(xtemp);
gtemp.Multiply(alpha, gtemp);
xtemp.Add(gtemp, temp2);
temp2.CopyTo(xtemp);
// Check convergence and stop if we are converged.
if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue)
{
// Calculate the true residual
CalculateTrueResidual(matrix, residuals, xtemp, input);
// Now recheck the convergence
if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue)
{
// We're all good now.
// Exit from the while loop.
break;
}
}
// FOR (i = 1,2, ...., k)
for (var i = 0; i < k; i++)
{
// z_d = u_(jk+1)
u.CopyTo(zd);
// z_g = r_(jk+i)
residuals.CopyTo(zg);
// z_w = 0
zw.Clear();
// FOR (s = i, ...., k-1) AND j >= 1
double beta;
if (iterationNumber >= 1)
{
for (var s = i; s < k - 1; s++)
{
// beta^(jk+i)_((j-1)k+s) = -q^t_(s+1) z_d / c_((j-1)k+s)
beta = -_startingVectors[s + 1].DotProduct(zd)/c[s];
// z_d = z_d + beta^(jk+i)_((j-1)k+s) d_((j-1)k+s)
d[s].Multiply(beta, temp);
zd.Add(temp, temp2);
temp2.CopyTo(zd);
// z_g = z_g + beta^(jk+i)_((j-1)k+s) g_((j-1)k+s)
g[s].Multiply(beta, temp);
zg.Add(temp, temp2);
temp2.CopyTo(zg);
// z_w = z_w + beta^(jk+i)_((j-1)k+s) w_((j-1)k+s)
w[s].Multiply(beta, temp);
zw.Add(temp, temp2);
temp2.CopyTo(zw);
}
}
beta = rho*c[k - 1];
if (beta.AlmostEqualNumbersBetween(0, 1))
{
throw new NumericalBreakdownException();
}
// beta^(jk+i)_((j-1)k+k) = -(q^T_1 (r_(jk+1) + rho_(j+1) z_w)) / (rho_(j+1) c_((j-1)k+k))
zw.Multiply(rho, temp2);
residuals.Add(temp2, temp);
beta = -_startingVectors[0].DotProduct(temp)/beta;
// z_g = z_g + beta^(jk+i)_((j-1)k+k) g_((j-1)k+k)
g[k - 1].Multiply(beta, temp);
zg.Add(temp, temp2);
temp2.CopyTo(zg);
// z_w = rho_(j+1) (z_w + beta^(jk+i)_((j-1)k+k) w_((j-1)k+k))
w[k - 1].Multiply(beta, temp);
zw.Add(temp, temp2);
temp2.CopyTo(zw);
zw.Multiply(rho, zw);
// z_d = r_(jk+i) + z_w
residuals.Add(zw, zd);
// FOR (s = 1, ... i - 1)
for (var s = 0; s < i - 1; s++)
{
// beta^(jk+i)_(jk+s) = -q^T_s+1 z_d / c_(jk+s)
beta = -_startingVectors[s + 1].DotProduct(zd)/c[s];
// z_d = z_d + beta^(jk+i)_(jk+s) * d_(jk+s)
d[s].Multiply(beta, temp);
zd.Add(temp, temp2);
temp2.CopyTo(zd);
// z_g = z_g + beta^(jk+i)_(jk+s) * g_(jk+s)
g[s].Multiply(beta, temp);
zg.Add(temp, temp2);
temp2.CopyTo(zg);
}
// d_(jk+i) = z_d - u_(jk+i)
zd.Subtract(u, d[i]);
// g_(jk+i) = z_g + z_w
zg.Add(zw, g[i]);
// IF (i < k - 1)
if (i < k - 1)
{
// c_(jk+1) = q^T_i+1 d_(jk+i)
c[i] = _startingVectors[i + 1].DotProduct(d[i]);
if (c[i].AlmostEqualNumbersBetween(0, 1))
{
throw new NumericalBreakdownException();
}
// alpha_(jk+i+1) = q^T_(i+1) u_(jk+i) / c_(jk+i)
alpha = _startingVectors[i + 1].DotProduct(u)/c[i];
// u_(jk+i+1) = u_(jk+i) - alpha_(jk+i+1) d_(jk+i)
d[i].Multiply(-alpha, temp);
u.Add(temp, temp2);
temp2.CopyTo(u);
// SOLVE M g~_(jk+i) = g_(jk+i)
preconditioner.Approximate(g[i], gtemp);
// x_(jk+i+1) = x_(jk+i) + rho_(j+1) alpha_(jk+i+1) g~_(jk+i)
gtemp.Multiply(rho*alpha, temp);
xtemp.Add(temp, temp2);
temp2.CopyTo(xtemp);
// w_(jk+i) = A g~_(jk+i)
matrix.Multiply(gtemp, w[i]);
// r_(jk+i+1) = r_(jk+i) - rho_(j+1) alpha_(jk+i+1) w_(jk+i)
w[i].Multiply(-rho*alpha, temp);
residuals.Add(temp, temp2);
temp2.CopyTo(residuals);
// We can check the residuals here if they're close
if (iterator.DetermineStatus(iterationNumber, xtemp, input, residuals) != IterationStatus.Continue)
{
// Recalculate the residuals and go round again. This is done to ensure that
// we have the proper residuals.
CalculateTrueResidual(matrix, residuals, xtemp, input);
}
}
} // END ITERATION OVER i
iterationNumber++;
}
// copy the temporary result to the real result vector
xtemp.CopyTo(result);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Navigation;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.SymbolMapping;
using Microsoft.CodeAnalysis.FindReferences;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.FindReferences
{
internal abstract partial class AbstractFindReferencesService :
ForegroundThreadAffinitizedObject, IFindReferencesService, IStreamingFindReferencesService
{
private readonly IEnumerable<IDefinitionsAndReferencesPresenter> _referenceSymbolPresenters;
private readonly IEnumerable<INavigableItemsPresenter> _navigableItemPresenters;
private readonly IEnumerable<IFindReferencesResultProvider> _externalReferencesProviders;
protected AbstractFindReferencesService(
IEnumerable<IDefinitionsAndReferencesPresenter> referenceSymbolPresenters,
IEnumerable<INavigableItemsPresenter> navigableItemPresenters,
IEnumerable<IFindReferencesResultProvider> externalReferencesProviders)
{
_referenceSymbolPresenters = referenceSymbolPresenters;
_navigableItemPresenters = navigableItemPresenters;
_externalReferencesProviders = externalReferencesProviders;
}
/// <summary>
/// Common helper for both the synchronous and streaming versions of FAR.
/// It returns the symbol we want to search for and the solution we should
/// be searching.
///
/// Note that the <see cref="Solution"/> returned may absolutely *not* be
/// the same as <code>document.Project.Solution</code>. This is because
/// there may be symbol mapping involved (for example in Metadata-As-Source
/// scenarios).
/// </summary>
private async Task<Tuple<ISymbol, Solution>> GetRelevantSymbolAndSolutionAtPositionAsync(
Document document, int position, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var symbol = await SymbolFinder.FindSymbolAtPositionAsync(document, position, cancellationToken: cancellationToken).ConfigureAwait(false);
if (symbol != null)
{
// If this document is not in the primary workspace, we may want to search for results
// in a solution different from the one we started in. Use the starting workspace's
// ISymbolMappingService to get a context for searching in the proper solution.
var mappingService = document.Project.Solution.Workspace.Services.GetService<ISymbolMappingService>();
var mapping = await mappingService.MapSymbolAsync(document, symbol, cancellationToken).ConfigureAwait(false);
if (mapping != null)
{
return Tuple.Create(mapping.Symbol, mapping.Solution);
}
}
return null;
}
/// <summary>
/// Finds references using the externally defined <see cref="IFindReferencesResultProvider"/>s.
/// </summary>
private async Task AddExternalReferencesAsync(Document document, int position, ArrayBuilder<INavigableItem> builder, CancellationToken cancellationToken)
{
// CONSIDER: Do the computation in parallel.
foreach (var provider in _externalReferencesProviders)
{
var references = await provider.FindReferencesAsync(document, position, cancellationToken).ConfigureAwait(false);
if (references != null)
{
builder.AddRange(references.WhereNotNull());
}
}
}
private async Task<Tuple<IEnumerable<ReferencedSymbol>, Solution>> FindReferencedSymbolsAsync(
Document document, int position, IWaitContext waitContext)
{
var cancellationToken = waitContext.CancellationToken;
var symbolAndSolution = await GetRelevantSymbolAndSolutionAtPositionAsync(document, position, cancellationToken).ConfigureAwait(false);
if (symbolAndSolution == null)
{
return null;
}
var symbol = symbolAndSolution.Item1;
var solution = symbolAndSolution.Item2;
var displayName = GetDisplayName(symbol);
waitContext.Message = string.Format(
EditorFeaturesResources.Finding_references_of_0, displayName);
var result = await SymbolFinder.FindReferencesAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
return Tuple.Create(result, solution);
}
private static string GetDisplayName(ISymbol symbol)
{
return symbol.IsConstructor() ? symbol.ContainingType.Name : symbol.Name;
}
public bool TryFindReferences(Document document, int position, IWaitContext waitContext)
{
var cancellationToken = waitContext.CancellationToken;
var workspace = document.Project.Solution.Workspace;
// First see if we have any external navigable item references.
// If so, we display the results as navigable items.
var succeeded = TryFindAndDisplayNavigableItemsReferencesAsync(document, position, waitContext).WaitAndGetResult(cancellationToken);
if (succeeded)
{
return true;
}
// Otherwise, fall back to displaying SymbolFinder based references.
var result = this.FindReferencedSymbolsAsync(document, position, waitContext).WaitAndGetResult(cancellationToken);
return TryDisplayReferences(result);
}
/// <summary>
/// Attempts to find and display navigable item references, including the references provided by external providers.
/// </summary>
/// <returns>False if there are no external references or display was not successful.</returns>
private async Task<bool> TryFindAndDisplayNavigableItemsReferencesAsync(Document document, int position, IWaitContext waitContext)
{
var foundReferences = false;
if (_externalReferencesProviders.Any())
{
var cancellationToken = waitContext.CancellationToken;
var builder = ArrayBuilder<INavigableItem>.GetInstance();
await AddExternalReferencesAsync(document, position, builder, cancellationToken).ConfigureAwait(false);
// TODO: Merging references from SymbolFinder and external providers might lead to duplicate or counter-intuitive results.
// TODO: For now, we avoid merging and just display the results either from SymbolFinder or the external result providers but not both.
if (builder.Count > 0 && TryDisplayReferences(builder))
{
foundReferences = true;
}
builder.Free();
}
return foundReferences;
}
private bool TryDisplayReferences(IEnumerable<INavigableItem> result)
{
if (result != null && result.Any())
{
var title = result.First().DisplayTaggedParts.JoinText();
foreach (var presenter in _navigableItemPresenters)
{
presenter.DisplayResult(title, result);
return true;
}
}
return false;
}
private bool TryDisplayReferences(Tuple<IEnumerable<ReferencedSymbol>, Solution> result)
{
if (result != null && result.Item1 != null)
{
var solution = result.Item2;
var factory = solution.Workspace.Services.GetService<IDefinitionsAndReferencesFactory>();
var definitionsAndReferences = factory.CreateDefinitionsAndReferences(
solution, result.Item1);
foreach (var presenter in _referenceSymbolPresenters)
{
presenter.DisplayResult(definitionsAndReferences);
return true;
}
}
return false;
}
public async Task FindReferencesAsync(
Document document, int position, FindReferencesContext context)
{
var cancellationToken = context.CancellationToken;
cancellationToken.ThrowIfCancellationRequested();
// Find the symbol we want to search and the solution we want to search in.
var symbolAndSolution = await GetRelevantSymbolAndSolutionAtPositionAsync(
document, position, cancellationToken).ConfigureAwait(false);
if (symbolAndSolution == null)
{
return;
}
var symbol = symbolAndSolution.Item1;
var solution = symbolAndSolution.Item2;
var displayName = GetDisplayName(symbol);
context.SetSearchLabel(displayName);
var progressAdapter = new ProgressAdapter(solution, context);
// Now call into the underlying FAR engine to find reference. The FAR
// engine will push results into the 'progress' instance passed into it.
// We'll take those results, massage them, and forward them along to the
// FindReferencesContext instance we were given.
//
// Note: we pass along ConfigureAwait(true) because we need to come back
// to the UI thread. There's more work we need to do once the FAR engine
// is done.
await SymbolFinder.FindReferencesAsync(
symbol,
solution,
progressAdapter,
documents: null,
cancellationToken: cancellationToken).ConfigureAwait(true);
// After the FAR engine is done call into any third party extensions to see
// if they want to add results.
progressAdapter.CallThirdPartyExtensions();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs
{
/// <summary>
/// Packets for SmbTrans2QueryPathInformation Request
/// </summary>
public class SmbTrans2QueryPathInformationRequestPacket : SmbTransaction2RequestPacket
{
#region Fields
private TRANS2_QUERY_PATH_INFORMATION_Request_Trans2_Parameters trans2Parameters;
private TRANS2_QUERY_PATH_INFORMATION_Request_Trans2_Data trans2Data;
/// <summary>
/// The size of InformationLevel field in trans2Parameters
/// </summary>
private const ushort infoLevelLength = 2;
/// <summary>
/// The size of Reserved field in trans2Parameters
/// </summary>
private const ushort reservedLength = 4;
/// <summary>
/// The size of SizeOfListInBytes field in trans2Data
/// </summary>
private const ushort sizeOfListInBytesLength = 4;
#endregion
#region Properties
/// <summary>
/// get or set the Trans2_Parameters:TRANS2_QUERY_PATH_INFORMATION_Request_Trans2_Parameters
/// </summary>
public TRANS2_QUERY_PATH_INFORMATION_Request_Trans2_Parameters Trans2Parameters
{
get
{
return this.trans2Parameters;
}
set
{
this.trans2Parameters = value;
}
}
/// <summary>
/// get or set the Trans2_Data:TRANS2_QUERY_PATH_INFORMATION_Request_Trans2_Data
/// </summary>
public TRANS2_QUERY_PATH_INFORMATION_Request_Trans2_Data Trans2Data
{
get
{
return this.trans2Data;
}
set
{
this.trans2Data = value;
}
}
/// <summary>
/// get the FID of Trans2_Parameters
/// </summary>
internal override ushort FID
{
get
{
return INVALID_FID;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbTrans2QueryPathInformationRequestPacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbTrans2QueryPathInformationRequestPacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbTrans2QueryPathInformationRequestPacket(SmbTrans2QueryPathInformationRequestPacket packet)
: base(packet)
{
this.InitDefaultValue();
this.trans2Parameters.InformationLevel = packet.trans2Parameters.InformationLevel;
this.trans2Parameters.Reserved = packet.trans2Parameters.Reserved;
if (packet.trans2Parameters.FileName != null && packet.trans2Parameters.FileName.Length > 0)
{
this.trans2Parameters.FileName = new byte[packet.trans2Parameters.FileName.Length];
Array.Copy(packet.trans2Parameters.FileName,
this.trans2Parameters.FileName, packet.trans2Parameters.FileName.Length);
}
else
{
this.trans2Parameters.FileName = new byte[0];
}
this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes =
packet.trans2Data.GetExtendedAttributeList.SizeOfListInBytes;
if (packet.trans2Data.GetExtendedAttributeList.GEAList != null
&& packet.trans2Data.GetExtendedAttributeList.GEAList.Length > 0)
{
this.trans2Data.GetExtendedAttributeList.GEAList =
new SMB_GEA[packet.trans2Data.GetExtendedAttributeList.GEAList.Length];
Array.Copy(
packet.trans2Data.GetExtendedAttributeList.GEAList,
this.trans2Data.GetExtendedAttributeList.GEAList,
packet.trans2Data.GetExtendedAttributeList.GEAList.Length);
}
else
{
this.trans2Data.GetExtendedAttributeList.GEAList = new SMB_GEA[0];
}
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this.</returns>
public override StackPacket Clone()
{
return new SmbTrans2QueryPathInformationRequestPacket(this);
}
/// <summary>
/// Encode the struct of Trans2Parameters into the byte array in SmbData.Trans2_Parameters
/// </summary>
protected override void EncodeTrans2Parameters()
{
int trans2ParametersCount = infoLevelLength + reservedLength;
if (this.trans2Parameters.FileName != null)
{
trans2ParametersCount += this.trans2Parameters.FileName.Length;
}
this.smbData.Trans2_Parameters = new byte[trans2ParametersCount];
using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Parameters))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
channel.Write<QueryInformationLevel>(this.trans2Parameters.InformationLevel);
channel.Write<uint>(this.trans2Parameters.Reserved);
if (this.trans2Parameters.FileName != null)
{
channel.WriteBytes(this.trans2Parameters.FileName);
}
channel.EndWriteGroup();
}
}
}
/// <summary>
/// Encode the struct of Trans2Data into the byte array in SmbData.Trans2_Data
/// </summary>
protected override void EncodeTrans2Data()
{
if (this.trans2Parameters.InformationLevel == QueryInformationLevel.SMB_INFO_QUERY_EAS_FROM_LIST)
{
this.smbData.Trans2_Data = new byte[sizeOfListInBytesLength + CifsMessageUtils.GetSmbQueryEAListSize(
this.trans2Data.GetExtendedAttributeList.GEAList)];
using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
channel.Write<uint>(this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes);
if (this.trans2Data.GetExtendedAttributeList.GEAList != null)
{
foreach (SMB_GEA smbQueryEa in this.trans2Data.GetExtendedAttributeList.GEAList)
{
channel.Write<byte>(smbQueryEa.AttributeNameLengthInBytes);
if (smbQueryEa.AttributeName != null)
{
channel.WriteBytes(smbQueryEa.AttributeName);
}
}
}
channel.EndWriteGroup();
}
}
}
else
{
this.smbData.Trans2_Data = new byte[0];
}
}
/// <summary>
/// to decode the Trans2 parameters: from the general Trans2Parameters to the concrete Trans2 Parameters.
/// </summary>
protected override void DecodeTrans2Parameters()
{
using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Parameters))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.trans2Parameters.InformationLevel = channel.Read<QueryInformationLevel>();
this.trans2Parameters.Reserved = channel.Read<uint>();
this.trans2Parameters.FileName = channel.ReadBytes(
this.smbParameters.ParameterCount - infoLevelLength - reservedLength);
}
}
}
/// <summary>
/// to decode the Trans2 data: from the general Trans2Dada to the concrete Trans2 Data.
/// </summary>
protected override void DecodeTrans2Data()
{
if (this.trans2Parameters.InformationLevel == QueryInformationLevel.SMB_INFO_QUERY_EAS_FROM_LIST)
{
using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes = channel.Read<uint>();
uint sizeOfListInBytes =
this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes - sizeOfListInBytesLength;
List<SMB_GEA> attributeList = new List<SMB_GEA>();
while (sizeOfListInBytes > 0)
{
SMB_GEA smbQueryEa = channel.Read<SMB_GEA>();
attributeList.Add(smbQueryEa);
sizeOfListInBytes -= (uint)(EA.SMB_QUERY_EA_FIXED_SIZE + smbQueryEa.AttributeName.Length);
}
this.trans2Data.GetExtendedAttributeList.GEAList = attributeList.ToArray();
}
}
}
else
{
this.trans2Data.GetExtendedAttributeList.GEAList = new SMB_GEA[0];
}
}
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
namespace OpenSim.Framework.Servers
{
public class ServerBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public IConfigSource Config { get; protected set; }
/// <summary>
/// Console to be used for any command line output. Can be null, in which case there should be no output.
/// </summary>
protected ICommandConsole m_console;
protected OpenSimAppender m_consoleAppender;
protected FileAppender m_logFileAppender;
protected DateTime m_startuptime;
protected string m_startupDirectory = Environment.CurrentDirectory;
protected string m_pidFile = String.Empty;
/// <summary>
/// Server version information. Usually VersionInfo + information about git commit, operating system, etc.
/// </summary>
protected string m_version;
public ServerBase()
{
m_startuptime = DateTime.Now;
m_version = VersionInfo.Version;
EnhanceVersionInformation();
}
protected void CreatePIDFile(string path)
{
try
{
string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
using (FileStream fs = File.Create(path))
{
Byte[] buf = Encoding.ASCII.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
}
m_pidFile = path;
m_log.InfoFormat("[SERVER BASE]: Created pid file {0}", m_pidFile);
}
catch (Exception e)
{
m_log.Warn(string.Format("[SERVER BASE]: Could not create PID file at {0} ", path), e);
}
}
protected void RemovePIDFile()
{
if (m_pidFile != String.Empty)
{
try
{
File.Delete(m_pidFile);
}
catch (Exception e)
{
m_log.Error(string.Format("[SERVER BASE]: Error whilst removing {0} ", m_pidFile), e);
}
m_pidFile = String.Empty;
}
}
public void RegisterCommonAppenders(IConfig startupConfig)
{
ILoggerRepository repository = LogManager.GetRepository();
IAppender[] appenders = repository.GetAppenders();
foreach (IAppender appender in appenders)
{
if (appender.Name == "Console")
{
m_consoleAppender = (OpenSimAppender)appender;
}
else if (appender.Name == "LogFileAppender")
{
m_logFileAppender = (FileAppender)appender;
}
}
if (null == m_consoleAppender)
{
Notice("No appender named Console found (see the log4net config file for this executable)!");
}
else
{
// FIXME: This should be done through an interface rather than casting.
m_consoleAppender.Console = (ConsoleBase)m_console;
// If there is no threshold set then the threshold is effectively everything.
if (null == m_consoleAppender.Threshold)
m_consoleAppender.Threshold = Level.All;
Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold));
}
if (m_logFileAppender != null && startupConfig != null)
{
string cfgFileName = startupConfig.GetString("LogFile", null);
if (cfgFileName != null)
{
m_logFileAppender.File = cfgFileName;
m_logFileAppender.ActivateOptions();
}
m_log.InfoFormat("[SERVER BASE]: Logging started to file {0}", m_logFileAppender.File);
}
}
/// <summary>
/// Register common commands once m_console has been set if it is going to be set
/// </summary>
public void RegisterCommonCommands()
{
if (m_console == null)
return;
m_console.Commands.AddCommand(
"General", false, "show info", "show info", "Show general information about the server", HandleShow);
m_console.Commands.AddCommand(
"General", false, "show version", "show version", "Show server version", HandleShow);
m_console.Commands.AddCommand(
"General", false, "show uptime", "show uptime", "Show server uptime", HandleShow);
m_console.Commands.AddCommand(
"General", false, "get log level", "get log level", "Get the current console logging level",
(mod, cmd) => ShowLogLevel());
m_console.Commands.AddCommand(
"General", false, "set log level", "set log level <level>",
"Set the console logging level for this session.", HandleSetLogLevel);
m_console.Commands.AddCommand(
"General", false, "config set",
"config set <section> <key> <value>",
"Set a config option. In most cases this is not useful since changed parameters are not dynamically reloaded. Neither do changed parameters persist - you will have to change a config file manually and restart.", HandleConfig);
m_console.Commands.AddCommand(
"General", false, "config get",
"config get [<section>] [<key>]",
"Synonym for config show",
HandleConfig);
m_console.Commands.AddCommand(
"General", false, "config show",
"config show [<section>] [<key>]",
"Show config information",
"If neither section nor field are specified, then the whole current configuration is printed." + Environment.NewLine
+ "If a section is given but not a field, then all fields in that section are printed.",
HandleConfig);
m_console.Commands.AddCommand(
"General", false, "config save",
"config save <path>",
"Save current configuration to a file at the given path", HandleConfig);
m_console.Commands.AddCommand(
"General", false, "command-script",
"command-script <script>",
"Run a command script from file", HandleScript);
m_console.Commands.AddCommand(
"General", false, "show threads",
"show threads",
"Show thread status", HandleShow);
m_console.Commands.AddCommand(
"General", false, "threads abort",
"threads abort <thread-id>",
"Abort a managed thread. Use \"show threads\" to find possible threads.", HandleThreadsAbort);
m_console.Commands.AddCommand(
"General", false, "threads show",
"threads show",
"Show thread status. Synonym for \"show threads\"",
(string module, string[] args) => Notice(GetThreadsReport()));
m_console.Commands.AddCommand(
"General", false, "force gc",
"force gc",
"Manually invoke runtime garbage collection. For debugging purposes",
HandleForceGc);
}
private void HandleForceGc(string module, string[] args)
{
Notice("Manually invoking runtime garbage collection");
GC.Collect();
}
public virtual void HandleShow(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] showParams = args.ToArray();
switch (showParams[0])
{
case "info":
ShowInfo();
break;
case "version":
Notice(GetVersionText());
break;
case "uptime":
Notice(GetUptimeReport());
break;
case "threads":
Notice(GetThreadsReport());
break;
}
}
/// <summary>
/// Change and load configuration file data.
/// </summary>
/// <param name="module"></param>
/// <param name="cmd"></param>
private void HandleConfig(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] cmdparams = args.ToArray();
if (cmdparams.Length > 0)
{
string firstParam = cmdparams[0].ToLower();
switch (firstParam)
{
case "set":
if (cmdparams.Length < 4)
{
Notice("Syntax: config set <section> <key> <value>");
Notice("Example: config set ScriptEngine.DotNetEngine NumberOfScriptThreads 5");
}
else
{
IConfig c;
IConfigSource source = new IniConfigSource();
c = source.AddConfig(cmdparams[1]);
if (c != null)
{
string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3);
c.Set(cmdparams[2], _value);
Config.Merge(source);
Notice("In section [{0}], set {1} = {2}", c.Name, cmdparams[2], _value);
}
}
break;
case "get":
case "show":
if (cmdparams.Length == 1)
{
foreach (IConfig config in Config.Configs)
{
Notice("[{0}]", config.Name);
string[] keys = config.GetKeys();
foreach (string key in keys)
Notice(" {0} = {1}", key, config.GetString(key));
}
}
else if (cmdparams.Length == 2 || cmdparams.Length == 3)
{
IConfig config = Config.Configs[cmdparams[1]];
if (config == null)
{
Notice("Section \"{0}\" does not exist.",cmdparams[1]);
break;
}
else
{
if (cmdparams.Length == 2)
{
Notice("[{0}]", config.Name);
foreach (string key in config.GetKeys())
Notice(" {0} = {1}", key, config.GetString(key));
}
else
{
Notice(
"config get {0} {1} : {2}",
cmdparams[1], cmdparams[2], config.GetString(cmdparams[2]));
}
}
}
else
{
Notice("Syntax: config {0} [<section>] [<key>]", firstParam);
Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam);
}
break;
case "save":
if (cmdparams.Length < 2)
{
Notice("Syntax: config save <path>");
return;
}
string path = cmdparams[1];
Notice("Saving configuration file: {0}", path);
if (Config is IniConfigSource)
{
IniConfigSource iniCon = (IniConfigSource)Config;
iniCon.Save(path);
}
else if (Config is XmlConfigSource)
{
XmlConfigSource xmlCon = (XmlConfigSource)Config;
xmlCon.Save(path);
}
break;
}
}
}
private void HandleSetLogLevel(string module, string[] cmd)
{
if (cmd.Length != 4)
{
Notice("Usage: set log level <level>");
return;
}
if (null == m_consoleAppender)
{
Notice("No appender named Console found (see the log4net config file for this executable)!");
return;
}
string rawLevel = cmd[3];
ILoggerRepository repository = LogManager.GetRepository();
Level consoleLevel = repository.LevelMap[rawLevel];
if (consoleLevel != null)
m_consoleAppender.Threshold = consoleLevel;
else
Notice(
"{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF",
rawLevel);
ShowLogLevel();
}
private void ShowLogLevel()
{
Notice("Console log level is {0}", m_consoleAppender.Threshold);
}
protected virtual void HandleScript(string module, string[] parms)
{
if (parms.Length != 2)
{
Notice("Usage: command-script <path-to-script");
return;
}
RunCommandScript(parms[1]);
}
/// <summary>
/// Run an optional startup list of commands
/// </summary>
/// <param name="fileName"></param>
protected void RunCommandScript(string fileName)
{
if (m_console == null)
return;
if (File.Exists(fileName))
{
m_log.Info("[SERVER BASE]: Running " + fileName);
using (StreamReader readFile = File.OpenText(fileName))
{
string currentCommand;
while ((currentCommand = readFile.ReadLine()) != null)
{
currentCommand = currentCommand.Trim();
if (!(currentCommand == ""
|| currentCommand.StartsWith(";")
|| currentCommand.StartsWith("//")
|| currentCommand.StartsWith("#")))
{
m_log.Info("[SERVER BASE]: Running '" + currentCommand + "'");
m_console.RunCommand(currentCommand);
}
}
}
}
}
/// <summary>
/// Return a report about the uptime of this server
/// </summary>
/// <returns></returns>
protected string GetUptimeReport()
{
StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now));
sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime));
sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime));
return sb.ToString();
}
protected void ShowInfo()
{
Notice(GetVersionText());
Notice("Startup directory: " + m_startupDirectory);
if (null != m_consoleAppender)
Notice(String.Format("Console log level: {0}", m_consoleAppender.Threshold));
}
/// <summary>
/// Enhance the version string with extra information if it's available.
/// </summary>
protected void EnhanceVersionInformation()
{
string buildVersion = string.Empty;
// The subversion information is deprecated and will be removed at a later date
// Add subversion revision information if available
// Try file "svn_revision" in the current directory first, then the .svn info.
// This allows to make the revision available in simulators not running from the source tree.
// FIXME: Making an assumption about the directory we're currently in - we do this all over the place
// elsewhere as well
string gitDir = "../.git/";
string gitRefPointerPath = gitDir + "HEAD";
string svnRevisionFileName = "svn_revision";
string svnFileName = ".svn/entries";
string manualVersionFileName = ".version";
string inputLine;
int strcmp;
if (File.Exists(manualVersionFileName))
{
using (StreamReader CommitFile = File.OpenText(manualVersionFileName))
buildVersion = CommitFile.ReadLine();
m_version += buildVersion ?? "";
}
else if (File.Exists(gitRefPointerPath))
{
// m_log.DebugFormat("[SERVER BASE]: Found {0}", gitRefPointerPath);
string rawPointer = "";
using (StreamReader pointerFile = File.OpenText(gitRefPointerPath))
rawPointer = pointerFile.ReadLine();
// m_log.DebugFormat("[SERVER BASE]: rawPointer [{0}]", rawPointer);
Match m = Regex.Match(rawPointer, "^ref: (.+)$");
if (m.Success)
{
// m_log.DebugFormat("[SERVER BASE]: Matched [{0}]", m.Groups[1].Value);
string gitRef = m.Groups[1].Value;
string gitRefPath = gitDir + gitRef;
if (File.Exists(gitRefPath))
{
// m_log.DebugFormat("[SERVER BASE]: Found gitRefPath [{0}]", gitRefPath);
using (StreamReader refFile = File.OpenText(gitRefPath))
{
string gitHash = refFile.ReadLine();
m_version += gitHash.Substring(0, 7);
}
}
}
}
else
{
// Remove the else logic when subversion mirror is no longer used
if (File.Exists(svnRevisionFileName))
{
StreamReader RevisionFile = File.OpenText(svnRevisionFileName);
buildVersion = RevisionFile.ReadLine();
buildVersion.Trim();
RevisionFile.Close();
}
if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName))
{
StreamReader EntriesFile = File.OpenText(svnFileName);
inputLine = EntriesFile.ReadLine();
while (inputLine != null)
{
// using the dir svn revision at the top of entries file
strcmp = String.Compare(inputLine, "dir");
if (strcmp == 0)
{
buildVersion = EntriesFile.ReadLine();
break;
}
else
{
inputLine = EntriesFile.ReadLine();
}
}
EntriesFile.Close();
}
m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6);
}
}
protected string GetVersionText()
{
return String.Format("Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion);
}
/// <summary>
/// Get a report about the registered threads in this server.
/// </summary>
protected string GetThreadsReport()
{
// This should be a constant field.
string reportFormat = "{0,6} {1,35} {2,16} {3,13} {4,10} {5,30}";
StringBuilder sb = new StringBuilder();
Watchdog.ThreadWatchdogInfo[] threads = Watchdog.GetThreadsInfo();
sb.Append(threads.Length + " threads are being tracked:" + Environment.NewLine);
int timeNow = Environment.TickCount & Int32.MaxValue;
sb.AppendFormat(reportFormat, "ID", "NAME", "LAST UPDATE (MS)", "LIFETIME (MS)", "PRIORITY", "STATE");
sb.Append(Environment.NewLine);
foreach (Watchdog.ThreadWatchdogInfo twi in threads)
{
Thread t = twi.Thread;
sb.AppendFormat(
reportFormat,
t.ManagedThreadId,
t.Name,
timeNow - twi.LastTick,
timeNow - twi.FirstTick,
t.Priority,
t.ThreadState);
sb.Append("\n");
}
sb.Append("\n");
// For some reason mono 2.6.7 returns an empty threads set! Not going to confuse people by reporting
// zero active threads.
int totalThreads = Process.GetCurrentProcess().Threads.Count;
if (totalThreads > 0)
sb.AppendFormat("Total threads active: {0}\n\n", totalThreads);
sb.Append("Main threadpool (excluding script engine pools)\n");
sb.Append(Util.GetThreadPoolReport());
return sb.ToString();
}
public virtual void HandleThreadsAbort(string module, string[] cmd)
{
if (cmd.Length != 3)
{
MainConsole.Instance.Output("Usage: threads abort <thread-id>");
return;
}
int threadId;
if (!int.TryParse(cmd[2], out threadId))
{
MainConsole.Instance.Output("ERROR: Thread id must be an integer");
return;
}
if (Watchdog.AbortThread(threadId))
MainConsole.Instance.OutputFormat("Aborted thread with id {0}", threadId);
else
MainConsole.Instance.OutputFormat("ERROR - Thread with id {0} not found in managed threads", threadId);
}
/// <summary>
/// Console output is only possible if a console has been established.
/// That is something that cannot be determined within this class. So
/// all attempts to use the console MUST be verified.
/// </summary>
/// <param name="msg"></param>
protected void Notice(string msg)
{
if (m_console != null)
{
m_console.Output(msg);
}
}
/// <summary>
/// Console output is only possible if a console has been established.
/// That is something that cannot be determined within this class. So
/// all attempts to use the console MUST be verified.
/// </summary>
/// <param name="format"></param>
/// <param name="components"></param>
protected void Notice(string format, params object[] components)
{
if (m_console != null)
m_console.OutputFormat(format, components);
}
}
}
| |
// WindowsNameTransform.cs
//
// Copyright 2007 John Reilly
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7
using System;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Core;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// WindowsNameTransform transforms <see cref="ZipFile"/> names to windows compatible ones.
/// </summary>
internal class WindowsNameTransform : INameTransform
{
/// <summary>
/// Initialises a new instance of <see cref="WindowsNameTransform"/>
/// </summary>
/// <param name="baseDirectory"></param>
public WindowsNameTransform(string baseDirectory)
{
if ( baseDirectory == null ) {
throw new ArgumentNullException("baseDirectory", "Directory name is invalid");
}
BaseDirectory = baseDirectory;
}
/// <summary>
/// Initialise a default instance of <see cref="WindowsNameTransform"/>
/// </summary>
public WindowsNameTransform()
{
// Do nothing.
}
/// <summary>
/// Gets or sets a value containing the target directory to prefix values with.
/// </summary>
public string BaseDirectory
{
get { return _baseDirectory; }
set {
if ( value == null ) {
throw new ArgumentNullException("value");
}
_baseDirectory = Path.GetFullPath(value);
}
}
/// <summary>
/// Gets or sets a value indicating wether paths on incoming values should be removed.
/// </summary>
public bool TrimIncomingPaths
{
get { return _trimIncomingPaths; }
set { _trimIncomingPaths = value; }
}
/// <summary>
/// Transform a Zip directory name to a windows directory name.
/// </summary>
/// <param name="name">The directory name to transform.</param>
/// <returns>The transformed name.</returns>
public string TransformDirectory(string name)
{
name = TransformFile(name);
if (name.Length > 0) {
while ( name.EndsWith(@"\") ) {
name = name.Remove(name.Length - 1, 1);
}
}
else {
throw new ZipException("Cannot have an empty directory name");
}
return name;
}
/// <summary>
/// Transform a Zip format file name to a windows style one.
/// </summary>
/// <param name="name">The file name to transform.</param>
/// <returns>The transformed name.</returns>
public string TransformFile(string name)
{
if (name != null) {
name = MakeValidName(name, _replacementChar);
if ( _trimIncomingPaths ) {
name = Path.GetFileName(name);
}
// This may exceed windows length restrictions.
// Combine will throw a PathTooLongException in that case.
if ( _baseDirectory != null ) {
name = Path.Combine(_baseDirectory, name);
}
}
else {
name = string.Empty;
}
return name;
}
/// <summary>
/// Test a name to see if it is a valid name for a windows filename as extracted from a Zip archive.
/// </summary>
/// <param name="name">The name to test.</param>
/// <returns>Returns true if the name is a valid zip name; false otherwise.</returns>
/// <remarks>The filename isnt a true windows path in some fundamental ways like no absolute paths, no rooted paths etc.</remarks>
public static bool IsValidName(string name)
{
bool result =
(name != null) &&
(name.Length <= MaxPath) &&
(string.Compare(name, MakeValidName(name, '_')) == 0)
;
return result;
}
/// <summary>
/// Initialise static class information.
/// </summary>
static WindowsNameTransform()
{
char[] invalidPathChars;
invalidPathChars = Path.GetInvalidPathChars();
int howMany = invalidPathChars.Length + 3;
InvalidEntryChars = new char[howMany];
Array.Copy(invalidPathChars, 0, InvalidEntryChars, 0, invalidPathChars.Length);
InvalidEntryChars[howMany - 1] = '*';
InvalidEntryChars[howMany - 2] = '?';
InvalidEntryChars[howMany - 3] = ':';
}
/// <summary>
/// Force a name to be valid by replacing invalid characters with a fixed value
/// </summary>
/// <param name="name">The name to make valid</param>
/// <param name="replacement">The replacement character to use for any invalid characters.</param>
/// <returns>Returns a valid name</returns>
public static string MakeValidName(string name, char replacement)
{
if ( name == null ) {
throw new ArgumentNullException("name");
}
name = WindowsPathUtils.DropPathRoot(name.Replace("/", @"\"));
// Drop any leading slashes.
while ( (name.Length > 0) && (name[0] == '\\')) {
name = name.Remove(0, 1);
}
// Drop any trailing slashes.
while ( (name.Length > 0) && (name[name.Length - 1] == '\\')) {
name = name.Remove(name.Length - 1, 1);
}
// Convert consecutive \\ characters to \
int index = name.IndexOf(@"\\");
while (index >= 0) {
name = name.Remove(index, 1);
index = name.IndexOf(@"\\");
}
// Convert any invalid characters using the replacement one.
index = name.IndexOfAny(InvalidEntryChars);
if (index >= 0) {
StringBuilder builder = new StringBuilder(name);
while (index >= 0 ) {
builder[index] = replacement;
if (index >= name.Length) {
index = -1;
}
else {
index = name.IndexOfAny(InvalidEntryChars, index + 1);
}
}
name = builder.ToString();
}
// Check for names greater than MaxPath characters.
// TODO: Were is CLR version of MaxPath defined? Can't find it in Environment.
if ( name.Length > MaxPath ) {
throw new PathTooLongException();
}
return name;
}
/// <summary>
/// Gets or set the character to replace invalid characters during transformations.
/// </summary>
public char Replacement
{
get { return _replacementChar; }
set {
for ( int i = 0; i < InvalidEntryChars.Length; ++i ) {
if ( InvalidEntryChars[i] == value ) {
throw new ArgumentException("invalid path character");
}
}
if ((value == '\\') || (value == '/')) {
throw new ArgumentException("invalid replacement character");
}
_replacementChar = value;
}
}
/// <summary>
/// The maximum windows path name permitted.
/// </summary>
/// <remarks>This may not valid for all windows systems - CE?, etc but I cant find the equivalent in the CLR.</remarks>
const int MaxPath = 260;
#region Instance Fields
string _baseDirectory;
bool _trimIncomingPaths;
char _replacementChar = '_';
#endregion
#region Class Fields
static readonly char[] InvalidEntryChars;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace Python.Runtime
{
public sealed class PyBuffer : IDisposable
{
private PyObject _exporter;
private Py_buffer _view;
unsafe internal PyBuffer(PyObject exporter, PyBUF flags)
{
_view = new Py_buffer();
if (Runtime.PyObject_GetBuffer(exporter.Handle, ref _view, (int)flags) < 0)
{
throw new PythonException();
}
_exporter = exporter;
var intPtrBuf = new IntPtr[_view.ndim];
if (_view.shape != IntPtr.Zero)
{
Marshal.Copy(_view.shape, intPtrBuf, 0, (int)_view.len * sizeof(IntPtr));
Shape = intPtrBuf.Select(x => (long)x).ToArray();
}
if (_view.strides != IntPtr.Zero) {
Marshal.Copy(_view.strides, intPtrBuf, 0, (int)_view.len * sizeof(IntPtr));
Strides = intPtrBuf.Select(x => (long)x).ToArray();
}
if (_view.suboffsets != IntPtr.Zero) {
Marshal.Copy(_view.suboffsets, intPtrBuf, 0, (int)_view.len * sizeof(IntPtr));
SubOffsets = intPtrBuf.Select(x => (long)x).ToArray();
}
}
public PyObject Object => _exporter;
public long Length => (long)_view.len;
public long ItemSize => (long)_view.itemsize;
public int Dimensions => _view.ndim;
public bool ReadOnly => _view._readonly;
public IntPtr Buffer => _view.buf;
public string Format => _view.format;
/// <summary>
/// An array of length <see cref="Dimensions"/> indicating the shape of the memory as an n-dimensional array.
/// </summary>
public long[] Shape { get; private set; }
/// <summary>
/// An array of length <see cref="Dimensions"/> giving the number of bytes to skip to get to a new element in each dimension.
/// Will be null except when PyBUF_STRIDES or PyBUF_INDIRECT flags in GetBuffer/>.
/// </summary>
public long[] Strides { get; private set; }
/// <summary>
/// An array of Py_ssize_t of length ndim. If suboffsets[n] >= 0,
/// the values stored along the nth dimension are pointers and the suboffset value dictates how many bytes to add to each pointer after de-referencing.
/// A suboffset value that is negative indicates that no de-referencing should occur (striding in a contiguous memory block).
/// </summary>
public long[] SubOffsets { get; private set; }
private static char OrderStyleToChar(BufferOrderStyle order, bool eitherOneValid)
{
char style = 'C';
if (order == BufferOrderStyle.C)
style = 'C';
else if (order == BufferOrderStyle.Fortran)
style = 'F';
else if (order == BufferOrderStyle.EitherOne)
{
if (eitherOneValid) style = 'A';
else throw new ArgumentException("BufferOrderStyle can not be EitherOne and has to be C or Fortran");
}
return style;
}
/// <summary>
/// Return the implied itemsize from format. On error, raise an exception and return -1.
/// New in version 3.9.
/// </summary>
public static long SizeFromFormat(string format)
{
if (Runtime.PyVersion < new Version(3,9))
throw new NotSupportedException("SizeFromFormat requires at least Python 3.9");
return (long)Runtime.PyBuffer_SizeFromFormat(format);
}
/// <summary>
/// Returns true if the memory defined by the view is C-style (order is 'C') or Fortran-style (order is 'F') contiguous or either one (order is 'A'). Returns false otherwise.
/// </summary>
/// <param name="order">C-style (order is 'C') or Fortran-style (order is 'F') contiguous or either one (order is 'A')</param>
public bool IsContiguous(BufferOrderStyle order)
{
if (disposedValue)
throw new ObjectDisposedException(nameof(PyBuffer));
return Convert.ToBoolean(Runtime.PyBuffer_IsContiguous(ref _view, OrderStyleToChar(order, true)));
}
/// <summary>
/// Get the memory area pointed to by the indices inside the given view. indices must point to an array of view->ndim indices.
/// </summary>
public IntPtr GetPointer(long[] indices)
{
if (disposedValue)
throw new ObjectDisposedException(nameof(PyBuffer));
if (Runtime.PyVersion < new Version(3, 7))
throw new NotSupportedException("GetPointer requires at least Python 3.7");
return Runtime.PyBuffer_GetPointer(ref _view, indices.Select(x => (IntPtr)x).ToArray());
}
/// <summary>
/// Copy contiguous len bytes from buf to view. fort can be 'C' or 'F' (for C-style or Fortran-style ordering).
/// </summary>
public void FromContiguous(IntPtr buf, long len, BufferOrderStyle fort)
{
if (disposedValue)
throw new ObjectDisposedException(nameof(PyBuffer));
if (Runtime.PyVersion < new Version(3, 7))
throw new NotSupportedException("FromContiguous requires at least Python 3.7");
if (Runtime.PyBuffer_FromContiguous(ref _view, buf, (IntPtr)len, OrderStyleToChar(fort, false)) < 0)
throw new PythonException();
}
/// <summary>
/// Copy len bytes from view to its contiguous representation in buf. order can be 'C' or 'F' or 'A' (for C-style or Fortran-style ordering or either one). 0 is returned on success, -1 on error.
/// </summary>
/// <param name="order">order can be 'C' or 'F' or 'A' (for C-style or Fortran-style ordering or either one).</param>
/// <param name="buf">Buffer to copy to</param>
public void ToContiguous(IntPtr buf, BufferOrderStyle order)
{
if (disposedValue)
throw new ObjectDisposedException(nameof(PyBuffer));
if (Runtime.PyBuffer_ToContiguous(buf, ref _view, _view.len, OrderStyleToChar(order, true)) < 0)
throw new PythonException();
}
/// <summary>
/// Fill the strides array with byte-strides of a contiguous (C-style if order is 'C' or Fortran-style if order is 'F') array of the given shape with the given number of bytes per element.
/// </summary>
public static void FillContiguousStrides(int ndims, IntPtr shape, IntPtr strides, int itemsize, BufferOrderStyle order)
{
Runtime.PyBuffer_FillContiguousStrides(ndims, shape, strides, itemsize, OrderStyleToChar(order, false));
}
/// <summary>
/// FillInfo Method
/// </summary>
/// <remarks>
/// Handle buffer requests for an exporter that wants to expose buf of size len with writability set according to readonly. buf is interpreted as a sequence of unsigned bytes.
/// The flags argument indicates the request type. This function always fills in view as specified by flags, unless buf has been designated as read-only and PyBUF_WRITABLE is set in flags.
/// On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise PyExc_BufferError, set view->obj to NULL and return -1;
/// If this function is used as part of a getbufferproc, exporter MUST be set to the exporting object and flags must be passed unmodified.Otherwise, exporter MUST be NULL.
/// </remarks>
/// <returns>On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise PyExc_BufferError, set view->obj to NULL and return -1;</returns>
public void FillInfo(IntPtr exporter, IntPtr buf, long len, bool _readonly, int flags)
{
if (disposedValue)
throw new ObjectDisposedException(nameof(PyBuffer));
if (Runtime.PyBuffer_FillInfo(ref _view, exporter, buf, (IntPtr)len, Convert.ToInt32(_readonly), flags) < 0)
throw new PythonException();
}
/// <summary>
/// Writes a managed byte array into the buffer of a python object. This can be used to pass data like images from managed to python.
/// </summary>
public void Write(byte[] buffer, int offset, int count)
{
if (disposedValue)
throw new ObjectDisposedException(nameof(PyBuffer));
if (ReadOnly)
throw new InvalidOperationException("Buffer is read-only");
if ((long)_view.len > int.MaxValue)
throw new NotSupportedException("Python buffers bigger than int.MaxValue are not supported.");
if (count > buffer.Length)
throw new ArgumentOutOfRangeException("count", "Count is bigger than the buffer.");
if (count > (int)_view.len)
throw new ArgumentOutOfRangeException("count", "Count is bigger than the python buffer.");
if (_view.ndim != 1)
throw new NotSupportedException("Multidimensional arrays, scalars and objects without a buffer are not supported.");
Marshal.Copy(buffer, offset, _view.buf, count);
}
/// <summary>
/// Reads the buffer of a python object into a managed byte array. This can be used to pass data like images from python to managed.
/// </summary>
public int Read(byte[] buffer, int offset, int count) {
if (disposedValue)
throw new ObjectDisposedException(nameof(PyBuffer));
if (count > buffer.Length)
throw new ArgumentOutOfRangeException("count", "Count is bigger than the buffer.");
if (_view.ndim != 1)
throw new NotSupportedException("Multidimensional arrays, scalars and objects without a buffer are not supported.");
if (_view.len.ToInt64() > int.MaxValue)
throw new NotSupportedException("Python buffers bigger than int.MaxValue are not supported.");
int copylen = count < (int)_view.len ? count : (int)_view.len;
Marshal.Copy(_view.buf, buffer, offset, copylen);
return copylen;
}
private bool disposedValue = false; // To detect redundant calls
private void Dispose(bool disposing)
{
if (!disposedValue)
{
if (Runtime.Py_IsInitialized() == 0)
throw new InvalidOperationException("Python runtime must be initialized");
// this also decrements ref count for _view->obj
Runtime.PyBuffer_Release(ref _view);
_exporter = null;
Shape = null;
Strides = null;
SubOffsets = null;
disposedValue = true;
}
}
~PyBuffer()
{
if (disposedValue)
{
return;
}
Finalizer.Instance.AddFinalizedObject(ref _view.obj);
}
/// <summary>
/// Release the buffer view and decrement the reference count for view->obj. This function MUST be called when the buffer is no longer being used, otherwise reference leaks may occur.
/// It is an error to call this function on a buffer that was not obtained via <see cref="PyObject.GetBuffer"/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
// 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.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class TypeManager
{
private BSYMMGR _BSymmgr;
private PredefinedTypes _predefTypes;
private readonly TypeFactory _typeFactory;
private readonly TypeTable _typeTable;
private SymbolTable _symbolTable;
// Special types
private readonly VoidType _voidType;
private readonly NullType _nullType;
private readonly MethodGroupType _typeMethGrp;
private readonly ArgumentListType _argListType;
private readonly ErrorType _errorType;
private readonly StdTypeVarColl _stvcMethod;
private readonly StdTypeVarColl _stvcClass;
public TypeManager(BSYMMGR bsymmgr, PredefinedTypes predefTypes)
{
_typeFactory = new TypeFactory();
_typeTable = new TypeTable();
// special types with their own symbol kind.
_errorType = _typeFactory.CreateError(null);
_voidType = _typeFactory.CreateVoid();
_nullType = _typeFactory.CreateNull();
_typeMethGrp = _typeFactory.CreateMethodGroup();
_argListType = _typeFactory.CreateArgList();
_errorType.SetErrors(true);
_stvcMethod = new StdTypeVarColl();
_stvcClass = new StdTypeVarColl();
_BSymmgr = bsymmgr;
_predefTypes = predefTypes;
}
public void InitTypeFactory(SymbolTable table)
{
_symbolTable = table;
}
public SymbolTable SymbolTable => _symbolTable;
private sealed class StdTypeVarColl
{
private readonly List<TypeParameterType> prgptvs;
public StdTypeVarColl()
{
prgptvs = new List<TypeParameterType>();
}
////////////////////////////////////////////////////////////////////////////////
// Get the standard type variable (eg, !0, !1, or !!0, !!1).
//
// iv is the index.
// pbsm is the containing symbol manager
// fMeth designates whether this is a method type var or class type var
//
// The standard class type variables are useful during emit, but not for type
// comparison when binding. The standard method type variables are useful during
// binding for signature comparison.
public TypeParameterType GetTypeVarSym(int iv, TypeManager pTypeManager, bool fMeth)
{
Debug.Assert(iv >= 0);
TypeParameterType tpt;
if (iv >= this.prgptvs.Count)
{
TypeParameterSymbol pTypeParameter = new TypeParameterSymbol();
pTypeParameter.SetIsMethodTypeParameter(fMeth);
pTypeParameter.SetIndexInOwnParameters(iv);
pTypeParameter.SetIndexInTotalParameters(iv);
pTypeParameter.SetAccess(ACCESS.ACC_PRIVATE);
tpt = pTypeManager.GetTypeParameter(pTypeParameter);
this.prgptvs.Add(tpt);
}
else
{
tpt = this.prgptvs[iv];
}
Debug.Assert(tpt != null);
return tpt;
}
}
public ArrayType GetArray(CType elementType, int args, bool isSZArray)
{
Name name;
Debug.Assert(args > 0 && args < 32767);
Debug.Assert(args == 1 || !isSZArray);
switch (args)
{
case 1:
if (isSZArray)
{
goto case 2;
}
else
{
goto default;
}
case 2:
name = NameManager.GetPredefinedName(PredefinedName.PN_ARRAY0 + args);
break;
default:
name = NameManager.Add("[X" + args + 1);
break;
}
// See if we already have an array type of this element type and rank.
ArrayType pArray = _typeTable.LookupArray(name, elementType);
if (pArray == null)
{
// No existing array symbol. Create a new one.
pArray = _typeFactory.CreateArray(name, elementType, args, isSZArray);
pArray.InitFromParent();
_typeTable.InsertArray(name, elementType, pArray);
}
else
{
Debug.Assert(pArray.HasErrors() == elementType.HasErrors());
}
Debug.Assert(pArray.rank == args);
Debug.Assert(pArray.GetElementType() == elementType);
return pArray;
}
public AggregateType GetAggregate(AggregateSymbol agg, AggregateType atsOuter, TypeArray typeArgs)
{
Debug.Assert(agg.GetTypeManager() == this);
Debug.Assert(atsOuter == null || atsOuter.getAggregate() == agg.Parent, "");
if (typeArgs == null)
{
typeArgs = BSYMMGR.EmptyTypeArray();
}
Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count);
AggregateType pAggregate = _typeTable.LookupAggregate(agg, atsOuter, typeArgs);
if (pAggregate == null)
{
pAggregate = _typeFactory.CreateAggregateType(
agg,
typeArgs,
atsOuter
);
Debug.Assert(!pAggregate.fConstraintsChecked && !pAggregate.fConstraintError);
pAggregate.SetErrors(false);
_typeTable.InsertAggregate(agg, atsOuter, typeArgs, pAggregate);
}
else
{
Debug.Assert(!pAggregate.HasErrors());
}
Debug.Assert(pAggregate.getAggregate() == agg);
Debug.Assert(pAggregate.GetTypeArgsThis() != null && pAggregate.GetTypeArgsAll() != null);
Debug.Assert(pAggregate.GetTypeArgsThis() == typeArgs);
return pAggregate;
}
public AggregateType GetAggregate(AggregateSymbol agg, TypeArray typeArgsAll)
{
Debug.Assert(typeArgsAll != null && typeArgsAll.Count == agg.GetTypeVarsAll().Count);
if (typeArgsAll.Count == 0)
return agg.getThisType();
AggregateSymbol aggOuter = agg.GetOuterAgg();
if (aggOuter == null)
return GetAggregate(agg, null, typeArgsAll);
int cvarOuter = aggOuter.GetTypeVarsAll().Count;
Debug.Assert(cvarOuter <= typeArgsAll.Count);
TypeArray typeArgsOuter = _BSymmgr.AllocParams(cvarOuter, typeArgsAll, 0);
TypeArray typeArgsInner = _BSymmgr.AllocParams(agg.GetTypeVars().Count, typeArgsAll, cvarOuter);
AggregateType atsOuter = GetAggregate(aggOuter, typeArgsOuter);
return GetAggregate(agg, atsOuter, typeArgsInner);
}
public PointerType GetPointer(CType baseType)
{
PointerType pPointer = _typeTable.LookupPointer(baseType);
if (pPointer == null)
{
// No existing type. Create a new one.
Name namePtr = NameManager.GetPredefinedName(PredefinedName.PN_PTR);
pPointer = _typeFactory.CreatePointer(namePtr, baseType);
pPointer.InitFromParent();
_typeTable.InsertPointer(baseType, pPointer);
}
else
{
Debug.Assert(pPointer.HasErrors() == baseType.HasErrors());
}
Debug.Assert(pPointer.GetReferentType() == baseType);
return pPointer;
}
public NullableType GetNullable(CType pUnderlyingType)
{
if (pUnderlyingType is NullableType nt)
{
Debug.Fail("Attempt to make nullable of nullable");
return nt;
}
NullableType pNullableType = _typeTable.LookupNullable(pUnderlyingType);
if (pNullableType == null)
{
Name pName = NameManager.GetPredefinedName(PredefinedName.PN_NUB);
pNullableType = _typeFactory.CreateNullable(pName, pUnderlyingType, _BSymmgr, this);
pNullableType.InitFromParent();
_typeTable.InsertNullable(pUnderlyingType, pNullableType);
}
return pNullableType;
}
public NullableType GetNubFromNullable(AggregateType ats)
{
Debug.Assert(ats.isPredefType(PredefinedType.PT_G_OPTIONAL));
return GetNullable(ats.GetTypeArgsAll()[0]);
}
public ParameterModifierType GetParameterModifier(CType paramType, bool isOut)
{
Name name = NameManager.GetPredefinedName(isOut ? PredefinedName.PN_OUTPARAM : PredefinedName.PN_REFPARAM);
ParameterModifierType pParamModifier = _typeTable.LookupParameterModifier(name, paramType);
if (pParamModifier == null)
{
// No existing parammod symbol. Create a new one.
pParamModifier = _typeFactory.CreateParameterModifier(name, paramType);
pParamModifier.isOut = isOut;
pParamModifier.InitFromParent();
_typeTable.InsertParameterModifier(name, paramType, pParamModifier);
}
else
{
Debug.Assert(pParamModifier.HasErrors() == paramType.HasErrors());
}
Debug.Assert(pParamModifier.GetParameterType() == paramType);
return pParamModifier;
}
public ErrorType GetErrorType(Name nameText)
{
Debug.Assert(nameText != null);
ErrorType pError = _typeTable.LookupError(nameText);
if (pError == null)
{
// No existing error symbol. Create a new one.
pError = _typeFactory.CreateError(nameText);
pError.SetErrors(true);
_typeTable.InsertError(nameText, pError);
}
else
{
Debug.Assert(pError.HasErrors());
Debug.Assert(pError.nameText == nameText);
}
return pError;
}
public VoidType GetVoid()
{
return _voidType;
}
public NullType GetNullType()
{
return _nullType;
}
public MethodGroupType GetMethGrpType()
{
return _typeMethGrp;
}
public ArgumentListType GetArgListType()
{
return _argListType;
}
public ErrorType GetErrorSym()
{
return _errorType;
}
public AggregateSymbol GetNullable() => GetPredefAgg(PredefinedType.PT_G_OPTIONAL);
private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (typeSrc == null)
return null;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
return ctx.FNop() ? typeSrc : SubstTypeCore(typeSrc, ctx);
}
public AggregateType SubstType(AggregateType typeSrc, TypeArray typeArgsCls)
{
if (typeSrc != null)
{
SubstContext ctx = new SubstContext(typeArgsCls, null, SubstTypeFlags.NormNone);
if (!ctx.FNop())
{
return SubstTypeCore(typeSrc, ctx);
}
}
return typeSrc;
}
private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone);
}
public TypeArray SubstTypeArray(TypeArray taSrc, SubstContext ctx)
{
if (taSrc != null && taSrc.Count != 0 && ctx != null && !ctx.FNop())
{
CType[] srcs = taSrc.Items;
for (int i = 0; i < srcs.Length; i++)
{
CType src = srcs[i];
CType dst = SubstTypeCore(src, ctx);
if (src != dst)
{
CType[] dsts = new CType[srcs.Length];
Array.Copy(srcs, dsts, i);
dsts[i] = dst;
while (++i < srcs.Length)
{
dsts[i] = SubstTypeCore(srcs[i], ctx);
}
return _BSymmgr.AllocParams(dsts);
}
}
}
return taSrc;
}
public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
=> taSrc == null || taSrc.Count == 0
? taSrc
: SubstTypeArray(taSrc, new SubstContext(typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone));
public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls) => SubstTypeArray(taSrc, typeArgsCls, null);
private AggregateType SubstTypeCore(AggregateType type, SubstContext ctx)
{
TypeArray args = type.GetTypeArgsAll();
if (args.Count > 0)
{
TypeArray typeArgs = SubstTypeArray(args, ctx);
if (args != typeArgs)
{
return GetAggregate(type.getAggregate(), typeArgs);
}
}
return type;
}
private CType SubstTypeCore(CType type, SubstContext pctx)
{
CType typeSrc;
CType typeDst;
switch (type.GetTypeKind())
{
default:
Debug.Assert(false);
return type;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_ArgumentListType:
case TypeKind.TK_ErrorType:
return type;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType mod = (ParameterModifierType)type;
typeDst = SubstTypeCore(typeSrc = mod.GetParameterType(), pctx);
return (typeDst == typeSrc) ? type : GetParameterModifier(typeDst, mod.isOut);
case TypeKind.TK_ArrayType:
var arr = (ArrayType)type;
typeDst = SubstTypeCore(typeSrc = arr.GetElementType(), pctx);
return (typeDst == typeSrc) ? type : GetArray(typeDst, arr.rank, arr.IsSZArray);
case TypeKind.TK_PointerType:
typeDst = SubstTypeCore(typeSrc = ((PointerType)type).GetReferentType(), pctx);
return (typeDst == typeSrc) ? type : GetPointer(typeDst);
case TypeKind.TK_NullableType:
typeDst = SubstTypeCore(typeSrc = ((NullableType)type).GetUnderlyingType(), pctx);
return (typeDst == typeSrc) ? type : GetNullable(typeDst);
case TypeKind.TK_AggregateType:
return SubstTypeCore((AggregateType)type, pctx);
case TypeKind.TK_TypeParameterType:
{
TypeParameterSymbol tvs = ((TypeParameterType)type).GetTypeParameterSymbol();
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null)
return type;
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
if (index < pctx.ctypeMeth)
{
Debug.Assert(pctx.prgtypeMeth != null);
return pctx.prgtypeMeth[index];
}
else
{
return ((pctx.grfst & SubstTypeFlags.NormMeth) != 0 ? GetStdMethTypeVar(index) : type);
}
}
if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null)
return type;
return index < pctx.ctypeCls ? pctx.prgtypeCls[index] :
((pctx.grfst & SubstTypeFlags.NormClass) != 0 ? GetStdClsTypeVar(index) : type);
}
}
}
public bool SubstEqualTypes(CType typeDst, CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (typeDst.Equals(typeSrc))
{
Debug.Assert(typeDst.Equals(SubstType(typeSrc, typeArgsCls, typeArgsMeth, grfst)));
return true;
}
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
return !ctx.FNop() && SubstEqualTypesCore(typeDst, typeSrc, ctx);
}
public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
// Handle the simple common cases first.
if (taDst == taSrc || (taDst != null && taDst.Equals(taSrc)))
{
// The following assertion is not always true and indicates a problem where
// the signature of override method does not match the one inherited from
// the base class. The method match we have found does not take the type
// arguments of the base class into account. So actually we are not overriding
// the method that we "intend" to.
// Debug.Assert(taDst == SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, grfst));
return true;
}
if (taDst.Count != taSrc.Count)
return false;
if (taDst.Count == 0)
return true;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
if (ctx.FNop())
return false;
for (int i = 0; i < taDst.Count; i++)
{
if (!SubstEqualTypesCore(taDst[i], taSrc[i], ctx))
return false;
}
return true;
}
private bool SubstEqualTypesCore(CType typeDst, CType typeSrc, SubstContext pctx)
{
LRecurse: // Label used for "tail" recursion.
if (typeDst == typeSrc || typeDst.Equals(typeSrc))
{
return true;
}
switch (typeSrc.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in SubstEqualTypesCore");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeDst.GetTypeKind() != typeSrc.GetTypeKind());
return false;
case TypeKind.TK_ArrayType:
ArrayType arrSrc = (ArrayType)typeSrc;
if (!(typeDst is ArrayType arrDst) || arrDst.rank != arrSrc.rank || arrDst.IsSZArray != arrSrc.IsSZArray)
return false;
goto LCheckBases;
case TypeKind.TK_ParameterModifierType:
if (!(typeDst is ParameterModifierType modDest) ||
((pctx.grfst & SubstTypeFlags.NoRefOutDifference) == 0 &&
modDest.isOut != ((ParameterModifierType)typeSrc).isOut))
return false;
goto LCheckBases;
case TypeKind.TK_PointerType:
case TypeKind.TK_NullableType:
if (typeDst.GetTypeKind() != typeSrc.GetTypeKind())
return false;
LCheckBases:
typeSrc = typeSrc.GetBaseOrParameterOrElementType();
typeDst = typeDst.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
if (!(typeDst is AggregateType atsDst))
return false;
{ // BLOCK
AggregateType atsSrc = (AggregateType)typeSrc;
if (atsSrc.getAggregate() != atsDst.getAggregate())
return false;
Debug.Assert(atsSrc.GetTypeArgsAll().Count == atsDst.GetTypeArgsAll().Count);
// All the args must unify.
for (int i = 0; i < atsSrc.GetTypeArgsAll().Count; i++)
{
if (!SubstEqualTypesCore(atsDst.GetTypeArgsAll()[i], atsSrc.GetTypeArgsAll()[i], pctx))
return false;
}
}
return true;
case TypeKind.TK_ErrorType:
ErrorType errSrc = (ErrorType)typeSrc;
if (!(typeDst is ErrorType errDst))
{
return false;
}
Name srcName = errSrc.nameText;
return srcName != null && errSrc.nameText == errDst.nameText;
case TypeKind.TK_TypeParameterType:
{ // BLOCK
TypeParameterSymbol tvs = ((TypeParameterType)typeSrc).GetTypeParameterSymbol();
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
Debug.Assert(pctx.prgtypeMeth == null || tvs.GetIndexInTotalParameters() < pctx.ctypeMeth);
if (index < pctx.ctypeMeth && pctx.prgtypeMeth != null)
{
return typeDst == pctx.prgtypeMeth[index];
}
if ((pctx.grfst & SubstTypeFlags.NormMeth) != 0)
{
return typeDst == GetStdMethTypeVar(index);
}
}
else
{
if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(pctx.prgtypeCls == null || tvs.GetIndexInTotalParameters() < pctx.ctypeCls);
if (index < pctx.ctypeCls)
return typeDst == pctx.prgtypeCls[index];
if ((pctx.grfst & SubstTypeFlags.NormClass) != 0)
return typeDst == GetStdClsTypeVar(index);
}
}
return false;
}
}
public static bool TypeContainsType(CType type, CType typeFind)
{
LRecurse: // Label used for "tail" recursion.
if (type == typeFind || type.Equals(typeFind))
return true;
switch (type.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in TypeContainsType");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeFind.GetTypeKind() != type.GetTypeKind());
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.GetTypeArgsAll().Count; i++)
{
if (TypeContainsType(ats.GetTypeArgsAll()[i], typeFind))
return true;
}
}
return false;
case TypeKind.TK_ErrorType:
case TypeKind.TK_TypeParameterType:
return false;
}
}
public static bool TypeContainsTyVars(CType type, TypeArray typeVars)
{
LRecurse: // Label used for "tail" recursion.
switch (type.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in TypeContainsTyVars");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_ErrorType:
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.GetTypeArgsAll().Count; i++)
{
if (TypeContainsTyVars(ats.GetTypeArgsAll()[i], typeVars))
{
return true;
}
}
}
return false;
case TypeKind.TK_TypeParameterType:
if (typeVars != null && typeVars.Count > 0)
{
int ivar = ((TypeParameterType)type).GetIndexInTotalParameters();
return ivar < typeVars.Count && type == typeVars[ivar];
}
return true;
}
}
public static bool ParametersContainTyVar(TypeArray @params, TypeParameterType typeFind)
{
Debug.Assert(@params != null);
Debug.Assert(typeFind != null);
for (int p = 0; p < @params.Count; p++)
{
CType sym = @params[p];
if (TypeContainsType(sym, typeFind))
{
return true;
}
}
return false;
}
public AggregateSymbol GetPredefAgg(PredefinedType pt) => _predefTypes.GetPredefinedAggregate(pt);
public TypeArray ConcatenateTypeArrays(TypeArray pTypeArray1, TypeArray pTypeArray2)
{
return _BSymmgr.ConcatParams(pTypeArray1, pTypeArray2);
}
public TypeArray GetStdMethTyVarArray(int cTyVars)
{
TypeParameterType[] prgvar = new TypeParameterType[cTyVars];
for (int ivar = 0; ivar < cTyVars; ivar++)
{
prgvar[ivar] = GetStdMethTypeVar(ivar);
}
return _BSymmgr.AllocParams(cTyVars, (CType[])prgvar);
}
public AggregateType SubstType(AggregateType typeSrc, SubstContext ctx) =>
ctx == null || ctx.FNop() ? typeSrc : SubstTypeCore(typeSrc, ctx);
public CType SubstType(CType typeSrc, SubstContext pctx)
{
return (pctx == null || pctx.FNop()) ? typeSrc : SubstTypeCore(typeSrc, pctx);
}
public CType SubstType(CType typeSrc, AggregateType atsCls)
{
return SubstType(typeSrc, atsCls, (TypeArray)null);
}
public CType SubstType(CType typeSrc, AggregateType atsCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth);
}
public CType SubstType(CType typeSrc, CType typeCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, (typeCls as AggregateType)?.GetTypeArgsAll(), typeArgsMeth);
}
public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth)
{
return SubstTypeArray(taSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth);
}
public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls)
{
return this.SubstTypeArray(taSrc, atsCls, (TypeArray)null);
}
private bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls, TypeArray typeArgsMeth)
{
return SubstEqualTypes(typeDst, typeSrc, (typeCls as AggregateType)?.GetTypeArgsAll(), typeArgsMeth, SubstTypeFlags.NormNone);
}
public bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls)
{
return SubstEqualTypes(typeDst, typeSrc, typeCls, (TypeArray)null);
}
//public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth)
//{
// return SubstEqualTypeArrays(taDst, taSrc, atsCls != null ? atsCls.GetTypeArgsAll() : (TypeArray)null, typeArgsMeth, SubstTypeFlags.NormNone);
//}
public TypeParameterType GetStdMethTypeVar(int iv)
{
return _stvcMethod.GetTypeVarSym(iv, this, true);
}
private TypeParameterType GetStdClsTypeVar(int iv)
{
return _stvcClass.GetTypeVarSym(iv, this, false);
}
// These are singletons for each.
public TypeParameterType GetTypeParameter(TypeParameterSymbol pSymbol)
{
Debug.Assert(pSymbol.GetTypeParameterType() == null); // Should have been checked first before creating
return _typeFactory.CreateTypeParameter(pSymbol);
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal bool GetBestAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, CType typeSrc, out CType typeDst)
{
// This method implements the "best accessible type" algorithm for determining the type
// of untyped arguments in the runtime binder. It is also used in method type inference
// to fix type arguments to types that are accessible.
// The new type is returned in an out parameter. The result will be true (and the out param
// non-null) only when the algorithm could find a suitable accessible type.
Debug.Assert(semanticChecker != null);
Debug.Assert(bindingContext != null);
Debug.Assert(typeSrc != null);
typeDst = null;
if (semanticChecker.CheckTypeAccess(typeSrc, bindingContext.ContextForMemberLookup))
{
// If we already have an accessible type, then use it. This is the terminal point of the recursion.
typeDst = typeSrc;
return true;
}
// These guys have no accessibility concerns.
Debug.Assert(!(typeSrc is VoidType) && !(typeSrc is ErrorType) && !(typeSrc is TypeParameterType));
if (typeSrc is ParameterModifierType || typeSrc is PointerType)
{
// We cannot vary these.
return false;
}
CType intermediateType;
if (typeSrc is AggregateType aggSrc && (aggSrc.isInterfaceType() || aggSrc.isDelegateType()) && TryVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, aggSrc, out intermediateType))
{
// If we have an interface or delegate type, then it can potentially be varied by its type arguments
// to produce an accessible type, and if that's the case, then return that.
// Example: IEnumerable<PrivateConcreteFoo> --> IEnumerable<PublicAbstractFoo>
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc is ArrayType arrSrc && TryArrayVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, arrSrc, out intermediateType))
{
// Similarly to the interface and delegate case, arrays are covariant in their element type and
// so we can potentially produce an array type that is accessible.
// Example: PrivateConcreteFoo[] --> PublicAbstractFoo[]
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc is NullableType)
{
// We have an inaccessible nullable type, which means that the best we can do is System.ValueType.
typeDst = GetPredefAgg(PredefinedType.PT_VALUE).getThisType();
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc is ArrayType)
{
// We have an inaccessible array type for which we could not earlier find a better array type
// with a covariant conversion, so the best we can do is System.Array.
typeDst = GetPredefAgg(PredefinedType.PT_ARRAY).getThisType();
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
Debug.Assert(typeSrc is AggregateType);
if (typeSrc is AggregateType aggType)
{
// We have an AggregateType, so recurse on its base class.
AggregateType baseType = aggType.GetBaseClass();
if (baseType == null)
{
// This happens with interfaces, for instance. But in that case, the
// conversion to object does exist, is an implicit reference conversion,
// and so we will use it.
baseType = GetPredefAgg(PredefinedType.PT_OBJECT).getThisType();
}
return GetBestAccessibleType(semanticChecker, bindingContext, baseType, out typeDst);
}
return false;
}
private bool TryVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, AggregateType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
Debug.Assert(typeSrc.isInterfaceType() || typeSrc.isDelegateType());
typeDst = null;
AggregateSymbol aggSym = typeSrc.GetOwningAggregate();
AggregateType aggOpenType = aggSym.getThisType();
if (!semanticChecker.CheckTypeAccess(aggOpenType, bindingContext.ContextForMemberLookup))
{
// if the aggregate symbol itself is not accessible, then forget it, there is no
// variance that will help us arrive at an accessible type.
return false;
}
TypeArray typeArgs = typeSrc.GetTypeArgsThis();
TypeArray typeParams = aggOpenType.GetTypeArgsThis();
CType[] newTypeArgsTemp = new CType[typeArgs.Count];
for (int i = 0; i < typeArgs.Count; i++)
{
if (semanticChecker.CheckTypeAccess(typeArgs[i], bindingContext.ContextForMemberLookup))
{
// we have an accessible argument, this position is not a problem.
newTypeArgsTemp[i] = typeArgs[i];
continue;
}
if (!typeArgs[i].IsRefType() || !((TypeParameterType)typeParams[i]).Covariant)
{
// This guy is inaccessible, and we are not going to be able to vary him, so we need to fail.
return false;
}
CType intermediateTypeArg;
if (GetBestAccessibleType(semanticChecker, bindingContext, typeArgs[i], out intermediateTypeArg))
{
// now we either have a value type (which must be accessible due to the above
// check, OR we have an inaccessible type (which must be a ref type). In either
// case, the recursion worked out and we are OK to vary this argument.
newTypeArgsTemp[i] = intermediateTypeArg;
continue;
}
else
{
Debug.Assert(false, "GetBestAccessibleType unexpectedly failed on a type that was used as a type parameter");
return false;
}
}
TypeArray newTypeArgs = semanticChecker.getBSymmgr().AllocParams(typeArgs.Count, newTypeArgsTemp);
CType intermediateType = this.GetAggregate(aggSym, typeSrc.outerType, newTypeArgs);
// All type arguments were varied successfully, which means now we must be accessible. But we could
// have violated constraints. Let's check that out.
if (!TypeBind.CheckConstraints(semanticChecker, null/*ErrorHandling*/, intermediateType, CheckConstraintsFlags.NoErrors))
{
return false;
}
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
private bool TryArrayVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, ArrayType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
typeDst = null;
// We are here because we have an array type with an inaccessible element type. If possible,
// we should create a new array type that has an accessible element type for which a
// conversion exists.
CType elementType = typeSrc.GetElementType();
if (!elementType.IsRefType())
{
// Covariant array conversions exist for reference types only.
return false;
}
CType intermediateType;
if (GetBestAccessibleType(semanticChecker, bindingContext, elementType, out intermediateType))
{
typeDst = this.GetArray(intermediateType, typeSrc.rank, typeSrc.IsSZArray);
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
return false;
}
public AggregateType ObjectAggregateType => (AggregateType)_symbolTable.GetCTypeFromType(typeof(object));
private readonly Dictionary<Tuple<Assembly, Assembly>, bool> _internalsVisibleToCalculated
= new Dictionary<Tuple<Assembly, Assembly>, bool>();
internal bool InternalsVisibleTo(Assembly assemblyThatDefinesAttribute, Assembly assemblyToCheck)
{
bool result;
var key = Tuple.Create(assemblyThatDefinesAttribute, assemblyToCheck);
if (!_internalsVisibleToCalculated.TryGetValue(key, out result))
{
AssemblyName assyName;
// Assembly.GetName() requires FileIOPermission to FileIOPermissionAccess.PathDiscovery.
// If we don't have that (we're in low trust), then we are going to effectively turn off
// InternalsVisibleTo. The alternative is to crash when this happens.
try
{
assyName = assemblyToCheck.GetName();
}
catch (System.Security.SecurityException)
{
result = false;
goto SetMemo;
}
result = assemblyThatDefinesAttribute.GetCustomAttributes()
.OfType<InternalsVisibleToAttribute>()
.Select(ivta => new AssemblyName(ivta.AssemblyName))
.Any(an => AssemblyName.ReferenceMatchesDefinition(an, assyName));
SetMemo:
_internalsVisibleToCalculated[key] = result;
}
return result;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// END RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
| |
/*
* 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:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// Pool-wide updates to the host software
/// First published in XenServer 7.1.
/// </summary>
public partial class Pool_update : XenObject<Pool_update>
{
public Pool_update()
{
}
public Pool_update(string uuid,
string name_label,
string name_description,
string version,
long installation_size,
string key,
List<update_after_apply_guidance> after_apply_guidance,
XenRef<VDI> vdi,
List<XenRef<Host>> hosts,
Dictionary<string, string> other_config,
bool enforce_homogeneity)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.installation_size = installation_size;
this.key = key;
this.after_apply_guidance = after_apply_guidance;
this.vdi = vdi;
this.hosts = hosts;
this.other_config = other_config;
this.enforce_homogeneity = enforce_homogeneity;
}
/// <summary>
/// Creates a new Pool_update from a Proxy_Pool_update.
/// </summary>
/// <param name="proxy"></param>
public Pool_update(Proxy_Pool_update proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Pool_update.
/// </summary>
public override void UpdateFrom(Pool_update update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
version = update.version;
installation_size = update.installation_size;
key = update.key;
after_apply_guidance = update.after_apply_guidance;
vdi = update.vdi;
hosts = update.hosts;
other_config = update.other_config;
enforce_homogeneity = update.enforce_homogeneity;
}
internal void UpdateFromProxy(Proxy_Pool_update proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
name_label = proxy.name_label == null ? null : (string)proxy.name_label;
name_description = proxy.name_description == null ? null : (string)proxy.name_description;
version = proxy.version == null ? null : (string)proxy.version;
installation_size = proxy.installation_size == null ? 0 : long.Parse((string)proxy.installation_size);
key = proxy.key == null ? null : (string)proxy.key;
after_apply_guidance = proxy.after_apply_guidance == null ? null : Helper.StringArrayToEnumList<update_after_apply_guidance>(proxy.after_apply_guidance);
vdi = proxy.vdi == null ? null : XenRef<VDI>.Create(proxy.vdi);
hosts = proxy.hosts == null ? null : XenRef<Host>.Create(proxy.hosts);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
enforce_homogeneity = (bool)proxy.enforce_homogeneity;
}
public Proxy_Pool_update ToProxy()
{
Proxy_Pool_update result_ = new Proxy_Pool_update();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.version = version ?? "";
result_.installation_size = installation_size.ToString();
result_.key = key ?? "";
result_.after_apply_guidance = (after_apply_guidance != null) ? Helper.ObjectListToStringArray(after_apply_guidance) : new string[] {};
result_.vdi = vdi ?? "";
result_.hosts = (hosts != null) ? Helper.RefListToStringArray(hosts) : new string[] {};
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
result_.enforce_homogeneity = enforce_homogeneity;
return result_;
}
/// <summary>
/// Creates a new Pool_update from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Pool_update(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Pool_update
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("installation_size"))
installation_size = Marshalling.ParseLong(table, "installation_size");
if (table.ContainsKey("key"))
key = Marshalling.ParseString(table, "key");
if (table.ContainsKey("after_apply_guidance"))
after_apply_guidance = Helper.StringArrayToEnumList<update_after_apply_guidance>(Marshalling.ParseStringArray(table, "after_apply_guidance"));
if (table.ContainsKey("vdi"))
vdi = Marshalling.ParseRef<VDI>(table, "vdi");
if (table.ContainsKey("hosts"))
hosts = Marshalling.ParseSetRef<Host>(table, "hosts");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
if (table.ContainsKey("enforce_homogeneity"))
enforce_homogeneity = Marshalling.ParseBool(table, "enforce_homogeneity");
}
public bool DeepEquals(Pool_update other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._installation_size, other._installation_size) &&
Helper.AreEqual2(this._key, other._key) &&
Helper.AreEqual2(this._after_apply_guidance, other._after_apply_guidance) &&
Helper.AreEqual2(this._vdi, other._vdi) &&
Helper.AreEqual2(this._hosts, other._hosts) &&
Helper.AreEqual2(this._other_config, other._other_config) &&
Helper.AreEqual2(this._enforce_homogeneity, other._enforce_homogeneity);
}
internal static List<Pool_update> ProxyArrayToObjectList(Proxy_Pool_update[] input)
{
var result = new List<Pool_update>();
foreach (var item in input)
result.Add(new Pool_update(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Pool_update server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Pool_update.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static Pool_update get_record(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_record(session.opaque_ref, _pool_update);
else
return new Pool_update((Proxy_Pool_update)session.proxy.pool_update_get_record(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get a reference to the pool_update instance with the specified UUID.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Pool_update> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Pool_update>.Create(session.proxy.pool_update_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the pool_update instances with the given label.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
public static List<XenRef<Pool_update>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Pool_update>.Create(session.proxy.pool_update_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_uuid(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_uuid(session.opaque_ref, _pool_update);
else
return (string)session.proxy.pool_update_get_uuid(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_name_label(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_name_label(session.opaque_ref, _pool_update);
else
return (string)session.proxy.pool_update_get_name_label(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_name_description(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_name_description(session.opaque_ref, _pool_update);
else
return (string)session.proxy.pool_update_get_name_description(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the version field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_version(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_version(session.opaque_ref, _pool_update);
else
return (string)session.proxy.pool_update_get_version(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the installation_size field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static long get_installation_size(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_installation_size(session.opaque_ref, _pool_update);
else
return long.Parse((string)session.proxy.pool_update_get_installation_size(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the key field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static string get_key(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_key(session.opaque_ref, _pool_update);
else
return (string)session.proxy.pool_update_get_key(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Get the after_apply_guidance field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static List<update_after_apply_guidance> get_after_apply_guidance(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_after_apply_guidance(session.opaque_ref, _pool_update);
else
return Helper.StringArrayToEnumList<update_after_apply_guidance>(session.proxy.pool_update_get_after_apply_guidance(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the vdi field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<VDI> get_vdi(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_vdi(session.opaque_ref, _pool_update);
else
return XenRef<VDI>.Create(session.proxy.pool_update_get_vdi(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the hosts field of the given pool_update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static List<XenRef<Host>> get_hosts(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_hosts(session.opaque_ref, _pool_update);
else
return XenRef<Host>.Create(session.proxy.pool_update_get_hosts(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static Dictionary<string, string> get_other_config(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_other_config(session.opaque_ref, _pool_update);
else
return Maps.convert_from_proxy_string_string(session.proxy.pool_update_get_other_config(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Get the enforce_homogeneity field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static bool get_enforce_homogeneity(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_enforce_homogeneity(session.opaque_ref, _pool_update);
else
return (bool)session.proxy.pool_update_get_enforce_homogeneity(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pool_update, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_set_other_config(session.opaque_ref, _pool_update, _other_config);
else
session.proxy.pool_update_set_other_config(session.opaque_ref, _pool_update ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given pool_update.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pool_update, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_add_to_other_config(session.opaque_ref, _pool_update, _key, _value);
else
session.proxy.pool_update_add_to_other_config(session.opaque_ref, _pool_update ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given pool_update. If the key is not in that Map, then do nothing.
/// First published in XenServer 7.3.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pool_update, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_remove_from_other_config(session.opaque_ref, _pool_update, _key);
else
session.proxy.pool_update_remove_from_other_config(session.opaque_ref, _pool_update ?? "", _key ?? "").parse();
}
/// <summary>
/// Introduce update VDI
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vdi">The VDI which contains a software update.</param>
public static XenRef<Pool_update> introduce(Session session, string _vdi)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_introduce(session.opaque_ref, _vdi);
else
return XenRef<Pool_update>.Create(session.proxy.pool_update_introduce(session.opaque_ref, _vdi ?? "").parse());
}
/// <summary>
/// Introduce update VDI
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vdi">The VDI which contains a software update.</param>
public static XenRef<Task> async_introduce(Session session, string _vdi)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_introduce(session.opaque_ref, _vdi);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_introduce(session.opaque_ref, _vdi ?? "").parse());
}
/// <summary>
/// Execute the precheck stage of the selected update on a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to run the prechecks on.</param>
public static livepatch_status precheck(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_precheck(session.opaque_ref, _pool_update, _host);
else
return (livepatch_status)Helper.EnumParseDefault(typeof(livepatch_status), (string)session.proxy.pool_update_precheck(session.opaque_ref, _pool_update ?? "", _host ?? "").parse());
}
/// <summary>
/// Execute the precheck stage of the selected update on a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to run the prechecks on.</param>
public static XenRef<Task> async_precheck(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_precheck(session.opaque_ref, _pool_update, _host);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_precheck(session.opaque_ref, _pool_update ?? "", _host ?? "").parse());
}
/// <summary>
/// Apply the selected update to a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to apply the update to.</param>
public static void apply(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_apply(session.opaque_ref, _pool_update, _host);
else
session.proxy.pool_update_apply(session.opaque_ref, _pool_update ?? "", _host ?? "").parse();
}
/// <summary>
/// Apply the selected update to a host
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
/// <param name="_host">The host to apply the update to.</param>
public static XenRef<Task> async_apply(Session session, string _pool_update, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_apply(session.opaque_ref, _pool_update, _host);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_apply(session.opaque_ref, _pool_update ?? "", _host ?? "").parse());
}
/// <summary>
/// Apply the selected update to all hosts in the pool
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static void pool_apply(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_pool_apply(session.opaque_ref, _pool_update);
else
session.proxy.pool_update_pool_apply(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Apply the selected update to all hosts in the pool
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<Task> async_pool_apply(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_pool_apply(session.opaque_ref, _pool_update);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_pool_apply(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Removes the update's files from all hosts in the pool, but does not revert the update
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static void pool_clean(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_pool_clean(session.opaque_ref, _pool_update);
else
session.proxy.pool_update_pool_clean(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Removes the update's files from all hosts in the pool, but does not revert the update
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<Task> async_pool_clean(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_pool_clean(session.opaque_ref, _pool_update);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_pool_clean(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Removes the database entry. Only works on unapplied update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static void destroy(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_update_destroy(session.opaque_ref, _pool_update);
else
session.proxy.pool_update_destroy(session.opaque_ref, _pool_update ?? "").parse();
}
/// <summary>
/// Removes the database entry. Only works on unapplied update.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_update">The opaque_ref of the given pool_update</param>
public static XenRef<Task> async_destroy(Session session, string _pool_update)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_update_destroy(session.opaque_ref, _pool_update);
else
return XenRef<Task>.Create(session.proxy.async_pool_update_destroy(session.opaque_ref, _pool_update ?? "").parse());
}
/// <summary>
/// Return a list of all the pool_updates known to the system.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Pool_update>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_all(session.opaque_ref);
else
return XenRef<Pool_update>.Create(session.proxy.pool_update_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the pool_update Records at once, in a single XML RPC call
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Pool_update>, Pool_update> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_update_get_all_records(session.opaque_ref);
else
return XenRef<Pool_update>.Create<Proxy_Pool_update>(session.proxy.pool_update_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
Changed = true;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
Changed = true;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Update version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
Changed = true;
NotifyPropertyChanged("version");
}
}
}
private string _version = "";
/// <summary>
/// Size of the update in bytes
/// </summary>
public virtual long installation_size
{
get { return _installation_size; }
set
{
if (!Helper.AreEqual(value, _installation_size))
{
_installation_size = value;
Changed = true;
NotifyPropertyChanged("installation_size");
}
}
}
private long _installation_size = 0;
/// <summary>
/// GPG key of the update
/// </summary>
public virtual string key
{
get { return _key; }
set
{
if (!Helper.AreEqual(value, _key))
{
_key = value;
Changed = true;
NotifyPropertyChanged("key");
}
}
}
private string _key = "";
/// <summary>
/// What the client should do after this update has been applied.
/// </summary>
public virtual List<update_after_apply_guidance> after_apply_guidance
{
get { return _after_apply_guidance; }
set
{
if (!Helper.AreEqual(value, _after_apply_guidance))
{
_after_apply_guidance = value;
Changed = true;
NotifyPropertyChanged("after_apply_guidance");
}
}
}
private List<update_after_apply_guidance> _after_apply_guidance = new List<update_after_apply_guidance>() {};
/// <summary>
/// VDI the update was uploaded to
/// </summary>
[JsonConverter(typeof(XenRefConverter<VDI>))]
public virtual XenRef<VDI> vdi
{
get { return _vdi; }
set
{
if (!Helper.AreEqual(value, _vdi))
{
_vdi = value;
Changed = true;
NotifyPropertyChanged("vdi");
}
}
}
private XenRef<VDI> _vdi = new XenRef<VDI>(Helper.NullOpaqueRef);
/// <summary>
/// The hosts that have applied this update.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Host>))]
public virtual List<XenRef<Host>> hosts
{
get { return _hosts; }
set
{
if (!Helper.AreEqual(value, _hosts))
{
_hosts = value;
Changed = true;
NotifyPropertyChanged("hosts");
}
}
}
private List<XenRef<Host>> _hosts = new List<XenRef<Host>>() {};
/// <summary>
/// additional configuration
/// First published in XenServer 7.3.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
/// <summary>
/// Flag - if true, all hosts in a pool must apply this update
/// First published in XenServer 7.3.
/// </summary>
public virtual bool enforce_homogeneity
{
get { return _enforce_homogeneity; }
set
{
if (!Helper.AreEqual(value, _enforce_homogeneity))
{
_enforce_homogeneity = value;
Changed = true;
NotifyPropertyChanged("enforce_homogeneity");
}
}
}
private bool _enforce_homogeneity = false;
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.DotNet.VersionTools.Dependencies;
#nullable enable
namespace Dotnet.Docker
{
/// <summary>
/// An IDependencyUpdater that will scan a Dockerfile for the .NET artifacts that are installed.
/// The updater will then retrieve and update the checksum sha used to validate the downloaded artifacts.
/// </summary>
public class DockerfileShaUpdater : FileRegexUpdater
{
private const string ReleaseDotnetBaseUrl = "https://dotnetcli.blob.core.windows.net/dotnet";
private const string ReleaseChecksumsBaseUrl = "https://dotnetclichecksums.blob.core.windows.net/dotnet";
private const string BuildsDotnetBaseUrl = "https://dotnetbuilds.blob.core.windows.net/public";
private const string BuildsChecksumsBaseUrl = "https://dotnetbuilds.blob.core.windows.net/public-checksums";
private const string ShaVariableGroupName = "shaVariable";
private const string ShaValueGroupName = "shaValue";
private const string NetStandard21TargetingPack = "netstandard-targeting-pack-2.1.0";
private static readonly Dictionary<string, string> s_shaCache = new();
private static readonly Dictionary<string, Dictionary<string, string>> s_releaseChecksumCache = new();
private static HttpClient s_httpClient { get; } = new();
private readonly string _productName;
private readonly Version _dockerfileVersion;
private readonly string? _buildVersion;
private readonly string _arch;
private readonly string _os;
private readonly Options _options;
private readonly string _versions;
private readonly Dictionary<string, string[]> _urls;
public DockerfileShaUpdater(
string productName, string dockerfileVersion, string? buildVersion, string arch, string os, string versions, Options options)
{
_productName = productName;
_dockerfileVersion = new Version(dockerfileVersion);
_buildVersion = buildVersion;
_arch = arch;
_os = os;
_versions = versions;
_options = options;
// Maps a product name to a set of one or more candidate URLs referencing the associated artifact. The order of the URLs
// should be in priority order with each subsequent URL being the fallback. This is primarily intended to support targeting
// pack RPMs because they only ship once for a given major/minor release and never again for servicing releases. However, during
// preview releases, they ship with each build. By making use of fallback URLs it allows support for either scenario, first checking
// for the build-specific location and then falling back to the overall major/minor release location.
_urls = new()
{
{ "powershell", new string[] { "https://pwshtool.blob.core.windows.net/tool/$VERSION_DIR/PowerShell.$OS.$ARCH.$VERSION_FILE.nupkg" } },
{ "monitor", new string[] { $"$DOTNET_BASE_URL/diagnostics/monitor/$VERSION_DIR/dotnet-monitor.$VERSION_FILE.nupkg" } },
{ "runtime", new string[] { $"$DOTNET_BASE_URL/Runtime/$VERSION_DIR/dotnet-runtime-$VERSION_FILE$OPTIONAL_OS-$ARCH.$ARCHIVE_EXT" } },
{ "runtime-host", new string[] { $"$DOTNET_BASE_URL/Runtime/$VERSION_DIR/dotnet-host-$VERSION_FILE-$ARCH.$ARCHIVE_EXT" } },
{ "runtime-hostfxr", new string[] { $"$DOTNET_BASE_URL/Runtime/$VERSION_DIR/dotnet-hostfxr-$VERSION_FILE-$ARCH.$ARCHIVE_EXT" } },
{
"runtime-targeting-pack",
new string[]
{
$"$DOTNET_BASE_URL/Runtime/$VERSION_DIR/dotnet-targeting-pack-$VERSION_FILE-$ARCH.$ARCHIVE_EXT",
$"$DOTNET_BASE_URL/Runtime/$DF_VERSION.0/dotnet-targeting-pack-$DF_VERSION.0-$ARCH.$ARCHIVE_EXT"
}
},
{ "runtime-apphost-pack", new string[] { $"$DOTNET_BASE_URL/Runtime/$VERSION_DIR/dotnet-apphost-pack-$VERSION_FILE-$ARCH.$ARCHIVE_EXT" } },
{ NetStandard21TargetingPack, new string[] { $"{ReleaseChecksumsBaseUrl}/Runtime/3.1.0/netstandard-targeting-pack-2.1.0-$ARCH.$ARCHIVE_EXT" } },
{ "runtime-deps-cm.1", new string[] { $"$DOTNET_BASE_URL/Runtime/$VERSION_DIR/dotnet-runtime-deps-$VERSION_FILE-cm.1-$ARCH.$ARCHIVE_EXT" } },
{ "aspnet", new string[] { $"$DOTNET_BASE_URL/aspnetcore/Runtime/$VERSION_DIR/aspnetcore-runtime-$VERSION_FILE$OPTIONAL_OS-$ARCH.$ARCHIVE_EXT" } },
{
"aspnet-runtime-targeting-pack",
new string[]
{
$"$DOTNET_BASE_URL/aspnetcore/Runtime/$VERSION_DIR/aspnetcore-targeting-pack-$VERSION_FILE.$ARCHIVE_EXT",
$"$DOTNET_BASE_URL/aspnetcore/Runtime/$DF_VERSION.0/aspnetcore-targeting-pack-$DF_VERSION.0.$ARCHIVE_EXT"
}
},
{ "sdk", new string[] { $"$DOTNET_BASE_URL/Sdk/$VERSION_DIR/dotnet-sdk-$VERSION_FILE$OPTIONAL_OS-$ARCH.$ARCHIVE_EXT" } },
{ "lzma", new string[] { $"$DOTNET_BASE_URL/Sdk/$VERSION_DIR/nuGetPackagesArchive.lzma" } }
};
}
public static IEnumerable<IDependencyUpdater> CreateUpdaters(
string productName, string dockerfileVersion, string repoRoot, Options options)
{
string versionsPath = System.IO.Path.Combine(repoRoot, UpdateDependencies.VersionsFilename);
string versions = File.ReadAllText(versionsPath);
// The format of the sha variable name is '<productName>|<dockerfileVersion>|<os>|<arch>|sha'.
// The 'os' and 'arch' segments are optional.
string shaVariablePattern;
if (productName == NetStandard21TargetingPack)
{
// NetStandard targeting pack is not associated with a specific Dockerfile version
shaVariablePattern = $"\"(?<{ShaVariableGroupName}>{Regex.Escape(productName)}.*\\|sha)\":";
}
else
{
shaVariablePattern = $"\"(?<{ShaVariableGroupName}>{Regex.Escape(productName)}\\|{Regex.Escape(dockerfileVersion)}.*\\|sha)\":";
}
Regex shaVariableRegex = new(shaVariablePattern);
return shaVariableRegex.Matches(versions)
.Select(match => match.Groups[ShaVariableGroupName].Value)
.Select(variable =>
{
Trace.TraceInformation($"Updating {variable}");
string[] parts = variable.Split('|');
DockerfileShaUpdater updater = new(
productName,
dockerfileVersion,
GetBuildVersion(productName, dockerfileVersion, versions, options),
GetArch(parts),
GetOs(parts),
versions,
options)
{
Path = versionsPath,
VersionGroupName = ShaValueGroupName
};
string archPattern = updater._arch == string.Empty ? string.Empty : "|" + updater._arch;
string osPattern = updater._os == string.Empty ? string.Empty : "|" + updater._os;
updater.Regex = new Regex(
$"{shaVariablePattern.Replace(".*", Regex.Escape(osPattern + archPattern))} \"(?<{ShaValueGroupName}>.*)\"");
return updater;
})
.ToArray();
}
protected override string? TryGetDesiredValue(
IEnumerable<IDependencyInfo> dependencyBuildInfos, out IEnumerable<IDependencyInfo> usedBuildInfos)
{
IDependencyInfo productInfo = dependencyBuildInfos.First(info => info.SimpleName == _productName);
usedBuildInfos = new IDependencyInfo[] { productInfo };
string? versionDir = _buildVersion;
string? versionFile = UpdateDependencies.ResolveProductVersion(_buildVersion, _options);
string archiveExt;
if (_os.Contains("win"))
{
archiveExt = "zip";
}
else if (_os.Contains("rpm"))
{
archiveExt = "rpm";
}
else
{
archiveExt = "tar.gz";
}
string optionalOs = _os.Contains("rpm") ? string.Empty : $"-{_os}";
// Each product name has one or more candidate URLs from which to retrieve the artifact. Multiple candidate URLs
// should be listed in priority order. Each subsequent URL listed is treated as a fallback.
string[] candidateUrls = _urls[_productName];
string[] baseUrls = new[] { BuildsDotnetBaseUrl, ReleaseDotnetBaseUrl };
for (int candidateUrlIndex = 0; candidateUrlIndex < candidateUrls.Length; candidateUrlIndex++)
{
for (int baseUrlIndex = 0; baseUrlIndex < baseUrls.Length; baseUrlIndex++)
{
string downloadUrl = candidateUrls[candidateUrlIndex]
.Replace("$DOTNET_BASE_URL", baseUrls[baseUrlIndex])
.Replace("$ARCHIVE_EXT", archiveExt)
.Replace("$VERSION_DIR", versionDir)
.Replace("$VERSION_FILE", versionFile)
.Replace("$CHANNEL_NAME", _options.ChannelName)
.Replace("$OS", _os)
.Replace("$OPTIONAL_OS", optionalOs)
.Replace("$ARCH", _arch)
.Replace("$DF_VERSION", _options.DockerfileVersion)
.Replace("..", ".");
bool isLastUrlToCheck =
candidateUrlIndex == candidateUrls.Length - 1 &&
baseUrlIndex == baseUrls.Length - 1;
string? result = GetArtifactShaAsync(downloadUrl, errorOnNotFound: isLastUrlToCheck).Result;
if (result is not null)
{
return result;
}
}
}
return null;
}
private static string GetOs(string[] variableParts)
{
if (variableParts.Length == 4 && !Version.TryParse(variableParts[1], out _))
{
// Handles the case of "netstandard-targeting-pack-2.1.0|linux-rpm|x64|sha".
return variableParts[1];
}
else if (variableParts.Length >= 4)
{
return variableParts[2];
}
return string.Empty;
}
private static string GetArch(string[] variableParts)
{
if (variableParts.Length == 4 && !Version.TryParse(variableParts[1], out _))
{
// Handles the case of "netstandard-targeting-pack-2.1.0|linux-rpm|x64|sha".
return variableParts[2];
}
else if (variableParts.Length >= 5)
{
return variableParts[3];
}
return string.Empty;
}
private async Task<string?> GetArtifactShaAsync(string downloadUrl, bool errorOnNotFound)
{
if (!s_shaCache.TryGetValue(downloadUrl, out string? sha))
{
sha = await GetDotNetReleaseChecksumsShaFromRuntimeVersionAsync(downloadUrl)
?? await GetDotNetReleaseChecksumsShaFromBuildVersionAsync(downloadUrl)
?? await GetDotNetReleaseChecksumsShaFromPreviewVersionAsync(downloadUrl)
?? await GetDotNetBinaryStorageChecksumsShaAsync(downloadUrl)
?? await ComputeChecksumShaAsync(downloadUrl);
if (sha != null)
{
sha = sha.ToLowerInvariant();
s_shaCache.Add(downloadUrl, sha);
Trace.TraceInformation($"Retrieved sha '{sha}' for '{downloadUrl}'.");
}
else
{
string notFoundMsg = $"Unable to retrieve sha for '{downloadUrl}'.";
if (errorOnNotFound)
{
Trace.TraceError(notFoundMsg);
}
else
{
Trace.TraceWarning(notFoundMsg);
}
}
}
return sha;
}
private async Task<string?> ComputeChecksumShaAsync(string downloadUrl)
{
if (!_options.ComputeChecksums)
{
return null;
}
string? sha = null;
Trace.TraceInformation($"Downloading '{downloadUrl}'.");
using (HttpResponseMessage response = await s_httpClient.GetAsync(downloadUrl))
{
if (response.IsSuccessStatusCode)
{
using (Stream httpStream = await response.Content.ReadAsStreamAsync())
using (SHA512 hash = SHA512.Create())
{
byte[] hashedInputBytes = hash.ComputeHash(httpStream);
StringBuilder stringBuilder = new StringBuilder(128);
foreach (byte b in hashedInputBytes)
{
stringBuilder.Append(b.ToString("X2"));
}
sha = stringBuilder.ToString();
}
}
else
{
Trace.TraceInformation($"Failed to download {downloadUrl}.");
}
}
return sha;
}
private async Task<string?> GetDotNetBinaryStorageChecksumsShaAsync(string productDownloadUrl)
{
string? sha = null;
string shaExt = _productName.Contains("sdk", StringComparison.OrdinalIgnoreCase) ? ".sha" : ".sha512";
string shaUrl = productDownloadUrl
.Replace(ReleaseDotnetBaseUrl, ReleaseChecksumsBaseUrl)
.Replace(BuildsDotnetBaseUrl, BuildsChecksumsBaseUrl)
+ shaExt;
Trace.TraceInformation($"Downloading '{shaUrl}'.");
using (HttpResponseMessage response = await s_httpClient.GetAsync(shaUrl))
{
if (response.IsSuccessStatusCode)
{
sha = await response.Content.ReadAsStringAsync();
}
else
{
Trace.TraceInformation($"Failed to find dotnet binary storage account sha");
}
}
return sha;
}
private Task<string?> GetDotNetReleaseChecksumsShaFromRuntimeVersionAsync(string productDownloadUrl) =>
GetDotNetReleaseChecksumsShaAsync(productDownloadUrl, GetRuntimeVersion());
private string? GetRuntimeVersion()
{
string? version = _buildVersion;
// The release checksum file contains content for all products in the release (runtime, sdk, etc.)
// and is referenced by the runtime version.
if (_productName.Contains("sdk", StringComparison.OrdinalIgnoreCase) ||
_productName.Contains("aspnet", StringComparison.OrdinalIgnoreCase))
{
version = GetBuildVersion("runtime", _dockerfileVersion.ToString(), _versions, _options);
}
return version;
}
private Task<string?> GetDotNetReleaseChecksumsShaFromBuildVersionAsync(string productDownloadUrl) =>
GetDotNetReleaseChecksumsShaAsync(productDownloadUrl, _buildVersion);
private Task<string?> GetDotNetReleaseChecksumsShaFromPreviewVersionAsync(string productDownloadUrl)
{
string? runtimeVersion = GetRuntimeVersion();
if (runtimeVersion is not null && TryParsePreviewVersion(runtimeVersion, out string? previewVersion))
{
return GetDotNetReleaseChecksumsShaAsync(productDownloadUrl, previewVersion);
}
return Task.FromResult<string?>(null);
}
private static async Task<string?> GetDotNetReleaseChecksumsShaAsync(
string productDownloadUrl, string? version)
{
IDictionary<string, string> checksumEntries = await GetDotnetReleaseChecksums(version);
string installerFileName = productDownloadUrl.Substring(productDownloadUrl.LastIndexOf('/') + 1);
if (!checksumEntries.TryGetValue(installerFileName, out string? sha))
{
Trace.TraceInformation($"Failed to find `{installerFileName}` sha");
}
return sha;
}
private static bool TryParsePreviewVersion(string version, out string? previewVersion)
{
// Example format: 6.0.0-preview.5.21301.5
// This method returns the 6.0.0-preview.5 segment of that value.
const string PreviewGroup = "Preview";
string PreviewVersionRegex = @$"(?<{PreviewGroup}>\d+\.\d+\.\d+-[\w-]+\.\d+)\.[\d\.]+";
Match match = Regex.Match(version, PreviewVersionRegex);
if (match.Success)
{
previewVersion = match.Groups[PreviewGroup].Value;
return true;
}
else
{
previewVersion = null;
return false;
}
}
private static async Task<IDictionary<string, string>> GetDotnetReleaseChecksums(string? version)
{
string uri = $"{ReleaseDotnetBaseUrl}/checksums/{version}-sha.txt";
if (s_releaseChecksumCache.TryGetValue(uri, out Dictionary<string, string>? checksumEntries))
{
return checksumEntries;
}
checksumEntries = new Dictionary<string, string>();
s_releaseChecksumCache.Add(uri, checksumEntries);
Trace.TraceInformation($"Downloading '{uri}'.");
using (HttpResponseMessage response = await s_httpClient.GetAsync(uri))
{
if (response.IsSuccessStatusCode)
{
string checksums = await response.Content.ReadAsStringAsync();
string[] checksumLines = checksums.Replace("\r\n", "\n").Split("\n");
if (!checksumLines[0].StartsWith("Hash") || !string.IsNullOrEmpty(checksumLines[1]))
{
Trace.TraceError($"Checksum file is not in the expected format: {uri}");
}
for (int i = 2; i < checksumLines.Length - 1; i++)
{
string[] parts = checksumLines[i].Split(" ");
if (parts.Length != 2)
{
Trace.TraceError($"Checksum file is not in the expected format: {uri}");
}
string fileName = parts[1];
string checksum = parts[0];
checksumEntries.Add(fileName, checksum);
Trace.TraceInformation($"Parsed checksum '{checksum}' for '{fileName}'");
}
}
else
{
Trace.TraceInformation($"Failed to find dotnet release checksums");
}
}
return checksumEntries;
}
private static string? GetBuildVersion(string productName, string dockerfileVersion, string variables, Options options)
{
string? buildVersion;
if (options.ProductVersions.TryGetValue(productName, out string? version))
{
buildVersion = version;
}
else
{
buildVersion = VersionUpdater.GetBuildVersion(productName, dockerfileVersion, variables);
}
return buildVersion;
}
}
}
#nullable disable
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace System.Net.Security
{
// SecureChannel - a wrapper on SSPI based functionality.
// Provides an additional abstraction layer over SSPI for SslStream.
internal class SecureChannel
{
// When reading a frame from the wire first read this many bytes for the header.
internal const int ReadHeaderSize = 5;
private SafeFreeCredentials _credentialsHandle;
private SafeDeleteContext _securityContext;
private SslConnectionInfo _connectionInfo;
private X509Certificate _selectedClientCertificate;
private bool _isRemoteCertificateAvailable;
// These are the MAX encrypt buffer output sizes, not the actual sizes.
private int _headerSize = 5; //ATTN must be set to at least 5 by default
private int _trailerSize = 16;
private int _maxDataSize = 16354;
private bool _refreshCredentialNeeded;
private SslAuthenticationOptions _sslAuthenticationOptions;
private SslApplicationProtocol _negotiatedApplicationProtocol;
private readonly Oid _serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1");
private readonly Oid _clientAuthOid = new Oid("1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.2");
internal SecureChannel(SslAuthenticationOptions sslAuthenticationOptions)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates);
NetEventSource.Log.SecureChannelCtor(this, sslAuthenticationOptions.TargetHost, sslAuthenticationOptions.ClientCertificates, sslAuthenticationOptions.EncryptionPolicy);
}
SslStreamPal.VerifyPackageInfo();
if (sslAuthenticationOptions.TargetHost == null)
{
NetEventSource.Fail(this, "sslAuthenticationOptions.TargetHost == null");
}
_securityContext = null;
_refreshCredentialNeeded = true;
_sslAuthenticationOptions = sslAuthenticationOptions;
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this);
}
//
// SecureChannel properties
//
// LocalServerCertificate - local certificate for server mode channel
// LocalClientCertificate - selected certificated used in the client channel mode otherwise null
// IsRemoteCertificateAvailable - true if the remote side has provided a certificate
// HeaderSize - Header & trailer sizes used in the TLS stream
// TrailerSize -
//
internal X509Certificate LocalServerCertificate
{
get
{
return _sslAuthenticationOptions.ServerCertificate;
}
}
internal X509Certificate LocalClientCertificate
{
get
{
return _selectedClientCertificate;
}
}
internal bool IsRemoteCertificateAvailable
{
get
{
return _isRemoteCertificateAvailable;
}
}
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this, kind);
ChannelBinding result = null;
if (_securityContext != null)
{
result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind);
}
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, result);
return result;
}
internal X509RevocationMode CheckCertRevocationStatus
{
get
{
return _sslAuthenticationOptions.CertificateRevocationCheckMode;
}
}
internal int HeaderSize
{
get
{
return _headerSize;
}
}
internal int MaxDataSize
{
get
{
return _maxDataSize;
}
}
internal SslConnectionInfo ConnectionInfo
{
get
{
return _connectionInfo;
}
}
internal bool IsValidContext
{
get
{
return !(_securityContext == null || _securityContext.IsInvalid);
}
}
internal bool IsServer
{
get
{
return _sslAuthenticationOptions.IsServer;
}
}
internal bool RemoteCertRequired
{
get
{
return _sslAuthenticationOptions.RemoteCertRequired;
}
}
internal SslApplicationProtocol NegotiatedApplicationProtocol
{
get
{
return _negotiatedApplicationProtocol;
}
}
internal void SetRefreshCredentialNeeded()
{
_refreshCredentialNeeded = true;
}
internal void Close()
{
if (_sslAuthenticationOptions.AlpnProtocolsHandle.IsAllocated)
{
_sslAuthenticationOptions.AlpnProtocolsHandle.Free();
}
if (_securityContext != null)
{
_securityContext.Dispose();
}
if (_credentialsHandle != null)
{
_credentialsHandle.Dispose();
}
}
//
// SECURITY: we open a private key container on behalf of the caller
// and we require the caller to have permission associated with that operation.
//
private X509Certificate2 EnsurePrivateKey(X509Certificate certificate)
{
if (certificate == null)
{
return null;
}
if (NetEventSource.IsEnabled)
NetEventSource.Log.LocatingPrivateKey(certificate, this);
try
{
string certHash = null;
// Protecting from X509Certificate2 derived classes.
X509Certificate2 certEx = MakeEx(certificate);
certHash = certEx.Thumbprint;
if (certEx != null)
{
if (certEx.HasPrivateKey)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.CertIsType2(this);
return certEx;
}
if ((object)certificate != (object)certEx)
{
certEx.Dispose();
}
}
X509Certificate2Collection collectionEx;
// ELSE Try the MY user and machine stores for private key check.
// For server side mode MY machine store takes priority.
X509Store store = CertificateValidationPal.EnsureStoreOpened(_sslAuthenticationOptions.IsServer);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.FoundCertInStore(_sslAuthenticationOptions.IsServer, this);
return collectionEx[0];
}
}
store = CertificateValidationPal.EnsureStoreOpened(!_sslAuthenticationOptions.IsServer);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.FoundCertInStore(_sslAuthenticationOptions.IsServer, this);
return collectionEx[0];
}
}
}
catch (CryptographicException)
{
}
if (NetEventSource.IsEnabled)
NetEventSource.Log.NotFoundCertInStore(this);
return null;
}
private static X509Certificate2 MakeEx(X509Certificate certificate)
{
Debug.Assert(certificate != null, "certificate != null");
if (certificate.GetType() == typeof(X509Certificate2))
{
return (X509Certificate2)certificate;
}
X509Certificate2 certificateEx = null;
try
{
if (certificate.Handle != IntPtr.Zero)
{
certificateEx = new X509Certificate2(certificate.Handle);
}
}
catch (SecurityException) { }
catch (CryptographicException) { }
return certificateEx;
}
//
// Get certificate_authorities list, according to RFC 5246, Section 7.4.4.
// Used only by client SSL code, never returns null.
//
private string[] GetRequestCertificateAuthorities()
{
string[] issuers = Array.Empty<string>();
if (IsValidContext)
{
issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext);
}
return issuers;
}
/*++
AcquireCredentials - Attempts to find Client Credential
Information, that can be sent to the server. In our case,
this is only Client Certificates, that we have Credential Info.
How it works:
case 0: Cert Selection delegate is present
Always use its result as the client cert answer.
Try to use cached credential handle whenever feasible.
Do not use cached anonymous creds if the delegate has returned null
and the collection is not empty (allow responding with the cert later).
case 1: Certs collection is empty
Always use the same statically acquired anonymous SSL Credential
case 2: Before our Connection with the Server
If we have a cached credential handle keyed by first X509Certificate
**content** in the passed collection, then we use that cached
credential and hoping to restart a session.
Otherwise create a new anonymous (allow responding with the cert later).
case 3: After our Connection with the Server (i.e. during handshake or re-handshake)
The server has requested that we send it a Certificate then
we Enumerate a list of server sent Issuers trying to match against
our list of Certificates, the first match is sent to the server.
Once we got a cert we again try to match cached credential handle if possible.
This will not restart a session but helps minimizing the number of handles we create.
In the case of an error getting a Certificate or checking its private Key we fall back
to the behavior of having no certs, case 1.
Returns: True if cached creds were used, false otherwise.
--*/
private bool AcquireClientCredentials(ref byte[] thumbPrint)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
// Acquire possible Client Certificate information and set it on the handle.
X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart.
var filteredCerts = new List<X509Certificate>(); // This is an intermediate client certs collection that try to use if no selectedCert is available yet.
string[] issuers = null; // This is a list of issuers sent by the server, only valid is we do know what the server cert is.
bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds.
if (_sslAuthenticationOptions.CertSelectionDelegate != null)
{
issuers = GetRequestCertificateAuthorities();
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Calling CertificateSelectionCallback");
X509Certificate2 remoteCert = null;
try
{
X509Certificate2Collection dummyCollection;
remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext, out dummyCollection);
if (_sslAuthenticationOptions.ClientCertificates == null)
{
_sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection();
}
clientCertificate = _sslAuthenticationOptions.CertSelectionDelegate(_sslAuthenticationOptions.TargetHost, _sslAuthenticationOptions.ClientCertificates, remoteCert, issuers);
}
finally
{
if (remoteCert != null)
{
remoteCert.Dispose();
}
}
if (clientCertificate != null)
{
if (_credentialsHandle == null)
{
sessionRestartAttempt = true;
}
filteredCerts.Add(clientCertificate);
if (NetEventSource.IsEnabled)
NetEventSource.Log.CertificateFromDelegate(this);
}
else
{
if (_sslAuthenticationOptions.ClientCertificates == null || _sslAuthenticationOptions.ClientCertificates.Count == 0)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.NoDelegateNoClientCert(this);
sessionRestartAttempt = true;
}
else
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.NoDelegateButClientCert(this);
}
}
}
else if (_credentialsHandle == null && _sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0)
{
// This is where we attempt to restart a session by picking the FIRST cert from the collection.
// Otherwise it is either server sending a client cert request or the session is renegotiated.
clientCertificate = _sslAuthenticationOptions.ClientCertificates[0];
sessionRestartAttempt = true;
if (clientCertificate != null)
{
filteredCerts.Add(clientCertificate);
}
if (NetEventSource.IsEnabled)
NetEventSource.Log.AttemptingRestartUsingCert(clientCertificate, this);
}
else if (_sslAuthenticationOptions.ClientCertificates != null && _sslAuthenticationOptions.ClientCertificates.Count > 0)
{
//
// This should be a server request for the client cert sent over currently anonymous sessions.
//
issuers = GetRequestCertificateAuthorities();
if (NetEventSource.IsEnabled)
{
if (issuers == null || issuers.Length == 0)
{
NetEventSource.Log.NoIssuersTryAllCerts(this);
}
else
{
NetEventSource.Log.LookForMatchingCerts(issuers.Length, this);
}
}
for (int i = 0; i < _sslAuthenticationOptions.ClientCertificates.Count; ++i)
{
//
// Make sure we add only if the cert matches one of the issuers.
// If no issuers were sent and then try all client certs starting with the first one.
//
if (issuers != null && issuers.Length != 0)
{
X509Certificate2 certificateEx = null;
X509Chain chain = null;
try
{
certificateEx = MakeEx(_sslAuthenticationOptions.ClientCertificates[i]);
if (certificateEx == null)
{
continue;
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"Root cert: {certificateEx}");
chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName;
chain.Build(certificateEx);
bool found = false;
//
// We ignore any errors happened with chain.
//
if (chain.ChainElements.Count > 0)
{
for (int ii = 0; ii < chain.ChainElements.Count; ++ii)
{
string issuer = chain.ChainElements[ii].Certificate.Issuer;
found = Array.IndexOf(issuers, issuer) != -1;
if (found)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"Matched {issuer}");
break;
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"No match: {issuer}");
}
}
if (!found)
{
continue;
}
}
finally
{
if (chain != null)
{
chain.Dispose();
}
if (certificateEx != null && (object)certificateEx != (object)_sslAuthenticationOptions.ClientCertificates[i])
{
certificateEx.Dispose();
}
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Log.SelectedCert(_sslAuthenticationOptions.ClientCertificates[i], this);
filteredCerts.Add(_sslAuthenticationOptions.ClientCertificates[i]);
}
}
bool cachedCred = false; // This is a return result from this method.
X509Certificate2 selectedCert = null; // This is a final selected cert (ensured that it does have private key with it).
clientCertificate = null;
if (NetEventSource.IsEnabled)
{
NetEventSource.Log.CertsAfterFiltering(filteredCerts.Count, this);
if (filteredCerts.Count != 0)
{
NetEventSource.Log.FindingMatchingCerts(this);
}
}
//
// ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key,
// THEN anonymous (no client cert) credential will be used.
//
// SECURITY: Accessing X509 cert Credential is disabled for semitrust.
// We no longer need to demand for unmanaged code permissions.
// EnsurePrivateKey should do the right demand for us.
for (int i = 0; i < filteredCerts.Count; ++i)
{
clientCertificate = filteredCerts[i];
if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null)
{
break;
}
clientCertificate = null;
selectedCert = null;
}
if ((object)clientCertificate != (object)selectedCert && !clientCertificate.Equals(selectedCert))
{
NetEventSource.Fail(this, "'selectedCert' does not match 'clientCertificate'.");
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"Selected cert = {selectedCert}");
try
{
// Try to locate cached creds first.
//
// SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type.
//
byte[] guessedThumbPrint = selectedCert == null ? null : selectedCert.GetCertHash();
SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy);
// We can probably do some optimization here. If the selectedCert is returned by the delegate
// we can always go ahead and use the certificate to create our credential
// (instead of going anonymous as we do here).
if (sessionRestartAttempt &&
cachedCredentialHandle == null &&
selectedCert != null &&
SslStreamPal.StartMutualAuthAsAnonymous)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Reset to anonymous session.");
// IIS does not renegotiate a restarted session if client cert is needed.
// So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate.
// The following block happens if client did specify a certificate but no cached creds were found in the cache.
// Since we don't restart a session the server side can still challenge for a client cert.
if ((object)clientCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
guessedThumbPrint = null;
selectedCert = null;
clientCertificate = null;
}
if (cachedCredentialHandle != null)
{
if (NetEventSource.IsEnabled)
NetEventSource.Log.UsingCachedCredential(this);
_credentialsHandle = cachedCredentialHandle;
_selectedClientCertificate = clientCertificate;
cachedCred = true;
}
else
{
_credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer);
thumbPrint = guessedThumbPrint; // Delay until here in case something above threw.
_selectedClientCertificate = clientCertificate;
}
}
finally
{
// An extra cert could have been created, dispose it now.
if (selectedCert != null && (object)clientCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, cachedCred, _credentialsHandle);
return cachedCred;
}
//
// Acquire Server Side Certificate information and set it on the class.
//
private bool AcquireServerCredentials(ref byte[] thumbPrint)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
X509Certificate localCertificate = null;
bool cachedCred = false;
if (_sslAuthenticationOptions.CertSelectionDelegate != null)
{
X509CertificateCollection tempCollection = new X509CertificateCollection();
tempCollection.Add(_sslAuthenticationOptions.ServerCertificate);
localCertificate = _sslAuthenticationOptions.CertSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>());
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "Use delegate selected Cert");
}
else
{
localCertificate = _sslAuthenticationOptions.ServerCertificate;
}
if (localCertificate == null)
{
throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
}
// SECURITY: Accessing X509 cert Credential is disabled for semitrust.
// We no longer need to demand for unmanaged code permissions.
// EnsurePrivateKey should do the right demand for us.
X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate);
if (selectedCert == null)
{
throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
}
if (!localCertificate.Equals(selectedCert))
{
NetEventSource.Fail(this, "'selectedCert' does not match 'localCertificate'.");
}
//
// Note selectedCert is a safe ref possibly cloned from the user passed Cert object
//
byte[] guessedThumbPrint = selectedCert.GetCertHash();
try
{
SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy);
if (cachedCredentialHandle != null)
{
_credentialsHandle = cachedCredentialHandle;
_sslAuthenticationOptions.ServerCertificate = localCertificate;
cachedCred = true;
}
else
{
_credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.EncryptionPolicy, _sslAuthenticationOptions.IsServer);
thumbPrint = guessedThumbPrint;
_sslAuthenticationOptions.ServerCertificate = localCertificate;
}
}
finally
{
// An extra cert could have been created, dispose it now.
if ((object)localCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, cachedCred, _credentialsHandle);
return cachedCred;
}
//
internal ProtocolToken NextMessage(byte[] incoming, int offset, int count)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
byte[] nextmsg = null;
SecurityStatusPal status = GenerateToken(incoming, offset, count, ref nextmsg);
if (!_sslAuthenticationOptions.IsServer && status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, "NextMessage() returned SecurityStatusPal.CredentialsNeeded");
SetRefreshCredentialNeeded();
status = GenerateToken(incoming, offset, count, ref nextmsg);
}
ProtocolToken token = new ProtocolToken(nextmsg, status);
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, token);
return token;
}
/*++
GenerateToken - Called after each successive state
in the Client - Server handshake. This function
generates a set of bytes that will be sent next to
the server. The server responds, each response,
is pass then into this function, again, and the cycle
repeats until successful connection, or failure.
Input:
input - bytes from the wire
output - ref to byte [], what we will send to the
server in response
Return:
status - error information
--*/
private SecurityStatusPal GenerateToken(byte[] input, int offset, int count, ref byte[] output)
{
#if TRACE_VERBOSE
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"_refreshCredentialNeeded = {_refreshCredentialNeeded}");
#endif
if (offset < 0 || offset > (input == null ? 0 : input.Length))
{
NetEventSource.Fail(this, "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (input == null ? 0 : input.Length - offset))
{
NetEventSource.Fail(this, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
SecurityBuffer incomingSecurity = null;
SecurityBuffer[] incomingSecurityBuffers = null;
if (input != null)
{
incomingSecurity = new SecurityBuffer(input, offset, count, SecurityBufferType.SECBUFFER_TOKEN);
}
incomingSecurityBuffers = SslStreamPal.GetIncomingSecurityBuffers(_sslAuthenticationOptions, ref incomingSecurity);
SecurityBuffer outgoingSecurity = new SecurityBuffer(null, SecurityBufferType.SECBUFFER_TOKEN);
SecurityStatusPal status = default(SecurityStatusPal);
bool cachedCreds = false;
byte[] thumbPrint = null;
//
// Looping through ASC or ISC with potentially cached credential that could have been
// already disposed from a different thread before ISC or ASC dir increment a cred ref count.
//
try
{
do
{
thumbPrint = null;
if (_refreshCredentialNeeded)
{
cachedCreds = _sslAuthenticationOptions.IsServer
? AcquireServerCredentials(ref thumbPrint)
: AcquireClientCredentials(ref thumbPrint);
}
if (_sslAuthenticationOptions.IsServer)
{
status = SslStreamPal.AcceptSecurityContext(
ref _credentialsHandle,
ref _securityContext,
incomingSecurityBuffers,
outgoingSecurity,
_sslAuthenticationOptions);
}
else
{
if (incomingSecurityBuffers == null)
{
status = SslStreamPal.InitializeSecurityContext(
ref _credentialsHandle,
ref _securityContext,
_sslAuthenticationOptions.TargetHost,
incomingSecurity,
outgoingSecurity,
_sslAuthenticationOptions);
}
else
{
status = SslStreamPal.InitializeSecurityContext(
_credentialsHandle,
ref _securityContext,
_sslAuthenticationOptions.TargetHost,
incomingSecurityBuffers,
outgoingSecurity,
_sslAuthenticationOptions);
}
}
} while (cachedCreds && _credentialsHandle == null);
}
finally
{
if (_sslAuthenticationOptions.AlpnProtocolsHandle.IsAllocated)
{
_sslAuthenticationOptions.AlpnProtocolsHandle.Free();
}
if (_refreshCredentialNeeded)
{
_refreshCredentialNeeded = false;
//
// Assuming the ISC or ASC has referenced the credential,
// we want to call dispose so to decrement the effective ref count.
//
if (_credentialsHandle != null)
{
_credentialsHandle.Dispose();
}
//
// This call may bump up the credential reference count further.
// Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert.
//
if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid)
{
SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslAuthenticationOptions.EnabledSslProtocols, _sslAuthenticationOptions.IsServer, _sslAuthenticationOptions.EncryptionPolicy);
}
}
}
output = outgoingSecurity.token;
byte[] alpnResult = SslStreamPal.GetNegotiatedApplicationProtocol(_securityContext);
_negotiatedApplicationProtocol = alpnResult == null ? default : new SslApplicationProtocol(alpnResult, false);
return status;
}
/*++
ProcessHandshakeSuccess -
Called on successful completion of Handshake -
used to set header/trailer sizes for encryption use
Fills in the information about established protocol
--*/
internal void ProcessHandshakeSuccess()
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
StreamSizes streamSizes;
SslStreamPal.QueryContextStreamSizes(_securityContext, out streamSizes);
if (streamSizes != null)
{
try
{
_headerSize = streamSizes.Header;
_trailerSize = streamSizes.Trailer;
_maxDataSize = checked(streamSizes.MaximumMessage - (_headerSize + _trailerSize));
Debug.Assert(_maxDataSize > 0, "_maxDataSize > 0");
}
catch (Exception e) when (!ExceptionCheck.IsFatal(e))
{
NetEventSource.Fail(this, "StreamSizes out of range.");
throw;
}
}
SslStreamPal.QueryContextConnectionInfo(_securityContext, out _connectionInfo);
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this);
}
/*++
Encrypt - Encrypts our bytes before we send them over the wire
PERF: make more efficient, this does an extra copy when the offset
is non-zero.
Input:
buffer - bytes for sending
offset -
size -
output - Encrypted bytes
--*/
internal SecurityStatusPal Encrypt(ReadOnlyMemory<byte> buffer, ref byte[] output, out int resultSize)
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this, buffer, buffer.Length);
NetEventSource.DumpBuffer(this, buffer);
}
byte[] writeBuffer = output;
SecurityStatusPal secStatus = SslStreamPal.EncryptMessage(
_securityContext,
buffer,
_headerSize,
_trailerSize,
ref writeBuffer,
out resultSize);
if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK)
{
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, $"ERROR {secStatus}");
}
else
{
output = writeBuffer;
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, $"OK data size:{resultSize}");
}
return secStatus;
}
internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this, payload, offset, count);
if (offset < 0 || offset > (payload == null ? 0 : payload.Length))
{
NetEventSource.Fail(this, "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (payload == null ? 0 : payload.Length - offset))
{
NetEventSource.Fail(this, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
SecurityStatusPal secStatus = SslStreamPal.DecryptMessage(_securityContext, payload, ref offset, ref count);
return secStatus;
}
/*++
VerifyRemoteCertificate - Validates the content of a Remote Certificate
checkCRL if true, checks the certificate revocation list for validity.
checkCertName, if true checks the CN field of the certificate
--*/
//This method validates a remote certificate.
//SECURITY: The scenario is allowed in semitrust StorePermission is asserted for Chain.Build
// A user callback has unique signature so it is safe to call it under permission assert.
//
internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback, ref ProtocolToken alertToken)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
// We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true.
bool success = false;
X509Chain chain = null;
X509Certificate2 remoteCertificateEx = null;
try
{
X509Certificate2Collection remoteCertificateStore;
remoteCertificateEx = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore);
_isRemoteCertificateAvailable = remoteCertificateEx != null;
if (remoteCertificateEx == null)
{
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, "(no remote cert)", !_sslAuthenticationOptions.RemoteCertRequired);
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
}
else
{
chain = new X509Chain();
chain.ChainPolicy.RevocationMode = _sslAuthenticationOptions.CertificateRevocationCheckMode;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
// Authenticate the remote party: (e.g. when operating in server mode, authenticate the client).
chain.ChainPolicy.ApplicationPolicy.Add(_sslAuthenticationOptions.IsServer ? _clientAuthOid : _serverAuthOid);
if (remoteCertificateStore != null)
{
chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore);
}
sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties(
_securityContext,
chain,
remoteCertificateEx,
_sslAuthenticationOptions.CheckCertName,
_sslAuthenticationOptions.IsServer,
_sslAuthenticationOptions.TargetHost);
}
if (remoteCertValidationCallback != null)
{
success = remoteCertValidationCallback(_sslAuthenticationOptions.TargetHost, remoteCertificateEx, chain, sslPolicyErrors);
}
else
{
if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable && !_sslAuthenticationOptions.RemoteCertRequired)
{
success = true;
}
else
{
success = (sslPolicyErrors == SslPolicyErrors.None);
}
}
if (NetEventSource.IsEnabled)
{
LogCertificateValidation(remoteCertValidationCallback, sslPolicyErrors, success, chain);
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"Cert validation, remote cert = {remoteCertificateEx}");
}
if (!success)
{
alertToken = CreateFatalHandshakeAlertToken(sslPolicyErrors, chain);
}
}
finally
{
// At least on Win2k server the chain is found to have dependencies on the original cert context.
// So it should be closed first.
if (chain != null)
{
chain.Dispose();
}
if (remoteCertificateEx != null)
{
remoteCertificateEx.Dispose();
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, success);
return success;
}
public ProtocolToken CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain)
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
TlsAlertMessage alertMessage;
switch (sslPolicyErrors)
{
case SslPolicyErrors.RemoteCertificateChainErrors:
alertMessage = GetAlertMessageFromChain(chain);
break;
case SslPolicyErrors.RemoteCertificateNameMismatch:
alertMessage = TlsAlertMessage.BadCertificate;
break;
case SslPolicyErrors.RemoteCertificateNotAvailable:
default:
alertMessage = TlsAlertMessage.CertificateUnknown;
break;
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"alertMessage:{alertMessage}");
SecurityStatusPal status;
status = SslStreamPal.ApplyAlertToken(ref _credentialsHandle, _securityContext, TlsAlertType.Fatal, alertMessage);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}");
if (status.Exception != null)
{
ExceptionDispatchInfo.Throw(status.Exception);
}
return null;
}
ProtocolToken token = GenerateAlertToken();
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, token);
return token;
}
public ProtocolToken CreateShutdownToken()
{
if (NetEventSource.IsEnabled)
NetEventSource.Enter(this);
SecurityStatusPal status;
status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
if (NetEventSource.IsEnabled)
NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}");
if (status.Exception != null)
{
ExceptionDispatchInfo.Throw(status.Exception);
}
return null;
}
ProtocolToken token = GenerateAlertToken();
if (NetEventSource.IsEnabled)
NetEventSource.Exit(this, token);
return token;
}
private ProtocolToken GenerateAlertToken()
{
byte[] nextmsg = null;
SecurityStatusPal status;
status = GenerateToken(null, 0, 0, ref nextmsg);
ProtocolToken token = new ProtocolToken(nextmsg, status);
return token;
}
private static TlsAlertMessage GetAlertMessageFromChain(X509Chain chain)
{
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
if (chainStatus.Status == X509ChainStatusFlags.NoError)
{
continue;
}
if ((chainStatus.Status &
(X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.PartialChain |
X509ChainStatusFlags.Cyclic)) != 0)
{
return TlsAlertMessage.UnknownCA;
}
if ((chainStatus.Status &
(X509ChainStatusFlags.Revoked | X509ChainStatusFlags.OfflineRevocation)) != 0)
{
return TlsAlertMessage.CertificateRevoked;
}
if ((chainStatus.Status &
(X509ChainStatusFlags.CtlNotTimeValid | X509ChainStatusFlags.NotTimeNested |
X509ChainStatusFlags.NotTimeValid)) != 0)
{
return TlsAlertMessage.CertificateExpired;
}
if ((chainStatus.Status & X509ChainStatusFlags.CtlNotValidForUsage) != 0)
{
return TlsAlertMessage.UnsupportedCert;
}
if ((chainStatus.Status &
(X509ChainStatusFlags.CtlNotSignatureValid | X509ChainStatusFlags.InvalidExtension |
X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.InvalidPolicyConstraints) |
X509ChainStatusFlags.NoIssuanceChainPolicy | X509ChainStatusFlags.NotValidForUsage) != 0)
{
return TlsAlertMessage.BadCertificate;
}
// All other errors:
return TlsAlertMessage.CertificateUnknown;
}
Debug.Fail("GetAlertMessageFromChain was called but none of the chain elements had errors.");
return TlsAlertMessage.BadCertificate;
}
private void LogCertificateValidation(RemoteCertValidationCallback remoteCertValidationCallback, SslPolicyErrors sslPolicyErrors, bool success, X509Chain chain)
{
if (!NetEventSource.IsEnabled)
return;
if (sslPolicyErrors != SslPolicyErrors.None)
{
NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_has_errors);
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0)
{
NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_not_available);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
{
NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_name_mismatch);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
string chainStatusString = "ChainStatus: ";
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
chainStatusString += "\t" + chainStatus.StatusInformation;
}
NetEventSource.Log.RemoteCertificateError(this, chainStatusString);
}
}
if (success)
{
if (remoteCertValidationCallback != null)
{
NetEventSource.Log.RemoteCertDeclaredValid(this);
}
else
{
NetEventSource.Log.RemoteCertHasNoErrors(this);
}
}
else
{
if (remoteCertValidationCallback != null)
{
NetEventSource.Log.RemoteCertUserDeclaredInvalid(this);
}
}
}
}
// ProtocolToken - used to process and handle the return codes from the SSPI wrapper
internal class ProtocolToken
{
internal SecurityStatusPal Status;
internal byte[] Payload;
internal int Size;
internal bool Failed
{
get
{
return ((Status.ErrorCode != SecurityStatusPalErrorCode.OK) && (Status.ErrorCode != SecurityStatusPalErrorCode.ContinueNeeded));
}
}
internal bool Done
{
get
{
return (Status.ErrorCode == SecurityStatusPalErrorCode.OK);
}
}
internal bool Renegotiate
{
get
{
return (Status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate);
}
}
internal bool CloseConnection
{
get
{
return (Status.ErrorCode == SecurityStatusPalErrorCode.ContextExpired);
}
}
internal ProtocolToken(byte[] data, SecurityStatusPal status)
{
Status = status;
Payload = data;
Size = data != null ? data.Length : 0;
}
internal Exception GetException()
{
// If it's not done, then there's got to be an error, even if it's
// a Handshake message up, and we only have a Warning message.
return this.Done ? null : SslStreamPal.GetException(Status);
}
#if TRACE_VERBOSE
public override string ToString()
{
return "Status=" + Status.ToString() + ", data size=" + Size;
}
#endif
}
}
| |
#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.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Manages client side native call lifecycle.
/// </summary>
internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>();
Channel channel;
// Completion of a pending unary response if not null.
TaskCompletionSource<TResponse> unaryResponseTcs;
// Set after status is received. Used for both unary and streaming response calls.
ClientSideStatus? finishedStatus;
bool readObserverCompleted; // True if readObserver has already been completed.
public AsyncCall(Func<TRequest, byte[]> serializer, Func<byte[], TResponse> deserializer) : base(serializer, deserializer)
{
}
public void Initialize(Channel channel, CompletionQueueSafeHandle cq, string methodName, Timespec deadline)
{
this.channel = channel;
var call = channel.Handle.CreateCall(channel.CompletionRegistry, cq, methodName, null, deadline);
channel.Environment.DebugStats.ActiveClientCalls.Increment();
InitializeInternal(call);
}
// TODO: this method is not Async, so it shouldn't be in AsyncCall class, but
// it is reusing fair amount of code in this class, so we are leaving it here.
// TODO: for other calls, you need to call Initialize, this methods calls initialize
// on its own, so there's a usage inconsistency.
/// <summary>
/// Blocking unary request - unary response call.
/// </summary>
public TResponse UnaryCall(Channel channel, string methodName, TRequest msg, Metadata headers, DateTime deadline)
{
using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.Create())
{
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
lock (myLock)
{
Initialize(channel, cq, methodName, Timespec.FromDateTime(deadline));
started = true;
halfcloseRequested = true;
readingDone = true;
}
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
using (var ctx = BatchContextSafeHandle.Create())
{
call.StartUnary(payload, ctx, metadataArray);
var ev = cq.Pluck(ctx.Handle);
bool success = (ev.success != 0);
try
{
HandleUnaryResponse(success, ctx);
}
catch (Exception e)
{
Logger.Error(e, "Exception occured while invoking completion delegate.");
}
}
}
try
{
// Once the blocking call returns, the result should be available synchronously.
return unaryResponseTcs.Task.Result;
}
catch (AggregateException ae)
{
throw ExceptionHelper.UnwrapRpcException(ae);
}
}
}
/// <summary>
/// Starts a unary request - unary response call.
/// </summary>
public Task<TResponse> UnaryCallAsync(TRequest msg, Metadata headers, DateTime deadline)
{
lock (myLock)
{
Preconditions.CheckNotNull(call);
started = true;
halfcloseRequested = true;
readingDone = true;
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartUnary(payload, HandleUnaryResponse, metadataArray);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a streamed request - unary response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public Task<TResponse> ClientStreamingCallAsync(Metadata headers, DateTime deadline)
{
lock (myLock)
{
Preconditions.CheckNotNull(call);
started = true;
readingDone = true;
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartClientStreaming(HandleUnaryResponse, metadataArray);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a unary request - streamed response call.
/// </summary>
public void StartServerStreamingCall(TRequest msg, Metadata headers, DateTime deadline)
{
lock (myLock)
{
Preconditions.CheckNotNull(call);
started = true;
halfcloseRequested = true;
halfclosed = true; // halfclose not confirmed yet, but it will be once finishedHandler is called.
byte[] payload = UnsafeSerialize(msg);
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartServerStreaming(payload, HandleFinished, metadataArray);
}
}
}
/// <summary>
/// Starts a streaming request - streaming response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public void StartDuplexStreamingCall(Metadata headers, DateTime deadline)
{
lock (myLock)
{
Preconditions.CheckNotNull(call);
started = true;
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartDuplexStreaming(HandleFinished, metadataArray);
}
}
}
/// <summary>
/// Sends a streaming request. Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendMessage(TRequest msg, AsyncCompletionDelegate<object> completionDelegate)
{
StartSendMessageInternal(msg, completionDelegate);
}
/// <summary>
/// Receives a streaming response. Only one pending read action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartReadMessage(AsyncCompletionDelegate<TResponse> completionDelegate)
{
StartReadMessageInternal(completionDelegate);
}
/// <summary>
/// Sends halfclose, indicating client is done with streaming requests.
/// Only one pending send action is allowed at any given time.
/// completionDelegate is called when the operation finishes.
/// </summary>
public void StartSendCloseFromClient(AsyncCompletionDelegate<object> completionDelegate)
{
lock (myLock)
{
Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null");
CheckSendingAllowed();
call.StartSendCloseFromClient(HandleHalfclosed);
halfcloseRequested = true;
sendCompletionDelegate = completionDelegate;
}
}
/// <summary>
/// Gets the resulting status if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Status GetStatus()
{
lock (myLock)
{
Preconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished.");
return finishedStatus.Value.Status;
}
}
/// <summary>
/// Gets the trailing metadata if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Metadata GetTrailers()
{
lock (myLock)
{
Preconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished.");
return finishedStatus.Value.Trailers;
}
}
/// <summary>
/// On client-side, we only fire readCompletionDelegate once all messages have been read
/// and status has been received.
/// </summary>
protected override void ProcessLastRead(AsyncCompletionDelegate<TResponse> completionDelegate)
{
if (completionDelegate != null && readingDone && finishedStatus.HasValue)
{
bool shouldComplete;
lock (myLock)
{
shouldComplete = !readObserverCompleted;
readObserverCompleted = true;
}
if (shouldComplete)
{
var status = finishedStatus.Value.Status;
if (status.StatusCode != StatusCode.OK)
{
FireCompletion(completionDelegate, default(TResponse), new RpcException(status));
}
else
{
FireCompletion(completionDelegate, default(TResponse), null);
}
}
}
}
protected override void OnReleaseResources()
{
channel.Environment.DebugStats.ActiveClientCalls.Decrement();
}
/// <summary>
/// Handler for unary response completion.
/// </summary>
private void HandleUnaryResponse(bool success, BatchContextSafeHandle ctx)
{
var fullStatus = ctx.GetReceivedStatusOnClient();
lock (myLock)
{
finished = true;
finishedStatus = fullStatus;
halfclosed = true;
ReleaseResourcesIfPossible();
}
if (!success)
{
unaryResponseTcs.SetException(new RpcException(new Status(StatusCode.Internal, "Internal error occured.")));
return;
}
var status = fullStatus.Status;
if (status.StatusCode != StatusCode.OK)
{
unaryResponseTcs.SetException(new RpcException(status));
return;
}
// TODO: handle deserialization error
TResponse msg;
TryDeserialize(ctx.GetReceivedMessage(), out msg);
unaryResponseTcs.SetResult(msg);
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleFinished(bool success, BatchContextSafeHandle ctx)
{
var fullStatus = ctx.GetReceivedStatusOnClient();
AsyncCompletionDelegate<TResponse> origReadCompletionDelegate = null;
lock (myLock)
{
finished = true;
finishedStatus = fullStatus;
origReadCompletionDelegate = readCompletionDelegate;
ReleaseResourcesIfPossible();
}
ProcessLastRead(origReadCompletionDelegate);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RecommendationsOperations operations.
/// </summary>
public partial interface IRecommendationsOperations
{
/// <summary>
/// List all recommendations for a subscription.
/// </summary>
/// <remarks>
/// List all recommendations for a subscription.
/// </remarks>
/// <param name='featured'>
/// Specify <code>true</code> to return only the most
/// critical recommendations. The default is
/// <code>false</code>, which returns all recommendations.
/// </param>
/// <param name='filter'>
/// Filter is specified by using OData syntax. Example:
/// $filter=channels eq 'Api' or channel eq 'Notification' and
/// startTime eq '2014-01-01T00:00:00Z' and endTime eq
/// '2014-12-31T23:59:59Z' and timeGrain eq duration'[PT1H|PT1M|P1D]
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IList<Recommendation>>> ListWithHttpMessagesAsync(bool? featured = default(bool?), string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Reset all recommendation opt-out settings for a subscription.
/// </summary>
/// <remarks>
/// Reset all recommendation opt-out settings for a subscription.
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ResetAllFiltersWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get past recommendations for an app, optionally specified by the
/// time range.
/// </summary>
/// <remarks>
/// Get past recommendations for an app, optionally specified by the
/// time range.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='siteName'>
/// Name of the app.
/// </param>
/// <param name='filter'>
/// Filter is specified by using OData syntax. Example:
/// $filter=channels eq 'Api' or channel eq 'Notification' and
/// startTime eq '2014-01-01T00:00:00Z' and endTime eq
/// '2014-12-31T23:59:59Z' and timeGrain eq duration'[PT1H|PT1M|P1D]
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IList<Recommendation>>> ListHistoryForWebAppWithHttpMessagesAsync(string resourceGroupName, string siteName, string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get all recommendations for an app.
/// </summary>
/// <remarks>
/// Get all recommendations for an app.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='siteName'>
/// Name of the app.
/// </param>
/// <param name='featured'>
/// Specify <code>true</code> to return only the most
/// critical recommendations. The default is
/// <code>false</code>, which returns all recommendations.
/// </param>
/// <param name='filter'>
/// Return only channels specified in the filter. Filter is specified
/// by using OData syntax. Example: $filter=channels eq 'Api' or
/// channel eq 'Notification'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IList<Recommendation>>> ListRecommendedRulesForWebAppWithHttpMessagesAsync(string resourceGroupName, string siteName, bool? featured = default(bool?), string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Disable all recommendations for an app.
/// </summary>
/// <remarks>
/// Disable all recommendations for an app.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='siteName'>
/// Name of the app.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DisableAllForWebAppWithHttpMessagesAsync(string resourceGroupName, string siteName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Reset all recommendation opt-out settings for an app.
/// </summary>
/// <remarks>
/// Reset all recommendation opt-out settings for an app.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='siteName'>
/// Name of the app.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> ResetAllFiltersForWebAppWithHttpMessagesAsync(string resourceGroupName, string siteName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a recommendation rule for an app.
/// </summary>
/// <remarks>
/// Get a recommendation rule for an app.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='siteName'>
/// Name of the app.
/// </param>
/// <param name='name'>
/// Name of the recommendation.
/// </param>
/// <param name='updateSeen'>
/// Specify <code>true</code> to update the last-seen
/// timestamp of the recommendation object.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<RecommendationRule>> GetRuleDetailsByWebAppWithHttpMessagesAsync(string resourceGroupName, string siteName, string name, bool? updateSeen = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.