context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace applicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for NetworkWatchersOperations.
/// </summary>
public static partial class NetworkWatchersOperationsExtensions
{
/// <summary>
/// Creates or updates a network watcher in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the network watcher resource.
/// </param>
public static NetworkWatcher CreateOrUpdate(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, NetworkWatcher parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a network watcher in the specified resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the network watcher resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkWatcher> CreateOrUpdateAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, NetworkWatcher parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the specified network watcher by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
public static NetworkWatcher Get(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName)
{
return operations.GetAsync(resourceGroupName, networkWatcherName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified network watcher by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkWatcher> GetAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkWatcherName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified network watcher resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
public static void Delete(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName)
{
operations.DeleteAsync(resourceGroupName, networkWatcherName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network watcher resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets all network watchers by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IEnumerable<NetworkWatcher> List(this INetworkWatchersOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network watchers by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<NetworkWatcher>> ListAsync(this INetworkWatchersOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network watchers by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IEnumerable<NetworkWatcher> ListAll(this INetworkWatchersOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network watchers by subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<NetworkWatcher>> ListAllAsync(this INetworkWatchersOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the current network topology by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the representation of topology.
/// </param>
public static Topology GetTopology(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, TopologyParameters parameters)
{
return operations.GetTopologyAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the current network topology by resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the representation of topology.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Topology> GetTopologyAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, TopologyParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetTopologyWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Verify IP flow from the specified VM to a location given the currently
/// configured NSG rules.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the IP flow to be verified.
/// </param>
public static VerificationIPFlowResult VerifyIPFlow(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters)
{
return operations.VerifyIPFlowAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Verify IP flow from the specified VM to a location given the currently
/// configured NSG rules.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the IP flow to be verified.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VerificationIPFlowResult> VerifyIPFlowAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.VerifyIPFlowWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the next hop from the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the source and destination endpoint.
/// </param>
public static NextHopResult GetNextHop(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, NextHopParameters parameters)
{
return operations.GetNextHopAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next hop from the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the source and destination endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NextHopResult> GetNextHopAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, NextHopParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNextHopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the configured and effective security group rules on the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the VM to check security groups for.
/// </param>
public static SecurityGroupViewResult GetVMSecurityRules(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters)
{
return operations.GetVMSecurityRulesAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the configured and effective security group rules on the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the VM to check security groups for.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityGroupViewResult> GetVMSecurityRulesAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetVMSecurityRulesWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Initiate troubleshooting on a specified resource
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to troubleshoot.
/// </param>
public static TroubleshootingResult GetTroubleshooting(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters)
{
return operations.GetTroubleshootingAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Initiate troubleshooting on a specified resource
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to troubleshoot.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<TroubleshootingResult> GetTroubleshootingAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetTroubleshootingWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get the last completed troubleshooting result on a specified resource
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to query the troubleshooting result.
/// </param>
public static TroubleshootingResult GetTroubleshootingResult(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters)
{
return operations.GetTroubleshootingResultAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Get the last completed troubleshooting result on a specified resource
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to query the troubleshooting result.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<TroubleshootingResult> GetTroubleshootingResultAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetTroubleshootingResultWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Configures flow log on a specified resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the configuration of flow log.
/// </param>
public static FlowLogInformation SetFlowLogConfiguration(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, FlowLogInformation parameters)
{
return operations.SetFlowLogConfigurationAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Configures flow log on a specified resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the configuration of flow log.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FlowLogInformation> SetFlowLogConfigurationAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.SetFlowLogConfigurationWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Queries status of flow log on a specified resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define a resource to query flow log status.
/// </param>
public static FlowLogInformation GetFlowLogStatus(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters)
{
return operations.GetFlowLogStatusAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Queries status of flow log on a specified resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define a resource to query flow log status.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FlowLogInformation> GetFlowLogStatusAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetFlowLogStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified network watcher resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
public static void BeginDelete(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName)
{
operations.BeginDeleteAsync(resourceGroupName, networkWatcherName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network watcher resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Verify IP flow from the specified VM to a location given the currently
/// configured NSG rules.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the IP flow to be verified.
/// </param>
public static VerificationIPFlowResult BeginVerifyIPFlow(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters)
{
return operations.BeginVerifyIPFlowAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Verify IP flow from the specified VM to a location given the currently
/// configured NSG rules.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the IP flow to be verified.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<VerificationIPFlowResult> BeginVerifyIPFlowAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, VerificationIPFlowParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginVerifyIPFlowWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the next hop from the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the source and destination endpoint.
/// </param>
public static NextHopResult BeginGetNextHop(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, NextHopParameters parameters)
{
return operations.BeginGetNextHopAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the next hop from the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the source and destination endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NextHopResult> BeginGetNextHopAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, NextHopParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetNextHopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the configured and effective security group rules on the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the VM to check security groups for.
/// </param>
public static SecurityGroupViewResult BeginGetVMSecurityRules(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters)
{
return operations.BeginGetVMSecurityRulesAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the configured and effective security group rules on the specified VM.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='parameters'>
/// Parameters that define the VM to check security groups for.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SecurityGroupViewResult> BeginGetVMSecurityRulesAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, SecurityGroupViewParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetVMSecurityRulesWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Initiate troubleshooting on a specified resource
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to troubleshoot.
/// </param>
public static TroubleshootingResult BeginGetTroubleshooting(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters)
{
return operations.BeginGetTroubleshootingAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Initiate troubleshooting on a specified resource
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to troubleshoot.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<TroubleshootingResult> BeginGetTroubleshootingAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, TroubleshootingParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetTroubleshootingWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get the last completed troubleshooting result on a specified resource
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to query the troubleshooting result.
/// </param>
public static TroubleshootingResult BeginGetTroubleshootingResult(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters)
{
return operations.BeginGetTroubleshootingResultAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Get the last completed troubleshooting result on a specified resource
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the resource to query the troubleshooting result.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<TroubleshootingResult> BeginGetTroubleshootingResultAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, QueryTroubleshootingParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetTroubleshootingResultWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Configures flow log on a specified resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the configuration of flow log.
/// </param>
public static FlowLogInformation BeginSetFlowLogConfiguration(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, FlowLogInformation parameters)
{
return operations.BeginSetFlowLogConfigurationAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Configures flow log on a specified resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define the configuration of flow log.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FlowLogInformation> BeginSetFlowLogConfigurationAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, FlowLogInformation parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginSetFlowLogConfigurationWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Queries status of flow log on a specified resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define a resource to query flow log status.
/// </param>
public static FlowLogInformation BeginGetFlowLogStatus(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters)
{
return operations.BeginGetFlowLogStatusAsync(resourceGroupName, networkWatcherName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Queries status of flow log on a specified resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the network watcher resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher resource.
/// </param>
/// <param name='parameters'>
/// Parameters that define a resource to query flow log status.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<FlowLogInformation> BeginGetFlowLogStatusAsync(this INetworkWatchersOperations operations, string resourceGroupName, string networkWatcherName, FlowLogStatusParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginGetFlowLogStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
namespace au.util.io
{
public enum FtpTransferType {
Binary,
ASCII
}
/// <summary>
/// Client connection to an FTP server
/// </summary>
public class FtpClient {
#region Constants
private const int BLOCKSIZE = 512;
#endregion // Constants
#region Data Members
private Socket _sock;
private IPEndPoint _ip;
private int _rspCode;
private string _rspMessage;
#endregion // Data Members
#region Constructors
/// <summary>
/// Set parameters for FTP connection
/// </summary>
/// <param name="hostname">Name of FTP server to connect to</param>
/// <param name="port">Port of FTP server to connect to</param>
public FtpClient(string hostname, int port) {
_sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_ip = new IPEndPoint(Dns.Resolve(hostname).AddressList[0], port);
}
#endregion // Constructors
#region Properties
/// <summary>
/// Last response code recieved from the FTP server
/// </summary>
public int Code {
get {return _rspCode;}
}
/// <summary>
/// Last message recieved from the FTP server
/// </summary>
public string Message {
get {return _rspMessage;}
}
#endregion // Properties
#region Methods
/// <summary>
/// Attempts to open the FTP connection
/// </summary>
/// <param name="username">Username to log in to FTP server with</param>
/// <param name="password">Password to log in to FTP server with</param>
/// <returns>True if the connection is opened</returns>
public bool Open(string username, string password) {
_sock.Connect(_ip);
GetResponse();
if(_rspCode != 220) {
Close();
return false;
}
SendCommand("USER " + username);
if(_rspCode != 230 && _rspCode != 331) {
Bye();
return false;
}
if(_rspCode != 230) {
SendCommand("PASS " + password);
if(_rspCode != 230 && _rspCode != 202) {
Bye();
return false;
}
}
return true;
}
/// <summary>
/// Closes the FTP connection
/// </summary>
public void Bye() {
if(_sock != null)
SendCommand("QUIT");
Close();
}
/// <summary>
/// Closes the socket used by the FTP connection
/// </summary>
private void Close() {
if(_sock != null)
_sock.Close();
}
/// <summary>
/// Sends a command to the FTP server
/// </summary>
/// <param name="command"></param>
public void SendCommand(string command) {
byte[] buffer = Encoding.ASCII.GetBytes((command + "\r\n").ToCharArray());
_sock.Send(buffer);
GetResponse();
}
/// <summary>
/// Change working directory on the FTP server
/// </summary>
/// <param name="path">Directory to change to</param>
/// <returns>True if successful</returns>
public bool CWD(string path) {
SendCommand("CWD " + path);
return _rspCode == 250;
}
/// <summary>
/// Sends a file to the FTP server
/// </summary>
/// <param name="filename">Full path to the file to send</param>
/// <returns>True if file is sent</returns>
public bool SendFile(string filename, FtpTransferType type) {
if(type.Equals(FtpTransferType.ASCII))
SendCommand("TYPE A");
else
SendCommand("TYPE I");
if(_rspCode != 200)
return false;
Socket data = OpenDataSocket();
if(data == null) {
_rspCode = -1;
_rspMessage = Properties.Resources.ErrorFtpOpenSocket;
return false;
}
SendCommand("STOR " + Path.GetFileName(filename));
if(_rspCode != 125 && _rspCode != 150)
return false;
try {
FileStream fs = new FileStream(filename, FileMode.Open);
byte[] buffer = new byte[BLOCKSIZE];
int bytes;
while((bytes = fs.Read(buffer, 0, BLOCKSIZE)) > 0) {
data.Send(buffer, bytes, 0);
}
fs.Close();
data.Close();
GetResponse();
if(_rspCode != 226 && _rspCode != 250)
return false;
return true;
} catch {
_rspCode = -1;
_rspMessage = Properties.Resources.ErrorFtpReadFile;
return false;
}
}
/// <summary>
/// Sends a string to the FTP server as a file
/// </summary>
/// <param name="filename">File name to create on FTP server (no path)</param>
/// <param name="contents">Contents of the file to create</param>
/// <returns>True if file is sent</returns>
public bool SendText(string filename, string contents) {
SendCommand("TYPE A");
if(_rspCode != 200)
return false;
Socket data = OpenDataSocket();
if(data == null) {
_rspCode = -1;
_rspMessage = Properties.Resources.ErrorFtpOpenSocket;
return false;
}
SendCommand("STOR " + filename);
if(_rspCode != 125 && _rspCode != 150)
return false;
byte[] buffer;
for(int pos = 0; pos < contents.Length; pos += BLOCKSIZE) {
if(contents.Length - pos < BLOCKSIZE)
buffer = Encoding.ASCII.GetBytes(contents.ToCharArray(), pos, contents.Length - pos);
else
buffer = Encoding.ASCII.GetBytes(contents.ToCharArray(), pos, BLOCKSIZE);
data.Send(buffer, buffer.Length, 0);
}
data.Close();
GetResponse();
if(_rspCode != 226 && _rspCode != 250)
return false;
return true;
}
#endregion // Methods
#region Private Methods
/// <summary>
/// Read the response from the FTP server
/// </summary>
private void GetResponse() {
byte[] buffer = new byte[BLOCKSIZE];
int bytes;
string msg = "";
do {
bytes = _sock.Receive(buffer, BLOCKSIZE, 0);
msg += Encoding.ASCII.GetString(buffer, 0, bytes);
} while(bytes > BLOCKSIZE);
string[] msgAr = msg.Replace("\r\n", "\n").Split('\n');
if(msgAr.Length > 2)
msg = msgAr[msgAr.Length - 2];
else
msg = msgAr[0];
_rspCode = int.Parse(msg.Substring(0, 3));
_rspMessage = msg.Substring(4);
}
/// <summary>
/// Open a data socket for transferring
/// </summary>
/// <returns></returns>
private Socket OpenDataSocket() {
SendCommand("PASV");
if(_rspCode != 227)
return null;
try {
string[] pasvdata = _rspMessage.Split('(')[1].Split(')')[0].Split(',');
string ipAddress = pasvdata[0] + '.' + pasvdata[1] + '.' + pasvdata[2] + '.' + pasvdata[3];
int port = (int.Parse(pasvdata[4]) << 8) + int.Parse(pasvdata[5]);
IPEndPoint ip = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try {
sock.Connect(ip);
return sock;
} catch {
return null;
}
} catch {
return null; // response to PASV not as expected
}
}
#endregion // Private Methods
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
// Include Silverlight's managed resources
#if SILVERLIGHT
using System.Core;
#endif //SILVERLIGHT
namespace System.Linq {
public interface IQueryable : IEnumerable {
Expression Expression { get; }
Type ElementType { get; }
// the provider that created this query
IQueryProvider Provider { get; }
}
public interface IQueryable<out T> : IEnumerable<T>, IQueryable {
}
public interface IQueryProvider{
IQueryable CreateQuery(Expression expression);
IQueryable<TElement> CreateQuery<TElement>(Expression expression);
object Execute(Expression expression);
TResult Execute<TResult>(Expression expression);
}
public interface IOrderedQueryable : IQueryable {
}
public interface IOrderedQueryable<out T> : IQueryable<T>, IOrderedQueryable {
}
public static class Queryable {
public static IQueryable<TElement> AsQueryable<TElement>(this IEnumerable<TElement> source) {
if (source == null)
throw Error.ArgumentNull("source");
if (source is IQueryable<TElement>)
return (IQueryable<TElement>)source;
return new EnumerableQuery<TElement>(source);
}
public static IQueryable AsQueryable(this IEnumerable source) {
if (source == null)
throw Error.ArgumentNull("source");
if (source is IQueryable)
return (IQueryable)source;
Type enumType = TypeHelper.FindGenericType(typeof(IEnumerable<>), source.GetType());
if (enumType == null)
throw Error.ArgumentNotIEnumerableGeneric("source");
return EnumerableQuery.Create(enumType.GetGenericArguments()[0], source);
}
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static IQueryable<TResult> OfType<TResult>(this IQueryable source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TResult)),
new Expression[] { source.Expression }
));
}
public static IQueryable<TResult> Cast<TResult>(this IQueryable source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TResult)),
new Expression[] { source.Expression }
));
}
public static IQueryable<TResult> Select<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static IQueryable<TResult> Select<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, int, TResult>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static IQueryable<TResult> SelectMany<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, IEnumerable<TResult>>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static IQueryable<TResult> SelectMany<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, int, IEnumerable<TResult>>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static IQueryable<TResult> SelectMany<TSource, TCollection, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, int, IEnumerable<TCollection>>> collectionSelector, Expression<Func<TSource, TCollection, TResult>> resultSelector){
if (source == null)
throw Error.ArgumentNull("source");
if (collectionSelector == null)
throw Error.ArgumentNull("collectionSelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TCollection), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(collectionSelector), Expression.Quote(resultSelector) }
));
}
public static IQueryable<TResult> SelectMany<TSource,TCollection,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, IEnumerable<TCollection>>> collectionSelector, Expression<Func<TSource, TCollection, TResult>> resultSelector) {
if (source == null)
throw Error.ArgumentNull("source");
if (collectionSelector == null)
throw Error.ArgumentNull("collectionSelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TCollection), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(collectionSelector), Expression.Quote(resultSelector) }
));
}
private static Expression GetSourceExpression<TSource>(IEnumerable<TSource> source) {
IQueryable<TSource> q = source as IQueryable<TSource>;
if (q != null) return q.Expression;
return Expression.Constant(source, typeof(IEnumerable<TSource>));
}
public static IQueryable<TResult> Join<TOuter,TInner,TKey,TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter,TKey>> outerKeySelector, Expression<Func<TInner,TKey>> innerKeySelector, Expression<Func<TOuter,TInner,TResult>> resultSelector) {
if (outer == null)
throw Error.ArgumentNull("outer");
if (inner == null)
throw Error.ArgumentNull("inner");
if (outerKeySelector == null)
throw Error.ArgumentNull("outerKeySelector");
if (innerKeySelector == null)
throw Error.ArgumentNull("innerKeySelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return outer.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(TResult)),
new Expression[] {
outer.Expression,
GetSourceExpression(inner),
Expression.Quote(outerKeySelector),
Expression.Quote(innerKeySelector),
Expression.Quote(resultSelector)
}
));
}
public static IQueryable<TResult> Join<TOuter, TInner, TKey, TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<TOuter, TInner, TResult>> resultSelector, IEqualityComparer<TKey> comparer) {
if (outer == null)
throw Error.ArgumentNull("outer");
if (inner == null)
throw Error.ArgumentNull("inner");
if (outerKeySelector == null)
throw Error.ArgumentNull("outerKeySelector");
if (innerKeySelector == null)
throw Error.ArgumentNull("innerKeySelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return outer.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(TResult)),
new Expression[] {
outer.Expression,
GetSourceExpression(inner),
Expression.Quote(outerKeySelector),
Expression.Quote(innerKeySelector),
Expression.Quote(resultSelector),
Expression.Constant(comparer, typeof(IEqualityComparer<TKey>))
}
));
}
public static IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<TOuter, IEnumerable<TInner>, TResult>> resultSelector) {
if (outer == null)
throw Error.ArgumentNull("outer");
if (inner == null)
throw Error.ArgumentNull("inner");
if (outerKeySelector == null)
throw Error.ArgumentNull("outerKeySelector");
if (innerKeySelector == null)
throw Error.ArgumentNull("innerKeySelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return outer.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(TResult)),
new Expression[] {
outer.Expression,
GetSourceExpression(inner),
Expression.Quote(outerKeySelector),
Expression.Quote(innerKeySelector),
Expression.Quote(resultSelector) }
));
}
public static IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<TOuter, IEnumerable<TInner>, TResult>> resultSelector, IEqualityComparer<TKey> comparer) {
if (outer == null)
throw Error.ArgumentNull("outer");
if (inner == null)
throw Error.ArgumentNull("inner");
if (outerKeySelector == null)
throw Error.ArgumentNull("outerKeySelector");
if (innerKeySelector == null)
throw Error.ArgumentNull("innerKeySelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return outer.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TOuter), typeof(TInner), typeof(TKey), typeof(TResult)),
new Expression[] {
outer.Expression,
GetSourceExpression(inner),
Expression.Quote(outerKeySelector),
Expression.Quote(innerKeySelector),
Expression.Quote(resultSelector),
Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) }
));
}
public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector)
{
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector) }
));
}
public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer<TKey>)) }
));
}
public static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector) }
));
}
public static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer<TKey>)) }
));
}
public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector) }
));
}
public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer<TKey>)) }
));
}
public static IOrderedQueryable<TSource> ThenByDescending<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector) }
));
}
public static IOrderedQueryable<TSource> ThenByDescending<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer<TKey>)) }
));
}
public static IQueryable<TSource> Take<TSource>(this IQueryable<TSource> source, int count) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Constant(count) }
));
}
public static IQueryable<TSource> TakeWhile<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static IQueryable<TSource> TakeWhile<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static IQueryable<TSource> Skip<TSource>(this IQueryable<TSource> source, int count) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Constant(count) }
));
}
public static IQueryable<TSource> SkipWhile<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static IQueryable<TSource> SkipWhile<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static IQueryable<IGrouping<TKey,TSource>> GroupBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return source.Provider.CreateQuery<IGrouping<TKey,TSource>>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector) }
));
}
public static IQueryable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
if (elementSelector == null)
throw Error.ArgumentNull("elementSelector");
return source.Provider.CreateQuery<IGrouping<TKey,TElement>>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey), typeof(TElement)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector) }
));
}
public static IQueryable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IEqualityComparer<TKey> comparer) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
return source.Provider.CreateQuery<IGrouping<TKey,TSource>>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) }
));
}
public static IQueryable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource,TElement>> elementSelector, IEqualityComparer<TKey> comparer) {
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
if (elementSelector == null)
throw Error.ArgumentNull("elementSelector");
return source.Provider.CreateQuery<IGrouping<TKey,TElement>>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey), typeof(TElement)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) }
));
}
public static IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector, Expression<Func<TKey, IEnumerable<TElement>, TResult>> resultSelector)
{
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
if (elementSelector == null)
throw Error.ArgumentNull("elementSelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey), typeof(TElement), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector), Expression.Quote(resultSelector) }
));
}
public static IQueryable<TResult> GroupBy<TSource, TKey, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector,Expression<Func<TKey, IEnumerable<TSource>, TResult>> resultSelector)
{
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(resultSelector) }
));
}
public static IQueryable<TResult> GroupBy<TSource, TKey, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TKey, IEnumerable<TSource>, TResult>> resultSelector, IEqualityComparer<TKey> comparer)
{
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) }
));
}
public static IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector, Expression<Func<TKey, IEnumerable<TElement>, TResult>> resultSelector, IEqualityComparer<TKey> comparer)
{
if (source == null)
throw Error.ArgumentNull("source");
if (keySelector == null)
throw Error.ArgumentNull("keySelector");
if (elementSelector == null)
throw Error.ArgumentNull("elementSelector");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return source.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TKey), typeof(TElement), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) }
));
}
public static IQueryable<TSource> Distinct<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static IQueryable<TSource> Distinct<TSource>(this IQueryable<TSource> source, IEqualityComparer<TSource> comparer) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Constant(comparer, typeof(IEqualityComparer<TSource>)) }
));
}
public static IQueryable<TSource> Concat<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
return source1.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source1.Expression, GetSourceExpression(source2) }
));
}
public static IQueryable<TResult> Zip<TFirst, TSecond, TResult>(this IQueryable<TFirst> source1, IEnumerable<TSecond> source2, Expression<Func<TFirst, TSecond, TResult>> resultSelector) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
if (resultSelector == null)
throw Error.ArgumentNull("resultSelector");
return source1.Provider.CreateQuery<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TFirst), typeof(TSecond), typeof(TResult)),
new Expression[] { source1.Expression, GetSourceExpression(source2), Expression.Quote(resultSelector) }
));
}
public static IQueryable<TSource> Union<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
return source1.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source1.Expression, GetSourceExpression(source2) }
));
}
public static IQueryable<TSource> Union<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
return source1.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] {
source1.Expression,
GetSourceExpression(source2),
Expression.Constant(comparer, typeof(IEqualityComparer<TSource>))
}
));
}
public static IQueryable<TSource> Intersect<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
return source1.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source1.Expression, GetSourceExpression(source2) }
));
}
public static IQueryable<TSource> Intersect<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
return source1.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] {
source1.Expression,
GetSourceExpression(source2),
Expression.Constant(comparer, typeof(IEqualityComparer<TSource>))
}
));
}
public static IQueryable<TSource> Except<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
return source1.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source1.Expression, GetSourceExpression(source2) }
));
}
public static IQueryable<TSource> Except<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
return source1.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] {
source1.Expression,
GetSourceExpression(source2),
Expression.Constant(comparer, typeof(IEqualityComparer<TSource>))
}
));
}
public static TSource First<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static TSource First<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static TSource FirstOrDefault<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static TSource FirstOrDefault<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static TSource Last<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static TSource Last<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static TSource LastOrDefault<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static TSource LastOrDefault<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static TSource Single<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static TSource Single<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static TSource SingleOrDefault<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static TSource SingleOrDefault<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static TSource ElementAt<TSource>(this IQueryable<TSource> source, int index) {
if (source == null)
throw Error.ArgumentNull("source");
if (index < 0)
throw Error.ArgumentOutOfRange("index");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Constant(index) }
));
}
public static TSource ElementAtOrDefault<TSource>(this IQueryable<TSource> source, int index) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Constant(index) }
));
}
public static IQueryable<TSource> DefaultIfEmpty<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static IQueryable<TSource> DefaultIfEmpty<TSource>(this IQueryable<TSource> source, TSource defaultValue) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Constant(defaultValue, typeof(TSource)) }
));
}
public static bool Contains<TSource>(this IQueryable<TSource> source, TSource item) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<bool>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Constant(item, typeof(TSource)) }
));
}
public static bool Contains<TSource>(this IQueryable<TSource> source, TSource item, IEqualityComparer<TSource> comparer) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<bool>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Constant(item, typeof(TSource)), Expression.Constant(comparer, typeof(IEqualityComparer<TSource>)) }
));
}
public static IQueryable<TSource> Reverse<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.CreateQuery<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static bool SequenceEqual<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
return source1.Provider.Execute<bool>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source1.Expression, GetSourceExpression(source2) }
));
}
public static bool SequenceEqual<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) {
if (source1 == null)
throw Error.ArgumentNull("source1");
if (source2 == null)
throw Error.ArgumentNull("source2");
return source1.Provider.Execute<bool>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] {
source1.Expression,
GetSourceExpression(source2),
Expression.Constant(comparer, typeof(IEqualityComparer<TSource>))
}
));
}
public static bool Any<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<bool>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static bool Any<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<bool>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static bool All<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<bool>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static int Count<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<int>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static int Count<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<int>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static long LongCount<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<long>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static long LongCount<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) {
if (source == null)
throw Error.ArgumentNull("source");
if (predicate == null)
throw Error.ArgumentNull("predicate");
return source.Provider.Execute<long>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(predicate) }
));
}
public static TSource Min<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static TResult Min<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource,TResult>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static TSource Max<TSource>(this IQueryable<TSource> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression }
));
}
public static TResult Max<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource,TResult>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TResult)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static int Sum(this IQueryable<int> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<int>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static int? Sum(this IQueryable<int?> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<int?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static long Sum(this IQueryable<long> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<long>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static long? Sum(this IQueryable<long?> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<long?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static float Sum(this IQueryable<float> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<float>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static float? Sum(this IQueryable<float?> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<float?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static double Sum(this IQueryable<double> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<double>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static double? Sum(this IQueryable<double?> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<double?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static decimal Sum(this IQueryable<decimal> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<decimal>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static decimal? Sum(this IQueryable<decimal?> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<decimal?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static int Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,int>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<int>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static int? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,int?>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<int?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static long Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,long>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<long>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static long? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,long?>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<long?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static float Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,float>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<float>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static float? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,float?>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<float?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static double Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,double>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<double>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static double? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,double?>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<double?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static decimal Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,decimal>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<decimal>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static decimal? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,decimal?>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<decimal?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static double Average(this IQueryable<int> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<double>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static double? Average(this IQueryable<int?> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<double?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static double Average(this IQueryable<long> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<double>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static double? Average(this IQueryable<long?> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<double?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static float Average(this IQueryable<float> source)
{
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<float>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static float? Average(this IQueryable<float?> source)
{
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<float?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static double Average(this IQueryable<double> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<double>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static double? Average(this IQueryable<double?> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<double?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static decimal Average(this IQueryable<decimal> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<decimal>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static decimal? Average(this IQueryable<decimal?> source) {
if (source == null)
throw Error.ArgumentNull("source");
return source.Provider.Execute<decimal?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()),
new Expression[] { source.Expression }
));
}
public static double Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,int>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<double>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static double? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,int?>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<double?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static float Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float>> selector)
{
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<float>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static float? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float?>> selector)
{
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<float?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static double Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,long>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<double>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static double? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,long?>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<double?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static double Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,double>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<double>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static double? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,double?>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<double?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static decimal Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,decimal>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<decimal>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static decimal? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,decimal?>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<decimal?>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(selector) }
));
}
public static TSource Aggregate<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,TSource,TSource>> func) {
if (source == null)
throw Error.ArgumentNull("source");
if (func == null)
throw Error.ArgumentNull("func");
return source.Provider.Execute<TSource>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource)),
new Expression[] { source.Expression, Expression.Quote(func) }
));
}
public static TAccumulate Aggregate<TSource,TAccumulate>(this IQueryable<TSource> source, TAccumulate seed, Expression<Func<TAccumulate,TSource,TAccumulate>> func) {
if (source == null)
throw Error.ArgumentNull("source");
if (func == null)
throw Error.ArgumentNull("func");
return source.Provider.Execute<TAccumulate>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TAccumulate)),
new Expression[] { source.Expression, Expression.Constant(seed), Expression.Quote(func) }
));
}
public static TResult Aggregate<TSource,TAccumulate,TResult>(this IQueryable<TSource> source, TAccumulate seed, Expression<Func<TAccumulate,TSource,TAccumulate>> func, Expression<Func<TAccumulate,TResult>> selector) {
if (source == null)
throw Error.ArgumentNull("source");
if (func == null)
throw Error.ArgumentNull("func");
if (selector == null)
throw Error.ArgumentNull("selector");
return source.Provider.Execute<TResult>(
Expression.Call(
null,
((MethodInfo)MethodBase.GetCurrentMethod()).MakeGenericMethod(typeof(TSource), typeof(TAccumulate), typeof(TResult)),
new Expression[] { source.Expression, Expression.Constant(seed), Expression.Quote(func), Expression.Quote(selector) }
));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Xml;
using System.IO;
using System.Threading;
using Microsoft.Win32; // for registry
namespace LibSystem
{
public sealed class Project
{
public const string PROGRAM_VERSION_RELEASEDATE = "20070220";
public static string driveSystem = "C:\\";
public static string driveProgramInstalled = "C:\\";
public static string DEFAULT_PREF_DIR = "C:\\Program Files\\Common Files";
public const string DEFAULT_PREF_FILE = "msvb_6572.sys";
private const string registryKeyPath = "Software\\VitalBytes\\RMRobot";
// The following are filled with paths relative to current directory in Project():
public static string startupPath;
private static string iniFilePath;
private static string miscFolderPath;
public const string iniFileName = "rmrobot.ini"; // make sure installation script makes this one
public const string PROGRAM_NAME_LOGICAL = "rmrobot"; // used for making URLs on the servers
public const string PROGRAM_NAME_HUMAN = "RealMansRobot"; // used for title in the frame etc.
public const string PROGRAM_VERSION_HUMAN = "0.5"; // used for greeting.
public const string WEBSITE_NAME_HUMAN = "QuakeMap.com"; // used for watermark printing etc.
public const string WEBSITE_LINK_WEBSTYLE = "http://www.quakemap.com"; // used for links etc.
public static CommBaseSettings controllerPortSettings = new CommBaseSettings();
public const string CONTROLLER_PORTCONFIG_FILE_NAME = "portsettings";
public const string OPTIONS_FILE_NAME = "options.xml";
public const string SEED_XML = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\"?>";
// debugging tool for Controller protocol:
public static bool controllerLogProtocol = true;
public static bool controllerLogErrors = true;
public static bool controllerLogPackets = true;
#region Constructor and Executables
public Project()
{
FileInfo myExe = new FileInfo(Project.GetLongPathName(Application.ExecutablePath));
startupPath = myExe.Directory.Parent.FullName;
try
{
driveProgramInstalled = startupPath.Substring(0, 3);
string[] str = Directory.GetLogicalDrives();
for (int i = 0; i < str.Length; i++)
{
DirectoryInfo di = new DirectoryInfo(str[i]);
if ((int)di.Attributes > 0 && (di.Attributes & FileAttributes.System) != 0)
{
driveSystem = str[i];
DEFAULT_PREF_DIR = DEFAULT_PREF_DIR.Replace("C:\\", driveSystem);
break;
}
}
}
catch { }
iniFilePath = Path.Combine(startupPath, iniFileName);
if (!File.Exists(iniFilePath))
{
// this is probably click-on-file startup, hope registry key made by installer is ok:
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(registryKeyPath);
if (regKey != null)
{
startupPath = "" + regKey.GetValue("INSTALLDIR");
iniFilePath = Path.Combine(startupPath, iniFileName);
regKey.Close();
}
}
string mainDirPath = readIniFile("MAINDIR");
miscFolderPath = Path.Combine(startupPath, "Misc");
}
~Project()
{
cleanupFilesToDelete();
}
#endregion // Constructor and Executables
#region Read/Write INI file
/*
* this is how the .ini file looks like:
*
[folders]
INSTALLDIR=C:\Program Files\VitalBytes\QuakeMap
WINDIR=C:\WINNT
MAPSDIR=C:\Program Files\VitalBytes\QuakeMap\Maps
SERIALNO=1c309c5638166
*/
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// <summary>
/// Write Data to the INI File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// Section name
/// <PARAM name="Key"></PARAM>
/// Key Name
/// <PARAM name="Value"></PARAM>
/// Value Name
public static void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, iniFilePath);
}
/// <summary>
/// Read Data Value From the Ini File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// <PARAM name="Key"></PARAM>
/// <PARAM name="Path"></PARAM>
/// <returns></returns>
public static string IniReadValue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, iniFilePath);
return temp.ToString();
}
public static string readIniFile(string key)
{
try
{
return IniReadValue("folders", key);
}
catch { }
return "";
}
#endregion // Read/Write INI file
#region System Helpers
public static ArrayList filesToDelete = new ArrayList();
private static void cleanupFilesToDelete()
{
foreach (string fileName in filesToDelete)
{
if (Directory.Exists(fileName))
{
// allow folder removal only in temp path
if (fileName.StartsWith(Path.GetTempPath()))
{
try
{
Directory.Delete(fileName, true);
}
catch { }
}
}
else if (File.Exists(fileName))
{
try
{
File.Delete(fileName);
}
catch { }
}
}
}
public static void writeTextFile(string filename, string content)
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read);
StreamWriter tw = new StreamWriter(fs);
tw.WriteLine(content);
tw.Close();
}
public static Encoding xmlEncoding = Encoding.ASCII;
public static byte[] StrToByteArray(string str)
{
return xmlEncoding.GetBytes(str);
}
public static string ByteArrayToStr(byte[] bytes)
{
return xmlEncoding.GetString(bytes, 0, bytes.Length);
}
[DllImport("kernel32.dll")]
static extern uint GetLongPathName(string shortname, StringBuilder longnamebuff, uint buffersize);
public static string GetLongPathName(string shortname)
{
string ret = "";
if (shortname != null && shortname.Length > 0)
{
StringBuilder longnamebuff = new StringBuilder(512);
uint buffersize = (uint)longnamebuff.Capacity;
GetLongPathName(shortname, longnamebuff, buffersize);
ret = longnamebuff.ToString();
}
return ret;
}
public static string GetMiscPath(string miscFile)
{
if (!Directory.Exists(miscFolderPath))
{
Directory.CreateDirectory(miscFolderPath);
}
return Path.Combine(miscFolderPath, miscFile);
}
public static void setDlgIcon(Form dlg)
{
try
{
string iconFileName = GetMiscPath(PROGRAM_NAME_HUMAN + ".ico");
dlg.Icon = new Icon(iconFileName);
}
catch { }
}
#endregion // System Helpers
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OrderManager.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// Defines the OrderProvider class. Provides order management functionality such as creating, updating and selecting orders.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.Orders
{
using System;
using System.Collections.Generic;
using System.Linq;
using Configuration;
using Data;
using Diagnostics;
using DomainModel.Carts;
using DomainModel.Configurations;
using DomainModel.Data;
using DomainModel.Orders;
using DomainModel.Payments;
using Payments;
using Search;
using SecurityModel;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Exceptions;
using Statuses;
using Utils;
/// <summary>
/// Defines the OrderProvider class. Provides order management functionality such as creating, updating and selecting orders.
/// </summary>
/// <typeparam name="T">The order type</typeparam>
public class OrderManager<T> : IOrderManager<T> where T : DomainModel.Orders.Order
{
/// <summary>
/// The entity helper instance.
/// </summary>
private readonly EntityHelper entityHelper;
/// <summary>
/// The order display template Id.
/// </summary>
private readonly ID orderItemTempalteId = new ID(Settings.GetSetting("Ecommerce.Order.OrderItemTempalteId"));
/// <summary>
/// The order line template Id.
/// </summary>
private readonly TemplateID orderLineItemTempalteId = new TemplateID(new ID(Settings.GetSetting("Ecommerce.Order.OrderLineItemTempalteId")));
/// <summary>
/// The search provider.
/// </summary>
private ISearchProvider searchProvider;
/// <summary>
/// Initializes a new instance of the <see cref="OrderManager<T>"/> class.
/// </summary>
/// <param name="searchProvider">The search provider.</param>
/// <param name="orderIdGenerator">The order id generator.</param>
public OrderManager(ISearchProvider searchProvider, OrderIDGenerator orderIdGenerator)
{
this.entityHelper = Context.Entity.Resolve<EntityHelper>();
this.searchProvider = searchProvider;
this.OrderIDGenerator = orderIdGenerator;
BusinessCatalogSettings settings = Context.Entity.GetConfiguration<BusinessCatalogSettings>();
Assert.IsNotNull(settings, typeof(BusinessCatalogSettings), "Unable initialize BusinessCatalogSettings.");
Assert.IsNotNullOrEmpty(settings.OrdersLink, "Unable initialize Orders root item.");
this.Database = Sitecore.Context.ContentDatabase;
this.ItemId = settings.OrdersLink;
}
/// <summary>
/// Gets or sets the order number generator.
/// </summary>
/// <value>
/// The order number generator.
/// </value>
public OrderIDGenerator OrderIDGenerator { get; set; }
/// <summary>
/// Gets or sets the database.
/// </summary>
/// <value>The database.</value>
protected Database Database { get; set; }
/// <summary>
/// Gets or sets the item id.
/// </summary>
/// <value>The item id.</value>
protected string ItemId { get; set; }
/// <summary>
/// Gets or sets the search provider.
/// </summary>
/// <value>The search provider.</value>
protected virtual ISearchProvider SearchProvider
{
get { return this.searchProvider; }
set { this.searchProvider = value; }
}
/// <summary>
/// Gets the orders source item.
/// </summary>
/// <value>The orders item.</value>
private Item OrdersItem
{
get
{
Assert.IsNotNull(this.Database, "Orders database not found.");
return this.Database.GetItem(this.ItemId);
}
}
#region Implementation of the IOrderManager
/// <summary>
/// Gets the order number.
/// </summary>
/// <returns>
/// If ordernumber exists, returns ordernumber, else returns null.
/// </returns>
public virtual string GenerateOrderNumber()
{
return this.OrderIDGenerator.Generate();
}
/// <summary>
/// Gets the order.
/// </summary>
/// <param name="orderNumber">The order number.</param>
/// <returns>The order.</returns>
public virtual T GetOrder(string orderNumber)
{
Query query = new Query();
query.Add(new FieldQuery("OrderNumber", orderNumber, MatchVariant.Exactly));
return this.GetOrders(query).FirstOrDefault();
}
/// <summary>
/// Gets the orders.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <param name="searchQuery">The search query.</param>
/// <returns>The order collection</returns>
public virtual IEnumerable<T> GetOrders<TQuery>(TQuery searchQuery)
{
return this.GetOrdersItems(searchQuery).Select<Item, T>(this.GetOrderFromItem);
}
/// <summary>
/// Gets the orders.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <param name="query">The query.</param>
/// <param name="pageIndex">Index of the page.</param>
/// <param name="pageSize">Size of the page.</param>
/// <returns>The orders.</returns>
public virtual IEnumerable<T> GetOrders<TQuery>(TQuery query, int pageIndex, int pageSize)
{
return this.GetOrdersItems(query).Skip(pageIndex * pageSize).Take(pageSize).Select<Item, T>(this.GetOrderFromItem);
}
/// <summary>
/// Gets the orders count.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <param name="query">The query.</param>
/// <returns>Return selected orders count.</returns>
public virtual int GetOrdersCount<TQuery>(TQuery query)
{
return this.GetOrdersItems(query).Count();
}
/// <summary>
/// Gets the orders items.
/// </summary>
/// <typeparam name="TQuery">The type of the query.</typeparam>
/// <param name="searchQuery">The search query.</param>
/// <returns>Returns orders items.</returns>
protected virtual IEnumerable<Item> GetOrdersItems<TQuery>(TQuery searchQuery)
{
Assert.ArgumentNotNull(searchQuery, "Query");
Assert.IsTrue(searchQuery is Query, "Query type is invalid");
Query query = searchQuery as Query;
if (string.IsNullOrEmpty(query.SearchRoot))
{
Item orderRoot = this.OrdersItem;
Assert.IsNotNull(orderRoot, "Orders root item is null");
query.SearchRoot = orderRoot.ID.ToString();
}
AttributeQuery templateId = new AttributeQuery("TemplateId", this.orderItemTempalteId.ToString(), MatchVariant.Exactly);
if (!query.Contains(templateId))
{
if (!query.IsEmpty())
{
query.AppendCondition(QueryCondition.And);
}
query.Add(templateId);
}
return this.SearchProvider.Search(query, this.OrdersItem.Database).OrderByDescending(itm => itm["OrderNumber"]);
}
/// <summary>
/// Creates the order.
/// </summary>
/// <typeparam name="TShoppingCart">The type of the shopping cart.</typeparam>
/// <param name="shoppingCart">The shopping cart.</param>
/// <returns>The order.</returns>
/// <exception cref="ConfigurationException">The Order/Default Status For Order Registration setting did't contain a valid Status item.</exception>
/// <exception cref="Exception"><c>Exception</c>.</exception>
public virtual T CreateOrder<TShoppingCart>(TShoppingCart shoppingCart) where TShoppingCart : ShoppingCart
{
Assert.IsNotNull(shoppingCart, "Shopping Cart is null");
Events.Event.RaiseEvent("order:creating", this);
TemplateItem orderTemplateItem = this.Database.GetTemplate(this.orderItemTempalteId);
Assert.IsNotNull(orderTemplateItem, "Order item template is null");
T order = Context.Entity.Resolve<T>();
this.entityHelper.CopyPropertiesValues(shoppingCart, ref order);
foreach (ShoppingCartLine line in shoppingCart.ShoppingCartLines)
{
DomainModel.Orders.OrderLine orderLine = Context.Entity.Resolve<DomainModel.Orders.OrderLine>();
orderLine.Product = line.Product;
orderLine.Totals = line.Totals;
orderLine.Quantity = line.Quantity;
orderLine.FriendlyUrl = line.FriendlyUrl;
order.OrderLines.Add(orderLine);
}
// NOTE: Save transaction number.
ITransactionData transactionData = Context.Entity.Resolve<ITransactionData>();
string transactionNumber = TypeUtil.TryParse(transactionData.GetPersistentValue(shoppingCart.OrderNumber, TransactionConstants.TransactionNumber), string.Empty);
if (!string.IsNullOrEmpty(transactionNumber))
{
order.TransactionNumber = transactionNumber;
}
order.OrderDate = DateTime.Now;
order.Status = Context.Entity.Resolve<NewOrder>();
order.ProcessStatus();
Item orderItem;
using (new SecurityDisabler())
{
orderItem = this.OrdersItem.Add(shoppingCart.OrderNumber, orderTemplateItem);
Assert.IsNotNull(orderItem, "Failed to create to order item");
if (order is IEntity)
{
((IEntity)order).Alias = orderItem.ID.ToString();
}
}
try
{
this.SaveOrder(orderItem, order);
}
catch
{
using (new SecurityDisabler())
{
orderItem.Delete();
}
throw;
}
Events.Event.RaiseEvent("order:created", this, order);
return order;
}
/// <summary>
/// Saves the order.
/// </summary>
/// <param name="order">The order.</param>
/// <exception cref="ConfigurationException">The Order id is invalid.</exception>
public virtual void SaveOrder(T order)
{
Assert.ArgumentNotNull(order, "order");
Item orderItem = this.GetOrderItem(order);
Events.Event.RaiseEvent("order:saving", this, this.GetOrder(order.OrderNumber), order);
this.SaveOrder(orderItem, order);
Events.Event.RaiseEvent("order:saved", this, order);
}
#endregion
/// <summary>
/// Saves the order.
/// </summary>
/// <param name="orderItem">The order item.</param>
/// <param name="order">The order.</param>
protected virtual void SaveOrder(Item orderItem, T order)
{
Assert.ArgumentNotNull(orderItem, "orderItem");
Assert.ArgumentNotNull(order, "order");
IDataMapper dataMapper = Context.Entity.Resolve<IDataMapper>();
dataMapper.SaveEntity(order, orderItem, "OrderMappingRule");
using (new SecurityDisabler())
{
foreach (DomainModel.Orders.OrderLine orderLine in order.OrderLines)
{
Query query = new Query();
query.SearchRoot = orderItem.ID.ToString();
query.AppendAttribute("templateid", this.orderLineItemTempalteId.ToString(), MatchVariant.Exactly);
query.AppendCondition(QueryCondition.And);
query.AppendField("id", orderLine.Product.Code, MatchVariant.Exactly);
Item orderLineItem = this.SearchProvider.Search(query, this.Database).FirstOrDefault();
if (orderLineItem == null)
{
orderLineItem = orderItem.Add(orderLine.Product.Code, this.orderLineItemTempalteId);
}
dataMapper.SaveEntity(orderLine, orderLineItem, "OrderLineMappingRule");
}
}
}
/// <summary>
/// Gets the order from item.
/// </summary>
/// <param name="orderItem">The order item.</param>
/// <returns>The order from item.</returns>
protected virtual T GetOrderFromItem(Item orderItem)
{
if (orderItem == null)
{
return Context.Entity.Resolve<T>();
}
IDataMapper dataMapper = Context.Entity.Resolve<IDataMapper>();
T order = dataMapper.GetEntity<T>(orderItem, "OrderMappingRule");
order.OrderLines = new List<DomainModel.Orders.OrderLine>();
foreach (Item orderLineItem in orderItem.Children)
{
DomainModel.Orders.OrderLine orderLine = dataMapper.GetEntity<DomainModel.Orders.OrderLine>(orderLineItem, "OrderLineMappingRule");
orderLine.Id = orderLineItem.ID.ToString();
Assert.IsNotNull(orderLine.Product, "There is no products in the orderline");
order.OrderLines.Add(orderLine);
}
return order;
}
/// <summary>
/// Gets the order item.
/// </summary>
/// <param name="order">The order.</param>
/// <returns>The order item.</returns>
/// <exception cref="ConfigurationException">The Order id is null or empty.</exception>
/// <exception cref="InvalidOperationException">The order number is null or empty.</exception>
protected virtual Item GetOrderItem(T order)
{
if (order is IEntity)
{
IEntity entity = order as IEntity;
if (!string.IsNullOrEmpty(entity.Alias) || ID.IsID(entity.Alias))
{
Item item = this.Database.GetItem(entity.Alias);
if (item != null)
{
return item;
}
}
}
if (string.IsNullOrEmpty(order.OrderNumber))
{
Log.Warn("The order number is null or empty.", this);
throw new InvalidOperationException("The order number is null or empty.");
}
string orderItemTemplateId = string.IsNullOrEmpty(this.entityHelper.GetTemplate(typeof(T)))
? this.orderItemTempalteId.ToString()
: this.entityHelper.GetTemplate(typeof(T));
string number = this.entityHelper.GetField<T>(i => i.OrderNumber);
if (string.IsNullOrEmpty(number))
{
Log.Warn(string.Concat("Field name is undefined. Type: ", typeof(T).ToString(), ". Property: 'OrderNumber'."), this);
number = "OrderNumber";
}
Query query = new Query { SearchRoot = this.OrdersItem.ID.ToString() };
query.AppendAttribute("TemplateId", orderItemTemplateId, MatchVariant.Exactly);
query.AppendCondition(QueryCondition.And);
query.AppendField(number, order.OrderNumber, MatchVariant.Exactly);
return this.SearchProvider.Search(query, this.Database).FirstOrDefault();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using CS = Microsoft.CodeAnalysis.CSharp;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities
{
public class SymbolEquivalenceComparerTests
{
public static readonly CS.CSharpCompilationOptions CSharpDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
public static readonly CS.CSharpCompilationOptions CSharpSignedDllOptions = new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).
WithCryptoKeyFile(SigningTestHelpers.KeyPairFile).
WithStrongNameProvider(new SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create<string>()));
[Fact]
public void TestArraysAreEquivalent()
{
var csharpCode =
@"class C
{
int intField1;
int[] intArrayField1;
string[] stringArrayField1;
int[][] intArrayArrayField1;
int[,] intArrayRank2Field1;
System.Int32 int32Field1;
int intField2;
int[] intArrayField2;
string[] stringArrayField2;
int[][] intArrayArrayField2;
int[,] intArrayRank2Field2;
System.Int32 int32Field2;
}";
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode))
{
var type = (ITypeSymbol)workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var intField1 = (IFieldSymbol)type.GetMembers("intField1").Single();
var intArrayField1 = (IFieldSymbol)type.GetMembers("intArrayField1").Single();
var stringArrayField1 = (IFieldSymbol)type.GetMembers("stringArrayField1").Single();
var intArrayArrayField1 = (IFieldSymbol)type.GetMembers("intArrayArrayField1").Single();
var intArrayRank2Field1 = (IFieldSymbol)type.GetMembers("intArrayRank2Field1").Single();
var int32Field1 = (IFieldSymbol)type.GetMembers("int32Field1").Single();
var intField2 = (IFieldSymbol)type.GetMembers("intField2").Single();
var intArrayField2 = (IFieldSymbol)type.GetMembers("intArrayField2").Single();
var stringArrayField2 = (IFieldSymbol)type.GetMembers("stringArrayField2").Single();
var intArrayArrayField2 = (IFieldSymbol)type.GetMembers("intArrayArrayField2").Single();
var intArrayRank2Field2 = (IFieldSymbol)type.GetMembers("intArrayRank2Field2").Single();
var int32Field2 = (IFieldSymbol)type.GetMembers("int32Field2").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intField2.Type));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intField1.Type),
SymbolEquivalenceComparer.Instance.GetHashCode(intField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, intArrayField2.Type));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField1.Type),
SymbolEquivalenceComparer.Instance.GetHashCode(intArrayField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, stringArrayField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayArrayField2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, intArrayRank2Field2.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, int32Field2.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intField1.Type, intArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayField1.Type, stringArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(stringArrayField1.Type, intArrayArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayArrayField1.Type, intArrayRank2Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(intArrayRank2Field1.Type, int32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(int32Field1.Type, intField1.Type));
}
}
[Fact]
public void TestArraysInDifferentLanguagesAreEquivalent()
{
var csharpCode =
@"class C
{
int intField1;
int[] intArrayField1;
string[] stringArrayField1;
int[][] intArrayArrayField1;
int[,] intArrayRank2Field1;
System.Int32 int32Field1;
}";
var vbCode =
@"class C
dim intField1 as Integer;
dim intArrayField1 as Integer()
dim stringArrayField1 as String()
dim intArrayArrayField1 as Integer()()
dim intArrayRank2Field1 as Integer(,)
dim int32Field1 as System.Int32
end class";
using (var csharpWorkspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode))
using (var vbWorkspace = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode))
{
var csharpType = (ITypeSymbol)csharpWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var vbType = vbWorkspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var csharpIntField1 = (IFieldSymbol)csharpType.GetMembers("intField1").Single();
var csharpIntArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayField1").Single();
var csharpStringArrayField1 = (IFieldSymbol)csharpType.GetMembers("stringArrayField1").Single();
var csharpIntArrayArrayField1 = (IFieldSymbol)csharpType.GetMembers("intArrayArrayField1").Single();
var csharpIntArrayRank2Field1 = (IFieldSymbol)csharpType.GetMembers("intArrayRank2Field1").Single();
var csharpInt32Field1 = (IFieldSymbol)csharpType.GetMembers("int32Field1").Single();
var vbIntField1 = (IFieldSymbol)vbType.GetMembers("intField1").Single();
var vbIntArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayField1").Single();
var vbStringArrayField1 = (IFieldSymbol)vbType.GetMembers("stringArrayField1").Single();
var vbIntArrayArrayField1 = (IFieldSymbol)vbType.GetMembers("intArrayArrayField1").Single();
var vbIntArrayRank2Field1 = (IFieldSymbol)vbType.GetMembers("intArrayRank2Field1").Single();
var vbInt32Field1 = (IFieldSymbol)vbType.GetMembers("int32Field1").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbIntArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbStringArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayArrayField1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbInt32Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntField1.Type, vbIntArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayField1.Type, csharpStringArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpStringArrayField1.Type, vbIntArrayArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayArrayField1.Type, csharpIntArrayRank2Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayRank2Field1.Type, vbInt32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpInt32Field1.Type, vbIntField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntField1.Type, csharpIntArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayField1.Type, vbStringArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbStringArrayField1.Type, csharpIntArrayArrayField1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpIntArrayArrayField1.Type, vbIntArrayRank2Field1.Type));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(vbIntArrayRank2Field1.Type, csharpInt32Field1.Type));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(vbInt32Field1.Type, csharpIntField1.Type));
}
}
[Fact]
public void TestFields()
{
var csharpCode1 =
@"class Type1
{
int field1;
string field2;
}
class Type2
{
bool field3;
short field4;
}";
var csharpCode2 =
@"class Type1
{
int field1;
short field4;
}
class Type2
{
bool field3;
string field2;
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var field1_v1 = type1_v1.GetMembers("field1").Single();
var field1_v2 = type1_v2.GetMembers("field1").Single();
var field2_v1 = type1_v1.GetMembers("field2").Single();
var field2_v2 = type2_v2.GetMembers("field2").Single();
var field3_v1 = type2_v1.GetMembers("field3").Single();
var field3_v2 = type2_v2.GetMembers("field3").Single();
var field4_v1 = type2_v1.GetMembers("field4").Single();
var field4_v2 = type1_v2.GetMembers("field4").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(field1_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(field1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2));
}
}
[WorkItem(538124)]
[Fact]
public void TestFieldsAcrossLanguages()
{
var csharpCode1 =
@"class Type1
{
int field1;
string field2;
}
class Type2
{
bool field3;
short field4;
}";
var vbCode1 =
@"class Type1
dim field1 as Integer;
dim field4 as Short;
end class
class Type2
dim field3 as Boolean;
dim field2 as String;
end class";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var field1_v1 = type1_v1.GetMembers("field1").Single();
var field1_v2 = type1_v2.GetMembers("field1").Single();
var field2_v1 = type1_v1.GetMembers("field2").Single();
var field2_v2 = type2_v2.GetMembers("field2").Single();
var field3_v1 = type2_v1.GetMembers("field3").Single();
var field3_v2 = type2_v2.GetMembers("field3").Single();
var field4_v1 = type2_v1.GetMembers("field4").Single();
var field4_v2 = type1_v2.GetMembers("field4").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field2_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(field3_v1, field3_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field4_v1, field4_v2));
}
}
[Fact]
public void TestFieldsInGenericTypes()
{
var code =
@"class C<T>
{
int foo;
C<int> intInstantiation1;
C<string> stringInstantiation;
C<T> instanceInstantiation;
}
class D
{
C<int> intInstantiation2;
}
";
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var typeC = workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("C").Single();
var typeD = workspace.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("D").Single();
var intInstantiation1 = (IFieldSymbol)typeC.GetMembers("intInstantiation1").Single();
var stringInstantiation = (IFieldSymbol)typeC.GetMembers("stringInstantiation").Single();
var instanceInstantiation = (IFieldSymbol)typeC.GetMembers("instanceInstantiation").Single();
var intInstantiation2 = (IFieldSymbol)typeD.GetMembers("intInstantiation2").Single();
var foo = typeC.GetMembers("foo").Single();
var foo_intInstantiation1 = intInstantiation1.Type.GetMembers("foo").Single();
var foo_stringInstantiation = stringInstantiation.Type.GetMembers("foo").Single();
var foo_instanceInstantiation = instanceInstantiation.Type.GetMembers("foo").Single();
var foo_intInstantiation2 = intInstantiation2.Type.GetMembers("foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_intInstantiation2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo, foo_stringInstantiation));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_stringInstantiation));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo, foo_instanceInstantiation));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo),
SymbolEquivalenceComparer.Instance.GetHashCode(foo_instanceInstantiation));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(foo_intInstantiation1, foo_intInstantiation2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation1),
SymbolEquivalenceComparer.Instance.GetHashCode(foo_intInstantiation2));
}
}
[Fact]
public void TestMethodsWithDifferentReturnTypeNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
int Foo() {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentNamesAreNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
void Foo1() {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentAritiesAreNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
void Foo<T>() {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentParametersAreNotEquivalent()
{
var csharpCode1 =
@"class Type1
{
void Foo() {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentTypeParameters()
{
var csharpCode1 =
@"class Type1
{
void Foo<A>(A a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo<B>(B a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsWithSameParameters()
{
var csharpCode1 =
@"class Type1
{
void Foo(int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsWithDifferentParameterNames()
{
var csharpCode1 =
@"class Type1
{
void Foo(int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int b) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsAreNotEquivalentOutToRef()
{
var csharpCode1 =
@"class Type1
{
void Foo(out int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(ref int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsNotEquivalentRemoveOut()
{
var csharpCode1 =
@"class Type1
{
void Foo(out int a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsAreEquivalentIgnoreParams()
{
var csharpCode1 =
@"class Type1
{
void Foo(params int[] a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(int[] a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestMethodsNotEquivalentDifferentParameterTypes()
{
var csharpCode1 =
@"class Type1
{
void Foo(int[] a) {}
}";
var csharpCode2 =
@"class Type1
{
void Foo(string[] a) {}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
}
}
[Fact]
public void TestMethodsAcrossLanguages()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
T Foo<T>(IList<T> list, int a) {}
void Bar() { }
}";
var vbCode1 =
@"
Imports System.Collections.Generic
class Type1
function Foo(of U)(list as IList(of U), a as Integer) as U
end function
sub Quux()
end sub
end class";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1))
{
var csharpType1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var vbType1 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var csharpFooMethod = csharpType1.GetMembers("Foo").Single();
var csharpBarMethod = csharpType1.GetMembers("Bar").Single();
var vbFooMethod = vbType1.GetMembers("Foo").Single();
var vbQuuxMethod = vbType1.GetMembers("Quux").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod),
SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbQuuxMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbQuuxMethod));
}
}
[Fact]
public void TestMethodsInGenericTypesAcrossLanguages()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1<X>
{
T Foo<T>(IList<T> list, X a) {}
void Bar(X x) { }
}";
var vbCode1 =
@"
Imports System.Collections.Generic
class Type1(of M)
function Foo(of U)(list as IList(of U), a as M) as U
end function
sub Bar(x as Object)
end sub
end class";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(vbCode1))
{
var csharpType1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var vbType1 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var csharpFooMethod = csharpType1.GetMembers("Foo").Single();
var csharpBarMethod = csharpType1.GetMembers("Bar").Single();
var vbFooMethod = vbType1.GetMembers("Foo").Single();
var vbBarMethod = vbType1.GetMembers("Bar").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbFooMethod));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(csharpFooMethod),
SymbolEquivalenceComparer.Instance.GetHashCode(vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, csharpBarMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpFooMethod, vbBarMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, csharpFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbFooMethod));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(csharpBarMethod, vbBarMethod));
}
}
[Fact]
public void TestObjectAndDynamicAreNotEqualNormally()
{
var csharpCode1 =
@"class Type1
{
object field1;
dynamic field2;
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var field1_v1 = type1_v1.GetMembers("field1").Single();
var field2_v1 = type1_v1.GetMembers("field2").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field1_v1, field2_v1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(field2_v1, field1_v1));
}
}
[Fact]
public void TestObjectAndDynamicAreEqualInSignatures()
{
var csharpCode1 =
@"class Type1
{
void Foo(object o1) { }
}";
var csharpCode2 =
@"class Type1
{
void Foo(dynamic o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestUnequalGenericsInSignatures()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<int> o1) { }
}";
var csharpCode2 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<string> o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
}
}
[Fact]
public void TestGenericsWithDynamicAndObjectInSignatures()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<object> o1) { }
}";
var csharpCode2 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(IList<dynamic> o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestDynamicAndUnrelatedTypeInSignatures()
{
var csharpCode1 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(dynamic o1) { }
}";
var csharpCode2 =
@"
using System.Collections.Generic;
class Type1
{
void Foo(string o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
}
}
[Fact]
public void TestNamespaces()
{
var csharpCode1 =
@"namespace Outer
{
namespace Inner
{
class Type
{
}
}
class Type
{
}
}
";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
{
var outer1 = (INamespaceSymbol)workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetMembers("Outer").Single();
var outer2 = (INamespaceSymbol)workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetMembers("Outer").Single();
var inner1 = (INamespaceSymbol)outer1.GetMembers("Inner").Single();
var inner2 = (INamespaceSymbol)outer2.GetMembers("Inner").Single();
var outerType1 = outer1.GetTypeMembers("Type").Single();
var outerType2 = outer2.GetTypeMembers("Type").Single();
var innerType1 = inner1.GetTypeMembers("Type").Single();
var innerType2 = inner2.GetTypeMembers("Type").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outer2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(outer2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, inner2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1),
SymbolEquivalenceComparer.Instance.GetHashCode(inner2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outerType1, outerType2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outerType1),
SymbolEquivalenceComparer.Instance.GetHashCode(outerType2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(innerType1, innerType2));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(innerType1),
SymbolEquivalenceComparer.Instance.GetHashCode(innerType2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(inner1, outerType1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(outerType1, innerType1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(innerType1, outer1));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, inner1.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(inner1.ContainingSymbol));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, innerType1.ContainingSymbol.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol.ContainingSymbol));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(inner1, innerType1.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(inner1),
SymbolEquivalenceComparer.Instance.GetHashCode(innerType1.ContainingSymbol));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(outer1, outerType1.ContainingSymbol));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(outer1),
SymbolEquivalenceComparer.Instance.GetHashCode(outerType1.ContainingSymbol));
}
}
[Fact]
public void TestNamedTypesEquivalent()
{
var csharpCode1 =
@"
class Type1
{
}
class Type2<X>
{
}
";
var csharpCode2 =
@"
class Type1
{
void Foo();
}
class Type2<Y>
{
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type2_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
var type2_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type1_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(type1_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type2_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(type2_v2, type2_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(type2_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(type2_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type2_v1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type2_v1, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfNameChanges()
{
var csharpCode1 =
@"
class Type1
{
}";
var csharpCode2 =
@"
class Type2
{
void Foo();
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type2").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfTypeKindChanges()
{
var csharpCode1 =
@"
struct Type1
{
}";
var csharpCode2 =
@"
class Type1
{
void Foo();
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfArityChanges()
{
var csharpCode1 =
@"
class Type1
{
}";
var csharpCode2 =
@"
class Type1<T>
{
void Foo();
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestNamedTypesDifferentIfContainerDifferent()
{
var csharpCode1 =
@"
class Outer
{
class Type1
{
}
}";
var csharpCode2 =
@"
class Other
{
class Type1
{
void Foo();
}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var outer = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Outer").Single();
var other = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Other").Single();
var type1_v1 = outer.GetTypeMembers("Type1").Single();
var type1_v2 = other.GetTypeMembers("Type1").Single();
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v1, type1_v2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(type1_v2, type1_v1));
}
}
[Fact]
public void TestAliasedTypes1()
{
var csharpCode1 =
@"
using i = System.Int32;
class Type1
{
void Foo(i o1) { }
}";
var csharpCode2 =
@"
class Type1
{
void Foo(int o1) { }
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode1))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(csharpCode2))
{
var type1_v1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var type1_v2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetTypeMembers("Type1").Single();
var method_v1 = type1_v1.GetMembers("Foo").Single();
var method_v2 = type1_v2.GetMembers("Foo").Single();
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v1, method_v2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method_v2, method_v1));
Assert.Equal(SymbolEquivalenceComparer.Instance.GetHashCode(method_v1),
SymbolEquivalenceComparer.Instance.GetHashCode(method_v2));
}
}
[Fact]
public void TestCSharpReducedExtensionMethodsAreEquivalent()
{
var code = @"
class Zed {}
public static class Extensions
{
public static void NotGeneric(this Zed z, int data) { }
public static void GenericThis<T>(this T me, int data) where T : Zed { }
public static void GenericNotThis<T>(this Zed z, T data) { }
public static void GenericThisAndMore<T,S>(this T me, S data) where T : Zed { }
public static void GenericThisAndOther<T>(this T me, T data) where T : Zed { }
}
class Test
{
void NotGeneric()
{
Zed z;
int n;
z.NotGeneric(n);
}
void GenericThis()
{
Zed z;
int n;
z.GenericThis(n);
}
void GenericNotThis()
{
Zed z;
int n;
z.GenericNotThis(n);
}
void GenericThisAndMore()
{
Zed z;
int n;
z.GenericThisAndMore(n);
}
void GenericThisAndOther()
{
Zed z;
z.GenericThisAndOther(z);
}
}
";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var comp1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
var comp2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore");
TestReducedExtension<CS.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther");
}
}
[Fact]
public void TestVisualBasicReducedExtensionMethodsAreEquivalent()
{
var code = @"
Imports System.Runtime.CompilerServices
Class Zed
End Class
Module Extensions
<Extension>
Public Sub NotGeneric(z As Zed, data As Integer)
End Sub
<Extension>
Public Sub GenericThis(Of T As Zed)(m As T, data as Integer)
End Sub
<Extension>
Public Sub GenericNotThis(Of T)(z As Zed, data As T)
End Sub
<Extension>
Public Sub GenericThisAndMore(Of T As Zed, S)(m As T, data As S)
End Sub
<Extension>
Public Sub GenericThisAndOther(Of T As Zed)(m As T, data As T)
End Sub
End Module
Class Test
Sub NotGeneric()
Dim z As Zed
Dim n As Integer
z.NotGeneric(n)
End Sub
Sub GenericThis()
Dim z As Zed
Dim n As Integer
z.GenericThis(n)
End Sub
Sub GenericNotThis()
Dim z As Zed
Dim n As Integer
z.GenericNotThis(n)
End Sub
Sub GenericThisAndMore()
Dim z As Zed
Dim n As Integer
z.GenericThisAndMore(n)
End Sub
Sub GenericThisAndOther()
Dim z As Zed
z.GenericThisAndOther(z)
End Sub
End Class
";
using (var workspace1 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(code))
using (var workspace2 = VisualBasicWorkspaceFactory.CreateWorkspaceFromLines(code))
{
var comp1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
var comp2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result;
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "NotGeneric");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThis");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericNotThis");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndMore");
TestReducedExtension<VB.Syntax.InvocationExpressionSyntax>(comp1, comp2, "Test", "GenericThisAndOther");
}
}
[Fact]
public void TestDifferentModules()
{
var csharpCode =
@"namespace N
{
namespace M
{
}
}";
using (var workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "FooModule")))
using (var workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(new[] { csharpCode }, compilationOptions: new CS.CSharpCompilationOptions(OutputKind.NetModule, moduleName: "BarModule")))
{
var namespace1 = workspace1.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M");
var namespace2 = workspace2.CurrentSolution.Projects.Single().GetCompilationAsync().Result.GlobalNamespace.GetNamespaceMembers().Single(n => n.Name == "N").GetNamespaceMembers().Single(n => n.Name == "M");
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(namespace1, namespace2));
Assert.Equal(SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace1),
SymbolEquivalenceComparer.IgnoreAssembliesInstance.GetHashCode(namespace2));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(namespace1, namespace2));
Assert.NotEqual(SymbolEquivalenceComparer.Instance.GetHashCode(namespace1),
SymbolEquivalenceComparer.Instance.GetHashCode(namespace2));
}
}
[Fact]
public void AssemblyComparer1()
{
var references = new[] { TestReferences.NetFx.v4_0_30319.mscorlib };
string source = "public class T {}";
string sourceV1 = "[assembly: System.Reflection.AssemblyVersion(\"1.0.0.0\")] public class T {}";
string sourceV2 = "[assembly: System.Reflection.AssemblyVersion(\"2.0.0.0\")] public class T {}";
var a1 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions);
var a2 = CS.CSharpCompilation.Create("a", new[] { CS.SyntaxFactory.ParseSyntaxTree(source) }, references, CSharpDllOptions);
var b1 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV1) }, references, CSharpSignedDllOptions);
var b2 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions);
var b3 = CS.CSharpCompilation.Create("b", new[] { CS.SyntaxFactory.ParseSyntaxTree(sourceV2) }, references, CSharpSignedDllOptions);
var ta1 = (ITypeSymbol)a1.GlobalNamespace.GetMembers("T").Single();
var ta2 = (ITypeSymbol)a2.GlobalNamespace.GetMembers("T").Single();
var tb1 = (ITypeSymbol)b1.GlobalNamespace.GetMembers("T").Single();
var tb2 = (ITypeSymbol)b2.GlobalNamespace.GetMembers("T").Single();
var tb3 = (ITypeSymbol)b3.GlobalNamespace.GetMembers("T").Single();
var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance);
// same name:
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, ta2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(ta1, ta2));
Assert.True(identityComparer.Equals(ta1, ta2));
// different name:
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(ta1, tb1));
Assert.False(SymbolEquivalenceComparer.Instance.Equals(ta1, tb1));
Assert.False(identityComparer.Equals(ta1, tb1));
// different identity
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb1, tb2));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb1, tb2));
Assert.False(identityComparer.Equals(tb1, tb2));
// same identity
Assert.True(SymbolEquivalenceComparer.IgnoreAssembliesInstance.Equals(tb2, tb3));
Assert.True(SymbolEquivalenceComparer.Instance.Equals(tb2, tb3));
Assert.True(identityComparer.Equals(tb2, tb3));
}
private sealed class AssemblySymbolIdentityComparer : IEqualityComparer<IAssemblySymbol>
{
public static readonly IEqualityComparer<IAssemblySymbol> Instance = new AssemblySymbolIdentityComparer();
public bool Equals(IAssemblySymbol x, IAssemblySymbol y)
{
return x.Identity.Equals(y.Identity);
}
public int GetHashCode(IAssemblySymbol obj)
{
return obj.Identity.GetHashCode();
}
}
[Fact]
public void CustomModifiers_Methods1()
{
const string ilSource = @"
.class public C
{
.method public instance int32 [] modopt([mscorlib]System.Int64) F( // 0
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b)
{
ldnull
throw
}
.method public instance int32 [] modopt([mscorlib]System.Boolean) F( // 1
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b)
{
ldnull
throw
}
.method public instance int32[] F( // 2
int32 a,
int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b)
{
ldnull
throw
}
.method public instance int32[] F( // 3
int32 a,
int32 b)
{
ldnull
throw
}
}
";
MetadataReference r1, r2;
using (var tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource))
{
byte[] bytes = File.ReadAllBytes(tempAssembly.Path);
r1 = MetadataReference.CreateFromImage(bytes);
r2 = MetadataReference.CreateFromImage(bytes);
}
var c1 = CS.CSharpCompilation.Create("comp1", Array.Empty<SyntaxTree>(), new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r1 });
var c2 = CS.CSharpCompilation.Create("comp2", Array.Empty<SyntaxTree>(), new[] { TestReferences.NetFx.v4_0_30319.mscorlib, r2 });
var type1 = (ITypeSymbol)c1.GlobalNamespace.GetMembers("C").Single();
var type2 = (ITypeSymbol)c2.GlobalNamespace.GetMembers("C").Single();
var identityComparer = new SymbolEquivalenceComparer(AssemblySymbolIdentityComparer.Instance);
var f1 = type1.GetMembers("F");
var f2 = type2.GetMembers("F");
Assert.True(identityComparer.Equals(f1[0], f2[0]));
Assert.False(identityComparer.Equals(f1[0], f2[1]));
Assert.False(identityComparer.Equals(f1[0], f2[2]));
Assert.False(identityComparer.Equals(f1[0], f2[3]));
Assert.False(identityComparer.Equals(f1[1], f2[0]));
Assert.True(identityComparer.Equals(f1[1], f2[1]));
Assert.False(identityComparer.Equals(f1[1], f2[2]));
Assert.False(identityComparer.Equals(f1[1], f2[3]));
Assert.False(identityComparer.Equals(f1[2], f2[0]));
Assert.False(identityComparer.Equals(f1[2], f2[1]));
Assert.True(identityComparer.Equals(f1[2], f2[2]));
Assert.False(identityComparer.Equals(f1[2], f2[3]));
Assert.False(identityComparer.Equals(f1[3], f2[0]));
Assert.False(identityComparer.Equals(f1[3], f2[1]));
Assert.False(identityComparer.Equals(f1[3], f2[2]));
Assert.True(identityComparer.Equals(f1[3], f2[3]));
}
private void TestReducedExtension<TInvocation>(Compilation comp1, Compilation comp2, string typeName, string methodName)
where TInvocation : SyntaxNode
{
var method1 = GetInvokedSymbol<TInvocation>(comp1, typeName, methodName);
var method2 = GetInvokedSymbol<TInvocation>(comp2, typeName, methodName);
Assert.NotNull(method1);
Assert.Equal(method1.MethodKind, MethodKind.ReducedExtension);
Assert.NotNull(method2);
Assert.Equal(method2.MethodKind, MethodKind.ReducedExtension);
Assert.True(SymbolEquivalenceComparer.Instance.Equals(method1, method2));
var cfmethod1 = method1.ConstructedFrom;
var cfmethod2 = method2.ConstructedFrom;
Assert.True(SymbolEquivalenceComparer.Instance.Equals(cfmethod1, cfmethod2));
}
private IMethodSymbol GetInvokedSymbol<TInvocation>(Compilation compilation, string typeName, string methodName)
where TInvocation : SyntaxNode
{
var type1 = compilation.GlobalNamespace.GetTypeMembers(typeName).Single();
var method = type1.GetMembers(methodName).Single();
var method_root = method.DeclaringSyntaxReferences[0].GetSyntax();
var invocation = method_root.DescendantNodes().OfType<TInvocation>().FirstOrDefault();
if (invocation == null)
{
// vb method root is statement, but we need block to find body with invocation
invocation = method_root.Parent.DescendantNodes().OfType<TInvocation>().First();
}
var model = compilation.GetSemanticModel(invocation.SyntaxTree);
var info = model.GetSymbolInfo(invocation);
return info.Symbol as IMethodSymbol;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using com.buzzlogix.Http.Request;
using com.buzzlogix.Http.Response;
using unirest_net.http;
using UniHttpRequest = unirest_net.request.HttpRequest;
using UniHttpMethod = System.Net.Http.HttpMethod;
namespace com.buzzlogix.Http.Client
{
public class UnirestClient: IHttpClient
{
public static IHttpClient SharedClient { get; set; }
static UnirestClient() {
SharedClient = new UnirestClient();
}
private static UniHttpMethod ConvertHttpMethod(HttpMethod method)
{
switch (method)
{
case HttpMethod.Get:
return new UniHttpMethod(HttpMethod.Get.ToString());
case HttpMethod.Post:
return new UniHttpMethod(HttpMethod.Post.ToString());
case HttpMethod.Put:
return new UniHttpMethod(HttpMethod.Put.ToString());
case HttpMethod.Patch:
return new UniHttpMethod(HttpMethod.Patch.ToString());
case HttpMethod.Delete:
return new UniHttpMethod(HttpMethod.Delete.ToString());
default:
throw new ArgumentOutOfRangeException("Unkown method" + method.ToString());
}
}
private static UniHttpRequest ConvertRequest(HttpRequest request)
{
var uniMethod = ConvertHttpMethod(request.HttpMethod);
var queryUrl = request.QueryUrl;
//instantiate unirest request object
UniHttpRequest uniRequest = new UniHttpRequest(uniMethod,queryUrl);
//set request payload
if (request.Body != null)
{
uniRequest.body(request.Body);
}
else if (request.FormParameters != null)
{
if (request.FormParameters.Any(p => p.Value is Stream || p.Value is FileStreamInfo))
{
//multipart
foreach (var kvp in request.FormParameters)
{
if (kvp.Value is FileStreamInfo){
var fileInfo = (FileStreamInfo) kvp.Value;
uniRequest.field(kvp.Key,fileInfo.FileStream);
continue;
}
uniRequest.field(kvp.Key,kvp.Value);
}
}
else
{
//URL Encode params
var paramsString = string.Join("&",
request.FormParameters.Select(kvp =>
string.Format("{0}={1}", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value.ToString()))));
uniRequest.body(paramsString);
uniRequest.header("Content-Type", "application/x-www-form-urlencoded");
}
}
//set request headers
Dictionary<String, Object> headers = request.Headers.ToDictionary(item=> item.Key,item=> (Object) item.Value);
uniRequest.headers(headers);
//Set basic auth credentials if any
if (!string.IsNullOrWhiteSpace(request.Username))
{
uniRequest.basicAuth(request.Username, request.Password);
}
return uniRequest;
}
private static HttpResponse ConvertResponse(HttpResponse<Stream> binaryResponse)
{
return new HttpResponse
{
Headers = binaryResponse.Headers,
RawBody = binaryResponse.Body,
StatusCode = binaryResponse.Code
};
}
private static HttpResponse ConvertResponse(HttpResponse<string> stringResponse)
{
return new HttpStringResponse
{
Headers = stringResponse.Headers,
RawBody = stringResponse.Raw,
Body = stringResponse.Body,
StatusCode = stringResponse.Code
};
}
public HttpResponse ExecuteAsString(HttpRequest request)
{
UniHttpRequest uniRequest = ConvertRequest(request);
return ConvertResponse(uniRequest.asString());
}
public Task<HttpResponse> ExecuteAsStringAsync(HttpRequest request)
{
return Task.Factory.StartNew(() => ExecuteAsString(request));
}
public HttpResponse ExecuteAsBinary(HttpRequest request)
{
UniHttpRequest uniRequest = ConvertRequest(request);
return ConvertResponse(uniRequest.asBinary());
}
public Task<HttpResponse> ExecuteAsBinaryAsync(HttpRequest request)
{
return Task.Factory.StartNew(() => ExecuteAsString(request));
}
public HttpRequest Get(string queryUrl, Dictionary<string, string> headers, string username = null, string password = null)
{
return new HttpRequest(HttpMethod.Get, queryUrl, headers, username, password);
}
public HttpRequest Get(string queryUrl)
{
return new HttpRequest(HttpMethod.Get,queryUrl);
}
public HttpRequest Post(string queryUrl)
{
return new HttpRequest(HttpMethod.Post, queryUrl);
}
public HttpRequest Put(string queryUrl)
{
return new HttpRequest(HttpMethod.Put, queryUrl);
}
public HttpRequest Delete(string queryUrl)
{
return new HttpRequest(HttpMethod.Delete, queryUrl);
}
public HttpRequest Patch(string queryUrl)
{
return new HttpRequest(HttpMethod.Patch, queryUrl);
}
public HttpRequest Post(string queryUrl, Dictionary<string, string> headers, Dictionary<string, object> formParameters, string username = null,
string password = null)
{
return new HttpRequest(HttpMethod.Post, queryUrl, headers,formParameters, username, password);
}
public HttpRequest PostBody(string queryUrl, Dictionary<string, string> headers, string body, string username = null, string password = null)
{
return new HttpRequest(HttpMethod.Post, queryUrl, headers, body, username, password);
}
public HttpRequest Put(string queryUrl, Dictionary<string, string> headers, Dictionary<string, object> formParameters, string username = null,
string password = null)
{
return new HttpRequest(HttpMethod.Put, queryUrl, headers, formParameters, username, password);
}
public HttpRequest PutBody(string queryUrl, Dictionary<string, string> headers, string body, string username = null, string password = null)
{
return new HttpRequest(HttpMethod.Put, queryUrl, headers, body, username, password);
}
public HttpRequest Patch(string queryUrl, Dictionary<string, string> headers, Dictionary<string, object> formParameters, string username = null,
string password = null)
{
return new HttpRequest(HttpMethod.Patch, queryUrl, headers, formParameters, username, password);
}
public HttpRequest PatchBody(string queryUrl, Dictionary<string, string> headers, string body, string username = null, string password = null)
{
return new HttpRequest(HttpMethod.Patch, queryUrl, headers, body, username, password);
}
public HttpRequest Delete(string queryUrl, Dictionary<string, string> headers, Dictionary<string, object> formParameters, string username = null,
string password = null)
{
return new HttpRequest(HttpMethod.Patch, queryUrl, headers, formParameters, username, password);
}
public HttpRequest DeleteBody(string queryUrl, Dictionary<string, string> headers, string body, string username = null, string password = null)
{
return new HttpRequest(HttpMethod.Patch, queryUrl, headers, body, username, password);
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Serialize and deserialize scene objects.
/// </summary>
/// This should really be in OpenSim.Framework.Serialization but this would mean circular dependency problems
/// right now - hopefully this isn't forever.
public class SceneObjectSerializer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="serialization"></param>
/// <returns></returns>
public static SceneObjectGroup FromOriginalXmlFormat(string serialization)
{
return FromOriginalXmlFormat(UUID.Zero, serialization);
}
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="serialization"></param>
/// <returns></returns>
public static SceneObjectPart RootPartInOriginalXmlFormat(UUID fromUserInventoryItemID, string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
SceneObjectPart part = new SceneObjectPart();
// libomv.types changes UUID to Guid
xmlData = xmlData.Replace("<UUID>", "<Guid>");
xmlData = xmlData.Replace("</UUID>", "</Guid>");
// Handle Nested <UUID><UUID> property
xmlData = xmlData.Replace("<Guid><Guid>", "<UUID><Guid>");
xmlData = xmlData.Replace("</Guid></Guid>", "</Guid></UUID>");
try
{
StringReader sr;
XmlTextReader reader;
XmlNodeList parts;
XmlDocument doc;
doc = new XmlDocument();
doc.LoadXml(xmlData);
parts = doc.GetElementsByTagName("RootPart");
if (parts.Count < 1)
return null;
sr = new StringReader(parts[0].InnerXml);
reader = new XmlTextReader(sr);
part = SceneObjectPart.FromXml(fromUserInventoryItemID, reader);
reader.Close();
sr.Close();
return part;
}
catch (Exception e)
{
m_log.ErrorFormat(
"[SERIALIZER]: Deserialization of root part xml failed with {0}.", e);
}
return null;
}
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="serialization"></param>
/// <returns></returns>
public static SceneObjectGroup FromOriginalXmlFormat(UUID fromUserInventoryItemID, string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
SceneObjectGroup sceneObject = new SceneObjectGroup();
// libomv.types changes UUID to Guid
xmlData = xmlData.Replace("<UUID>", "<Guid>");
xmlData = xmlData.Replace("</UUID>", "</Guid>");
// Handle Nested <UUID><UUID> property
xmlData = xmlData.Replace("<Guid><Guid>", "<UUID><Guid>");
xmlData = xmlData.Replace("</Guid></Guid>", "</Guid></UUID>");
try
{
StringReader sr;
XmlTextReader reader;
XmlNodeList parts;
XmlDocument doc;
int linkNum;
doc = new XmlDocument();
doc.LoadXml(xmlData);
parts = doc.GetElementsByTagName("RootPart");
if (parts.Count == 0)
{
throw new Exception("Invalid Xml format - no root part");
}
else
{
sr = new StringReader(parts[0].InnerXml);
reader = new XmlTextReader(sr);
sceneObject.SetRootPart(SceneObjectPart.FromXml(fromUserInventoryItemID, reader));
reader.Close();
sr.Close();
}
parts = doc.GetElementsByTagName("Part");
for (int i = 0; i < parts.Count; i++)
{
sr = new StringReader(parts[i].InnerXml);
reader = new XmlTextReader(sr);
SceneObjectPart part = SceneObjectPart.FromXml(reader);
linkNum = part.LinkNum;
sceneObject.AddPart(part);
part.LinkNum = linkNum;
part.TrimPermissions();
part.StoreUndoState();
reader.Close();
sr.Close();
}
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(doc);
//m_log.DebugFormat("[SERIALIZER]: Finished deserialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time);
return sceneObject;
}
catch (Exception e)
{
m_log.ErrorFormat(
"[SERIALIZER]: Deserialization of xml failed with {0}.", e);
}
return null;
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, StopScriptReason stopScriptReason)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
ToOriginalXmlFormat(sceneObject, writer, stopScriptReason);
}
return sw.ToString();
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer, StopScriptReason stopScriptReason)
{
//m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", Name);
//int time = System.Environment.TickCount;
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
writer.WriteStartElement(String.Empty, "RootPart", String.Empty);
sceneObject.RootPart.ToXml(writer);
writer.WriteEndElement();
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
foreach (SceneObjectPart part in sceneObject.GetParts())
{
if (part.UUID != sceneObject.RootPart.UUID)
{
writer.WriteStartElement(String.Empty, "Part", String.Empty);
part.ToXml(writer);
writer.WriteEndElement();
}
}
writer.WriteEndElement(); // OtherParts
sceneObject.SaveScriptedState(writer, stopScriptReason);
writer.WriteEndElement(); // SceneObjectGroup
//m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time);
}
public static SceneObjectGroup FromXml2Format(string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
SceneObjectGroup sceneObject = new SceneObjectGroup();
// libomv.types changes UUID to Guid
xmlData = xmlData.Replace("<UUID>", "<Guid>");
xmlData = xmlData.Replace("</UUID>", "</Guid>");
// Handle Nested <UUID><UUID> property
xmlData = xmlData.Replace("<Guid><Guid>", "<UUID><Guid>");
xmlData = xmlData.Replace("</Guid></Guid>", "</Guid></UUID>");
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlData);
XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart");
// Process the root part first
if (parts.Count > 0)
{
StringReader sr = new StringReader(parts[0].OuterXml);
XmlTextReader reader = new XmlTextReader(sr);
sceneObject.SetRootPart(SceneObjectPart.FromXml(reader));
reader.Close();
sr.Close();
}
// Then deal with the rest
for (int i = 1; i < parts.Count; i++)
{
StringReader sr = new StringReader(parts[i].OuterXml);
XmlTextReader reader = new XmlTextReader(sr);
SceneObjectPart part = SceneObjectPart.FromXml(reader);
int originalLinkNum = part.LinkNum;
sceneObject.AddPart(part);
// SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum.
// We override that here
if (originalLinkNum != 0)
part.LinkNum = originalLinkNum;
part.StoreUndoState();
reader.Close();
sr.Close();
}
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(doc);
//m_log.DebugFormat("[SERIALIZER]: Finished deserialization of SOG {0}, {1}ms", Name, System.Environment.TickCount - time);
return sceneObject;
}
catch (Exception e)
{
m_log.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}.", e);
}
return null;
}
/// <summary>
/// Serialize a scene object to the 'xml2' format.
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToXml2Format(SceneObjectGroup sceneObject, bool stopScripts)
{
StopScriptReason reason = stopScripts ? StopScriptReason.Derez : StopScriptReason.None;
return ToXml2Format(sceneObject, reason, true);
}
public static string ToXml2Format(SceneObjectGroup sceneObject, StopScriptReason stopScriptReason, bool saveScriptState)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
ToXml2Format(sceneObject, writer, stopScriptReason);
}
return sw.ToString();
}
}
public static void ToXml2Format(SceneObjectGroup sceneObject, XmlTextWriter writer, StopScriptReason stopScriptReason)
{
ToXml2Format(sceneObject, writer, stopScriptReason, true);
}
/// <summary>
/// Serialize a scene object to the 'xml2' format.
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static void ToXml2Format(SceneObjectGroup sceneObject, XmlTextWriter writer, StopScriptReason stopScriptReason, bool saveScriptState)
{
//m_log.DebugFormat("[SERIALIZER]: Starting serialization of SOG {0} to XML2", Name);
//int time = System.Environment.TickCount;
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
sceneObject.RootPart.ToXml(writer);
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
foreach (SceneObjectPart part in sceneObject.GetParts())
{
if (part.UUID != sceneObject.RootPart.UUID)
{
part.ToXml(writer);
}
}
writer.WriteEndElement(); // End of OtherParts
if (saveScriptState)
{
sceneObject.SaveScriptedState(writer, stopScriptReason);
}
writer.WriteEndElement(); // End of SceneObjectGroup
//m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0} to XML2, {1}ms", Name, System.Environment.TickCount - time);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace NinjaCamp.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Htc.Vita.Core.Json;
using Htc.Vita.Core.Util;
using Xunit;
namespace Htc.Vita.Core.Tests
{
public static class DictionaryExtensionTest
{
[Fact]
public static void Default_0_ToJsonObject_bool()
{
var map = new Dictionary<string, bool>
{
["a"] = true,
["b"] = false,
["c"] = true
};
var jsonObject = map.ToJsonObject();
var jsonObjectCount = jsonObject.AllKeys().Count;
Assert.Equal(map.Count, jsonObjectCount);
foreach (var item in map)
{
var matched = false;
foreach (var key in jsonObject.AllKeys())
{
var item1 = item.Value;
var item2 = jsonObject.ParseBool(key);
if (!item1.Equals(item2))
{
continue;
}
matched = true;
break;
}
Assert.True(matched);
}
}
[Fact]
public static void Default_0_ToJsonObject_double()
{
var map = new Dictionary<string, double>
{
["a"] = 1.1d,
["b"] = 2.2d,
["c"] = 3.3d
};
var jsonObject = map.ToJsonObject();
var jsonObjectCount = jsonObject.AllKeys().Count;
Assert.Equal(map.Count, jsonObjectCount);
foreach (var item in map)
{
var matched = false;
foreach (var key in jsonObject.AllKeys())
{
var item1 = item.Value;
var item2 = jsonObject.ParseDouble(key);
if (!item1.Equals(item2))
{
continue;
}
matched = true;
break;
}
Assert.True(matched);
}
}
[Fact]
public static void Default_0_ToJsonObject_float()
{
var map = new Dictionary<string, float>
{
["a"] = 1.1f,
["b"] = 2.2f,
["c"] = 3.3f
};
var jsonObject = map.ToJsonObject();
var jsonObjectCount = jsonObject.AllKeys().Count;
Assert.Equal(map.Count, jsonObjectCount);
foreach (var item in map)
{
var matched = false;
foreach (var key in jsonObject.AllKeys())
{
var item1 = item.Value;
var item2 = jsonObject.ParseFloat(key);
if (!item1.Equals(item2))
{
continue;
}
matched = true;
break;
}
Assert.True(matched);
}
}
[Fact]
public static void Default_0_ToJsonObject_int()
{
var map = new Dictionary<string, int>
{
["a"] = 1,
["b"] = 2,
["c"] = 3
};
var jsonObject = map.ToJsonObject();
var jsonObjectCount = jsonObject.AllKeys().Count;
Assert.Equal(map.Count, jsonObjectCount);
foreach (var item in map)
{
var matched = false;
foreach (var key in jsonObject.AllKeys())
{
var item1 = item.Value;
var item2 = jsonObject.ParseInt(key);
if (!item1.Equals(item2))
{
continue;
}
matched = true;
break;
}
Assert.True(matched);
}
}
[Fact]
public static void Default_0_ToJsonObject_long()
{
var map = new Dictionary<string, long>
{
["a"] = 1L,
["b"] = 2L,
["c"] = 3L
};
var jsonObject = map.ToJsonObject();
var jsonObjectCount = jsonObject.AllKeys().Count;
Assert.Equal(map.Count, jsonObjectCount);
foreach (var item in map)
{
var matched = false;
foreach (var key in jsonObject.AllKeys())
{
var item1 = item.Value;
var item2 = jsonObject.ParseLong(key);
if (!item1.Equals(item2))
{
continue;
}
matched = true;
break;
}
Assert.True(matched);
}
}
[Fact]
public static void Default_0_ToJsonObject_string()
{
var map = new Dictionary<string, string>
{
["a"] = "1",
["b"] = "2",
["c"] = "3"
};
var jsonObject = map.ToJsonObject();
var jsonObjectCount = jsonObject.AllKeys().Count;
Assert.Equal(map.Count, jsonObjectCount);
foreach (var item in map)
{
var matched = false;
foreach (var key in jsonObject.AllKeys())
{
var item1 = item.Value;
var item2 = jsonObject.ParseString(key);
if (!item1.Equals(item2))
{
continue;
}
matched = true;
break;
}
Assert.True(matched);
}
}
[Fact]
public static void Default_0_ToJsonObject_JsonArray()
{
var map = new Dictionary<string, JsonArray>
{
["a"] = JsonFactory.GetInstance().GetJsonArray("[]"),
["b"] = JsonFactory.GetInstance().GetJsonArray("[1,2,3]"),
["c"] = JsonFactory.GetInstance().GetJsonArray("[\"1\",\"2\"]")
};
var jsonObject = map.ToJsonObject();
var jsonObjectCount = jsonObject.AllKeys().Count;
Assert.Equal(map.Count, jsonObjectCount);
foreach (var item in map)
{
var matched = false;
foreach (var key in jsonObject.AllKeys())
{
var item1 = item.Value.ToString();
var item2 = jsonObject.ParseJsonArray(key).ToString();
if (!item1.Equals(item2))
{
continue;
}
matched = true;
break;
}
Assert.True(matched);
}
}
[Fact]
public static void Default_0_ToJsonObject_JsonObject()
{
var map = new Dictionary<string, JsonObject>
{
["a"] = JsonFactory.GetInstance().GetJsonObject("{}"),
["b"] = JsonFactory.GetInstance().GetJsonObject("{\"b\":\"2\"}"),
["c"] = JsonFactory.GetInstance().GetJsonObject("{\"c\":\"3\"}")
};
var jsonObject = map.ToJsonObject();
var jsonObjectCount = jsonObject.AllKeys().Count;
Assert.Equal(map.Count, jsonObjectCount);
foreach (var item in map)
{
var matched = false;
foreach (var key in jsonObject.AllKeys())
{
var item1 = item.Value.ToString();
var item2 = jsonObject.ParseJsonObject(key).ToString();
if (!item1.Equals(item2))
{
continue;
}
matched = true;
break;
}
Assert.True(matched);
}
}
[Fact]
public static void Default_1_ApplyIfNotNullAndNotWhiteSpace()
{
var map = new Dictionary<string, string>();
map.ApplyIfNotNullAndNotWhiteSpace("key1", null)
.ApplyIfNotNullAndNotWhiteSpace("key2", "")
.ApplyIfNotNullAndNotWhiteSpace("key3", " ")
.ApplyIfNotNullAndNotWhiteSpace("key4", "1");
Assert.False(map.ContainsKey("key1"));
Assert.False(map.ContainsKey("key2"));
Assert.False(map.ContainsKey("key3"));
Assert.True(map.ContainsKey("key4"));
var map2 = new Dictionary<string, object>();
map2.ApplyIfNotNullAndNotWhiteSpace("key1", null)
.ApplyIfNotNullAndNotWhiteSpace("key2", "")
.ApplyIfNotNullAndNotWhiteSpace("key3", " ")
.ApplyIfNotNullAndNotWhiteSpace("key4", "1");
Assert.False(map2.ContainsKey("key1"));
Assert.False(map2.ContainsKey("key2"));
Assert.False(map2.ContainsKey("key3"));
Assert.True(map2.ContainsKey("key4"));
}
[Fact]
public static void Default_2_ToEncodedUriQueryParameters()
{
var map = new Dictionary<string, string>
{
["a"] = "1",
["b"] = "2",
["c"] = "3"
};
var encodedUriQueryParameters = map.ToEncodedUriQueryParameters();
Assert.Contains("a=1", encodedUriQueryParameters);
Assert.Contains("b=2", encodedUriQueryParameters);
Assert.Contains("c=3", encodedUriQueryParameters);
Assert.Contains("&", encodedUriQueryParameters);
}
[Fact]
public static void Default_3_ParseString()
{
var map = new Dictionary<string, string>
{
["a"] = "1",
["b"] = "2",
["c"] = "3"
};
Assert.Equal("1", map.ParseString("a"));
Assert.Equal("2", map.ParseString("b"));
Assert.Equal("3", map.ParseString("c"));
Assert.Null(map.ParseString("d"));
Assert.Equal("5", map.ParseString("e", "5"));
}
[Fact]
public static void Default_3_ParseUri()
{
var map = new Dictionary<string, string>
{
["a"] = "1",
["b"] = "https://www.microsoft.com",
["c"] = "http://www.google.com"
};
Assert.Null(map.ParseUri("a"));
Assert.NotNull(map.ParseUri("b"));
Assert.Equal(new Uri("http://www.google.com"), map.ParseUri("c"));
Assert.NotNull(map.ParseUri("d", new Uri("https://www.apple.com")));
var map2 = new Dictionary<string, object>
{
["a"] = "1",
["b"] = JsonFactory.GetInstance().CreateJsonObject(),
["c"] = new Uri("https://www.microsoft.com"),
["d"] = "http://www.google.com"
};
Assert.Null(map2.ParseUri("a"));
Assert.Null(map2.ParseUri("b"));
Assert.Equal(new Uri("https://www.microsoft.com"), map2.ParseUri("c"));
Assert.Equal(new Uri("http://www.google.com"), map2.ParseUri("d"));
Assert.NotNull(map2.ParseUri("e", new Uri("https://www.apple.com")));
}
[Fact]
public static void Default_4_ParseData()
{
var map = new Dictionary<string, object>
{
["a"] = "1",
["b"] = JsonFactory.GetInstance().CreateJsonObject(),
["c"] = new Uri("https://www.microsoft.com"),
["d"] = null
};
Assert.NotNull(map.ParseData("a"));
Assert.NotNull(map.ParseData("b"));
Assert.NotNull(map.ParseData("c"));
Assert.Null(map.ParseData("d"));
Assert.NotNull(map.ParseData("e", new Uri("https://www.apple.com")));
}
}
}
| |
/*
* Copyright 2017 ZXing.Net authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using ZXing.Common;
using ZXing.OneD;
namespace ZXing.Windows.Compatibility
{
/// <summary>
/// Renders a <see cref="BitMatrix" /> to a <see cref="Bitmap" /> image
/// </summary>
public class BitmapRenderer : ZXing.Rendering.IBarcodeRenderer<Bitmap>
{
/// <summary>
/// Gets or sets the foreground color.
/// </summary>
/// <value>The foreground color.</value>
public Color Foreground { get; set; }
/// <summary>
/// Gets or sets the background color.
/// </summary>
/// <value>The background color.</value>
public Color Background { get; set; }
/// <summary>
/// Gets or sets the resolution which should be used to create the bitmap
/// If nothing is set the current system settings are used
/// </summary>
public float? DpiX { get; set; }
/// <summary>
/// Gets or sets the resolution which should be used to create the bitmap
/// If nothing is set the current system settings are used
/// </summary>
public float? DpiY { get; set; }
/// <summary>
/// Gets or sets the text font.
/// </summary>
/// <value>
/// The text font.
/// </value>
public Font TextFont { get; set; }
private static readonly Font DefaultTextFont;
static BitmapRenderer()
{
try
{
DefaultTextFont = new Font("Arial", 10, FontStyle.Regular);
}
catch (Exception)
{
// have to ignore, no better idea
}
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapRenderer"/> class.
/// </summary>
public BitmapRenderer()
{
Foreground = Color.Black;
Background = Color.White;
TextFont = DefaultTextFont;
}
/// <summary>
/// Renders the specified matrix.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <param name="format">The format.</param>
/// <param name="content">The content.</param>
/// <returns></returns>
public Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content)
{
return Render(matrix, format, content, new EncodingOptions());
}
/// <summary>
/// Renders the specified matrix.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <param name="format">The format.</param>
/// <param name="content">The content.</param>
/// <param name="options">The options.</param>
/// <returns></returns>
virtual public Bitmap Render(BitMatrix matrix, BarcodeFormat format, string content, EncodingOptions options)
{
var width = matrix.Width;
var height = matrix.Height;
var font = TextFont ?? DefaultTextFont;
var emptyArea = 0;
var outputContent = font != null &&
(options == null || !options.PureBarcode) &&
!String.IsNullOrEmpty(content) &&
(format == BarcodeFormat.CODE_39 ||
format == BarcodeFormat.CODE_93 ||
format == BarcodeFormat.CODE_128 ||
format == BarcodeFormat.EAN_13 ||
format == BarcodeFormat.EAN_8 ||
format == BarcodeFormat.CODABAR ||
format == BarcodeFormat.ITF ||
format == BarcodeFormat.UPC_A ||
format == BarcodeFormat.UPC_E ||
format == BarcodeFormat.MSI ||
format == BarcodeFormat.PLESSEY);
if (options != null)
{
if (options.Width > width)
{
width = options.Width;
}
if (options.Height > height)
{
height = options.Height;
}
}
// calculating the scaling factor
var pixelsizeWidth = width / matrix.Width;
var pixelsizeHeight = height / matrix.Height;
// create the bitmap and lock the bits because we need the stride
// which is the width of the image and possible padding bytes
var bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
var dpiX = DpiX ?? DpiY;
var dpiY = DpiY ?? DpiX;
if (dpiX != null)
bmp.SetResolution(dpiX.Value, dpiY.Value);
using (var g = Graphics.FromImage(bmp))
{
var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly,
PixelFormat.Format24bppRgb);
try
{
var pixels = new byte[bmpData.Stride * height];
var padding = bmpData.Stride - (3 * width);
var index = 0;
var color = Background;
// going through the lines of the matrix
for (int y = 0; y < matrix.Height; y++)
{
// stretching the line by the scaling factor
for (var pixelsizeHeightProcessed = 0;
pixelsizeHeightProcessed < pixelsizeHeight;
pixelsizeHeightProcessed++)
{
// going through the columns of the current line
for (var x = 0; x < matrix.Width; x++)
{
color = matrix[x, y] ? Foreground : Background;
// stretching the columns by the scaling factor
for (var pixelsizeWidthProcessed = 0;
pixelsizeWidthProcessed < pixelsizeWidth;
pixelsizeWidthProcessed++)
{
pixels[index++] = color.B;
pixels[index++] = color.G;
pixels[index++] = color.R;
}
}
// fill up to the right if the barcode doesn't fully fit in
for (var x = pixelsizeWidth * matrix.Width; x < width; x++)
{
pixels[index++] = Background.B;
pixels[index++] = Background.G;
pixels[index++] = Background.R;
}
index += padding;
}
}
// fill up to the bottom if the barcode doesn't fully fit in
for (var y = pixelsizeHeight * matrix.Height; y < height; y++)
{
for (var x = 0; x < width; x++)
{
pixels[index++] = Background.B;
pixels[index++] = Background.G;
pixels[index++] = Background.R;
}
index += padding;
}
// fill the bottom area with the background color if the content should be written below the barcode
if (outputContent)
{
var textAreaHeight = font.Height;
emptyArea = height > textAreaHeight ? textAreaHeight : 0;
if (emptyArea > 0)
{
index = (width * 3 + padding) * (height - emptyArea);
for (int y = height - emptyArea; y < height; y++)
{
for (var x = 0; x < width; x++)
{
pixels[index++] = Background.B;
pixels[index++] = Background.G;
pixels[index++] = Background.R;
}
index += padding;
}
}
}
//Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
}
finally
{
//Unlock the pixels
bmp.UnlockBits(bmpData);
}
// output content text below the barcode
if (emptyArea > 0)
{
switch (format)
{
case BarcodeFormat.UPC_E:
case BarcodeFormat.EAN_8:
if (content.Length < 8)
content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
if (content.Length > 4)
content = content.Insert(4, " ");
break;
case BarcodeFormat.EAN_13:
if (content.Length < 13)
content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
if (content.Length > 7)
content = content.Insert(7, " ");
if (content.Length > 1)
content = content.Insert(1, " ");
break;
case BarcodeFormat.UPC_A:
if (content.Length < 12)
content = OneDimensionalCodeWriter.CalculateChecksumDigitModulo10(content);
if (content.Length > 11)
content = content.Insert(11, " ");
if (content.Length > 6)
content = content.Insert(6, " ");
if (content.Length > 1)
content = content.Insert(1, " ");
break;
}
var brush = new SolidBrush(Foreground);
var drawFormat = new StringFormat { Alignment = StringAlignment.Center };
g.DrawString(content, font, brush, pixelsizeWidth * matrix.Width / 2, height - emptyArea, drawFormat);
}
}
return bmp;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SaveLoadScreen.cs
//
// Microsoft 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.Content;
using RolePlayingGameData;
#endregion
namespace RolePlaying
{
/// <summary>
/// Displays a list of existing save games,
/// allowing the user to save, load, or delete.
/// </summary>
class SaveLoadScreen : GameScreen
{
public enum SaveLoadScreenMode
{
Save,
Load,
};
/// <summary>
/// The mode of this screen.
/// </summary>
private SaveLoadScreenMode mode;
/// <summary>
/// The current selected slot.
/// </summary>
private int currentSlot;
#region Graphics Data
private Texture2D backgroundTexture;
private Vector2 backgroundPosition;
private Texture2D plankTexture;
private Vector2 plankPosition;
private Texture2D backTexture;
private Vector2 backPosition;
private Texture2D deleteTexture;
private Vector2 deletePosition = ScaledVector2.GetScaledVector(400f, 595);
private Vector2 deleteTextPosition = ScaledVector2.GetScaledVector(410f,595);
private Texture2D selectTexture;
private Vector2 selectPosition;
private Texture2D lineBorderTexture;
private Vector2 lineBorderPosition;
private Texture2D highlightTexture;
private Texture2D arrowTexture;
private Vector2 titleTextPosition;
private Vector2 backTextPosition;
private Vector2 selectTextPosition;
#endregion
#region Initialization
/// <summary>
/// Create a new SaveLoadScreen object.
/// </summary>
public SaveLoadScreen(SaveLoadScreenMode mode) : base()
{
this.mode = mode;
// refresh the save game descriptions
Session.RefreshSaveGameDescriptions();
}
/// <summary>
/// Loads the graphics content for this screen.
/// </summary>
public override void LoadContent()
{
// load the textures
ContentManager content = ScreenManager.Game.Content;
backgroundTexture =
content.Load<Texture2D>(@"Textures\MainMenu\MainMenu");
plankTexture =
content.Load<Texture2D>(@"Textures\MainMenu\MainMenuPlank03");
backTexture =
content.Load<Texture2D>(@"Textures\Buttons\rpgbtn");
selectTexture =
content.Load<Texture2D>(@"Textures\Buttons\rpgbtn");
deleteTexture =
content.Load<Texture2D>(@"Textures\Buttons\rpgbtn");
lineBorderTexture =
content.Load<Texture2D>(@"Textures\GameScreens\LineBorder");
highlightTexture =
content.Load<Texture2D>(@"Textures\GameScreens\HighlightLarge");
arrowTexture =
content.Load<Texture2D>(@"Textures\GameScreens\SelectionArrow");
// calculate the image positions
Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
backgroundPosition = new Vector2(
(viewport.Width - backgroundTexture.Width * ScaledVector2.DrawFactor) / 2,
(viewport.Height - backgroundTexture.Height * ScaledVector2.DrawFactor) / 2);
plankPosition = backgroundPosition + new Vector2(
backgroundTexture.Width * ScaledVector2.DrawFactor / 2 - plankTexture.Width
* ScaledVector2.DrawFactor / 2,
60f * ScaledVector2.ScaleFactor);
backPosition = backgroundPosition + ScaledVector2.GetScaledVector(220, 590);
selectPosition = backgroundPosition + ScaledVector2.GetScaledVector(900, 590);
deletePosition = backgroundPosition + ScaledVector2.GetScaledVector(400f, 590);
lineBorderPosition = backgroundPosition + ScaledVector2.GetScaledVector(200, 570);
// calculate the text positions
titleTextPosition = new Vector2(
plankPosition.X + (plankTexture.Width * ScaledVector2.DrawFactor -
Fonts.HeaderFont.MeasureString("Load").X) / 2,
plankPosition.Y + (plankTexture.Height * ScaledVector2.DrawFactor -
Fonts.HeaderFont.MeasureString("Load").Y) / 2);
backTextPosition = new Vector2(backPosition.X + 30, backPosition.Y + 5);
deleteTextPosition.X += deleteTexture.Width * ScaledVector2.DrawFactor;
selectTextPosition = new Vector2(
selectPosition.X - Fonts.ButtonNamesFont.MeasureString("Select").X - 5,
selectPosition.Y + 5);
base.LoadContent();
}
#endregion
#region Handle Input
/// <summary>
/// Respond to user input.
/// </summary>
public override void HandleInput()
{
bool backClicked = false;
bool selectClicked = false;
bool deleteClicked = false;
foreach (var item in ItemPositionMapping)
{
if (InputManager.IsButtonClicked(item.Key))
{
currentSlot = item.Value;
break;
}
}
if (InputManager.IsButtonClicked(new Rectangle
((int)(backPosition.X ),
(int)backPosition.Y,
(int)(backTexture.Width * ScaledVector2.DrawFactor),
(int)(backTexture.Height * ScaledVector2.DrawFactor))))
{
backClicked = true;
}
if (InputManager.IsButtonClicked(new Rectangle
((int)selectPosition.X,
(int)selectPosition.Y,
(int)(selectTexture.Width * ScaledVector2.DrawFactor),
(int)(selectTexture.Height * ScaledVector2.DrawFactor))))
{
selectClicked = true;
}
if (InputManager.IsButtonClicked(new Rectangle
((int)deletePosition.X ,
(int)deletePosition.Y,
(int)(deleteTexture.Width * ScaledVector2.DrawFactor),
(int)(deleteTexture.Height * ScaledVector2.DrawFactor))))
{
deleteClicked = true;
}
// handle exiting the screen
if (InputManager.IsActionTriggered(InputManager.Action.Back) || backClicked)
{
ExitScreen();
return;
}
// handle selecting a save game
if (selectClicked &&
(Session.SaveGameDescriptions != null))
{
switch (mode)
{
case SaveLoadScreenMode.Load:
if ((currentSlot >= 0) &&
(currentSlot < Session.SaveGameDescriptions.Count) &&
(Session.SaveGameDescriptions[currentSlot] != null))
{
if (Session.IsActive)
{
MessageBoxScreen messageBoxScreen = new MessageBoxScreen(
"Are you sure you want to load this game?");
messageBoxScreen.Accepted +=
ConfirmLoadMessageBoxAccepted;
ScreenManager.AddScreen(messageBoxScreen);
}
else
{
ConfirmLoadMessageBoxAccepted(null, EventArgs.Empty);
}
}
break;
case SaveLoadScreenMode.Save:
if ((currentSlot >= 0) &&
(currentSlot <= Session.SaveGameDescriptions.Count))
{
if (currentSlot == Session.SaveGameDescriptions.Count)
{
ConfirmSaveMessageBoxAccepted(null, EventArgs.Empty);
}
else
{
MessageBoxScreen messageBoxScreen = new MessageBoxScreen(
"Are you sure you want to overwrite this save game?");
messageBoxScreen.Accepted +=
ConfirmSaveMessageBoxAccepted;
ScreenManager.AddScreen(messageBoxScreen);
}
}
break;
}
}
// handle deletion
else if (InputManager.IsActionTriggered(InputManager.Action.DropUnEquip) || deleteClicked &&
(Session.SaveGameDescriptions != null))
{
if ((currentSlot >= 0) &&
(currentSlot < Session.SaveGameDescriptions.Count) &&
(Session.SaveGameDescriptions[currentSlot] != null))
{
MessageBoxScreen messageBoxScreen = new MessageBoxScreen(
"Are you sure you want to delete this save game?");
messageBoxScreen.Accepted += ConfirmDeleteMessageBoxAccepted;
ScreenManager.AddScreen(messageBoxScreen);
}
}
// handle cursor-down
else if (InputManager.IsActionTriggered(InputManager.Action.CursorDown) &&
(Session.SaveGameDescriptions != null))
{
int maximumSlot = Session.SaveGameDescriptions.Count;
if (mode == SaveLoadScreenMode.Save)
{
maximumSlot = Math.Min(maximumSlot + 1,
Session.MaximumSaveGameDescriptions);
}
if (currentSlot < maximumSlot - 1)
{
currentSlot++;
}
}
// handle cursor-up
else if (InputManager.IsActionTriggered(InputManager.Action.CursorUp) &&
(Session.SaveGameDescriptions != null))
{
if (currentSlot >= 1)
{
currentSlot--;
}
}
}
/// <summary>
/// Callback for the Save Game confirmation message box.
/// </summary>
void ConfirmSaveMessageBoxAccepted(object sender, EventArgs e)
{
if ((currentSlot >= 0) &&
(currentSlot <= Session.SaveGameDescriptions.Count))
{
if (currentSlot == Session.SaveGameDescriptions.Count)
{
Session.SaveSession(null);
}
else
{
Session.SaveSession(Session.SaveGameDescriptions[currentSlot]);
}
ExitScreen();
}
}
/// <summary>
/// Delegate type for the save-game-selected-to-load event.
/// </summary>
/// <param name="saveGameDescription">
/// The description of the file to load.
/// </param>
public delegate void LoadingSaveGameHandler(
SaveGameDescription saveGameDescription);
/// <summary>
/// Fired when a save game is selected to load.
/// </summary>
/// <remarks>
/// Loading save games exits multiple screens,
/// so we use events to move backwards.
/// </remarks>
public event LoadingSaveGameHandler LoadingSaveGame;
/// <summary>
/// Callback for the Load Game confirmation message box.
/// </summary>
void ConfirmLoadMessageBoxAccepted(object sender, EventArgs e)
{
if ((Session.SaveGameDescriptions != null) && (currentSlot >= 0) &&
(currentSlot < Session.SaveGameDescriptions.Count) &&
(Session.SaveGameDescriptions[currentSlot] != null))
{
ExitScreen();
if (LoadingSaveGame != null)
{
LoadingSaveGame(Session.SaveGameDescriptions[currentSlot]);
}
}
}
/// <summary>
/// Callback for the Delete Game confirmation message box.
/// </summary>
void ConfirmDeleteMessageBoxAccepted(object sender, EventArgs e)
{
if ((Session.SaveGameDescriptions != null) && (currentSlot >= 0) &&
(currentSlot < Session.SaveGameDescriptions.Count) &&
(Session.SaveGameDescriptions[currentSlot] != null))
{
Session.DeleteSaveGame(Session.SaveGameDescriptions[currentSlot]);
}
}
#endregion
#region Drawing
public Dictionary<Rectangle, int> ItemPositionMapping = new Dictionary<Rectangle, int>();
/// <summary>
/// Draws the screen.
/// </summary>
public override void Draw(GameTime gameTime)
{
ItemPositionMapping.Clear();
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
spriteBatch.Begin();
spriteBatch.Draw(backgroundTexture, backgroundPosition,null, Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
spriteBatch.Draw(plankTexture, plankPosition,null, Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
spriteBatch.Draw(lineBorderTexture, lineBorderPosition,null, Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
spriteBatch.Draw(backTexture, backPosition,null, Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
string text = "Back";
Vector2 textPosition = Fonts.GetCenterPositionInButton(Fonts.ButtonNamesFont,text,
new Rectangle((int)backPosition.X,(int)backPosition.Y,
backTexture.Width,backTexture.Height));
spriteBatch.DrawString(Fonts.ButtonNamesFont, text,textPosition, Color.White);
spriteBatch.DrawString(Fonts.HeaderFont,
(mode == SaveLoadScreenMode.Load ? "Load" : "Save"),
titleTextPosition, Fonts.TitleColor);
if ((Session.SaveGameDescriptions != null))
{
for (int i = 0; i < Session.SaveGameDescriptions.Count; i++)
{
Vector2 descriptionTextPosition = ScaledVector2.GetScaledVector(295f,
200f + i * (Fonts.GearInfoFont.LineSpacing + 80f));
ItemPositionMapping.Add(new Rectangle((int)descriptionTextPosition.X - 80,
(int)descriptionTextPosition.Y-25,600, 75), i);
Color descriptionTextColor = Color.Black;
// if the save game is selected, draw the highlight color
if (i == currentSlot)
{
descriptionTextColor = Fonts.HighlightColor;
spriteBatch.Draw(highlightTexture,
descriptionTextPosition + ScaledVector2.GetScaledVector(-100, -23),null,
Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
spriteBatch.Draw(arrowTexture,
descriptionTextPosition + ScaledVector2.GetScaledVector(-75, -15), null,
Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
spriteBatch.Draw(deleteTexture, deletePosition,null,Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
string deleteText = "Delete";
Vector2 deleteFontPosition = Fonts.GetCenterPositionInButton(Fonts.ButtonNamesFont, deleteText,
new Rectangle((int)deletePosition.X, (int)deletePosition.Y,
deleteTexture.Width, deleteTexture.Height));
spriteBatch.DrawString(Fonts.ButtonNamesFont, deleteText, deleteFontPosition, Color.White);
spriteBatch.Draw(selectTexture, selectPosition,null, Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
string selectText = "Select";
Vector2 selectFontPosition = Fonts.GetCenterPositionInButton(Fonts.ButtonNamesFont, selectText,
new Rectangle((int)selectPosition.X, (int)selectPosition.Y,
selectTexture.Width, selectTexture.Height));
spriteBatch.DrawString(Fonts.ButtonNamesFont, selectText, selectFontPosition, Color.White);
}
spriteBatch.DrawString(Fonts.GearInfoFont,
Session.SaveGameDescriptions[i].ChapterName,
descriptionTextPosition , descriptionTextColor);
descriptionTextPosition.X = 650 * ScaledVector2.ScaleFactor;
spriteBatch.DrawString(Fonts.GearInfoFont,
Session.SaveGameDescriptions[i].Description,
descriptionTextPosition, descriptionTextColor);
}
// if there is space for one, add an empty entry
if ((mode == SaveLoadScreenMode.Save) &&
(Session.SaveGameDescriptions.Count <
Session.MaximumSaveGameDescriptions))
{
int i = Session.SaveGameDescriptions.Count;
Vector2 descriptionTextPosition = ScaledVector2.GetScaledVector(
295f,
200f + i * (Fonts.GearInfoFont.LineSpacing + 80f));
Color descriptionTextColor = Color.Black;
// if the save game is selected, draw the highlight color
if (i == currentSlot)
{
descriptionTextColor = Fonts.HighlightColor;
spriteBatch.Draw(highlightTexture,
descriptionTextPosition + ScaledVector2.GetScaledVector(-100, -23),null,
Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
spriteBatch.Draw(arrowTexture,
descriptionTextPosition + ScaledVector2.GetScaledVector(-75, -15),null,
Color.White,0f,
Vector2.Zero, ScaledVector2.DrawFactor,SpriteEffects.None,0f);
spriteBatch.Draw(selectTexture, selectPosition, null, Color.White, 0f,
Vector2.Zero, ScaledVector2.DrawFactor, SpriteEffects.None, 0f);
string selectText = "Select";
Vector2 selectFontPosition = Fonts.GetCenterPositionInButton(Fonts.ButtonNamesFont, selectText,
new Rectangle((int)selectPosition.X, (int)selectPosition.Y,
selectTexture.Width, selectTexture.Height));
spriteBatch.DrawString(Fonts.ButtonNamesFont, selectText,
selectFontPosition, Color.White);
}
ItemPositionMapping.Add(new Rectangle((int)descriptionTextPosition.X - 80,
(int)descriptionTextPosition.Y -25, 600, 75), i);
spriteBatch.DrawString(Fonts.GearInfoFont, "-------empty------",
descriptionTextPosition, descriptionTextColor);
descriptionTextPosition.X = 650 * ScaledVector2.ScaleFactor;
spriteBatch.DrawString(Fonts.GearInfoFont, "-----",
descriptionTextPosition, descriptionTextColor);
}
}
// if there are no slots to load, report that
if (Session.SaveGameDescriptions == null)
{
spriteBatch.DrawString(Fonts.GearInfoFont,
"No Storage Device Available",
ScaledVector2.GetScaledVector(295f, 200f), Color.Black);
}
else if ((mode == SaveLoadScreenMode.Load) &&
(Session.SaveGameDescriptions.Count <= 0))
{
spriteBatch.DrawString(Fonts.GearInfoFont,
"No Save Games Available",
ScaledVector2.GetScaledVector(295f, 200f), Color.Black);
}
spriteBatch.End();
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Internal
{
using System;
using NLog.Common;
using Xunit;
public class ConversionHelpersTests : NLogTestBase
{
enum TestEnum
{
Foo,
bar,
}
#region tryparse - ignorecase parameter: false
[Fact]
public void EnumParse1_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam("Foo", false, TestEnum.Foo, true);
}
[Fact]
public void EnumParse2_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam("foo", false, TestEnum.Foo, false);
}
[Fact]
public void EnumParseDefault_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam("BAR", false, TestEnum.Foo, false);
}
[Fact]
public void EnumParseDefault2_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam("x", false, TestEnum.Foo, false);
}
[Fact]
public void EnumParseBar_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam("bar", false, TestEnum.bar, true);
}
[Fact]
public void EnumParseBar2_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam(" bar ", false, TestEnum.bar, true);
}
[Fact]
public void EnumParseBar3_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam(" \r\nbar ", false, TestEnum.bar, true);
}
[Fact]
public void EnumParse_null_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam(null, false, TestEnum.Foo, false);
}
[Fact]
public void EnumParse_emptystring_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam(string.Empty, false, TestEnum.Foo, false);
}
[Fact]
public void EnumParse_whitespace_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam(" ", false, TestEnum.Foo, false);
}
[Fact]
public void EnumParse_wrongInput_ignoreCaseFalse()
{
TestEnumParseCaseIgnoreCaseParam("not enum", false, TestEnum.Foo, false);
}
#endregion
#region tryparse - ignorecase parameter: true
[Fact]
public void EnumParse1_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam("Foo", true, TestEnum.Foo, true);
}
[Fact]
public void EnumParse2_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam("foo", true, TestEnum.Foo, true);
}
[Fact]
public void EnumParseDefault_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam("BAR", true, TestEnum.bar, true);
}
[Fact]
public void EnumParseDefault2_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam("x", true, TestEnum.Foo, false);
}
[Fact]
public void EnumParseBar_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam("bar", true, TestEnum.bar, true);
}
[Fact]
public void EnumParseBar2_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam(" bar ", true, TestEnum.bar, true);
}
[Fact]
public void EnumParseBar3_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam(" \r\nbar ", true, TestEnum.bar, true);
}
[Fact]
public void EnumParse_null_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam(null, true, TestEnum.Foo, false);
}
[Fact]
public void EnumParse_emptystring_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam(string.Empty, true, TestEnum.Foo, false);
}
[Fact]
public void EnumParse_whitespace_ignoreCaseTrue()
{
TestEnumParseCaseIgnoreCaseParam(" ", true, TestEnum.Foo, false);
}
[Fact]
public void EnumParse_ArgumentException_ignoreCaseTrue()
{
double result;
Assert.Throws<ArgumentException>(() => ConversionHelpers.TryParseEnum("not enum", true, out result));
}
#endregion
#region helpers
private static void TestEnumParseCaseIgnoreCaseParam(string value, bool ignoreCase, TestEnum expected, bool expectedReturn)
{
{
var returnResult = ConversionHelpers.TryParseEnum(value, ignoreCase, out TestEnum result);
Assert.Equal(expected, result);
Assert.Equal(expectedReturn, returnResult);
}
// if true, test also other TryParseEnum
if (ignoreCase)
{
{
var returnResult = ConversionHelpers.TryParseEnum<TestEnum>(value, out var result);
Assert.Equal(expected, result);
Assert.Equal(expectedReturn, returnResult);
}
{
var returnResult = ConversionHelpers.TryParseEnum(value, typeof(TestEnum), out var result);
Assert.Equal(expectedReturn, returnResult);
if (expectedReturn)
{
Assert.Equal(expected, result);
}
else
{
Assert.Null(result);
}
}
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
/// <summary>
/// Represents logging target.
/// </summary>
[NLogConfigurationItem]
public abstract class Target : ISupportsInitialize, IInternalLoggerContext, IDisposable
{
internal string _tostring;
private Layout[] _allLayouts = ArrayHelper.Empty<Layout>();
/// <summary> Are all layouts in this target thread-agnostic, if so we don't precalculate the layouts </summary>
private bool _allLayoutsAreThreadAgnostic;
private bool _oneLayoutIsMutableUnsafe;
private bool _scannedForLayouts;
private Exception _initializeException;
/// <summary>
/// The Max StackTraceUsage of all the <see cref="Layout"/> in this Target
/// </summary>
internal StackTraceUsage StackTraceUsage { get; private set; }
internal Exception InitializeException => _initializeException;
/// <summary>
/// Gets or sets the name of the target.
/// </summary>
/// <docgen category='General Options' order='1' />
public string Name
{
get => _name;
set
{
_name = value;
_tostring = null;
}
}
private string _name;
/// <summary>
/// Target supports reuse of internal buffers, and doesn't have to constantly allocate new buffers
/// Required for legacy NLog-targets, that expects buffers to remain stable after Write-method exit
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[Obsolete("No longer used, and always returns true. Marked obsolete on NLog 5.0")]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool OptimizeBufferReuse { get => _optimizeBufferReuse ?? true; set => _optimizeBufferReuse = value ? true : (bool?)null; }
private bool? _optimizeBufferReuse;
/// <summary>
/// NLog Layout are by default threadsafe, so multiple threads can be rendering logevents at the same time.
/// This ensure high concurrency with no lock-congestion for the application-threads, especially when using <see cref="Wrappers.AsyncTargetWrapper"/>
/// or AsyncTaskTarget.
///
/// But if using custom <see cref="Layout" /> or <see cref="LayoutRenderers.LayoutRenderer"/> that are not
/// threadsafe, then this option can enabled to protect against thread-concurrency-issues. Allowing one
/// to update to NLog 5.0 without having to fix custom/external layout-dependencies.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
public bool LayoutWithLock { get; set; }
/// <summary>
/// Gets the object which can be used to synchronize asynchronous operations that must rely on the .
/// </summary>
protected object SyncRoot { get; } = new object();
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
LogFactory IInternalLoggerContext.LogFactory => LoggingConfiguration?.LogFactory;
/// <summary>
/// Gets a value indicating whether the target has been initialized.
/// </summary>
protected bool IsInitialized
{
get
{
if (_isInitialized)
return true; // Initialization has completed
// Lets wait for initialization to complete, and then check again
lock (SyncRoot)
{
return _isInitialized;
}
}
}
private volatile bool _isInitialized;
internal readonly ReusableBuilderCreator ReusableLayoutBuilder = new ReusableBuilderCreator();
private StringBuilderPool _precalculateStringBuilderPool;
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
lock (SyncRoot)
{
bool wasInitialized = _isInitialized;
Initialize(configuration);
if (wasInitialized && configuration != null)
{
FindAllLayouts();
}
}
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
Close();
}
/// <summary>
/// Closes the target.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public void Flush(AsyncContinuation asyncContinuation)
{
if (asyncContinuation is null)
{
throw new ArgumentNullException(nameof(asyncContinuation));
}
asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation);
lock (SyncRoot)
{
if (!IsInitialized)
{
// In case target was Closed
asyncContinuation(null);
return;
}
try
{
FlushAsync(asyncContinuation);
}
catch (Exception exception)
{
if (ExceptionMustBeRethrown(exception))
throw;
asyncContinuation(exception);
}
}
}
/// <summary>
/// Calls the <see cref="Layout.Precalculate"/> on each volatile layout
/// used by this target.
/// This method won't prerender if all layouts in this target are thread-agnostic.
/// </summary>
/// <param name="logEvent">
/// The log event.
/// </param>
public void PrecalculateVolatileLayouts(LogEventInfo logEvent)
{
if (_allLayoutsAreThreadAgnostic && (!_oneLayoutIsMutableUnsafe || logEvent.IsLogEventMutableSafe()))
{
return;
}
if (!IsInitialized)
return;
if (LayoutWithLock)
{
PrecalculateVolatileLayoutsWithLock(logEvent);
}
else
{
PrecalculateVolatileLayoutsConcurrent(logEvent);
}
}
private void PrecalculateVolatileLayoutsConcurrent(LogEventInfo logEvent)
{
if (!IsInitialized)
return;
if (_precalculateStringBuilderPool is null)
{
System.Threading.Interlocked.CompareExchange(ref _precalculateStringBuilderPool, new StringBuilderPool(Environment.ProcessorCount * 2), null);
}
using (var targetBuilder = _precalculateStringBuilderPool.Acquire())
{
foreach (Layout layout in _allLayouts)
{
targetBuilder.Item.ClearBuilder();
layout.PrecalculateBuilder(logEvent, targetBuilder.Item);
}
}
}
private void PrecalculateVolatileLayoutsWithLock(LogEventInfo logEvent)
{
lock (SyncRoot)
{
if (!_isInitialized)
return;
using (var targetBuilder = ReusableLayoutBuilder.Allocate())
{
foreach (Layout layout in _allLayouts)
{
targetBuilder.Result.ClearBuilder();
layout.PrecalculateBuilder(logEvent, targetBuilder.Result);
}
}
}
}
/// <inheritdoc/>
public override string ToString()
{
return _tostring ?? (_tostring = GenerateTargetToString(false));
}
internal string GenerateTargetToString(bool targetWrapper, string targetName = null)
{
var targetAttribute = GetType().GetFirstCustomAttribute<TargetAttribute>();
string targetType = (targetAttribute?.Name ?? GetType().Name).Trim();
targetWrapper = targetWrapper || targetAttribute?.IsCompound == true || targetAttribute?.IsWrapper == true;
if (!targetWrapper && targetType.IndexOf("Target", StringComparison.OrdinalIgnoreCase) < 0)
{
targetType += "Target";
}
targetName = targetName ?? Name;
if (string.IsNullOrEmpty(targetName))
return targetWrapper ? targetType : $"{targetType}([unnamed])";
else
return $"{targetType}(Name={targetName})";
}
/// <summary>
/// Writes the log to the target.
/// </summary>
/// <param name="logEvent">Log event to write.</param>
public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent)
{
if (!IsInitialized)
{
lock (SyncRoot)
{
logEvent.Continuation(null);
}
return;
}
if (_initializeException != null)
{
lock (SyncRoot)
{
WriteFailedNotInitialized(logEvent, _initializeException);
}
return;
}
var wrappedContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation);
var wrappedLogEvent = logEvent.LogEvent.WithContinuation(wrappedContinuation);
try
{
WriteAsyncThreadSafe(wrappedLogEvent);
}
catch (Exception ex)
{
if (ExceptionMustBeRethrown(ex))
throw;
wrappedLogEvent.Continuation(ex);
}
}
/// <summary>
/// Writes the array of log events.
/// </summary>
/// <param name="logEvents">The log events.</param>
public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents)
{
if (logEvents?.Length > 0)
{
WriteAsyncLogEvents((IList<AsyncLogEventInfo>)logEvents);
}
}
/// <summary>
/// Writes the array of log events.
/// </summary>
/// <param name="logEvents">The log events.</param>
public void WriteAsyncLogEvents(IList<AsyncLogEventInfo> logEvents)
{
if (logEvents is null || logEvents.Count == 0)
{
return;
}
if (!IsInitialized)
{
lock (SyncRoot)
{
for (int i = 0; i < logEvents.Count; ++i)
{
logEvents[i].Continuation(null);
}
}
return;
}
if (_initializeException != null)
{
lock (SyncRoot)
{
for (int i = 0; i < logEvents.Count; ++i)
{
WriteFailedNotInitialized(logEvents[i], _initializeException);
}
}
return;
}
for (int i = 0; i < logEvents.Count; ++i)
{
logEvents[i] = logEvents[i].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[i].Continuation));
}
try
{
WriteAsyncThreadSafe(logEvents);
}
catch (Exception exception)
{
if (ExceptionMustBeRethrown(exception))
throw;
// in case of synchronous failure, assume that nothing is running asynchronously
for (int i = 0; i < logEvents.Count; ++i)
{
logEvents[i].Continuation(exception);
}
}
}
/// <summary>
/// LogEvent is written to target, but target failed to succesfully initialize
/// </summary>
protected virtual void WriteFailedNotInitialized(AsyncLogEventInfo logEvent, Exception initializeException)
{
var initializeFailedException = new NLogRuntimeException($"Target {this} failed to initialize.", initializeException);
logEvent.Continuation(initializeFailedException);
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
lock (SyncRoot)
{
LoggingConfiguration = configuration;
if (!IsInitialized)
{
try
{
PropertyHelper.CheckRequiredParameters(this);
InitializeTarget();
_initializeException = null;
if (!_scannedForLayouts)
{
InternalLogger.Debug("{0}: InitializeTarget is done but not scanned For Layouts", this);
//this is critical, as we need the layouts. So if base.InitializeTarget() isn't called, we fix the layouts here.
FindAllLayouts();
}
}
catch (NLogDependencyResolveException exception)
{
// Target is now in disabled state, and cannot be used for writing LogEvents
_initializeException = exception;
if (ExceptionMustBeRethrown(exception))
throw;
}
catch (Exception exception)
{
// Target is now in disabled state, and cannot be used for writing LogEvents
_initializeException = exception;
if (ExceptionMustBeRethrown(exception))
throw;
var logFactory = LoggingConfiguration?.LogFactory ?? LogManager.LogFactory;
if ((logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions))
{
throw new NLogConfigurationException($"Error during initialization of target {this}", exception);
}
}
finally
{
_isInitialized = true; // Only one attempt, must Close to retry
}
}
}
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
lock (SyncRoot)
{
LoggingConfiguration = null;
if (IsInitialized)
{
_isInitialized = false;
try
{
if (_initializeException is null)
{
// if Init succeeded, call Close()
InternalLogger.Debug("{0}: Closing...", this);
CloseTarget();
InternalLogger.Debug("{0}: Closed.", this);
}
}
catch (Exception exception)
{
if (ExceptionMustBeRethrown(exception))
throw;
}
}
}
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing && _isInitialized)
{
_isInitialized = false;
if (_initializeException is null)
{
CloseTarget();
}
}
}
/// <summary>
/// Initializes the target before writing starts
/// </summary>
protected virtual void InitializeTarget()
{
//rescan as amount layouts can be changed.
FindAllLayouts();
}
private void FindAllLayouts()
{
_allLayouts = ObjectGraphScanner.FindReachableObjects<Layout>(false, this).ToArray();
InternalLogger.Trace("{0} has {1} layouts", this, _allLayouts.Length);
_allLayoutsAreThreadAgnostic = _allLayouts.All(layout => layout.ThreadAgnostic);
_oneLayoutIsMutableUnsafe = _allLayoutsAreThreadAgnostic && _allLayouts.Any(layout => layout.MutableUnsafe);
var result = _allLayouts.Aggregate(StackTraceUsage.None, (agg, layout) => agg | layout.StackTraceUsage);
StackTraceUsage = result | ((this as IUsesStackTrace)?.StackTraceUsage ?? StackTraceUsage.None);
_scannedForLayouts = true;
}
/// <summary>
/// Closes the target to release any initialized resources
/// </summary>
protected virtual void CloseTarget()
{
}
/// <summary>
/// Flush any pending log messages
/// </summary>
/// <remarks>The asynchronous continuation parameter must be called on flush completed</remarks>
/// <param name="asyncContinuation">The asynchronous continuation to be called on flush completed.</param>
protected virtual void FlushAsync(AsyncContinuation asyncContinuation)
{
asyncContinuation(null);
}
/// <summary>
/// Writes logging event to the target destination
/// </summary>
/// <param name="logEvent">Logging event to be written out.</param>
protected virtual void Write(LogEventInfo logEvent)
{
// Override to perform the actual write-operation
}
/// <summary>
/// Writes async log event to the log target.
/// </summary>
/// <param name="logEvent">Async Log event to be written out.</param>
protected virtual void Write(AsyncLogEventInfo logEvent)
{
try
{
Write(logEvent.LogEvent);
logEvent.Continuation(null);
}
catch (Exception exception)
{
if (ExceptionMustBeRethrown(exception))
throw;
logEvent.Continuation(exception);
}
}
/// <summary>
/// Writes a log event to the log target, in a thread safe manner.
/// Any override of this method has to provide their own synchronization mechanism.
///
/// !WARNING! Custom targets should only override this method if able to provide their
/// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be
/// thread-safe, so using them without a SyncRoot-object can be dangerous.
/// </summary>
/// <param name="logEvent">Log event to be written out.</param>
protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent)
{
lock (SyncRoot)
{
if (!IsInitialized)
{
// In case target was Closed
logEvent.Continuation(null);
return;
}
Write(logEvent);
}
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected virtual void Write(IList<AsyncLogEventInfo> logEvents)
{
for (int i = 0; i < logEvents.Count; ++i)
{
Write(logEvents[i]);
}
}
/// <summary>
/// Writes an array of logging events to the log target, in a thread safe manner.
/// Any override of this method has to provide their own synchronization mechanism.
///
/// !WARNING! Custom targets should only override this method if able to provide their
/// own synchronization mechanism. <see cref="Layout" />-objects are not guaranteed to be
/// thread-safe, so using them without a SyncRoot-object can be dangerous.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected virtual void WriteAsyncThreadSafe(IList<AsyncLogEventInfo> logEvents)
{
lock (SyncRoot)
{
if (!IsInitialized)
{
// In case target was Closed
for (int i = 0; i < logEvents.Count; ++i)
{
logEvents[i].Continuation(null);
}
return;
}
Write(logEvents);
}
}
/// <summary>
/// Merges (copies) the event context properties from any event info object stored in
/// parameters of the given event info object.
/// </summary>
/// <param name="logEvent">The event info object to perform the merge to.</param>
[Obsolete("Logger.Trace(logEvent) now automatically captures the logEvent Properties. Marked obsolete on NLog 4.6")]
protected void MergeEventProperties(LogEventInfo logEvent)
{
if (logEvent.Parameters is null || logEvent.Parameters.Length == 0)
{
return;
}
//Memory profiling pointed out that using a foreach-loop was allocating
//an Enumerator. Switching to a for-loop avoids the memory allocation.
for (int i = 0; i < logEvent.Parameters.Length; ++i)
{
if (logEvent.Parameters[i] is LogEventInfo logEventParameter && logEventParameter.HasProperties)
{
foreach (var key in logEventParameter.Properties.Keys)
{
logEvent.Properties.Add(key, logEventParameter.Properties[key]);
}
logEventParameter.Properties.Clear();
}
}
}
/// <summary>
/// Renders the logevent into a string-result using the provided layout
/// </summary>
/// <param name="layout">The layout.</param>
/// <param name="logEvent">The logevent info.</param>
/// <returns>String representing log event.</returns>
protected string RenderLogEvent([CanBeNull] Layout layout, [CanBeNull] LogEventInfo logEvent)
{
if (layout is null || logEvent is null)
return null; // Signal that input was wrong
SimpleLayout simpleLayout = layout as SimpleLayout;
if (simpleLayout != null && simpleLayout.IsFixedText)
{
return simpleLayout.Render(logEvent);
}
if (TryGetCachedValue(layout, logEvent, out var value))
{
return value?.ToString() ?? string.Empty;
}
if (simpleLayout != null && simpleLayout.IsSimpleStringText)
{
return simpleLayout.Render(logEvent);
}
using (var localTarget = ReusableLayoutBuilder.Allocate())
{
return layout.RenderAllocateBuilder(logEvent, localTarget.Result);
}
}
/// <summary>
/// Renders the logevent into a result-value by using the provided layout
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="layout">The layout.</param>
/// <param name="logEvent">The logevent info.</param>
/// <param name="defaultValue">Fallback value when no value available</param>
/// <returns>Result value when available, else fallback to defaultValue</returns>
protected T RenderLogEvent<T>([CanBeNull] Layout<T> layout, [CanBeNull] LogEventInfo logEvent, T defaultValue = default(T))
{
if (layout is null || logEvent is null)
return defaultValue;
if (layout.IsFixed)
return layout.FixedValue;
if (TryGetCachedValue(layout, logEvent, out var value))
{
if (value != null)
return (T)value;
else
return defaultValue;
}
using (var localTarget = ReusableLayoutBuilder.Allocate())
{
return layout.RenderTypedValue(logEvent, localTarget.Result, defaultValue);
}
}
/// <summary>
/// Resolve from DI <see cref="LogFactory.ServiceRepository"/>
/// </summary>
/// <remarks>Avoid calling this while handling a LogEvent, since random deadlocks can occur.</remarks>
protected T ResolveService<T>() where T : class
{
return LoggingConfiguration.GetServiceProvider().ResolveService<T>(IsInitialized);
}
/// <summary>
/// Should the exception be rethrown?
/// </summary>
/// <remarks>Upgrade to private protected when using C# 7.2 </remarks>
///
internal bool ExceptionMustBeRethrown(Exception exception,
#if !NET35
[System.Runtime.CompilerServices.CallerMemberName]
#endif
string callerMemberName = null)
{
return exception.MustBeRethrown(this, callerMemberName);
}
private static bool TryGetCachedValue(Layout layout, LogEventInfo logEvent, out object value)
{
if ((!layout.ThreadAgnostic || layout.MutableUnsafe) && logEvent.TryGetCachedLayoutValue(layout, out value))
{
return true;
}
value = null;
return false;
}
/// <summary>
/// Register a custom Target.
/// </summary>
/// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks>
/// <typeparam name="T"> Type of the Target.</typeparam>
/// <param name="name"> Name of the Target.</param>
public static void Register<T>(string name)
where T : Target
{
var layoutRendererType = typeof(T);
Register(name, layoutRendererType);
}
/// <summary>
/// Register a custom Target.
/// </summary>
/// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks>
/// <param name="targetType"> Type of the Target.</param>
/// <param name="name"> Name of the Target.</param>
public static void Register(string name, Type targetType)
{
ConfigurationItemFactory.Default.Targets.RegisterDefinition(name, targetType);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.libcurl.CURLAUTH;
using CURLoption = Interop.libcurl.CURLoption;
using CurlProtocols = Interop.libcurl.CURLPROTO_Definitions;
using CURLProxyType = Interop.libcurl.curl_proxytype;
using SafeCurlHandle = Interop.libcurl.SafeCurlHandle;
using SafeCurlSlistHandle = Interop.libcurl.SafeCurlSlistHandle;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
internal readonly CurlHandler _handler;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal readonly HttpContentAsyncStream _requestContentStream;
internal SafeCurlHandle _easyHandle;
private SafeCurlSlistHandle _requestHeaders;
internal NetworkCredential _networkCredential;
internal MultiAgent _associatedMultiAgent;
internal SendTransferState _sendTransferState;
internal bool _isRedirect = false;
public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_handler = handler;
_requestMessage = requestMessage;
_cancellationToken = cancellationToken;
if (requestMessage.Content != null)
{
_requestContentStream = new HttpContentAsyncStream(requestMessage.Content);
}
_responseMessage = new CurlResponseMessage(this);
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.libcurl.curl_easy_init();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
// Configure the handle
SetUrl();
SetDebugging();
SetMultithreading();
SetRedirection();
SetVerb();
SetDecompressionOptions();
SetProxyOptions(_requestMessage.RequestUri);
SetCredentialsOptions(_handler.GetNetworkCredentials(_handler._serverCredentials,_requestMessage.RequestUri));
SetCookieOption(_requestMessage.RequestUri);
SetRequestHeaders();
}
public void EnsureResponseMessagePublished()
{
bool result = TrySetResult(_responseMessage);
Debug.Assert(result || Task.Status == TaskStatus.RanToCompletion,
"If the task was already completed, it should have been completed succesfully; " +
"we shouldn't be completing as successful after already completing as failed.");
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
if (error is IOException || error is CurlException || error == null)
{
error = CreateHttpRequestException(error);
}
TrySetException(error);
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
_responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream.
// Dispose of the input content stream if there was one. Nothing should be using it any more.
if (_requestContentStream != null)
_requestContentStream.Dispose();
// Dispose of the underlying easy handle. We're no longer processing it.
if (_easyHandle != null)
_easyHandle.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
if (_requestHeaders != null)
_requestHeaders.Dispose();
}
private void SetUrl()
{
VerboseTrace(_requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_URL, _requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS);
}
[Conditional(VerboseDebuggingConditional)]
private void SetDebugging()
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
// In addition to CURLOPT_VERBOSE, CURLOPT_DEBUGFUNCTION could be used here in the future to:
// - Route the verbose output to somewhere other than stderr
// - Dump additional data related to CURLINFO_DATA_* and CURLINFO_SSL_DATA_*
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
VerboseTrace(_handler._maxAutomaticRedirections.ToString());
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
long redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ?
CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https
CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https
SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, redirectProtocols);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
}
private void SetVerb()
{
VerboseTrace(_requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_INFILESIZE, 0L);
}
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
if (_requestMessage.Content == null)
{
SetCurlOption(CURLoption.CURLOPT_POSTFIELDSIZE, 0L);
SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, string.Empty);
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPTENCODING, encoding);
VerboseTrace(encoding);
}
}
internal void SetProxyOptions(Uri requestUri)
{
if (_handler._proxyPolicy == ProxyUsePolicy.DoNotUseProxy)
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("No proxy");
return;
}
if ((_handler._proxyPolicy == ProxyUsePolicy.UseDefaultProxy) ||
(_handler.Proxy == null))
{
VerboseTrace("Default proxy");
return;
}
Debug.Assert(_handler.Proxy != null, "proxy is null");
Debug.Assert(_handler._proxyPolicy == ProxyUsePolicy.UseCustomProxy, "_proxyPolicy is not UseCustomProxy");
if (_handler.Proxy.IsBypassed(requestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
VerboseTrace("Bypassed proxy");
return;
}
var proxyUri = _handler.Proxy.GetProxy(requestUri);
if (proxyUri == null)
{
VerboseTrace("No proxy URI");
return;
}
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
VerboseTrace("Set proxy: " + proxyUri.ToString());
KeyValuePair<NetworkCredential, ulong> credentialScheme = GetCredentials(_handler.Proxy.Credentials, _requestMessage.RequestUri);
NetworkCredential credentials = credentialScheme.Key;
if (credentials != null)
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
string.Format("{0}:{1}", credentials.UserName, credentials.Password) :
string.Format("{2}\\{0}:{1}", credentials.UserName, credentials.Password, credentials.Domain);
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
VerboseTrace("Set proxy credentials");
}
}
internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, ulong> credentialSchemePair)
{
if (credentialSchemePair.Key == null)
{
_networkCredential = null;
return;
}
NetworkCredential credentials = credentialSchemePair.Key;
ulong authScheme = credentialSchemePair.Value;
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, authScheme);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
_networkCredential = credentials;
VerboseTrace("Set credentials options");
}
internal void SetCookieOption(Uri uri)
{
if (!_handler._useCookie)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(uri);
if (cookieValues != null)
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
VerboseTrace("Set cookies");
}
}
private void SetRequestHeaders()
{
HttpContentHeaders contentHeaders = null;
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
// TODO: Content-Length header isn't getting correctly placed using ToString()
// This is a bug in HttpContentHeaders that needs to be fixed.
if (_requestMessage.Content.Headers.ContentLength.HasValue)
{
long contentLength = _requestMessage.Content.Headers.ContentLength.Value;
_requestMessage.Content.Headers.ContentLength = null;
_requestMessage.Content.Headers.ContentLength = contentLength;
}
contentHeaders = _requestMessage.Content.Headers;
}
var slist = new SafeCurlSlistHandle();
// Add request and content request headers
if (_requestMessage.Headers != null)
{
AddRequestHeaders(_requestMessage.Headers, slist);
}
if (contentHeaders != null)
{
AddRequestHeaders(contentHeaders, slist);
if (contentHeaders.ContentType == null)
{
if (!Interop.libcurl.curl_slist_append(slist, NoContentType))
{
throw CreateHttpRequestException();
}
}
}
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
if (!Interop.libcurl.curl_slist_append(slist, NoTransferEncoding))
{
throw CreateHttpRequestException();
}
}
if (!slist.IsInvalid)
{
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
VerboseTrace("Set headers");
}
else
{
slist.Dispose();
}
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSlistHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
string headerStr = header.Key + ": " + headers.GetHeaderString(header.Key);
if (!Interop.libcurl.curl_slist_append(handle, headerStr))
{
throw CreateHttpRequestException();
}
}
}
internal void SetCurlOption(int option, string value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, long value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, ulong value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, IntPtr value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, Delegate value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal void SetCurlOption(int option, SafeHandle value)
{
ThrowIfCURLEError(Interop.libcurl.curl_easy_setopt(_easyHandle, option, value));
}
internal sealed class SendTransferState
{
internal readonly byte[] _buffer = new byte[RequestBufferSize]; // PERF TODO: Determine if this should be optimized to start smaller and grow
internal int _offset;
internal int _count;
internal Task<int> _task;
internal void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
_task = task;
_offset = offset;
_count = count;
}
}
[Conditional(VerboseDebuggingConditional)]
private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null)
{
CurlHandler.VerboseTrace(text, memberName, easy: this, agent: null);
}
}
}
}
| |
//
// Copyright (C) 2008-2010 Jordi Mas i Hernandez, [email protected]
//
// 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 Gtk;
using Mono.Unix;
using System.Collections;
using System.IO;
using Mistelix.Widgets;
using Mistelix.DataModel;
using Mistelix.Core;
namespace Mistelix.Dialogs
{
// New project dialog box
public class NewProjectDialog : BuilderDialog
{
[GtkBeans.Builder.Object] Gtk.Entry output_dir;
[GtkBeans.Builder.Object] Gtk.Entry name;
[GtkBeans.Builder.Object] Gtk.RadioButton slideshows_radio;
[GtkBeans.Builder.Object] Gtk.RadioButton dvd_radio;
[GtkBeans.Builder.Object] Gtk.Label vformat_label;
[GtkBeans.Builder.Object] Gtk.Label aratio_label;
[GtkBeans.Builder.Object] Gtk.Label resolution_label;
[GtkBeans.Builder.Object] Gtk.Box palradio_vbox;
[GtkBeans.Builder.Object] Gtk.Box videoformat_vbox;
[GtkBeans.Builder.Object] Gtk.Box aspectratio_vbox;
[GtkBeans.Builder.Object] Gtk.ComboBox resolution_combobox;
[GtkBeans.Builder.Object] Gtk.Button ok_button;
Gtk.RadioButton pal_radio;
Gtk.RadioButton ntsc_radio;
Gtk.RadioButton fourbythree_radio;
Gtk.RadioButton sixteenbynine_radio;
Project project;
bool changed;
ListStore resolution_store;
const int COL_INDEX = 1;
public NewProjectDialog () : base ("NewProjectDialog.ui", "newproject")
{
TreeIter iter;
// Comboboxes are added with a HBox to be able to align them
pal_radio = new Gtk.RadioButton (Catalog.GetString ("PAL (Europe)"));
AddRadioButton (videoformat_vbox, pal_radio, 24);
ntsc_radio = new Gtk.RadioButton (pal_radio, Catalog.GetString ("NTSC"));
AddRadioButton (videoformat_vbox, ntsc_radio, 24);
fourbythree_radio = new Gtk.RadioButton (Catalog.GetString ("4:3 (TV)"));
AddRadioButton (aspectratio_vbox, fourbythree_radio, 10);
sixteenbynine_radio = new Gtk.RadioButton (fourbythree_radio, Catalog.GetString ("16:9 (Widescreen)"));
AddRadioButton (aspectratio_vbox, sixteenbynine_radio, 10);
resolution_store = new ListStore (typeof (string), typeof (int)); // DisplayName, index to array
CellRenderer resolution_combocell = new CellRendererText ();
resolution_combobox.Model = resolution_store;
resolution_combobox.PackStart (resolution_combocell, true);
resolution_combobox.SetCellDataFunc (resolution_combocell, Utils.ComboBoxCellFunc);
LoadResolutionIntoCombo ();
// Select default item in the combobox list
bool more = resolution_store.GetIterFirst (out iter);
while (more)
{
int idx = (int) resolution_store.GetValue (iter, COL_INDEX);
if (ResolutionManager.List[idx].Width == ResolutionManager.Default.Width &&
ResolutionManager.List[idx].Height == ResolutionManager.Default.Height) {
resolution_combobox.SetActiveIter (iter);
break;
}
more = resolution_store.IterNext (ref iter);
}
// Translators: This is the default project name for a new project
name.Text = Catalog.GetString ("Project");
output_dir.Text = OutputDirFromName ();
name.Changed += OnChangedProjectName;
output_dir.Changed += OnChangedOutputDir;
changed = false;
slideshows_radio.Toggled += new EventHandler (OnProjectTypeToggled);
ProjectTypeSensitive ();
}
public NewProjectDialog (ProjectType type) : this ()
{
if (type == ProjectType.DVD) {
slideshows_radio.Active = false;
dvd_radio.Active = true;
}
}
public Project NewProject {
get { return project; }
}
void LoadResolutionIntoCombo ()
{
for (int i = 0; i < ResolutionManager.List.Length; i++)
resolution_store.AppendValues (ResolutionManager.List[i].Name, i);
}
void AddRadioButton (Box parent, RadioButton button, uint padding)
{
Gtk.Box.BoxChild child;
HBox hbox = new HBox (false, 0);
parent.Add (hbox);
hbox.Add (button);
child = (Gtk.Box.BoxChild) (hbox [button]);
child.Padding = padding;
hbox.ShowAll ();
}
void OnChangedProjectName (object sender, EventArgs args)
{
SensitiveOkButton ();
if (changed)
return;
output_dir.Text = OutputDirFromName ();
changed = false; /// Setting the text via .Text fires the Changed event
}
void OnChangedOutputDir (object sender, EventArgs args)
{
changed = true;
SensitiveOkButton ();
}
void SensitiveOkButton ()
{
bool active;
if (output_dir.Text == string.Empty || name.Text == string.Empty)
active = false;
else
active = true;
ok_button.Sensitive = active;
}
string OutputDirFromName ()
{
return System.IO.Path.Combine (
Mistelix.Preferences.GetStringValue (Preferences.ProjectsDirectoryKey),
name.Text);
}
void OnOK (object sender, EventArgs args)
{
TreeIter iter;
// if directory doesn't exist ask the user to create it
if (!Directory.Exists (output_dir.Text)) {
MessageDialog md = new MessageDialog (this, DialogFlags.DestroyWithParent,
MessageType.Question, ButtonsType.YesNo,
Catalog.GetString ("The output directory provided does not exist. Do you want to create it?"));
ResponseType result = (ResponseType)md.Run ();
md.Destroy ();
if (result == ResponseType.Yes) {
try {
Directory.CreateDirectory (output_dir.Text);
}
catch (Exception) {
MessageDialog mderror = new MessageDialog (this, DialogFlags.DestroyWithParent,
MessageType.Error, ButtonsType.Ok,
Catalog.GetString ("Unable to create directory."));
mderror.Run ();
mderror.Destroy ();
return;
}
} else {
return;
}
}
project = new Project ();
project.Details.OutputDir = output_dir.Text;
project.Details.Name = name.Text;
if (pal_radio.Active)
project.Details.Format = VideoFormat.PAL;
else
project.Details.Format = VideoFormat.NTSC;
if (slideshows_radio.Active) {
project.Details.Type = ProjectType.Slideshows;
if (resolution_combobox.GetActiveIter (out iter)) {
int idx = (int) resolution_combobox.Model.GetValue (iter, COL_INDEX);
project.Details.SetResolution (ResolutionManager.List[idx].Width, ResolutionManager.List[idx].Height);
}
}
else {
project.Details.Type = ProjectType.DVD;
project.Details.SetDvdResolution ();
}
if (fourbythree_radio.Active)
project.Details.AspectRatio = AspectRatio.FourByThree;
else
project.Details.AspectRatio = AspectRatio.SixteenByNine;
Respond (ResponseType.Ok);
}
void OnCancel (object sender, EventArgs args)
{
Respond (ResponseType.Cancel);
}
void OnBrowse (object o, EventArgs args)
{
FileChooserDialog chooser_dialog = new FileChooserDialog (
Catalog.GetString ("Open Location") , null, FileChooserAction.SelectFolder);
chooser_dialog.SetCurrentFolder (Environment.GetFolderPath (Environment.SpecialFolder.Personal));
chooser_dialog.AddButton (Stock.Cancel, ResponseType.Cancel);
chooser_dialog.AddButton (Stock.Open, ResponseType.Ok);
chooser_dialog.DefaultResponse = ResponseType.Ok;
chooser_dialog.LocalOnly = false;
if(chooser_dialog.Run () == (int) ResponseType.Ok) {
output_dir.Text = chooser_dialog.Filename;
changed = true;
}
chooser_dialog.Destroy ();
}
void ProjectTypeSensitive ()
{
bool active = slideshows_radio.Active == false; // DVD project
// DVD Project
pal_radio.Sensitive = active;
ntsc_radio.Sensitive = active;
fourbythree_radio.Sensitive = active;
sixteenbynine_radio.Sensitive = active;
vformat_label.Sensitive = active;
aratio_label.Sensitive = active;
// Theora project
resolution_label.Sensitive = !active;
resolution_combobox.Sensitive = !active;
}
void OnProjectTypeToggled (object obj, EventArgs args)
{
ProjectTypeSensitive ();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;
namespace System.Runtime.InteropServices
{
public static class ___MethodBase
{
public static IObservable<System.UInt32> GetTypeInfoCount(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) =>
{
System.UInt32 pcTInfoOutput = default(System.UInt32);
_MethodBaseValueLambda.GetTypeInfoCount(out pcTInfoOutput);
return pcTInfoOutput;
});
}
public static IObservable<System.Reactive.Unit> GetTypeInfo(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue,
IObservable<System.UInt32> iTInfo, IObservable<System.UInt32> lcid, IObservable<System.IntPtr> ppTInfo)
{
return ObservableExt.ZipExecute(_MethodBaseValue, iTInfo, lcid, ppTInfo,
(_MethodBaseValueLambda, iTInfoLambda, lcidLambda, ppTInfoLambda) =>
_MethodBaseValueLambda.GetTypeInfo(iTInfoLambda, lcidLambda, ppTInfoLambda));
}
public static IObservable<System.Guid> GetIDsOfNames(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue, IObservable<System.Guid> riid,
IObservable<System.IntPtr> rgszNames, IObservable<System.UInt32> cNames, IObservable<System.UInt32> lcid,
IObservable<System.IntPtr> rgDispId)
{
return Observable.Zip(_MethodBaseValue, riid, rgszNames, cNames, lcid, rgDispId,
(_MethodBaseValueLambda, riidLambda, rgszNamesLambda, cNamesLambda, lcidLambda, rgDispIdLambda) =>
{
_MethodBaseValueLambda.GetIDsOfNames(ref riidLambda, rgszNamesLambda, cNamesLambda, lcidLambda,
rgDispIdLambda);
return riidLambda;
});
}
public static IObservable<System.Guid> Invoke(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue,
IObservable<System.UInt32> dispIdMember, IObservable<System.Guid> riid, IObservable<System.UInt32> lcid,
IObservable<System.Int16> wFlags, IObservable<System.IntPtr> pDispParams,
IObservable<System.IntPtr> pVarResult, IObservable<System.IntPtr> pExcepInfo,
IObservable<System.IntPtr> puArgErr)
{
return Observable.Zip(_MethodBaseValue, dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult,
pExcepInfo, puArgErr,
(_MethodBaseValueLambda, dispIdMemberLambda, riidLambda, lcidLambda, wFlagsLambda, pDispParamsLambda,
pVarResultLambda, pExcepInfoLambda, puArgErrLambda) =>
{
_MethodBaseValueLambda.Invoke(dispIdMemberLambda, ref riidLambda, lcidLambda, wFlagsLambda,
pDispParamsLambda, pVarResultLambda, pExcepInfoLambda, puArgErrLambda);
return riidLambda;
});
}
public static IObservable<System.String> ToString(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.ToString());
}
public static IObservable<System.Boolean> Equals(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue,
IObservable<System.Object> other)
{
return Observable.Zip(_MethodBaseValue, other,
(_MethodBaseValueLambda, otherLambda) => _MethodBaseValueLambda.Equals(otherLambda));
}
public static IObservable<System.Int32> GetHashCode(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.GetHashCode());
}
public static IObservable<System.Type> GetType(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.GetType());
}
public static IObservable<System.Object[]> GetCustomAttributes(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue,
IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit)
{
return Observable.Zip(_MethodBaseValue, attributeType, inherit,
(_MethodBaseValueLambda, attributeTypeLambda, inheritLambda) =>
_MethodBaseValueLambda.GetCustomAttributes(attributeTypeLambda, inheritLambda));
}
public static IObservable<System.Object[]> GetCustomAttributes(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue,
IObservable<System.Boolean> inherit)
{
return Observable.Zip(_MethodBaseValue, inherit,
(_MethodBaseValueLambda, inheritLambda) => _MethodBaseValueLambda.GetCustomAttributes(inheritLambda));
}
public static IObservable<System.Boolean> IsDefined(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue,
IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit)
{
return Observable.Zip(_MethodBaseValue, attributeType, inherit,
(_MethodBaseValueLambda, attributeTypeLambda, inheritLambda) =>
_MethodBaseValueLambda.IsDefined(attributeTypeLambda, inheritLambda));
}
public static IObservable<System.Reflection.ParameterInfo[]> GetParameters(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue,
(_MethodBaseValueLambda) => _MethodBaseValueLambda.GetParameters());
}
public static IObservable<System.Reflection.MethodImplAttributes> GetMethodImplementationFlags(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue,
(_MethodBaseValueLambda) => _MethodBaseValueLambda.GetMethodImplementationFlags());
}
public static IObservable<System.Object> Invoke(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue,
IObservable<System.Object> obj, IObservable<System.Reflection.BindingFlags> invokeAttr,
IObservable<System.Reflection.Binder> binder, IObservable<System.Object[]> parameters,
IObservable<System.Globalization.CultureInfo> culture)
{
return Observable.Zip(_MethodBaseValue, obj, invokeAttr, binder, parameters, culture,
(_MethodBaseValueLambda, objLambda, invokeAttrLambda, binderLambda, parametersLambda, cultureLambda) =>
_MethodBaseValueLambda.Invoke(objLambda, invokeAttrLambda, binderLambda, parametersLambda,
cultureLambda));
}
public static IObservable<System.Object> Invoke(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue,
IObservable<System.Object> obj, IObservable<System.Object[]> parameters)
{
return Observable.Zip(_MethodBaseValue, obj, parameters,
(_MethodBaseValueLambda, objLambda, parametersLambda) =>
_MethodBaseValueLambda.Invoke(objLambda, parametersLambda));
}
public static IObservable<System.Reflection.MemberTypes> get_MemberType(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.MemberType);
}
public static IObservable<System.String> get_Name(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.Name);
}
public static IObservable<System.Type> get_DeclaringType(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.DeclaringType);
}
public static IObservable<System.Type> get_ReflectedType(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.ReflectedType);
}
public static IObservable<System.RuntimeMethodHandle> get_MethodHandle(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.MethodHandle);
}
public static IObservable<System.Reflection.MethodAttributes> get_Attributes(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.Attributes);
}
public static IObservable<System.Reflection.CallingConventions> get_CallingConvention(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue,
(_MethodBaseValueLambda) => _MethodBaseValueLambda.CallingConvention);
}
public static IObservable<System.Boolean> get_IsPublic(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsPublic);
}
public static IObservable<System.Boolean> get_IsPrivate(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsPrivate);
}
public static IObservable<System.Boolean> get_IsFamily(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsFamily);
}
public static IObservable<System.Boolean> get_IsAssembly(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsAssembly);
}
public static IObservable<System.Boolean> get_IsFamilyAndAssembly(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue,
(_MethodBaseValueLambda) => _MethodBaseValueLambda.IsFamilyAndAssembly);
}
public static IObservable<System.Boolean> get_IsFamilyOrAssembly(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue,
(_MethodBaseValueLambda) => _MethodBaseValueLambda.IsFamilyOrAssembly);
}
public static IObservable<System.Boolean> get_IsStatic(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsStatic);
}
public static IObservable<System.Boolean> get_IsFinal(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsFinal);
}
public static IObservable<System.Boolean> get_IsVirtual(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsVirtual);
}
public static IObservable<System.Boolean> get_IsHideBySig(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsHideBySig);
}
public static IObservable<System.Boolean> get_IsAbstract(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsAbstract);
}
public static IObservable<System.Boolean> get_IsSpecialName(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsSpecialName);
}
public static IObservable<System.Boolean> get_IsConstructor(
this IObservable<System.Runtime.InteropServices._MethodBase> _MethodBaseValue)
{
return Observable.Select(_MethodBaseValue, (_MethodBaseValueLambda) => _MethodBaseValueLambda.IsConstructor);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Localization;
using Orchard.Admin;
using Orchard.Deployment.Indexes;
using Orchard.Deployment.ViewModels;
using Orchard.DisplayManagement;
using Orchard.DisplayManagement.ModelBinding;
using Orchard.DisplayManagement.Notify;
using Orchard.Navigation;
using Orchard.Settings;
using YesSql;
namespace Orchard.Deployment.Controllers
{
[Admin]
public class DeploymentPlanController : Controller, IUpdateModel
{
private readonly IAuthorizationService _authorizationService;
private readonly IDisplayManager<DeploymentStep> _displayManager;
private readonly IEnumerable<IDeploymentStepFactory> _factories;
private readonly ISession _session;
private readonly ISiteService _siteService;
private readonly INotifier _notifier;
public DeploymentPlanController(
IAuthorizationService authorizationService,
IDisplayManager<DeploymentStep> displayManager,
IEnumerable<IDeploymentStepFactory> factories,
ISession session,
ISiteService siteService,
IShapeFactory shapeFactory,
IStringLocalizer<DeploymentPlanController> stringLocalizer,
IHtmlLocalizer<DeploymentPlanController> htmlLocalizer,
INotifier notifier)
{
_displayManager = displayManager;
_factories = factories;
_authorizationService = authorizationService;
_session = session;
_siteService = siteService;
New = shapeFactory;
_notifier = notifier;
T = stringLocalizer;
H = htmlLocalizer;
}
public dynamic New { get; set; }
public IStringLocalizer T { get; set; }
public IHtmlLocalizer H { get; set; }
public async Task<IActionResult> Index(DeploymentPlanIndexOptions options, PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan))
{
return Unauthorized();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.Export))
{
return Unauthorized();
}
var siteSettings = await _siteService.GetSiteSettingsAsync();
var pager = new Pager(pagerParameters, siteSettings.PageSize);
// default options
if (options == null)
{
options = new DeploymentPlanIndexOptions();
}
var deploymentPlans = _session.Query<DeploymentPlan, DeploymentPlanIndex>();
if (!string.IsNullOrWhiteSpace(options.Search))
{
deploymentPlans = deploymentPlans.Where(dp => dp.Name.Contains(options.Search));
}
var count = await deploymentPlans.CountAsync();
var results = await deploymentPlans
.Skip(pager.GetStartIndex())
.Take(pager.PageSize)
.ListAsync();
// Maintain previous route data when generating page links
var routeData = new RouteData();
routeData.Values.Add("Options.Search", options.Search);
var pagerShape = New.Pager(pager).TotalItemCount(count).RouteData(routeData);
var model = new DeploymentPlanIndexViewModel
{
DeploymentPlans = results.Select(x => new DeploymentPlanEntry { DeploymentPlan = x }).ToList(),
Options = options,
Pager = pagerShape
};
return View(model);
}
public async Task<IActionResult> Display(int id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan))
{
return Unauthorized();
}
var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id);
if (deploymentPlan == null)
{
return NotFound();
}
var items = new List<dynamic>();
foreach (var step in deploymentPlan.DeploymentSteps)
{
var item = await _displayManager.BuildDisplayAsync(step, this, "Summary");
item.DeploymentStep = step;
items.Add(item);
}
var thumbnails = new Dictionary<string, dynamic>();
foreach (var factory in _factories)
{
var step = factory.Create();
var thumbnail = await _displayManager.BuildDisplayAsync(step, this, "Thumbnail");
thumbnail.DeploymentStep = step;
thumbnails.Add(factory.Name, thumbnail);
}
var model = new DisplayDeploymentPlanViewModel
{
DeploymentPlan = deploymentPlan,
Items = items,
Thumbnails = thumbnails,
};
return View(model);
}
public async Task<IActionResult> Create()
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan))
{
return Unauthorized();
}
var model = new CreateDeploymentPlanViewModel();
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create(CreateDeploymentPlanViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan))
{
return Unauthorized();
}
if (ModelState.IsValid)
{
if (String.IsNullOrWhiteSpace(model.Name))
{
ModelState.AddModelError(nameof(CreateDeploymentPlanViewModel.Name), T["The name is mandatory."]);
}
}
if (ModelState.IsValid)
{
var deploymentPlan = new DeploymentPlan { Name = model.Name };
_session.Save(deploymentPlan);
return RedirectToAction(nameof(Index));
}
// If we got this far, something failed, redisplay form
return View(model);
}
public async Task<IActionResult> Edit(int id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan))
{
return Unauthorized();
}
var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id);
if (deploymentPlan == null)
{
return NotFound();
}
var model = new EditDeploymentPlanViewModel
{
Id = deploymentPlan.Id,
Name = deploymentPlan.Name
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> Edit(EditDeploymentPlanViewModel model)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan))
{
return Unauthorized();
}
var deploymentPlan = await _session.GetAsync<DeploymentPlan>(model.Id);
if (deploymentPlan == null)
{
return NotFound();
}
if (ModelState.IsValid)
{
if (String.IsNullOrWhiteSpace(model.Name))
{
ModelState.AddModelError(nameof(EditDeploymentPlanViewModel.Name), T["The name is mandatory."]);
}
}
if (ModelState.IsValid)
{
deploymentPlan.Name = model.Name;
_session.Save(deploymentPlan);
_notifier.Success(H["Deployment plan updated successfully"]);
return RedirectToAction(nameof(Index));
}
// If we got this far, something failed, redisplay form
return View(model);
}
[HttpPost]
public async Task<IActionResult> Delete(int id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageDeploymentPlan))
{
return Unauthorized();
}
var deploymentPlan = await _session.GetAsync<DeploymentPlan>(id);
if (deploymentPlan == null)
{
return NotFound();
}
_session.Delete(deploymentPlan);
_notifier.Success(H["Deployment plan deleted successfully"]);
return RedirectToAction(nameof(Index));
}
}
}
| |
// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
namespace Microsoft.Xbox.Services.TitleStorage
{
using global::System;
using global::System.Collections.Generic;
using global::System.Text;
using global::System.Threading.Tasks;
using Microsoft.Xbox.Services.Shared.TitleStorage;
/// <summary>
/// Services that manage title storage.
/// </summary>
public class TitleStorageService: ITitleStorageService
{
private static readonly Uri TitleStorageBaseUri = new Uri("https://titlestorage.xboxlive.com");
private const string TitleStorageApiContract = "1";
private const string ContentTypeHeaderValue = "application/octet-stream";
private const string ETagHeaderName = "ETag";
private const string IfMatchHeaderName = "If-Match";
private const string IfNoneHeaderName = "If-None-Match";
private const uint MaxUploadBlockSize = 4 * 1024 * 1024;
private const uint MinUploadBlockSize = 1024;
private const uint MinDownloadBlockSize = 1024;
/// <summary>
/// Gets title storage quota information for the specified service configuration and storage type.
/// For user storage types (TrustedPlatform and Json) the request will be made for the calling user's
/// Xbox user Id.
/// </summary>
/// <param name="user">The Xbox User of the title storage to enumerate. Ignored when enumerating GlobalStorage.</param>
/// <param name="storageType">Type of the storage type</param>
/// <returns>An instance of the <see cref="TitleStorageQuota"/> class with the amount of storage space allocated and used.</returns>
public Task<TitleStorageQuota> GetQuotaAsync(XboxLiveUser user, TitleStorageType storageType)
{
var subQuery = this.GetTitleStorageSubpath(user, storageType);
var httpRequest = XboxLiveHttpRequest.Create(HttpMethod.Get, TitleStorageBaseUri.ToString(), subQuery);
httpRequest.ContractVersion = TitleStorageApiContract;
httpRequest.XboxLiveAPI = XboxLiveAPIName.GetQuota;
return httpRequest.GetResponseWithAuth(user).ContinueWith(
responseTask => this.HandleStorageQuoteResponse(responseTask, storageType));
}
/// <summary>
/// Gets a list of blob metadata objects under a given path for the specified service configuration, storage type and storage ID.
/// </summary>
/// <param name="user">The Xbox User of the title storage to enumerate. Ignored when enumerating GlobalStorage.</param>
/// <param name="storageType">The storage type to get blob metadata objects for.</param>
/// <param name="blobPath">(Optional) The root path to enumerate. Results will be for blobs contained in this path and all subpaths.</param>
/// <param name="skipItems">(Optional) The number of items to skip before returning results. (Optional)</param>
/// <param name="maxItems">(Optional) The maximum number of items to return.</param>
/// <returns>An instance of the <see cref="TitleStorageBlobMetadataResult"/> class containing the list of enumerated blob metadata objects.</returns>
public Task<TitleStorageBlobMetadataResult> GetBlobMetadataAsync(XboxLiveUser user, TitleStorageType storageType, string blobPath,uint skipItems = 0, uint maxItems = 0)
{
if (storageType == TitleStorageType.GlobalStorage && (user == null || !string.IsNullOrEmpty(user.XboxUserId)))
throw new Exception("Global Storage Type with a non-empty xbox user id");
return this.InternalGetBlobMetadata(user, storageType, blobPath, skipItems, maxItems);
}
/// <summary>
/// Deletes a blob from title storage.
/// </summary>
/// <param name="user">The Xbox User of the title storage to enumerate. Ignored when enumerating GlobalStorage.</param>
/// <param name="blobMetadata">The blob metadata for the title storage blob to delete.</param>
/// <param name="blobQueryProperties">An instance of the <see cref="BlobQueryProperties"/> class with properties of the download query.</param>
/// <returns>An empty task.</returns>
public Task DeleteBlobAsync(XboxLiveUser user, TitleStorageBlobMetadata blobMetadata, BlobQueryProperties blobQueryProperties)
{
var eTagMatchCondition = blobQueryProperties.ETagMatchCondition == TitleStorageETagMatchCondition.IfMatch ?
TitleStorageETagMatchCondition.IfMatch : TitleStorageETagMatchCondition.NotUsed;
var subPathAndQueryResult = this.GetTitleStorageBlobMetadataDownloadSubpath(user, blobMetadata, string.Empty);
if (string.IsNullOrEmpty(subPathAndQueryResult))
{
return Task.FromResult<object>(null);
}
var httpRequest = XboxLiveHttpRequest.Create(HttpMethod.Delete, TitleStorageBaseUri.ToString(), subPathAndQueryResult);
httpRequest.ContractVersion = TitleStorageApiContract;
httpRequest.ContentType = ContentTypeHeaderValue;
httpRequest.XboxLiveAPI = XboxLiveAPIName.DeleteBlob;
SetEtagHeader(httpRequest, blobMetadata.ETag, eTagMatchCondition);
return httpRequest.GetResponseWithAuth(user).ContinueWith(responseTask =>
{
if (responseTask.Result.ErrorCode != 0)
{
throw new Exception("Invalid HTTP received on delete. Error Message: " + responseTask.Result.ErrorMessage);
}
});
}
/// <summary>
/// Downloads blob data from title storage.
/// </summary>
/// <param name="user">The Xbox User of the title storage to enumerate. Ignored when enumerating GlobalStorage.</param>
/// <param name="blobMetadata">The blob metadata for the title storage blob to download.</param>
/// <param name="blobQueryProperties">An instance of the <see cref="BlobQueryProperties"/> class with properties of the download query.</param>
/// <returns>An instance of the <see cref="TitleStorageBlobResult"/> containing the blob content and an updated
/// <see cref="TitleStorageBlobMetadata"/> object.</returns>
public Task<TitleStorageBlobResult> DownloadBlobAsync(
XboxLiveUser user,
TitleStorageBlobMetadata blobMetadata,
BlobQueryProperties blobQueryProperties)
{
var blobBuffer = new List<byte>();
var resultBlocBlobMetadata = new TitleStorageBlobMetadata(
blobMetadata.StorageType, blobMetadata.BlobPath,
blobMetadata.BlobType, blobMetadata.DisplayName, blobMetadata.ETag);
var preferredDownloadBlockSize =
blobQueryProperties.PreferredBlockSize < MinDownloadBlockSize ?
MinDownloadBlockSize :
blobQueryProperties.PreferredBlockSize;
var isBinaryData = (blobMetadata.BlobType == TitleStorageBlobType.Binary);
var isDownloading = true;
uint startByte = 0;
var subPathAndQueryResult = this.GetTitleStorageBlobMetadataDownloadSubpath(
user, blobMetadata, blobQueryProperties.SelectQuery);
while (isDownloading)
{
var httpRequest = XboxLiveHttpRequest.Create(HttpMethod.Get, TitleStorageBaseUri.ToString(), subPathAndQueryResult);
httpRequest.ContractVersion = TitleStorageApiContract;
httpRequest.ContentType = ContentTypeHeaderValue;
httpRequest.LongHttpCall = true;
httpRequest.ResponseBodyType = HttpCallResponseBodyType.VectorBody;
SetEtagHeader(httpRequest, blobMetadata.ETag, blobQueryProperties.ETagMatchCondition);
if (isBinaryData)
{
httpRequest.SetRangeHeader(startByte, startByte + preferredDownloadBlockSize);
}
httpRequest.XboxLiveAPI = XboxLiveAPIName.DownloadBlob;
httpRequest.GetResponseWithAuth(user).ContinueWith(responseTask =>
{
var response = responseTask.Result;
if (response.ErrorCode == 0)
{
var responseVector = response.ResponseBodyVector;
if (responseVector.Length > 0)
{
blobBuffer.AddRange(responseVector);
}
startByte += (uint) responseVector.Length;
if (!isBinaryData || responseVector.Length < preferredDownloadBlockSize)
{
isDownloading = false;
resultBlocBlobMetadata.SetBlobMetadataProperties((uint)(responseVector.Length), response.ETag);
}
}
}).Wait();
}
var resultBlobMetadataResult = new TitleStorageBlobResult(resultBlocBlobMetadata, blobBuffer.ToArray());
return Task.FromResult(resultBlobMetadataResult);
}
/// <summary>
/// Upload blob data to title storage.
/// </summary>
/// <param name="user">The Xbox User of the title storage to enumerate. Ignored when enumerating GlobalStorage.</param>
/// <param name="blobMetadata">The blob metadata for the title storage blob to upload.</param>
/// <param name="blobBuffer">The Blob content to be uploaded.</param>
/// <param name="blobQueryProperties">An instance of the <see cref="BlobQueryProperties"/> class with properties of the upload query.</param>
/// <returns>An instance of the <see cref="TitleStorageBlobMetadata"/> class with updated ETag and Length Properties.</returns>
public Task<TitleStorageBlobMetadata> UploadBlobAsync(XboxLiveUser user, TitleStorageBlobMetadata blobMetadata, List<byte> blobBuffer, BlobQueryProperties blobQueryProperties)
{
if(blobBuffer == null)
throw new Exception("Blob buffer is null");
if(blobBuffer.Count == 0)
throw new Exception("Blob Buffer is empty");
var preferredUploadBlockSize = blobQueryProperties.PreferredBlockSize < MinUploadBlockSize ? MinUploadBlockSize : blobQueryProperties.PreferredBlockSize;
preferredUploadBlockSize = blobQueryProperties.PreferredBlockSize > MaxUploadBlockSize ? MaxUploadBlockSize : preferredUploadBlockSize;
var resultBlocBlobMetadata = new TitleStorageBlobMetadata(blobMetadata.StorageType, blobMetadata.BlobPath,
blobMetadata.BlobType, blobMetadata.DisplayName, blobMetadata.ETag);
var isBinaryData = (blobMetadata.BlobType == TitleStorageBlobType.Binary);
var dataChunk = new List<byte>();
uint start = 0;
var continuationToken = string.Empty;
while (start < blobBuffer.Count)
{
dataChunk.Clear();
bool isFinalBlock;
if (isBinaryData)
{
var count = (uint)(blobBuffer.Count) - start;
if (count > preferredUploadBlockSize)
count = preferredUploadBlockSize;
for (var index = 0; index < count; index++)
{
dataChunk.Add(blobBuffer[(int)(index + start)]);
}
start += count;
isFinalBlock = start == blobBuffer.Count;
}
else
{
dataChunk = blobBuffer;
start = (uint)(dataChunk.Count);
isFinalBlock = true;
}
var subpathAndQueryResult = this.GetTitleStorageBlobMetadataUploadSubpath(user, blobMetadata, continuationToken, isFinalBlock);
var httpRequest = XboxLiveHttpRequest.Create(HttpMethod.Put, TitleStorageBaseUri.ToString(), subpathAndQueryResult);
httpRequest.ContractVersion = TitleStorageApiContract;
httpRequest.ContentType = ContentTypeHeaderValue;
httpRequest.LongHttpCall = true;
SetEtagHeader(httpRequest, blobMetadata.ETag, blobQueryProperties.ETagMatchCondition);
var encoding = Encoding.UTF8;
httpRequest.RequestBody = encoding.GetString(dataChunk.ToArray());
httpRequest.XboxLiveAPI = XboxLiveAPIName.UploadBlob;
httpRequest.RetryAllowed = false;
var localIsFinalBlock = isFinalBlock;
httpRequest.GetResponseWithAuth(user).ContinueWith(responseTask =>
{
var json = responseTask.Result.ResponseBodyString;
continuationToken = string.Empty;
if (responseTask.Result.ErrorCode == 0 && !string.IsNullOrEmpty(json))
{
var pagingInfo = JsonSerialization.FromJson<PagingInfo>(json);
continuationToken = pagingInfo.ContinuationToken;
}
if (responseTask.Result.ErrorCode == 0 && localIsFinalBlock)
{
resultBlocBlobMetadata.SetBlobMetadataProperties((uint)(blobBuffer.Count), responseTask.Result.ETag);
}
}).Wait();
}
return Task.FromResult(resultBlocBlobMetadata);
}
internal TitleStorageQuota HandleStorageQuoteResponse(
Task<XboxLiveHttpResponse> responseTask,
TitleStorageType storageType)
{
var response = responseTask.Result;
return TitleStorageQuota.Deserialize(
response.ResponseBodyString,
storageType);
}
internal Task<TitleStorageBlobMetadataResult> InternalGetBlobMetadata(
XboxLiveUser user,
TitleStorageType storageType,
string blobPath,
uint skipItems,
uint maxItems,
string continuationToken = "")
{
string subPathAndQueryResult = this.GetTitleStorageBlobMetadataSubpath(
user,
storageType,
blobPath,
skipItems,
maxItems,
continuationToken);
var httpRequest = XboxLiveHttpRequest.Create(HttpMethod.Get, TitleStorageBaseUri.ToString(), subPathAndQueryResult);
httpRequest.ContractVersion = TitleStorageApiContract;
httpRequest.XboxLiveAPI = XboxLiveAPIName.GetBlobMetadata;
return httpRequest.GetResponseWithAuth(user)
.ContinueWith(
responseTask => this.HandleBlobMetadataResult(user, responseTask, storageType, blobPath));
}
internal TitleStorageBlobMetadataResult HandleBlobMetadataResult(
XboxLiveUser user,
Task<XboxLiveHttpResponse> responseTask,
TitleStorageType storageType,
string blobPath)
{
var response = responseTask.Result;
return TitleStorageBlobMetadataResult.Deserialize(
response.ResponseBodyString,
storageType,
user,
blobPath);
}
internal string GetTitleStorageSubpath(XboxLiveUser user, TitleStorageType titleStorageType)
{
var pathBuilder = new StringBuilder();
switch (titleStorageType)
{
case TitleStorageType.TrustedPlatform:
case TitleStorageType.UniversalPlatform:
pathBuilder.AppendFormat(
"{0}/users/xuid({1})/scids/{2}",
titleStorageType.ToString().ToLowerInvariant(),
user.XboxUserId,
XboxLive.Instance.AppConfig.PrimaryServiceConfigId);
break;
case TitleStorageType.GlobalStorage:
pathBuilder.AppendFormat(
"global/scids/{0}",
XboxLive.Instance.AppConfig.PrimaryServiceConfigId);
break;
default:
throw new ArgumentOutOfRangeException("titleStorageType");
}
return pathBuilder.ToString();
}
internal string GetTitleStorageBlobMetadataSubpath(
XboxLiveUser user,
TitleStorageType storageType,
string blobPath,
uint skipItems,
uint maxItems,
string continuationToken)
{
var subPathBuilder = new StringBuilder();
var path = this.GetTitleStorageSubpath(user, storageType);
subPathBuilder.Append(path);
subPathBuilder.Append("/data");
if (!string.IsNullOrEmpty(blobPath))
{
subPathBuilder.Append("/");
subPathBuilder.Append(Uri.EscapeUriString(blobPath));
}
AppendPagingInfo(subPathBuilder, skipItems, maxItems, continuationToken);
return subPathBuilder.ToString();
}
internal string GetTitleStorageBlobMetadataDownloadSubpath(
XboxLiveUser user,
TitleStorageBlobMetadata blobMetadata,
string selectQuery)
{
var pathBuilder = new StringBuilder();
pathBuilder.AppendFormat("{0}/data/{1},{2}",
this.GetTitleStorageSubpath(
user,
blobMetadata.StorageType),
blobMetadata.BlobPath,
blobMetadata.BlobType.ToString().ToLowerInvariant());
if (!string.IsNullOrEmpty(selectQuery))
{
switch (blobMetadata.BlobType)
{
case TitleStorageBlobType.Config:
pathBuilder.AppendFormat("?customerSelector={0}", Uri.EscapeUriString(selectQuery));
break;
case TitleStorageBlobType.Json:
pathBuilder.AppendFormat("?select={0}", Uri.EscapeUriString(selectQuery));
break;
}
}
return pathBuilder.ToString();
}
internal string GetTitleStorageBlobMetadataUploadSubpath(
XboxLiveUser user, TitleStorageBlobMetadata blobMetadata, string continuationToken, bool finalBlock)
{
var pathBuilder = new StringBuilder();
pathBuilder.Append(this.GetTitleStorageBlobMetadataDownloadSubpath(user, blobMetadata, string.Empty));
var parameterList = new Dictionary<string, string>();
if (blobMetadata.ClientTimeStamp != null)
{
var clientTimestamp = blobMetadata.ClientTimeStamp.ToString();
parameterList.Add("clientFileTime", Uri.EscapeUriString(clientTimestamp));
}
if (!string.IsNullOrEmpty(blobMetadata.DisplayName))
{
parameterList.Add("displayName", Uri.EscapeUriString(blobMetadata.DisplayName));
}
if (!string.IsNullOrEmpty(continuationToken))
{
parameterList.Add("continuationToken", Uri.EscapeUriString(continuationToken));
}
if (blobMetadata.BlobType == TitleStorageBlobType.Binary)
{
parameterList.Add("finalBlock", finalBlock.ToString());
}
pathBuilder.Append(XboxLiveHttpRequest.GetQueryFromParams(parameterList));
return pathBuilder.ToString();
}
internal static void AppendPagingInfo(
StringBuilder stringBuilder, uint skipItems, uint maxItems, string continuationToken)
{
var parameterList = new Dictionary<string, string>();
if (maxItems > 0)
{
parameterList.Add("maxItems", Convert.ToString(maxItems));
}
if (string.IsNullOrEmpty(continuationToken))
{
if (skipItems > 0)
{
parameterList.Add("skipItems", Convert.ToString(skipItems));
}
}
else
{
parameterList.Add("continuationToken", continuationToken);
}
stringBuilder.Append(XboxLiveHttpRequest.GetQueryFromParams(parameterList));
}
internal static void SetEtagHeader(
XboxLiveHttpRequest httpRequest, string eTag, TitleStorageETagMatchCondition eTagMatchCondition)
{
if (eTagMatchCondition != TitleStorageETagMatchCondition.NotUsed)
{
if (!string.IsNullOrEmpty(eTag))
{
httpRequest.SetCustomHeader(ETagHeaderName, eTag);
var headerToUse = eTagMatchCondition == TitleStorageETagMatchCondition.IfMatch ? IfMatchHeaderName : IfNoneHeaderName;
httpRequest.SetCustomHeader(headerToUse, eTag);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
namespace dotnet
{
internal static class ProjectPropertiesHelpers
{
public static ProjectProperties InitializeProperties(Settings settings, Log log)
{
// General Properites
var properties = new ProjectProperties();
var currentDirectory = Directory.GetCurrentDirectory();
var buildDll = settings.Target == "library";
properties.ProjectDirectory = Path.Combine(currentDirectory);
properties.PackagesDirectory = Path.Combine(properties.ProjectDirectory, "packages");
properties.OutputDirectory = Path.Combine(properties.ProjectDirectory, "bin");
properties.ToolsDirectory = Path.Combine(properties.ProjectDirectory, "tools");
properties.AssemblyName = Path.GetFileName(properties.ProjectDirectory);
properties.OutputType = buildDll ? ".dll" : ".exe";
FindCompiler(properties);
AddToListWithoutDuplicates(properties.Sources, ParseProjectFile(properties, settings.ProjectFile, "Compile"));
foreach (var file in settings.SourceFiles.Where(f => !f.StartsWith(properties.PackagesDirectory) && !f.StartsWith(properties.OutputDirectory) &&
!f.StartsWith(properties.ToolsDirectory)))
{
AddToListWithoutDuplicates(properties.Sources, file);
}
if (!string.IsNullOrWhiteSpace(settings.Recurse) && settings.Recurse != "*.cs")
{
AddToListWithoutDuplicates(properties.Sources,
Directory.GetFiles(properties.ProjectDirectory, settings.Recurse, SearchOption.AllDirectories));
}
if (properties.Sources.Count == 1)
{
properties.AssemblyName = Path.GetFileNameWithoutExtension(properties.Sources[0]);
}
var platformOptionSpecicifcation = GetPlatformOption(settings.Platform);
// The anycpu32bitpreferred setting is valid only for executable (.EXE) files
if (!(settings.Platform == "anycpu32bitpreferred" && buildDll))
properties.CscOptions.Add("/platform:" + settings.Platform);
// Packages
properties.Packages.Add(@"""Microsoft.NETCore"": ""5.0.0""");
properties.Packages.Add(@"""System.Console"": ""4.0.0-beta-23123""");
//properties.Packages.Add(@"""Microsoft.NETCore.Console"": ""1.0.0-beta-*""");
properties.Packages.Add(GetConsoleHost(platformOptionSpecicifcation));
properties.Packages.Add(GetRuntimeCoreClr(platformOptionSpecicifcation));
// References
properties.References.Add(Path.Combine(properties.PackagesDirectory,
@"System.Runtime\4.0.20\ref\dotnet\System.Runtime.dll"));
properties.References.Add(Path.Combine(properties.PackagesDirectory,
@"System.Console\4.0.0-beta-23123\ref\dotnet\System.Console.dll"));
// Runtime Dependencies
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
GetRuntimeCoreClrDependencyNative(platformOptionSpecicifcation, "win7")));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
GetRuntimeCoreClrDependencyLibrary(platformOptionSpecicifcation, "win7")));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
@"System.Runtime\4.0.20\lib\netcore50"));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
@"System.Console\4.0.0-beta-23123\lib\DNXCore50"));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory, @"System.IO\4.0.10\lib\netcore50"));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
@"System.Threading\4.0.10\lib\netcore50"));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
@"System.IO.FileSystem.Primitives\4.0.0\lib\dotnet"));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
@"System.Text.Encoding\4.0.10\lib\netcore50"));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
@"System.Threading.Tasks\4.0.10\lib\netcore50"));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
@"System.Text.Encoding.Extensions\4.0.10\lib\netcore50"));
properties.Dependencies.Add(Path.Combine(properties.PackagesDirectory,
@"System.Runtime.InteropServices\4.0.20\lib\netcore50"));
// CSC OPTIONS
properties.CscOptions.Add("/nostdlib");
properties.CscOptions.Add("/noconfig");
if (settings.Unsafe)
{
properties.CscOptions.Add("/unsafe");
}
if (settings.Optimize)
{
properties.CscOptions.Add("/optimize");
}
if (!string.IsNullOrWhiteSpace(settings.Debug))
{
properties.CscOptions.Add("/debug:" + settings.Debug);
}
properties.CscOptions.Add("/target:" + settings.Target);
LogProperties(log, properties, "Initialized Properties Log:", buildDll);
Adjust(properties, Path.Combine(properties.ProjectDirectory, "dependencies.txt"), properties.Dependencies);
Adjust(properties, Path.Combine(properties.ProjectDirectory, "references.txt"), properties.References);
AddToListWithoutDuplicates(properties.Packages, ParseProjectFile(properties, settings.ProjectFile, "Package"));
LogProperties(log, properties, "Adjusted Properties Log:", buildDll);
return properties;
}
public static string GetPlatformOption(string optionSpecification)
{
if (optionSpecification == "anycpu32bitpreferred" || optionSpecification == "x86")
{
return "x86";
}
return "x64";
}
public static string GetRuntimeCoreClr(string platform)
{
// platform - x86, x64, arm
return "\"Microsoft.NETCore.Runtime.CoreCLR-" + platform.ToLower() + "\": \"1.0.0\"";
}
public static string GetConsoleHost(string platform)
{
// platform - x86, x64, arm
return "\"Microsoft.NETCore.ConsoleHost-" + platform.ToLower() + "\": \"1.0.0-beta-23123\"";
}
public static string GetConsoleHostNative(string platform, string os)
{
// platform - x86, x64, arm
return "Microsoft.NETCore.ConsoleHost-" + platform.ToLower() + "\\1.0.0-beta-23123\\runtimes\\" +
os.ToLower() + "-" + platform.ToLower() + "\\native";
}
public static string GetRuntimeCoreClrDependencyNative(string platform, string os)
{
// platform - x86, x64, arm
// os - win7, win8
return "Microsoft.NETCore.Runtime.CoreCLR-" + platform.ToLower() + "\\1.0.0\\runtimes\\" + os.ToLower() +
"-" + platform.ToLower() + "\\native";
}
public static string GetRuntimeCoreClrDependencyLibrary(string platform, string os)
{
// platform - x86, x64, arm
// os - win7, win8
return "Microsoft.NETCore.Runtime.CoreCLR-" + platform.ToLower() + "\\1.0.0\\runtimes\\" + os.ToLower() +
"-" + platform.ToLower() + "\\lib\\dotnet";
}
private static void AddToListWithoutDuplicates(ICollection<string> list, List<string> files)
{
foreach (var file in files.Where(file => !list.Contains(file)))
{
list.Add(file);
}
}
private static void AddToListWithoutDuplicates(ICollection<string> list, string file)
{
if (!list.Contains(file))
{
list.Add(file);
}
}
private static void AddToListWithoutDuplicates(ICollection<string> list, IEnumerable<string> files)
{
foreach (var file in files.Where(file => !list.Contains(file)))
{
list.Add(file);
}
}
private static void LogProperties(this Log log, ProjectProperties project, string heading, bool buildDll)
{
if (!log.IsEnabled) return;
log.WriteLine(heading);
log.WriteLine("ProjectDirectory {0}", project.ProjectDirectory);
log.WriteLine("PackagesDirectory {0}", project.PackagesDirectory);
log.WriteLine("OutputDirectory {0}", project.OutputDirectory);
log.WriteLine("ToolsDirectory {0}", project.ToolsDirectory);
log.WriteLine(buildDll ? "LibraryFilename {0}" : "ExecutableFilename {0}", project.AssemblyName);
log.WriteLine("csc.exe Path {0}", project.CscPath);
log.WriteLine("output path {0}", project.OutputAssemblyPath);
log.WriteList(project.Sources, "SOURCES");
log.WriteList(project.Packages, "PACKAGES");
log.WriteList(project.References, "REFERENCES");
log.WriteList(project.Dependencies, "DEPENDENCIES");
log.WriteList(project.CscOptions, "CSCOPTIONS");
log.WriteLine("-------------------------------------------------");
}
private static void Adjust(ProjectProperties properties, string adjustmentFilePath, ICollection<string> list)
{
if (!File.Exists(adjustmentFilePath)) return;
foreach (var line in File.ReadAllLines(adjustmentFilePath))
{
if (string.IsNullOrWhiteSpace(line)) continue;
if (line.StartsWith("//")) continue; // commented out line
var adjustment = line.Substring(1).Trim();
if (line.StartsWith("-"))
{
list.Remove(Path.Combine(properties.PackagesDirectory, adjustment));
}
else
{
list.Add(Path.Combine(properties.PackagesDirectory, adjustment));
}
}
}
private static List<string> ParseProjectFile(ProjectProperties properties, string projectFile,
string elementName)
{
var attributes = GetAttributes(elementName);
if (!File.Exists(projectFile) || attributes == null)
{
return new List<string>();
}
var attributeValues = new List<string>();
using (var xmlReader = XmlReader.Create(projectFile))
{
xmlReader.MoveToContent();
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == elementName)
{
attributeValues.AddRange(attributes.Select(attribute => xmlReader.GetAttribute(attribute)));
}
}
}
List<string> values;
switch (elementName)
{
case "Compile":
values = GetSourcesFromProjectFile(properties, attributeValues);
break;
case "Package":
values = GetPackagesFromProjectFile(attributeValues);
break;
default:
values = new List<string>();
break;
}
return values;
}
private static List<string> GetAttributes(string elementName)
{
var compileAttributes = new List<string> {"Include"};
var packageAttributes = new List<string> {"Id", "Version"};
List<string> attributes;
switch (elementName)
{
case "Compile":
attributes = compileAttributes;
break;
case "Package":
attributes = packageAttributes;
break;
default:
attributes = null;
break;
}
return attributes;
}
private static List<string> GetSourcesFromProjectFile(ProjectProperties properties,
IEnumerable<string> attributeValues)
{
var sourceFiles = new List<string>();
foreach (var val in attributeValues)
{
if (val == "*.cs")
{
sourceFiles.AddRange(Directory.GetFiles(properties.ProjectDirectory, "*.cs"));
}
else if (val.EndsWith("\\*.cs"))
{
sourceFiles.AddRange(
Directory.GetFiles(Path.Combine(properties.ProjectDirectory, val.Replace("\\*.cs", "")), "*.cs"));
}
else
{
sourceFiles.Add(Path.Combine(properties.ProjectDirectory, val));
}
}
return sourceFiles;
}
private static List<string> GetPackagesFromProjectFile(IReadOnlyList<string> attributeValues)
{
var packages = new List<string>();
for (var i = 0; i < attributeValues.Count; i += 2)
{
packages.Add("\"" + attributeValues[i] + "\": \"" + attributeValues[i + 1] + "\"");
}
return packages;
}
private static void FindCompiler(ProjectProperties properties)
{
properties.CscPath = Path.Combine(properties.ToolsDirectory, "csc.exe");
if (File.Exists(properties.CscPath))
{
return;
}
properties.CscPath = @"D:\git\roslyn\Binaries\Debug\core-clr\csc.exe";
if (!File.Exists(properties.CscPath))
{
properties.CscPath = "csc.exe";
}
}
}
}
| |
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 VUnitOfMeasurePhenomena class.
/// </summary>
[Serializable]
public partial class VUnitOfMeasurePhenomenaCollection : ReadOnlyList<VUnitOfMeasurePhenomena, VUnitOfMeasurePhenomenaCollection>
{
public VUnitOfMeasurePhenomenaCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vUnitOfMeasurePhenomena view.
/// </summary>
[Serializable]
public partial class VUnitOfMeasurePhenomena : ReadOnlyRecord<VUnitOfMeasurePhenomena>, 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("vUnitOfMeasurePhenomena", TableType.View, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarUnitOfMeasureID = new TableSchema.TableColumn(schema);
colvarUnitOfMeasureID.ColumnName = "UnitOfMeasureID";
colvarUnitOfMeasureID.DataType = DbType.Guid;
colvarUnitOfMeasureID.MaxLength = 0;
colvarUnitOfMeasureID.AutoIncrement = false;
colvarUnitOfMeasureID.IsNullable = false;
colvarUnitOfMeasureID.IsPrimaryKey = false;
colvarUnitOfMeasureID.IsForeignKey = false;
colvarUnitOfMeasureID.IsReadOnly = false;
schema.Columns.Add(colvarUnitOfMeasureID);
TableSchema.TableColumn colvarCode = new TableSchema.TableColumn(schema);
colvarCode.ColumnName = "Code";
colvarCode.DataType = DbType.AnsiString;
colvarCode.MaxLength = 50;
colvarCode.AutoIncrement = false;
colvarCode.IsNullable = false;
colvarCode.IsPrimaryKey = false;
colvarCode.IsForeignKey = false;
colvarCode.IsReadOnly = false;
schema.Columns.Add(colvarCode);
TableSchema.TableColumn colvarName = new TableSchema.TableColumn(schema);
colvarName.ColumnName = "Name";
colvarName.DataType = DbType.AnsiString;
colvarName.MaxLength = 150;
colvarName.AutoIncrement = false;
colvarName.IsNullable = false;
colvarName.IsPrimaryKey = false;
colvarName.IsForeignKey = false;
colvarName.IsReadOnly = false;
schema.Columns.Add(colvarName);
TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema);
colvarDescription.ColumnName = "Description";
colvarDescription.DataType = DbType.AnsiString;
colvarDescription.MaxLength = 5000;
colvarDescription.AutoIncrement = false;
colvarDescription.IsNullable = true;
colvarDescription.IsPrimaryKey = false;
colvarDescription.IsForeignKey = false;
colvarDescription.IsReadOnly = false;
schema.Columns.Add(colvarDescription);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("vUnitOfMeasurePhenomena",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VUnitOfMeasurePhenomena()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VUnitOfMeasurePhenomena(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VUnitOfMeasurePhenomena(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VUnitOfMeasurePhenomena(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("UnitOfMeasureID")]
[Bindable(true)]
public Guid UnitOfMeasureID
{
get
{
return GetColumnValue<Guid>("UnitOfMeasureID");
}
set
{
SetColumnValue("UnitOfMeasureID", value);
}
}
[XmlAttribute("Code")]
[Bindable(true)]
public string Code
{
get
{
return GetColumnValue<string>("Code");
}
set
{
SetColumnValue("Code", value);
}
}
[XmlAttribute("Name")]
[Bindable(true)]
public string Name
{
get
{
return GetColumnValue<string>("Name");
}
set
{
SetColumnValue("Name", value);
}
}
[XmlAttribute("Description")]
[Bindable(true)]
public string Description
{
get
{
return GetColumnValue<string>("Description");
}
set
{
SetColumnValue("Description", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string UnitOfMeasureID = @"UnitOfMeasureID";
public static string Code = @"Code";
public static string Name = @"Name";
public static string Description = @"Description";
}
#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
}
}
| |
// 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: A wrapper class for the primitive type float.
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Internal.Runtime.CompilerServices;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct Single : IComparable, IConvertible, IFormattable, IComparable<float>, IEquatable<float>, ISpanFormattable
{
private readonly float m_value; // Do not rename (binary serialization)
//
// Public constants
//
public const float MinValue = (float)-3.40282346638528859e+38;
public const float Epsilon = (float)1.4e-45;
public const float MaxValue = (float)3.40282346638528859e+38;
public const float PositiveInfinity = (float)1.0 / (float)0.0;
public const float NegativeInfinity = (float)-1.0 / (float)0.0;
public const float NaN = (float)0.0 / (float)0.0;
// We use this explicit definition to avoid the confusion between 0.0 and -0.0.
internal const float NegativeZero = (float)-0.0;
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsFinite(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
return (bits & 0x7FFFFFFF) < 0x7F800000;
}
/// <summary>Determines whether the specified value is infinite.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsInfinity(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
return (bits & 0x7FFFFFFF) == 0x7F800000;
}
/// <summary>Determines whether the specified value is NaN.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsNaN(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
return (bits & 0x7FFFFFFF) > 0x7F800000;
}
/// <summary>Determines whether the specified value is negative.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsNegative(float f)
{
return BitConverter.SingleToInt32Bits(f) < 0;
}
/// <summary>Determines whether the specified value is negative infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsNegativeInfinity(float f)
{
return (f == float.NegativeInfinity);
}
/// <summary>Determines whether the specified value is normal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public static unsafe bool IsNormal(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
bits &= 0x7FFFFFFF;
return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) != 0);
}
/// <summary>Determines whether the specified value is positive infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsPositiveInfinity(float f)
{
return (f == float.PositiveInfinity);
}
/// <summary>Determines whether the specified value is subnormal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public static unsafe bool IsSubnormal(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
bits &= 0x7FFFFFFF;
return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) == 0);
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Single, this method throws an ArgumentException.
//
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
if (value is float)
{
float f = (float)value;
if (m_value < f) return -1;
if (m_value > f) return 1;
if (m_value == f) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(f) ? 0 : -1);
else // f is NaN.
return 1;
}
throw new ArgumentException(SR.Arg_MustBeSingle);
}
public int CompareTo(float value)
{
if (m_value < value) return -1;
if (m_value > value) return 1;
if (m_value == value) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(value) ? 0 : -1);
else // f is NaN.
return 1;
}
[NonVersionable]
public static bool operator ==(float left, float right)
{
return left == right;
}
[NonVersionable]
public static bool operator !=(float left, float right)
{
return left != right;
}
[NonVersionable]
public static bool operator <(float left, float right)
{
return left < right;
}
[NonVersionable]
public static bool operator >(float left, float right)
{
return left > right;
}
[NonVersionable]
public static bool operator <=(float left, float right)
{
return left <= right;
}
[NonVersionable]
public static bool operator >=(float left, float right)
{
return left >= right;
}
public override bool Equals(object obj)
{
if (!(obj is float))
{
return false;
}
float temp = ((float)obj).m_value;
if (temp == m_value)
{
return true;
}
return IsNaN(temp) && IsNaN(m_value);
}
public bool Equals(float obj)
{
if (obj == m_value)
{
return true;
}
return IsNaN(obj) && IsNaN(m_value);
}
public override int GetHashCode()
{
var bits = Unsafe.As<float, int>(ref Unsafe.AsRef(in m_value));
// Optimized check for IsNan() || IsZero()
if (((bits - 1) & 0x7FFFFFFF) >= 0x7F800000)
{
// Ensure that all NaNs and both zeros have the same hash code
bits &= 0x7F800000;
}
return bits;
}
public override string ToString()
{
return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo);
}
public string ToString(IFormatProvider provider)
{
return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public string ToString(string format)
{
return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo);
}
public string ToString(string format, IFormatProvider provider)
{
return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider));
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
{
return Number.TryFormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten);
}
// Parses a float from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
// This method will not throw an OverflowException, but will return
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
//
public static float Parse(string s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static float Parse(string s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseSingle(s, style, NumberFormatInfo.CurrentInfo);
}
public static float Parse(string s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
public static float Parse(string s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider));
}
public static float Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider));
}
public static bool TryParse(string s, out float result)
{
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(ReadOnlySpan<char> s, out float result)
{
return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out float result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result);
}
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out float result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out float result)
{
bool success = Number.TryParseSingle(s, style, info, out result);
if (!success)
{
ReadOnlySpan<char> sTrim = s.Trim();
if (sTrim.EqualsOrdinal(info.PositiveInfinitySymbol))
{
result = PositiveInfinity;
}
else if (sTrim.EqualsOrdinal(info.NegativeInfinitySymbol))
{
result = NegativeInfinity;
}
else if (sTrim.EqualsOrdinal(info.NaNSymbol))
{
result = NaN;
}
else
{
return false; // We really failed
}
}
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Single;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return m_value;
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// 47loader (c) Stephen Williams 2013
// See LICENSE for distribution terms
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using FortySevenLoader.Basic;
// writes the BASIC for bootstrapping 47loader
public static class FortySevenLoaderBootstrap
{
static readonly List<byte> _data = new List<byte>();
// options
static string _progName = string.Empty;
static bool _alkatraz;
static int _border = -1, _paper = -1, _ink = -1, _bright = -1, _clear;
static string _inputFileName, _outputFileName;
static int _pause = -1;
static List<string> _printTop = new List<string>();
static List<string> _printBottom = new List<string>();
static List<Tuple<ushort, ushort>> _usr = new List<Tuple<ushort, ushort>>();
// opens the input file or stream
static Stream OpenInput()
{
if (string.IsNullOrWhiteSpace(_inputFileName))
return Console.OpenStandardInput();
try
{
var str = File.Open(_inputFileName, FileMode.Open);
return str;
}
catch (IOException e)
{
Console.Error.WriteLine(e.Message);
Environment.Exit(1);
return null;
}
}
// opens the output file or stream
static Stream OpenOutput()
{
if (string.IsNullOrWhiteSpace(_outputFileName))
return Console.OpenStandardOutput();
var str = File.Open(_outputFileName, FileMode.OpenOrCreate);
str.Seek(0, SeekOrigin.End);
return str;
}
// parses string into integer
static T ParseInteger<T>(string s)
{
try {
T rv = (T)Convert.ChangeType(s, typeof(T));
return rv;
} catch {
Console.Error.WriteLine("Bad integer: " + s);
Die();
return default(T);
}
}
static void ParseArguments(string[] args)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i].FirstOrDefault() != '-')
{
// we've come to the end of the options
if (i < (args.Length - 1))
{
// more than one remaining argument
Die();
return;
}
_inputFileName = args[i];
return;
}
switch (args[i].TrimStart('-'))
{
case "output":
// next arg is name of file to which to write
_outputFileName = args[++i];
break;
case "border":
_border = ParseInteger<int>(args[++i]);
break;
case "paper":
_paper = ParseInteger<int>(args[++i]);
break;
case "ink":
_ink = ParseInteger<int>(args[++i]);
break;
case "bright":
_bright = ParseInteger<int>(args[++i]);
break;
case "clear":
_clear = ParseInteger<int>(args[++i]);
break;
case "name":
_progName = args[++i];
if (_progName.Length > 10)
_progName = _progName.Substring(0, 10);
break;
case "alkatraz":
_alkatraz = true;
break;
case "usr":
var addresses = args[++i].Split(':');
ushort clear = 0, usr = 0;
switch (addresses.Length)
{
case 1:
usr = ParseInteger<ushort>(addresses[0]);
break;
case 2:
clear = ParseInteger<ushort>(addresses[0]);
usr = ParseInteger<ushort>(addresses[1]);
break;
default:
Die();
break;
}
_usr.Add(Tuple.Create(clear, usr));
break;
case "pause":
_pause = ParseInteger<int>(args[++i]);
break;
case "top":
_printTop.Add(args[++i]);
break;
case "bottom":
_printBottom.Add(args[++i]);
break;
default:
// unknown option
Console.Error.WriteLine("Unknown option \"{0}\"", args[i]);
Die();
break;
}
if (_alkatraz && _progName.Length > 6)
{
Console.Error.WriteLine
("alkatraz program names may be no longer than 6 characters");
Die();
}
}
}
// prints usage and exists unsuccessfully
static void Die()
{
Console.Error.WriteLine(@"Usage: 47loader-bootstrap [options] [binary]
Reads binary to embed from standard input if not specified
Options:
-alkatraz : format BASIC program name like the Alkatraz loader. Program
name must be no longer than 6 characters
-border n : border colour
-bottom s : string to print at the bottom of the screen
-bright n : bright attribute
-clear n : CLEAR address
-ink n : ink colour
-name s : BASIC program name
-output : name of file to write; if not specified, writes to standard
output. Appends to file if it already exists
-paper n : paper colour
-pause n : PAUSE to perform after loading
-top s : string to print at the top of the screen
-usr [c:]n: address to jump to after loading, optionally CLEARing to
address c first");
Environment.Exit(1);
}
// writes the TZX file to standard output
static void WriteTzx()
{
using (var output = OpenOutput()) {
FortySevenLoader.Tzx.FileHeader.Standard.Write(output);
output.WriteByte(0x10); // standard speed block
output.WriteByte(0); // two-byte pause length, 0ms
output.WriteByte(0);
output.WriteByte(19); // two-byte length of following data
output.WriteByte(0);
// write program header
var headerData = new byte[19];
// space-padded ten-byte file name at offset 2
var progName = _progName;
if (_alkatraz)
// AT 1,0;progName,
// add a leading space if fewer than 6 chars
progName = string.Format("{0}{1}{2}{3}{4}{5}",
(char)0x16, // AT
(char)1,
(char)0,
progName.Length < 6 ? " " : string.Empty,
progName,
(char)6); // COMMA
Encoding.ASCII.GetBytes(progName).CopyTo(headerData, 2);
for (int i = 11; (i > 1) && (headerData[i] == 0); i--)
headerData[i] = (byte)' ';
// length of BASIC program + variables at offset 12
HighLow16 basicLen = (ushort)_data.Count;
headerData[12] = basicLen.Low;
headerData[13] = basicLen.High;
// autostart line at offset 14
var autostart = new HighLow16(BasicLine.FirstLine);
headerData[14] = autostart.Low;
headerData[15] = autostart.High;
// length of BASIC program without variables at offset 16
headerData[16] = basicLen.Low;
headerData[17] = basicLen.High;
// XOR checksum at offset 18
headerData[18] = headerData.Aggregate((x, n) => (byte)(x ^ n));
output.Write(headerData, 0, headerData.Length);
// write data block
output.WriteByte(0x10); // standard speed block
output.WriteByte(250); // two-byte pause length, 250ms
output.WriteByte(0);
HighLow16 dataBlockLen = (ushort)(2 + _data.Count);
output.WriteByte(dataBlockLen.Low);
output.WriteByte(dataBlockLen.High);
_data.Insert(0, 255); // flag byte
output.Write(_data.ToArray(), 0, _data.Count);
output.WriteByte(_data.Aggregate((x, n) => (byte)(x ^ n))); // checksum
}
}
// constructs BASIC program based on supplied options
static void BuildBasic()
{
var line = new BasicLine();
// colours
if (_border >= 0)
line.AddStatement(Token.Border, _border);
if (_paper >= 0)
line.AddStatement(Token.Paper, _paper);
if (_ink >= 0)
line.AddStatement(Token.Ink, _ink);
if (_bright >= 0)
line.AddStatement(Token.Bright, _bright);
// memory
line.AddStatement(Token.Clear, _clear);
// messages
if (_printBottom.Count > 0)
line.AddStatement(Token.Lprint, (byte)'#', 0/*1*/,
(byte)';', _printBottom);
if (_printTop.Count > 0)
line.AddStatement(Token.Print, _printTop);
// jump address (start of BASIC)
const string startOfBasic = "\x00be23635+256*\x00be23636";
line.AddStatement(Token.Randomize, Token.Usr, Token.Val, startOfBasic);
// optional pause
if (_pause >= 0)
line.AddStatement(Token.Pause, _pause);
_data.AddRange(line);
// if additional jump addresses specified, add them on their own
// lines
foreach (var tuple in _usr) {
line = new BasicLine();
if (tuple.Item1 > 0)
line.AddStatement(Token.Clear, tuple.Item1);
line.AddStatement(Token.Randomize, Token.Usr, tuple.Item2);
_data.AddRange(line);
}
}
public static int Main(string[] args)
{
try {
ParseArguments(args);
if (_clear < 1) {
Console.Error.WriteLine("no CLEAR address specified");
Die();
}
// read data to embed
using (var input = OpenInput()) {
int b;
while ((b = input.ReadByte()) >= 0)
_data.Add((byte)b);
}
// construct rest of program
BuildBasic();
WriteTzx();
return 0;
} catch (Exception e) {
Console.Error.WriteLine
("{0}: {1}", e.GetType().FullName, e.Message);
Console.Error.WriteLine(e.StackTrace);
Console.Error.WriteLine();
Die();
return 1;
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Text;
using System.Xml.XPath;
using System.Xml.Xsl;
using OpenADK.Library.Tools.XPath.Compiler;
using OpenADK.Library.Tools.XPath.Functions;
namespace OpenADK.Library.Tools.XPath
{
public class SifXPathContext : IXPathNavigable
{
private SifElement fContextElement;
private SifElementPointer fContextPointer;
private SifXsltContext fContext;
private SifXPathNavigator fDefaultNavigator;
public SifElement ContextElement
{
get { return fContextElement; }
}
/// <summary>
/// Creates a new SifXPathContext instance to use for traversing the
/// specified SIF Data Object
/// </summary>
/// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
/// <returns>an instance of SifXPathContext</returns>
public static SifXPathContext NewSIFContext( SifElement sdo )
{
return NewSIFContext( null, sdo );
}
/// <summary>
/// Creates a new SifXPathContext instance to use for traversing the
/// specified SIF Data Object
/// </summary>
/// <remarks>
/// NOTE: The SIFDataObject.setSIFVersion(version) is automatically
/// called and set to the target version.
/// </remarks>
/// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
/// <returns>an instance of SifXPathContext</returns>
/// <param name="version">The SIFVersion to use when traversing this object using XPath.</param>
public static SifXPathContext NewSIFContext( SifElement sdo, SifVersion version )
{
sdo.SifVersion = version;
SifXPathContext context = NewSIFContext( sdo );
return context;
}
/// <summary>
/// Creates a new SifXPathContext instance to use for traversing the
/// specified SIF Data Object
/// </summary>
/// <remarks>
/// Contexts that are created from other contexts automatically inherit all
/// custom variables and functions that are defined in the other context
/// </remarks>
/// <param name="parent">The SifXPathContext to share custom functions and
/// variables with</param>
/// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
/// <returns>an instance of SifXPathContext</returns>
public static SifXPathContext NewSIFContext( SifXPathContext parent,
SifElement sdo )
{
SifXPathContext context = new SifXPathContext( parent, sdo );
return context;
}
/// <summary>
/// Creates a new SifXPathContext instance to use for traversing the
/// specified SIF Data Object
/// </summary>
/// <remarks>
/// NOTE: The SIFDataObject.setSIFVersion(version) is automatically
/// called and set to the target version.
/// </remarks>
/// <param name="parent">The SifXPathContext to share custom functions and
/// variables with</param>
/// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
/// <returns>an instance of SifXPathContext</returns>
/// <param name="version">The SIFVersion to use when traversing this object using XPath.</param>
public static SifXPathContext NewSIFContext( SifXPathContext parent,
SifElement sdo, SifVersion version )
{
sdo.SifVersion = version;
return NewSIFContext( parent, sdo );
}
/// <summary>
/// Creates a new SifXPathContext
/// </summary>
/// <param name="parent"></param>
/// <param name="context"></param>
private SifXPathContext( SifXPathContext parent, SifElement context )
{
if ( parent != null )
{
fContext = parent.fContext;
}
else
{
fContext = new SifXsltContext();
fContext.AddFunctions( "adk", new ClassFunctions( typeof ( AdkFunctions ), null ) );
}
SifVersion version = context.SifVersion;
if( version == null )
{
version = SifVersion.LATEST;
}
fContextElement = context;
fContextPointer = new SifElementPointer( null, fContextElement, version );
fDefaultNavigator = new SifXPathNavigator( fContext, fContextPointer );
}
/// <summary>
/// Removes XPath syntax that was proprietary to the ADK in ADK 1.x versions and converts
/// the expression to the syntax supported by JXPath
/// </summary>
/// <param name="xPath"></param>
/// <returns></returns>
public static String ConvertLegacyXPath( String xPath )
{
StringBuilder sb = new StringBuilder( xPath );
bool inPredicate = false;
bool inString = false;
int parens = 0;
for ( int a = 0; a < sb.Length; a++ )
{
char chr = sb[a];
switch ( chr )
{
case '[':
inPredicate = true;
break;
case ']':
inPredicate = false;
break;
case '(':
parens++;
;
break;
case ')':
parens--;
break;
case '\'':
case '"':
inString = !inString;
break;
case ',': // The ADK syntax assumes that a comma seperating predicates means " and "
if ( inPredicate && !inString && parens == 0 )
{
sb.Remove( a, 1 );
sb.Insert( a, " and " );
a += 4;
}
break;
case '$':
if ( sb[a + 1] == '(' )
{
//int closeParen = sb.indexOf(")", a);
int closeParen;
for ( closeParen = a; closeParen < sb.Length; closeParen++ )
{
if ( sb[closeParen] == ')' )
{
break;
}
}
if ( sb[closeParen] == ')' )
{
sb.Remove( closeParen, 1 );
sb.Remove( a + 1, 1 );
if ( inString )
{
// Remove the single quotes around this variable, if present
if ( sb[a - 1] == '\'' )
{
sb.Remove( a - 1, 1 );
inString = false;
}
if ( sb[closeParen - 2] == '\'' )
{
sb.Remove( closeParen - 2, 1 );
}
}
}
}
break;
case '+': // The +] Syntax is ADK-specific and is used for outbound mappings
if ( inPredicate && !inString )
{
sb.Remove( a, 1 );
sb.Insert( a, " and adk:x()" );
a += 11;
}
break;
}
}
return sb.ToString();
}
/**
* Allows for getting Elements from a SIF Element using the legacy ADK 1.x
* style XPath queries.
*
* This method should only be used if the XPath syntax needs to be converted
* from ADK 1.x syntax to true XPath. If the query is already in true XPath
* format, call {@link JXPathContext#getValue(java.lang.String)}
*
* @param xPath
* @return An Element from this object representing the path, or null
*/
public Element GetElementOrAttribute( String xPath )
{
String adkXPath = ConvertLegacyXPath( xPath );
return GetValue( adkXPath ) as Element;
}
public void SetElementOrAttribute( String xPath, Object value )
{
String adkXPath = ConvertLegacyXPath( xPath );
CreatePathAndSetValue( adkXPath, value );
}
/// <summary>
/// Creates the specified path and returns a pointer
/// </summary>
/// <param name="xpath"></param>
/// <returns></returns>
public INodePointer CreatePath( String xpath )
{
INodePointer np = BuildADKPathWithPredicates( xpath, fContext );
return np;
}
internal INodePointer CreatePath( SifXPathExpression sifXPathExpression )
{
return CreatePath( sifXPathExpression.Expression );
}
/// <summary>
/// Creates the specified path and sets the value
/// </summary>
/// <param name="xpath"></param>
/// <returns></returns>
/// <param name="value">The value to set</param>
public void CreatePathAndSetValue( String xpath, object value )
{
IPointer np = BuildADKPathWithPredicates( xpath, fContext );
np.SetValue( value );
}
/// <summary>
/// Manually builds out a path to support the necessary mapping needs of the
/// ADK. By default, the JXPath implementation does not allow
/// context-dependend predicates (e.g. PhoneNumber[@Type='0096'] to be used
/// in XPaths that create the path. This implementation manually steps
/// through the XPath and builds it out. It's primary intent is to provide
/// the behavior that was present in the ADK before JXPath was used for
/// mapping
/// </summary>
/// <param name="expr">The Path expression to build out</param>
/// <param name="context"></param>
/// <returns></returns>
private INodePointer BuildADKPathWithPredicates( String expr, XsltContext context )
{
// Use the set of expression steps to determine which parts of the
// path already exist. Note that the order of evaluation used is optimized
// for first-time creation of elements. In other words, the path chosen was
// to evalaute the expression steps from the beginning rather than the end
// because for outbound mappings, that order will generally be the most efficient
AdkXPathStep[] steps = XPathParser.Parse( expr );
int currentStep = 0;
StringBuilder pathSoFar = new StringBuilder();
INodePointer parent = fContextPointer;
INodePointer current = null;
for ( ; currentStep < steps.Length; currentStep++ )
{
current = FindChild( fDefaultNavigator, pathSoFar, steps[currentStep] );
if ( current == null )
{
break;
}
pathSoFar.Append( "/" );
pathSoFar.Append( steps[currentStep].ToString() );
parent = current;
}
if ( current != null )
{
// We traversed the entire path and came up with a result.
// That means that the element we are trying to build the
// path to already exists. We will not create this path, so
// return null;
return null;
}
// We've traversed down to the level where we think we need to
// add a child. However, there are cases where this is not the proper
// location. For example, in SIF 1.5r1, the StudentAddressList element is
// repeatable and Address is not. It would not be proper to add a new Address
// element under StudentAddressList. Instead, the algorithm needs to back
// up the stack until it reaches the next repeatable element for the current
// version of SIF
// The following code is primarily in place for the StudentAddressList case, which is
// why the isContextDependent() logic applies. Currently, there is no known other place
// where this checking needs to occur.
if ( currentStep > 0 && steps[currentStep].IsContextDependent() )
{
int step = currentStep;
INodePointer stepParent = parent;
while ( step > -1 )
// don't evaluate step 0 at the root of the object because this problem doesn't apply there
{
if ( parent is SifElementPointer )
{
SifElementPointer sifParentPointer = (SifElementPointer) stepParent;
AdkNodeTest nt = steps[step].NodeTest;
if ( nt is AdkNodeNameTest )
{
SifElementPointer.AddChildDirective result =
sifParentPointer.GetAddChildDirective( ((AdkNodeNameTest) nt).NodeName );
if ( result != SifElementPointer.AddChildDirective.DONT_ADD_NOT_REPEATABLE )
{
break;
}
}
}
else
{
break;
}
step--;
stepParent = stepParent.Parent;
}
if ( step > -1 && step != currentStep )
{
currentStep = step;
parent = stepParent;
}
}
// At this point, we have a parent element and the index of the current
// step to evaluate
//InitialContext context = new InitialContext( new RootContext( this, (NodePointer) getContextPointer()));
for ( ; currentStep < steps.Length; currentStep++ )
{
AdkNodeTest nt = steps[currentStep].NodeTest;
if ( nt is AdkNodeNameTest )
{
current = parent.CreateChild( this, ((AdkNodeNameTest) nt).NodeName, 0 );
if ( current == null )
{
throw new ArgumentException( "Cannot evaluate expression step: " + steps[currentStep] );
}
foreach ( AdkExpression predicate in steps[currentStep].Predicates )
{
CreatePredicateValues( current, predicate, context );
}
}
else
{
throw new ArgumentException( "Cannot evaluate expression step: " + steps[currentStep] );
}
parent = current;
}
// At the end, the 'parent' variable will contain the last element created by this function
return parent;
}
private void CreatePredicateValues( INodePointer current, AdkExpression predicate, XsltContext evalContext )
{
if ( predicate is AdkEqualOperation )
{
AdkExpression[] components = ((AdkEqualOperation) predicate).Arguments;
AdkLocPath lp = (AdkLocPath) components[0];
AdkNodeNameTest attrName = (AdkNodeNameTest) lp.Steps[0].NodeTest;
INodePointer attr = current.CreateAttribute( this, attrName.NodeName );
Object value = components[1].ComputeValue( evalContext );
attr.SetValue( value );
return;
}
// This might be the 'adk:x()' function
if ( predicate is AdkAndOperation )
{
foreach ( AdkExpression expr in ((AdkAndOperation) predicate).Arguments )
{
if ( expr is AdkFunction && ((AdkFunction) expr).FunctionName.Equals( "adk:x" ) )
{
// This is the special marker function that tells the ADK to always
// create the parent repeatable element. Don't evaluate it.
continue;
}
else
{
CreatePredicateValues( current, expr, evalContext );
}
}
return;
}
// Unrecognized predicate
throw new ArgumentException( "Cannot evaluate expression predicate: " + predicate );
}
/// <summary>
/// Evaluates the current step in the path. If the path represented by the step does not
/// exist, NULL is returned. Otherwise, the node found is returned unless the special adk:X()
/// marker function is contained in the predicate expression, which signals that the specified
/// repeatable element should always be created
/// </summary>
/// <param name="navigator"></param>
/// <param name="parentPath"></param>
/// <param name="currentStep"></param>
/// <returns></returns>
private INodePointer FindChild( XPathNavigator navigator, StringBuilder parentPath, AdkXPathStep currentStep )
{
String currentStepxPath = currentStep.ToString();
if ( currentStep.IsContextDependent() )
{
// If the special 'adk:x()' function is present, that means to always
// create the element, therefore, return null as if it were not found
if ( currentStepxPath.IndexOf( "adk:x" ) > -1 )
{
return null;
}
}
navigator.MoveToRoot();
SifXPathNavigator sifNav =
(SifXPathNavigator) navigator.SelectSingleNode( parentPath + "/" + currentStepxPath );
if ( sifNav != null )
{
return sifNav.UnderlyingPointer;
}
return null;
}
/// <summary>
/// Install a library of XPath Variables within a specific namespace
/// </summary>
/// <param name="ns"></param>
/// <param name="variables"></param>
public void AddVariables( String ns, IXPathVariableLibrary variables )
{
fContext.AddVariables( ns, variables );
}
/// <summary>
/// Install a library of extension functions within a specific namespace
/// </summary>
/// <param name="ns"></param>
/// <param name="functions"></param>
public void AddFunctions( String ns, IXPathFunctionLibrary functions )
{
fContext.AddFunctions( ns, functions );
}
///<summary>
///Returns a new <see cref="T:System.Xml.XPath.XPathNavigator"></see> object.
///</summary>
///
///<returns>
///An <see cref="T:System.Xml.XPath.XPathNavigator"></see> object.
///</returns>
///
public XPathNavigator CreateNavigator()
{
return fDefaultNavigator.Clone();
}
/// <summary>
/// Evaluates the xpath and returns the resulting object. Primitive types are wrapped into SimpleField
/// objects. Complex Types are returned as a SIFElement
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public object GetValue( string s )
{
XPathExpression expression = fDefaultNavigator.Compile( s );
return GetValue( expression );
}
/// <summary>
/// Evaluates the xpath and returns the resulting object. Primitive types are wrapped into objects.
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public object GetValue( SifXPathExpression expression )
{
return GetValue( GetCompiledExpression( expression ) );
}
private XPathExpression GetCompiledExpression( SifXPathExpression expression )
{
XPathExpression returnValue = expression.CompiledExpression;
if ( returnValue == null )
{
returnValue = fDefaultNavigator.Compile( expression.Expression );
expression.CompiledExpression = returnValue;
}
return returnValue;
}
/// <summary>
/// Evaluates the xpath and returns the resulting object. Primitive types are wrapped into objects.
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
private object GetValue( XPathExpression expression )
{
Object value = fDefaultNavigator.Evaluate( expression );
XPathNodeIterator iterator = value as XPathNodeIterator;
if ( iterator == null )
{
return value;
}
if ( iterator.MoveNext() )
{
return iterator.Current.TypedValue;
}
return null;
}
/// <summary>
/// Evaluates the xpath and returns the resulting object. Primitive types are wrapped into objects.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public IPointer GetPointer( string s )
{
XPathExpression expression = fDefaultNavigator.Compile( s );
Object value = fDefaultNavigator.Evaluate( expression );
XPathNodeIterator iterator = value as XPathNodeIterator;
if ( iterator == null )
{
return null;
}
if ( iterator.MoveNext() )
{
return ((SifXPathNavigator) iterator.Current).UnderlyingPointer;
}
return null;
}
public static SifXPathExpression Compile( string xPath )
{
String convertedXPath = ConvertLegacyXPath( xPath );
return new SifXPathExpression( convertedXPath );
}
/// <summary>
/// Selects a node set, using the specified XPath expression.
/// </summary>
/// <param name="s">A String representing an XPath expression.</param>
/// <returns>An XPathNodeIterator pointing to the selected node set. </returns>
/// <seealso cref="System.Xml.XPath.XPathNavigator#Select(string)"/>
public XPathNodeIterator Select( string s )
{
return fDefaultNavigator.Select( s );
}
}
}
| |
using System;
namespace Bloop.ShellContext
{
[Flags()]
public enum SHCONTF
{
FOLDERS = 0x20,
NONFOLDERS = 0x40,
INCLUDEHIDDEN = 0x80,
INIT_ON_FIRST_NEXT = 0x100,
NETPRINTERSRCH = 0x200,
SHAREABLE = 0x400,
STORAGE = 0x800
}
[Flags()]
public enum SFGAO
{
CANCOPY = 0x1,
CANMOVE = 0x2,
CANLINK = 0x4,
STORAGE = 0x8,
CANRENAME = 0x10,
CANDELETE = 0x20,
HASPROPSHEET = 0x40,
DROPTARGET = 0x100,
CAPABILITYMASK = 0x177,
ENCRYPTED = 0x2000,
ISSLOW = 0x4000,
GHOSTED = 0x8000,
LINK = 0x10000,
SHARE = 0x20000,
READONLY = 0x40000,
HIDDEN = 0x80000,
DISPLAYATTRMASK = 0xFC000,
FILESYSANCESTOR = 0x10000000,
FOLDER = 0x20000000,
FILESYSTEM = 0x40000000,
HASSUBFOLDER = unchecked((int)0x80000000),
CONTENTSMASK = unchecked((int)0x80000000),
VALIDATE = 0x1000000,
REMOVABLE = 0x2000000,
COMPRESSED = 0x4000000,
BROWSABLE = 0x8000000,
NONENUMERATED = 0x100000,
NEWCONTENT = 0x200000,
CANMONIKER = 0x400000,
HASSTORAGE = 0x400000,
STREAM = 0x400000,
STORAGEANCESTOR = 0x800000,
STORAGECAPMASK = 0x70C50008
}
[Flags()]
public enum SHGNO
{
NORMAL = 0x0,
INFOLDER = 0x1,
FOREDITING = 0x1000,
FORADDRESSBAR = 0x4000,
FORPARSING = 0x8000,
}
[Flags()]
public enum CSIDL
{
ADMINTOOLS = 0x30,
ALTSTARTUP = 0x1d,
APPDATA = 0x1a,
BITBUCKET = 10,
CDBURN_AREA = 0x3b,
COMMON_ADMINTOOLS = 0x2f,
COMMON_ALTSTARTUP = 30,
COMMON_APPDATA = 0x23,
COMMON_DESKTOPDIRECTORY = 0x19,
COMMON_DOCUMENTS = 0x2e,
COMMON_FAVORITES = 0x1f,
COMMON_MUSIC = 0x35,
COMMON_PICTURES = 0x36,
COMMON_PROGRAMS = 0x17,
COMMON_STARTMENU = 0x16,
COMMON_STARTUP = 0x18,
COMMON_TEMPLATES = 0x2d,
COMMON_VIDEO = 0x37,
CONTROLS = 3,
COOKIES = 0x21,
DESKTOP = 0,
DESKTOPDIRECTORY = 0x10,
DRIVES = 0x11,
FAVORITES = 6,
FLAG_CREATE = 0x8000,
FONTS = 20,
HISTORY = 0x22,
INTERNET = 1,
INTERNET_CACHE = 0x20,
LOCAL_APPDATA = 0x1c,
MYDOCUMENTS = 12,
MYMUSIC = 13,
MYPICTURES = 0x27,
MYVIDEO = 14,
NETHOOD = 0x13,
NETWORK = 0x12,
PERSONAL = 5,
PRINTERS = 4,
PRINTHOOD = 0x1b,
PROFILE = 40,
PROFILES = 0x3e,
PROGRAM_FILES = 0x26,
PROGRAM_FILES_COMMON = 0x2b,
PROGRAMS = 2,
RECENT = 8,
SENDTO = 9,
STARTMENU = 11,
STARTUP = 7,
SYSTEM = 0x25,
TEMPLATES = 0x15,
WINDOWS = 0x24
}
[Flags()]
public enum SHGFI : uint
{
ADDOVERLAYS = 0x20,
ATTR_SPECIFIED = 0x20000,
ATTRIBUTES = 0x800,
DISPLAYNAME = 0x200,
EXETYPE = 0x2000,
ICON = 0x100,
ICONLOCATION = 0x1000,
LARGEICON = 0,
LINKOVERLAY = 0x8000,
OPENICON = 2,
OVERLAYINDEX = 0x40,
PIDL = 8,
SELECTED = 0x10000,
SHELLICONSIZE = 4,
SMALLICON = 1,
SYSICONINDEX = 0x4000,
TYPENAME = 0x400,
USEFILEATTRIBUTES = 0x10
}
[Flags]
public enum FILE_ATTRIBUTE
{
READONLY = 0x00000001,
HIDDEN = 0x00000002,
SYSTEM = 0x00000004,
DIRECTORY = 0x00000010,
ARCHIVE = 0x00000020,
DEVICE = 0x00000040,
NORMAL = 0x00000080,
TEMPORARY = 0x00000100,
SPARSE_FILE = 0x00000200,
REPARSE_POINT = 0x00000400,
COMPRESSED = 0x00000800,
OFFLINE = 0x00001000,
NOT_CONTENT_INDEXED = 0x00002000,
ENCRYPTED = 0x00004000
}
public enum GetCommandStringInformations
{
VERB = 0x00000004,
HELPTEXT = 0x00000005,
VALIDATE = 0x00000006,
}
[Flags]
public enum CMF : uint
{
NORMAL = 0x00000000,
DEFAULTONLY = 0x00000001,
VERBSONLY = 0x00000002,
EXPLORE = 0x00000004,
NOVERBS = 0x00000008,
CANRENAME = 0x00000010,
NODEFAULT = 0x00000020,
INCLUDESTATIC = 0x00000040,
EXTENDEDVERBS = 0x00000100,
RESERVED = 0xffff0000
}
[Flags]
public enum TPM : uint
{
LEFTBUTTON = 0x0000,
RIGHTBUTTON = 0x0002,
LEFTALIGN = 0x0000,
CENTERALIGN = 0x0004,
RIGHTALIGN = 0x0008,
TOPALIGN = 0x0000,
VCENTERALIGN = 0x0010,
BOTTOMALIGN = 0x0020,
HORIZONTAL = 0x0000,
VERTICAL = 0x0040,
NONOTIFY = 0x0080,
RETURNCMD = 0x0100,
RECURSE = 0x0001,
HORPOSANIMATION = 0x0400,
HORNEGANIMATION = 0x0800,
VERPOSANIMATION = 0x1000,
VERNEGANIMATION = 0x2000,
NOANIMATION = 0x4000,
LAYOUTRTL = 0x8000
}
}
| |
using System.IO;
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\Hyper.tcl
// output file is AVHyper.cs
/// <summary>
/// The testing class derived from AVHyper
/// </summary>
public class AVHyperClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVHyper(String [] argv)
{
//Prefix Content is: ""
// Create the RenderWindow, Renderer and interactive renderer[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
VTK_INTEGRATE_BOTH_DIRECTIONS = 2;
//[]
// generate tensors[]
ptLoad = new vtkPointLoad();
ptLoad.SetLoadValue((double)100.0);
ptLoad.SetSampleDimensions((int)20,(int)20,(int)20);
ptLoad.ComputeEffectiveStressOn();
ptLoad.SetModelBounds((double)-10,(double)10,(double)-10,(double)10,(double)-10,(double)10);
//[]
// If the current directory is writable, then test the witers[]
//[]
try
{
channel = new StreamWriter("test.tmp");
tryCatchError = "NOERROR";
}
catch(Exception)
{tryCatchError = "ERROR";}
if(tryCatchError.Equals("NOERROR"))
{
channel.Close();
File.Delete("test.tmp");
wSP = new vtkDataSetWriter();
wSP.SetInputConnection((vtkAlgorithmOutput)ptLoad.GetOutputPort());
wSP.SetFileName((string)"wSP.vtk");
wSP.SetTensorsName((string)"pointload");
wSP.SetScalarsName((string)"effective_stress");
wSP.Write();
rSP = new vtkDataSetReader();
rSP.SetFileName((string)"wSP.vtk");
rSP.SetTensorsName((string)"pointload");
rSP.SetScalarsName((string)"effective_stress");
rSP.Update();
input = rSP.GetOutput();
File.Delete("wSP.vtk");
}
else
{
input = ptLoad.GetOutput();
}
// Generate hyperstreamlines[]
s1 = new vtkHyperStreamline();
s1.SetInput((vtkDataObject)input);
s1.SetStartPosition((double)9,(double)9,(double)-9);
s1.IntegrateMinorEigenvector();
s1.SetMaximumPropagationDistance((double)18.0);
s1.SetIntegrationStepLength((double)0.1);
s1.SetStepLength((double)0.01);
s1.SetRadius((double)0.25);
s1.SetNumberOfSides((int)18);
s1.SetIntegrationDirection((int)VTK_INTEGRATE_BOTH_DIRECTIONS);
s1.Update();
// Map hyperstreamlines[]
lut = new vtkLogLookupTable();
lut.SetHueRange((double).6667,(double)0.0);
s1Mapper = vtkPolyDataMapper.New();
s1Mapper.SetInputConnection((vtkAlgorithmOutput)s1.GetOutputPort());
s1Mapper.SetLookupTable((vtkScalarsToColors)lut);
ptLoad.Update();
//force update for scalar range[]
s1Mapper.SetScalarRange((double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)ptLoad.GetOutput()).GetScalarRange()[1]);
s1Actor = new vtkActor();
s1Actor.SetMapper((vtkMapper)s1Mapper);
s2 = new vtkHyperStreamline();
s2.SetInput((vtkDataObject)input);
s2.SetStartPosition((double)-9,(double)-9,(double)-9);
s2.IntegrateMinorEigenvector();
s2.SetMaximumPropagationDistance((double)18.0);
s2.SetIntegrationStepLength((double)0.1);
s2.SetStepLength((double)0.01);
s2.SetRadius((double)0.25);
s2.SetNumberOfSides((int)18);
s2.SetIntegrationDirection((int)VTK_INTEGRATE_BOTH_DIRECTIONS);
s2.Update();
s2Mapper = vtkPolyDataMapper.New();
s2Mapper.SetInputConnection((vtkAlgorithmOutput)s2.GetOutputPort());
s2Mapper.SetLookupTable((vtkScalarsToColors)lut);
s2Mapper.SetScalarRange((double)((vtkDataSet)input).GetScalarRange()[0],(double)((vtkDataSet)input).GetScalarRange()[1]);
s2Actor = new vtkActor();
s2Actor.SetMapper((vtkMapper)s2Mapper);
s3 = new vtkHyperStreamline();
s3.SetInput((vtkDataObject)input);
s3.SetStartPosition((double)9,(double)-9,(double)-9);
s3.IntegrateMinorEigenvector();
s3.SetMaximumPropagationDistance((double)18.0);
s3.SetIntegrationStepLength((double)0.1);
s3.SetStepLength((double)0.01);
s3.SetRadius((double)0.25);
s3.SetNumberOfSides((int)18);
s3.SetIntegrationDirection((int)VTK_INTEGRATE_BOTH_DIRECTIONS);
s3.Update();
s3Mapper = vtkPolyDataMapper.New();
s3Mapper.SetInputConnection((vtkAlgorithmOutput)s3.GetOutputPort());
s3Mapper.SetLookupTable((vtkScalarsToColors)lut);
s3Mapper.SetScalarRange((double)((vtkDataSet)input).GetScalarRange()[0],
(double)((vtkDataSet)input).GetScalarRange()[1]);
s3Actor = new vtkActor();
s3Actor.SetMapper((vtkMapper)s3Mapper);
s4 = new vtkHyperStreamline();
s4.SetInput((vtkDataObject)input);
s4.SetStartPosition((double)-9,(double)9,(double)-9);
s4.IntegrateMinorEigenvector();
s4.SetMaximumPropagationDistance((double)18.0);
s4.SetIntegrationStepLength((double)0.1);
s4.SetStepLength((double)0.01);
s4.SetRadius((double)0.25);
s4.SetNumberOfSides((int)18);
s4.SetIntegrationDirection((int)VTK_INTEGRATE_BOTH_DIRECTIONS);
s4.Update();
s4Mapper = vtkPolyDataMapper.New();
s4Mapper.SetInputConnection((vtkAlgorithmOutput)s4.GetOutputPort());
s4Mapper.SetLookupTable((vtkScalarsToColors)lut);
s4Mapper.SetScalarRange((double)((vtkDataSet)input).GetScalarRange()[0],(double)((vtkDataSet)input).GetScalarRange()[1]);
s4Actor = new vtkActor();
s4Actor.SetMapper((vtkMapper)s4Mapper);
// plane for context[]
//[]
g = new vtkImageDataGeometryFilter();
g.SetInput((vtkDataObject)input);
g.SetExtent((int)0,(int)100,(int)0,(int)100,(int)0,(int)0);
g.Update();
//for scalar range[]
gm = vtkPolyDataMapper.New();
gm.SetInputConnection((vtkAlgorithmOutput)g.GetOutputPort());
gm.SetScalarRange((double)((vtkDataSet)g.GetOutput()).GetScalarRange()[0],(double)((vtkDataSet)g.GetOutput()).GetScalarRange()[1]);
ga = new vtkActor();
ga.SetMapper((vtkMapper)gm);
// Create outline around data[]
//[]
outline = new vtkOutlineFilter();
outline.SetInput((vtkDataObject)input);
outlineMapper = vtkPolyDataMapper.New();
outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort());
outlineActor = new vtkActor();
outlineActor.SetMapper((vtkMapper)outlineMapper);
outlineActor.GetProperty().SetColor((double)0,(double)0,(double)0);
// Create cone indicating application of load[]
//[]
coneSrc = new vtkConeSource();
coneSrc.SetRadius((double).5);
coneSrc.SetHeight((double)2);
coneMap = vtkPolyDataMapper.New();
coneMap.SetInputConnection((vtkAlgorithmOutput)coneSrc.GetOutputPort());
coneActor = new vtkActor();
coneActor.SetMapper((vtkMapper)coneMap);
coneActor.SetPosition((double)0,(double)0,(double)11);
coneActor.RotateY((double)90);
coneActor.GetProperty().SetColor((double)1,(double)0,(double)0);
camera = new vtkCamera();
camera.SetFocalPoint((double)0.113766,(double)-1.13665,(double)-1.01919);
camera.SetPosition((double)-29.4886,(double)-63.1488,(double)26.5807);
camera.SetViewAngle((double)24.4617);
camera.SetViewUp((double)0.17138,(double)0.331163,(double)0.927879);
camera.SetClippingRange((double)1,(double)100);
ren1.AddActor((vtkProp)s1Actor);
ren1.AddActor((vtkProp)s2Actor);
ren1.AddActor((vtkProp)s3Actor);
ren1.AddActor((vtkProp)s4Actor);
ren1.AddActor((vtkProp)outlineActor);
ren1.AddActor((vtkProp)coneActor);
ren1.AddActor((vtkProp)ga);
ren1.SetBackground((double)1.0,(double)1.0,(double)1.0);
ren1.SetActiveCamera((vtkCamera)camera);
renWin.SetSize((int)300,(int)300);
renWin.Render();
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static int VTK_INTEGRATE_BOTH_DIRECTIONS;
static vtkPointLoad ptLoad;
static string tryCatchError;
static StreamWriter channel;
static vtkDataSetWriter wSP;
static vtkDataSetReader rSP;
static vtkDataSet input;
static vtkHyperStreamline s1;
static vtkLogLookupTable lut;
static vtkPolyDataMapper s1Mapper;
static vtkActor s1Actor;
static vtkHyperStreamline s2;
static vtkPolyDataMapper s2Mapper;
static vtkActor s2Actor;
static vtkHyperStreamline s3;
static vtkPolyDataMapper s3Mapper;
static vtkActor s3Actor;
static vtkHyperStreamline s4;
static vtkPolyDataMapper s4Mapper;
static vtkActor s4Actor;
static vtkImageDataGeometryFilter g;
static vtkPolyDataMapper gm;
static vtkActor ga;
static vtkOutlineFilter outline;
static vtkPolyDataMapper outlineMapper;
static vtkActor outlineActor;
static vtkConeSource coneSrc;
static vtkPolyDataMapper coneMap;
static vtkActor coneActor;
static vtkCamera camera;
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int GetVTK_INTEGRATE_BOTH_DIRECTIONS()
{
return VTK_INTEGRATE_BOTH_DIRECTIONS;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_INTEGRATE_BOTH_DIRECTIONS(int toSet)
{
VTK_INTEGRATE_BOTH_DIRECTIONS = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPointLoad GetptLoad()
{
return ptLoad;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetptLoad(vtkPointLoad toSet)
{
ptLoad = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static string GettryCatchError()
{
return tryCatchError;
}
///<summary> A Set Method for Static Variables </summary>
public static void SettryCatchError(string toSet)
{
tryCatchError = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static StreamWriter Getchannel()
{
return channel;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setchannel(StreamWriter toSet)
{
channel = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetWriter GetwSP()
{
return wSP;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetwSP(vtkDataSetWriter toSet)
{
wSP = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSetReader GetrSP()
{
return rSP;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrSP(vtkDataSetReader toSet)
{
rSP = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataSet Getinput()
{
return input;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setinput(vtkDataSet toSet)
{
input = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkHyperStreamline Gets1()
{
return s1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets1(vtkHyperStreamline toSet)
{
s1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkLogLookupTable Getlut()
{
return lut;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setlut(vtkLogLookupTable toSet)
{
lut = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Gets1Mapper()
{
return s1Mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets1Mapper(vtkPolyDataMapper toSet)
{
s1Mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Gets1Actor()
{
return s1Actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets1Actor(vtkActor toSet)
{
s1Actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkHyperStreamline Gets2()
{
return s2;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets2(vtkHyperStreamline toSet)
{
s2 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Gets2Mapper()
{
return s2Mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets2Mapper(vtkPolyDataMapper toSet)
{
s2Mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Gets2Actor()
{
return s2Actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets2Actor(vtkActor toSet)
{
s2Actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkHyperStreamline Gets3()
{
return s3;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets3(vtkHyperStreamline toSet)
{
s3 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Gets3Mapper()
{
return s3Mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets3Mapper(vtkPolyDataMapper toSet)
{
s3Mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Gets3Actor()
{
return s3Actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets3Actor(vtkActor toSet)
{
s3Actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkHyperStreamline Gets4()
{
return s4;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets4(vtkHyperStreamline toSet)
{
s4 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Gets4Mapper()
{
return s4Mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets4Mapper(vtkPolyDataMapper toSet)
{
s4Mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Gets4Actor()
{
return s4Actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sets4Actor(vtkActor toSet)
{
s4Actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkImageDataGeometryFilter Getg()
{
return g;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setg(vtkImageDataGeometryFilter toSet)
{
g = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Getgm()
{
return gm;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setgm(vtkPolyDataMapper toSet)
{
gm = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getga()
{
return ga;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setga(vtkActor toSet)
{
ga = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkOutlineFilter Getoutline()
{
return outline;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoutline(vtkOutlineFilter toSet)
{
outline = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetoutlineMapper()
{
return outlineMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineMapper(vtkPolyDataMapper toSet)
{
outlineMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetoutlineActor()
{
return outlineActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetoutlineActor(vtkActor toSet)
{
outlineActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkConeSource GetconeSrc()
{
return coneSrc;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetconeSrc(vtkConeSource toSet)
{
coneSrc = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetconeMap()
{
return coneMap;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetconeMap(vtkPolyDataMapper toSet)
{
coneMap = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetconeActor()
{
return coneActor;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetconeActor(vtkActor toSet)
{
coneActor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcamera()
{
return camera;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcamera(vtkCamera toSet)
{
camera = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(ptLoad!= null){ptLoad.Dispose();}
if(wSP!= null){wSP.Dispose();}
if(rSP!= null){rSP.Dispose();}
if(input!= null){input.Dispose();}
if(s1!= null){s1.Dispose();}
if(lut!= null){lut.Dispose();}
if(s1Mapper!= null){s1Mapper.Dispose();}
if(s1Actor!= null){s1Actor.Dispose();}
if(s2!= null){s2.Dispose();}
if(s2Mapper!= null){s2Mapper.Dispose();}
if(s2Actor!= null){s2Actor.Dispose();}
if(s3!= null){s3.Dispose();}
if(s3Mapper!= null){s3Mapper.Dispose();}
if(s3Actor!= null){s3Actor.Dispose();}
if(s4!= null){s4.Dispose();}
if(s4Mapper!= null){s4Mapper.Dispose();}
if(s4Actor!= null){s4Actor.Dispose();}
if(g!= null){g.Dispose();}
if(gm!= null){gm.Dispose();}
if(ga!= null){ga.Dispose();}
if(outline!= null){outline.Dispose();}
if(outlineMapper!= null){outlineMapper.Dispose();}
if(outlineActor!= null){outlineActor.Dispose();}
if(coneSrc!= null){coneSrc.Dispose();}
if(coneMap!= null){coneMap.Dispose();}
if(coneActor!= null){coneActor.Dispose();}
if(camera!= null){camera.Dispose();}
}
}
//--- end of script --//
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.Collections;
using System.IO;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Belikov.Common.ThreadProcessing;
using Belikov.GenuineChannels.Messaging;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Receiving;
using Belikov.GenuineChannels.TransportContext;
using Belikov.GenuineChannels.Utilities;
namespace Belikov.GenuineChannels.BroadcastEngine
{
/// <summary>
/// Represents a method which is used to invoke the real proxy asynchronously.
/// </summary>
public delegate IMessage InvokeAsyncDelegate(IMessage msg);
/// <summary>
/// Sends the specified message to all receivers, collects results and completes broadcast call.
/// </summary>
public class ResultCollector : IResponseProcessor, IClientChannelSink, IMessageSink
{
/// <summary>
/// Constructs an instance of the ResultCollector class.
/// Created object is in "Sending" state by default.
/// </summary>
/// <param name="dispatcher">The dispatcher.</param>
/// <param name="capacity">The expected number of receivers.</param>
/// <param name="iMessage">The message.</param>
public ResultCollector(Dispatcher dispatcher, int capacity, IMessage iMessage)
{
this._iMessage = iMessage;
this._dispatcher = dispatcher;
this.Successful = new Hashtable(capacity);
this.Failed = new Hashtable(capacity);
}
/// <summary>
/// Releases acquired resources.
/// </summary>
public void Dispose()
{
}
private Dispatcher _dispatcher;
private IMessage _iMessage;
private string _broadcastGuid = Guid.NewGuid().ToString("N");
/// <summary>
/// The message being sent in serialized representation.
/// </summary>
private GenuineChunkedStream _messageStream;
/// <summary>
/// Indicates whether the second broadcast stage (sending the message via the usual channel(s) to the
/// failed receivers) was completed.
/// </summary>
private bool _secondStagePerformed = false;
/// <summary>
/// Represents a keyed collection containing successful results of invocations.
/// Keys are URIs of the remote hosts, values support the IMethodReturnMessage interface.
/// </summary>
public Hashtable Successful;
/// <summary>
/// Represents a keyed collection containing unsuccessful results of the invocations.
/// Keys contain URI, values support the IMethodReturnMessage interface or inherit the Exception class.
/// </summary>
public Hashtable Failed;
/// <summary>
/// Is set when all replies have arrived.
/// </summary>
public ManualResetEvent AllMessagesReceived = new ManualResetEvent(false);
/// <summary>
/// Represents a keyed collection containing receivers' uris of receivers that did not
/// respond to the send message.
/// Uri {string} => null.
/// </summary>
public Hashtable UnrepliedReceivers = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Writes down response came from the remote host.
/// </summary>
/// <param name="mbrUri">The uri of the remote MBR.</param>
/// <param name="returnMessage">The received message or a null reference.</param>
/// <param name="ex">The exception occurred during sending or receiving.</param>
public void ParseResult(string mbrUri, IMethodReturnMessage returnMessage, Exception ex)
{
// if time-out has expired
if (this.AllMessagesReceived.WaitOne(0, false))
return ;
// to increase or zero the number of consecutive fails
ReceiverInfo receiverInfo = this._dispatcher.GetReceiverInfo(mbrUri);
BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter;
// if an exception is received
Exception exception = null;
if (ex != null || (returnMessage != null && returnMessage.Exception != null))
{
exception = ex != null ? ex : returnMessage.Exception;
HostInformation dbgRemoteHost = (receiverInfo == null ? null : receiverInfo.DbgRemoteHost);
string numberOfFails = (receiverInfo == null ? string.Empty : receiverInfo.NumberOfFails.ToString());
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.ParseResult",
LogMessageType.BroadcastResponseParsed, exception, null, dbgRemoteHost, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, false, this._dispatcher, this, false, receiverInfo,
numberOfFails, "false",
"The exception is received in response to the broadcast. NumberOfFails: {0}.", numberOfFails);
}
}
// if it's a message that the invocation was repeated, ignore it
if (exception is OperationException)
{
OperationException operationException = (OperationException) exception;
if (operationException.OperationErrorMessage.ErrorIdentifier == "GenuineChannels.Exception.Broadcast.CallHasAlreadyBeenMade")
return ;
}
lock (this)
{
// if successful response from this object has already been received
this.UnrepliedReceivers.Remove(mbrUri);
if (this.Successful.ContainsKey(mbrUri))
return ;
}
lock(this)
{
// if an exception is received
if (exception != null)
{
this.Failed[mbrUri] = exception;
if (receiverInfo != null)
{
lock(receiverInfo)
{
if (receiverInfo.GeneralBroadcastSender == null && this._dispatcher.MaximumNumberOfConsecutiveFailsToExcludeReceiverAutomatically != 0 &&
receiverInfo.NumberOfFails >= this._dispatcher.MaximumNumberOfConsecutiveFailsToExcludeReceiverAutomatically)
{
// exclude it
this._dispatcher.Remove(receiverInfo.MbrObject);
}
}
}
}
else
{
// successful response
this.Successful[mbrUri] = returnMessage;
this.Failed.Remove(mbrUri);
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
HostInformation dbgRemoteHost = (receiverInfo == null ? null : receiverInfo.DbgRemoteHost);
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.ParseResult",
LogMessageType.BroadcastResponseParsed, null, null, dbgRemoteHost, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, false, this._dispatcher, this, false, receiverInfo,
null, "true",
"The successful response is received.");
}
if (receiverInfo != null)
{
lock(receiverInfo)
{
receiverInfo.NumberOfFails = 0;
}
}
}
if (this.UnrepliedReceivers.Count == 0)
this.AllMessagesReceived.Set();
}
}
private BroadcastCallFinishedHandler _broadcastCallFinishedHandler;
/// <summary>
/// Initiate the receiving of responses.
/// Returns true if the invocation has been completed synchronously.
/// </summary>
/// <returns>The true value if the invocation has been completed synchronously.</returns>
public bool StartReceiving()
{
bool callIsAsync = false;
lock (this._dispatcher)
{
callIsAsync = this._dispatcher.CallIsAsync;
this._broadcastCallFinishedHandler = this._dispatcher.BroadcastCallFinishedHandler;
}
if (! callIsAsync || this._broadcastCallFinishedHandler == null)
{
this.AllMessagesReceived.WaitOne(this._dispatcher.ReceiveResultsTimeOut, false);
// this call sends messages to failed receivers
this.WaitUntilReceiversReplyOrTimeOut(null, false);
// LOG:
BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter;
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.StartReceiving",
LogMessageType.BroadcastInvocationCompleted, null, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, false, this._dispatcher, this, false, null,
null, null,
"The broadcast invocation is completed.");
}
this.AllMessagesReceived.Set();
return true;
}
ThreadPool.RegisterWaitForSingleObject(this.AllMessagesReceived, new WaitOrTimerCallback(this.WaitUntilReceiversReplyOrTimeOut), null, this._dispatcher.ReceiveResultsTimeOut, true);
return false;
}
/// <summary>
/// Calls the callback when either all receivers reply or wait time elapses.
/// </summary>
/// <param name="state">Ignored.</param>
/// <param name="timeOut">Ignored.</param>
private void WaitUntilReceiversReplyOrTimeOut(object state, bool timeOut)
{
// check whether we have any unreplied true multicast-enabled receivers
bool unrepliedReceivers = false;
lock(this)
{
if (this.Failed.Count > 0 && ! this._secondStagePerformed)
foreach ( DictionaryEntry entry in this.Failed )
{
// fixed in 2.2 version
string uri = (string) entry.Key;
ReceiverInfo receiverInfo = this._dispatcher.GetReceiverInfo(uri);
int numberOfFails = 0;
if (receiverInfo != null)
{
lock(receiverInfo)
{
numberOfFails = ++receiverInfo.NumberOfFails;
}
}
if (this._dispatcher.MaximumNumberOfConsecutiveFailsToExcludeReceiverAutomatically != 0 &&
numberOfFails >= this._dispatcher.MaximumNumberOfConsecutiveFailsToExcludeReceiverAutomatically)
{
this._dispatcher.Remove(uri);
}
// set time-out exception
OperationException operationException = entry.Value as OperationException;
if (operationException != null && operationException.OperationErrorMessage != null &&
operationException.OperationErrorMessage.ErrorIdentifier == "GenuineChannels.Exception.Broadcast.RemoteEndPointDidNotReplyForTimeOut")
{
unrepliedReceivers = true;
break;
}
}
}
if (unrepliedReceivers)
{
this.SendMessageToFailedReceiversDirectly();
this.StartReceiving();
return ;
}
// LOG:
BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter;
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.WaitUntilReceiversReplyOrTimeOut",
LogMessageType.BroadcastInvocationCompleted, null, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, false, this._dispatcher, this, false, null,
null, null,
"The broadcast invocation is completed.");
}
// to stop receiving info
this.AllMessagesReceived.Set();
if (this._broadcastCallFinishedHandler != null)
this._broadcastCallFinishedHandler(this._dispatcher, this._iMessage, this);
}
private const string _uniqueReceiverName = "_";
/// <summary>
/// Sends the invocation to all registered receivers.
/// </summary>
/// <param name="msg">The message to be sent.</param>
public void PerformBroadcasting(IMessage msg)
{
BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter;
string methodName = null;
string invocationTarget = null;
// the first stage of the broadcasting
try
{
ArrayList listOfExcludedReceivers = new ArrayList();
this._iMessage = msg;
methodName = BinaryLogWriter.ParseInvocationMethod(msg.Properties["__MethodName"] as string, msg.Properties["__TypeName"] as string);
BinaryFormatter formatterForLocalRecipients = null;
// serialize the message
BinaryFormatter binaryFormatter = new BinaryFormatter(new RemotingSurrogateSelector(), new StreamingContext(StreamingContextStates.Other));
this._messageStream = new GenuineChunkedStream(false);
binaryFormatter.Serialize(this._messageStream, msg);
// to trace the message if it could reach the server via several channels
string callGuidSubstring = null;
if (this._dispatcher.IgnoreRecurrentCalls)
callGuidSubstring = Guid.NewGuid().ToString("N");
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.PerformBroadcasting",
LogMessageType.BroadcastInvocationInitiated, null, null, null,
binaryLogWriter[LogCategory.BroadcastEngine] > 1 ? (Stream) this._messageStream.Clone() : null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, true, this._dispatcher, this, false, null,
methodName, null,
"The broadcast invocation is initiated.");
}
// to prevent firing resultCollector.AllMessagesReceived event
this.UnrepliedReceivers[_uniqueReceiverName] = null;
object[] listOfReceiverInfo;
this._dispatcher.GetListOfReceivers(out listOfReceiverInfo, msg, this);
// through all recipients
for ( int i = 0; i < listOfReceiverInfo.Length; i++)
{
ReceiverInfo receiverInfo = listOfReceiverInfo[i] as ReceiverInfo;
if (receiverInfo == null)
continue;
string mbrUri = (string) receiverInfo.MbrUri;
invocationTarget = mbrUri;
try
{
lock (receiverInfo)
{
if (this._dispatcher.MaximumNumberOfConsecutiveFailsToExcludeReceiverAutomatically != 0 &&
receiverInfo.NumberOfFails >= this._dispatcher.MaximumNumberOfConsecutiveFailsToExcludeReceiverAutomatically)
{
// put it to the list containing receivers being excluded
listOfExcludedReceivers.Add(mbrUri);
continue;
}
}
// think that it'll fail
if ( !receiverInfo.Local && receiverInfo.GeneralBroadcastSender == null)
{
lock(this)
{
this.Failed[mbrUri] = GenuineExceptions.Get_Broadcast_RemoteEndPointDidNotReplyForTimeOut();
}
}
if (receiverInfo.Local)
{
// call to local appdomain
// ignore recurrent calls
if (this._dispatcher.IgnoreRecurrentCalls && UniqueCallTracer.Instance.WasGuidRegistered(mbrUri + callGuidSubstring))
continue;
// we'll wait for the answer from this receiver
this.UnrepliedReceivers[mbrUri] = null;
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.PerformBroadcasting",
LogMessageType.BroadcastRecipientInvoked, null, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, false, this._dispatcher, this, false, receiverInfo,
null, null,
"The local receiver is invoked via LocalPerformer.");
}
if (formatterForLocalRecipients == null)
formatterForLocalRecipients = new BinaryFormatter();
// fixed in 2.5.9.6
IMessage iLocalMessage = (IMessage)formatterForLocalRecipients.Deserialize((Stream)this._messageStream.Clone());
// queue task to run the call locally
//IMessage iLocalMessage = (IMessage) binaryFormatter.Deserialize( (Stream) this._messageStream.Clone() );
LocalPerformer localPerformer = new LocalPerformer(iLocalMessage, this, receiverInfo.MbrObject);
GenuineThreadPool.QueueUserWorkItem(new WaitCallback(localPerformer.Call), null, false);
}
else if (receiverInfo.GeneralBroadcastSender != null)
{
// call via true multicast channel
Stream messageToBeSent = (Stream) this._messageStream.Clone();
// send via real broadcast sender to the specific court
msg.Properties["__Uri"] = string.Empty;
Message message = Message.CreateOutcomingMessage(receiverInfo.GeneralBroadcastSender.ITransportContext, msg, new TransportHeaders(), messageToBeSent, false);
message.DestinationMarshalByRef = receiverInfo.SerializedObjRef;
message.GenuineMessageType = GenuineMessageType.TrueBroadcast;
// to ignore recurrent calls on the remote side
if (this._dispatcher.IgnoreRecurrentCalls)
message.ITransportHeaders[Message.TransportHeadersBroadcastSendGuid] = callGuidSubstring;
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
message.ITransportHeaders[Message.TransportHeadersInvocationTarget] = invocationTarget;
message.ITransportHeaders[Message.TransportHeadersMethodName] = methodName;
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.PerformBroadcasting",
LogMessageType.BroadcastRecipientInvoked, null, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, false, this._dispatcher, this, false, receiverInfo,
null, null,
"Mulsticast sender is being invoked.");
}
// register to catch all the answers
receiverInfo.GeneralBroadcastSender.ITransportContext.IIncomingStreamHandler.RegisterResponseProcessor(message.MessageId, this);
// and send it
receiverInfo.GeneralBroadcastSender.SendMessage(message, this);
}
else
{
// send the invocation through the usual channel
// we'll wait for the reply
this.UnrepliedReceivers[mbrUri] = null;
// send only if this receiver is not expected to receive message via broadcast channel
if (receiverInfo.NeedsBroadcastSimulation)
{
// each time a new stream is created because sinks change stream position concurrently
Stream messageToBeSent = (Stream) this._messageStream.Clone();
TransportHeaders transportHeaders = new TransportHeaders();
// to ignore recurrent calls on the remote side
if (this._dispatcher.IgnoreRecurrentCalls)
transportHeaders[Message.TransportHeadersBroadcastSendGuid] = callGuidSubstring;
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.PerformBroadcasting",
LogMessageType.BroadcastRecipientInvoked, null, null, receiverInfo.DbgRemoteHost, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, false, this._dispatcher, this, false, receiverInfo,
null, null,
"The broadcast recipient is being invoked directly.");
}
// invoke the destination MBR
msg.Properties["__Uri"] = receiverInfo.MbrUri;
transportHeaders[Message.TransportHeadersBroadcastObjRefOrCourt] = receiverInfo.SerializedObjRef;
transportHeaders[Message.TransportHeadersMbrUriName] = receiverInfo.MbrUri;
transportHeaders[Message.TransportHeadersGenuineMessageType] = GenuineMessageType.BroadcastEngine;
transportHeaders[Message.TransportHeadersInvocationTarget] = invocationTarget;
transportHeaders[Message.TransportHeadersMethodName] = methodName;
ClientChannelSinkStack clientChannelSinkStack = new ClientChannelSinkStack(this);
clientChannelSinkStack.Push(this, null);
receiverInfo.IClientChannelSink.AsyncProcessRequest(clientChannelSinkStack, this._iMessage, transportHeaders, messageToBeSent);
}
}
}
catch(Exception ex)
{
this.ParseResult(mbrUri, null, ex);
}
}
// remove set uri from the hash to check wither the invocation finished
this.UnrepliedReceivers.Remove(_uniqueReceiverName);
if (this.UnrepliedReceivers.Count <= 0)
this.AllMessagesReceived.Set();
this.StartReceiving();
if (listOfExcludedReceivers.Count > 0)
{
foreach(string uri in listOfExcludedReceivers)
this._dispatcher.Remove(uri);
}
}
catch(Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.PerformBroadcasting",
LogMessageType.BroadcastInvocationInitiated, ex, null, null, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, false, this._dispatcher, this, false, null,
invocationTarget, methodName,
"A critical failure occurred during broadcast.");
}
throw;
}
}
/// <summary>
/// Looks for a failed broadcast receivers and invoke them again.
/// </summary>
public void SendMessageToFailedReceiversDirectly()
{
if (this._secondStagePerformed)
return ;
this._secondStagePerformed = true;
BinaryLogWriter binaryLogWriter = GenuineLoggingServices.BinaryLogWriter;
// the second stage of the broadcasting
using (ReaderAutoLocker reader = new ReaderAutoLocker(this._dispatcher._readerWriterLock))
{
// to prevent firing resultCollector.AllMessagesReceived event
this.UnrepliedReceivers[_uniqueReceiverName] = null;
lock(this)
{
foreach ( DictionaryEntry entry in this.Failed )
{
OperationException operationException = entry.Value as OperationException;
if (operationException != null && operationException.OperationErrorMessage != null &&
operationException.OperationErrorMessage.ErrorIdentifier == "GenuineChannels.Exception.Broadcast.RemoteEndPointDidNotReplyForTimeOut")
{
string uri = (string) entry.Key;
ReceiverInfo receiverInfo = this._dispatcher.GetReceiverInfo(uri);
// whether this receiver is expected to receive message via broadcast channel
if (receiverInfo == null || receiverInfo.NeedsBroadcastSimulation)
continue;
// switch it back to simulation mode if the limit is exceeded
lock(receiverInfo)
{
receiverInfo.NumberOfMulticastFails++;
if (this._dispatcher.MaximumNumberOfConsecutiveFailsToEnableSimulationMode != 0 &&
receiverInfo.NumberOfMulticastFails >= this._dispatcher.MaximumNumberOfConsecutiveFailsToEnableSimulationMode)
{
// force simulation
receiverInfo.NeedsBroadcastSimulation = true;
receiverInfo.NumberOfMulticastFails = 0;
}
}
// each time a new stream is created because sinks change stream position concurrently
Stream messageToBeSent = (Stream) this._messageStream.Clone();
TransportHeaders transportHeaders = new TransportHeaders();
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.BroadcastEngine] > 0 )
{
string methodName = BinaryLogWriter.ParseInvocationMethod(this._iMessage.Properties["__MethodName"] as string, this._iMessage.Properties["__TypeName"] as string);
string invocationTarget = receiverInfo.MbrUri;
binaryLogWriter.WriteBroadcastEngineEvent(LogCategory.BroadcastEngine, "ResultCollector.SendMessageToFailedReceiversDirectly",
LogMessageType.BroadcastRecipientInvokedAfterTimeout, null, null, receiverInfo.DbgRemoteHost, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, false, this._dispatcher, this, false, receiverInfo,
invocationTarget, methodName,
"The broadcast invocation is being directed to the recipient, which did not respond during the first stage.");
}
// set destination MBR
this._iMessage.Properties["__Uri"] = receiverInfo.MbrUri;
transportHeaders[Message.TransportHeadersBroadcastObjRefOrCourt] = receiverInfo.SerializedObjRef;
ClientChannelSinkStack clientChannelSinkStack = new ClientChannelSinkStack(this);
clientChannelSinkStack.Push(this, null);
receiverInfo.IClientChannelSink.AsyncProcessRequest(clientChannelSinkStack, this._iMessage, transportHeaders, messageToBeSent);
}
}
}
this.UnrepliedReceivers.Remove(_uniqueReceiverName);
if (this.UnrepliedReceivers.Count <= 0)
this.AllMessagesReceived.Set();
}
}
#region -- IResponseProcessor --------------------------------------------------------------
/// <summary>
/// Processes the received response.
/// </summary>
/// <param name="message">The response.</param>
public void ProcessRespose(Message message)
{
// it's a response via the usual channel that the remote host successfully received a message via broadcast channel
// message.Sender - remote MBR uri
string objectUri = message.DestinationMarshalByRef as string;
if (objectUri == null)
return ;
lock(this._dispatcher)
{
ReceiverInfo receiverInfo = this._dispatcher.GetReceiverInfo(objectUri);
if (receiverInfo == null)
return ;
receiverInfo.NeedsBroadcastSimulation = false;
receiverInfo.NumberOfMulticastFails = 0;
}
// if time-out has expired
if (this.AllMessagesReceived.WaitOne(0, false))
return ;
try
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
object reply = binaryFormatter.Deserialize(message.Stream);
this.ParseResult(objectUri, reply as IMethodReturnMessage, reply as Exception);
}
catch(Exception ex)
{
this.ParseResult(objectUri, null, ex);
}
}
/// <summary>
/// An exception occurred during processing.
/// </summary>
/// <param name="exceptionAsObject">The exception.</param>
public void DispatchException(object exceptionAsObject)
{
// it's impossible to do something here because the target is unknown
}
/// <summary>
/// Indicates whether this message processor still waits for the response/responses.
/// </summary>
/// <param name="now">The current time elapsed since the system started.</param>
/// <returns>The true value if the message processor still waits for the response.</returns>
public bool IsExpired (int now)
{
return this.AllMessagesReceived.WaitOne(0, false);
}
/// <summary>
/// Gets the uri of the remote host which is expected to send a response.
/// </summary>
public HostInformation Remote
{
get
{
return null;
}
}
/// <summary>
/// Gets an indication whether the response processor does not require a separate thread for processing.
/// </summary>
public bool IsShortInProcessing
{
get
{
// deserialization & locking may take noticable time
return false;
}
}
/// <summary>
/// Gets the initial message for which the response is expected. Is used only for debugging purposes to track down
/// the source message.
/// </summary>
public Message Message
{
get
{
return null;
}
}
#endregion
#region -- IClientChannelSink --------------------------------------------------------------
/// <summary>
/// Gets a dictionary through which sink properties can be accessed.
/// </summary>
public IDictionary Properties
{
get
{
return null;
}
}
/// <summary>
/// Gets the next server channel sink in the server sink chain.
/// </summary>
public IClientChannelSink NextChannelSink
{
get
{
return null;
}
}
/// <summary>
/// Requests asynchronous processing of a method call on the current sink.
/// </summary>
/// <param name="sinkStack">A stack of channel sinks that called this sink.</param>
/// <param name="msg">The message to process.</param>
/// <param name="headers">The headers to add to the outgoing message heading to the server.</param>
/// <param name="stream">The stream headed to the transport sink.</param>
public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg,
ITransportHeaders headers, Stream stream)
{
return ;
}
/// <summary>
/// Requests asynchronous processing of a response to a method call on the current sink.
/// </summary>
/// <param name="sinkStack">A stack of sinks that called this sink.</param>
/// <param name="state">Information generated on the request side that is associated with this sink.</param>
/// <param name="headers">The headers retrieved from the server response stream.</param>
/// <param name="stream">The stream coming back from the transport sink.</param>
public void AsyncProcessResponse(IClientResponseChannelSinkStack sinkStack, object state,
ITransportHeaders headers, Stream stream)
{
IMethodReturnMessage iMethodReturnMessage = null;
string mbrUri = null;
// if time-out has expired
if (this.AllMessagesReceived.WaitOne(0, false))
return ;
try
{
mbrUri = (string) headers[Message.TransportHeadersMbrUriName];
BinaryFormatter binaryFormatter = new BinaryFormatter();
iMethodReturnMessage = (IMethodReturnMessage) binaryFormatter.Deserialize(stream);
this.ParseResult(mbrUri, iMethodReturnMessage, null);
}
catch(Exception ex)
{
if (mbrUri != null)
this.ParseResult(mbrUri, null, ex);
}
}
/// <summary>
/// Returns the Stream onto which the provided message is to be serialized.
/// </summary>
/// <param name="msg">The IMethodCallMessage containing details about the method call.</param>
/// <param name="headers">The headers to add to the outgoing message heading to the server.</param>
/// <returns>The Stream onto which the provided message is to be serialized.</returns>
public Stream GetRequestStream(IMessage msg, ITransportHeaders headers)
{
return null;
}
/// <summary>
/// Requests message processing from the current sink.
/// </summary>
/// <param name="msg">The message to process.</param>
/// <param name="requestHeaders">The headers to add to the outgoing message heading to the server.</param>
/// <param name="requestStream">The stream headed to the transport sink.</param>
/// <param name="responseHeaders">When this method returns, contains an ITransportHeaders interface that holds the headers that the server returned. This parameter is passed uninitialized.</param>
/// <param name="responseStream">When this method returns, contains a Stream coming back from the transport sink. This parameter is passed uninitialized.</param>
public void ProcessMessage(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream,
out ITransportHeaders responseHeaders, out Stream responseStream)
{
responseHeaders = null;
responseStream = null;
}
#endregion
#region -- IMessageSink --------------------------------------------------------------------
/// <summary>
/// Gets the next message sink in the sink chain.
/// </summary>
public IMessageSink NextSink
{
get
{
return null;
}
}
/// <summary>
/// Asynchronously processes the given message.
/// </summary>
/// <param name="msg">The message to process.</param>
/// <param name="replySink">The reply sink for the reply message.</param>
/// <returns>Returns an IMessageCtrl interface that provides a way to control asynchronous messages after they have been dispatched.</returns>
public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
{
return null;
}
/// <summary>
/// Synchronously processes the given message.
/// </summary>
/// <param name="msg">The message to process.</param>
/// <returns>A reply message in response to the request.</returns>
public IMessage SyncProcessMessage(IMessage msg)
{
return null;
}
#endregion
#region -- Debugging stuff -----------------------------------------------------------------
/// <summary>
/// Gets the unique identifier of the current instance. Is used for debugging purposes only.
/// </summary>
public int DbgResultCollectorId
{
get
{
return this._dbgResultCollectorId;
}
}
private int _dbgResultCollectorId = Interlocked.Increment(ref _dbgTotalResultCollectors);
private static int _dbgTotalResultCollectors = 0;
#endregion
}
}
| |
// 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="WebpageViewServiceClient"/> instances.</summary>
public sealed partial class WebpageViewServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="WebpageViewServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="WebpageViewServiceSettings"/>.</returns>
public static WebpageViewServiceSettings GetDefault() => new WebpageViewServiceSettings();
/// <summary>Constructs a new <see cref="WebpageViewServiceSettings"/> object with default settings.</summary>
public WebpageViewServiceSettings()
{
}
private WebpageViewServiceSettings(WebpageViewServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetWebpageViewSettings = existing.GetWebpageViewSettings;
OnCopy(existing);
}
partial void OnCopy(WebpageViewServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>WebpageViewServiceClient.GetWebpageView</c> and <c>WebpageViewServiceClient.GetWebpageViewAsync</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 GetWebpageViewSettings { 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="WebpageViewServiceSettings"/> object.</returns>
public WebpageViewServiceSettings Clone() => new WebpageViewServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="WebpageViewServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class WebpageViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<WebpageViewServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public WebpageViewServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public WebpageViewServiceClientBuilder()
{
UseJwtAccessWithScopes = WebpageViewServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref WebpageViewServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<WebpageViewServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override WebpageViewServiceClient Build()
{
WebpageViewServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<WebpageViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<WebpageViewServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private WebpageViewServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return WebpageViewServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<WebpageViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return WebpageViewServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => WebpageViewServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => WebpageViewServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => WebpageViewServiceClient.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>WebpageViewService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage webpage views.
/// </remarks>
public abstract partial class WebpageViewServiceClient
{
/// <summary>
/// The default endpoint for the WebpageViewService 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 WebpageViewService scopes.</summary>
/// <remarks>
/// The default WebpageViewService 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="WebpageViewServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="WebpageViewServiceClientBuilder"/>
/// .
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="WebpageViewServiceClient"/>.</returns>
public static stt::Task<WebpageViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new WebpageViewServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="WebpageViewServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="WebpageViewServiceClientBuilder"/>
/// .
/// </summary>
/// <returns>The created <see cref="WebpageViewServiceClient"/>.</returns>
public static WebpageViewServiceClient Create() => new WebpageViewServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="WebpageViewServiceClient"/> 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="WebpageViewServiceSettings"/>.</param>
/// <returns>The created <see cref="WebpageViewServiceClient"/>.</returns>
internal static WebpageViewServiceClient Create(grpccore::CallInvoker callInvoker, WebpageViewServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
WebpageViewService.WebpageViewServiceClient grpcClient = new WebpageViewService.WebpageViewServiceClient(callInvoker);
return new WebpageViewServiceClientImpl(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 WebpageViewService client</summary>
public virtual WebpageViewService.WebpageViewServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested webpage view in full detail.
/// </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::WebpageView GetWebpageView(GetWebpageViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested webpage view in full detail.
/// </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::WebpageView> GetWebpageViewAsync(GetWebpageViewRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested webpage view in full detail.
/// </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::WebpageView> GetWebpageViewAsync(GetWebpageViewRequest request, st::CancellationToken cancellationToken) =>
GetWebpageViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested webpage view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the webpage view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::WebpageView GetWebpageView(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetWebpageView(new GetWebpageViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested webpage view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the webpage view 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::WebpageView> GetWebpageViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetWebpageViewAsync(new GetWebpageViewRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested webpage view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the webpage view 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::WebpageView> GetWebpageViewAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetWebpageViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested webpage view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the webpage view to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::WebpageView GetWebpageView(gagvr::WebpageViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetWebpageView(new GetWebpageViewRequest
{
ResourceNameAsWebpageViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested webpage view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the webpage view 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::WebpageView> GetWebpageViewAsync(gagvr::WebpageViewName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetWebpageViewAsync(new GetWebpageViewRequest
{
ResourceNameAsWebpageViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested webpage view in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the webpage view 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::WebpageView> GetWebpageViewAsync(gagvr::WebpageViewName resourceName, st::CancellationToken cancellationToken) =>
GetWebpageViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>WebpageViewService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage webpage views.
/// </remarks>
public sealed partial class WebpageViewServiceClientImpl : WebpageViewServiceClient
{
private readonly gaxgrpc::ApiCall<GetWebpageViewRequest, gagvr::WebpageView> _callGetWebpageView;
/// <summary>
/// Constructs a client wrapper for the WebpageViewService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="WebpageViewServiceSettings"/> used within this client.</param>
public WebpageViewServiceClientImpl(WebpageViewService.WebpageViewServiceClient grpcClient, WebpageViewServiceSettings settings)
{
GrpcClient = grpcClient;
WebpageViewServiceSettings effectiveSettings = settings ?? WebpageViewServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetWebpageView = clientHelper.BuildApiCall<GetWebpageViewRequest, gagvr::WebpageView>(grpcClient.GetWebpageViewAsync, grpcClient.GetWebpageView, effectiveSettings.GetWebpageViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetWebpageView);
Modify_GetWebpageViewApiCall(ref _callGetWebpageView);
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_GetWebpageViewApiCall(ref gaxgrpc::ApiCall<GetWebpageViewRequest, gagvr::WebpageView> call);
partial void OnConstruction(WebpageViewService.WebpageViewServiceClient grpcClient, WebpageViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC WebpageViewService client</summary>
public override WebpageViewService.WebpageViewServiceClient GrpcClient { get; }
partial void Modify_GetWebpageViewRequest(ref GetWebpageViewRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested webpage view in full detail.
/// </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::WebpageView GetWebpageView(GetWebpageViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetWebpageViewRequest(ref request, ref callSettings);
return _callGetWebpageView.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested webpage view in full detail.
/// </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::WebpageView> GetWebpageViewAsync(GetWebpageViewRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetWebpageViewRequest(ref request, ref callSettings);
return _callGetWebpageView.Async(request, callSettings);
}
}
}
| |
#region Header
//
// CmdNewExtrusionRoof.cs - create a strangely stair shaped new extrusion roof
//
// Copyright (C) 2014-2021 by Jeremy Tammik,
// Autodesk Inc. All rights reserved.
//
// Keywords: The Building Coder Revit API C# .NET add-in.
//
#endregion // Header
#region Namespaces
using System;
using System.Diagnostics;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
#endregion // Namespaces
namespace BuildingCoder
{
[Transaction(TransactionMode.Manual)]
internal class CmdNewExtrusionRoof : IExternalCommand
{
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
var uiapp = commandData.Application;
var uidoc = uiapp.ActiveUIDocument;
var doc = uidoc.Document;
using var tx = new Transaction(doc);
tx.Start("NewExtrusionRoof");
var fs
= new FilteredElementCollector(doc)
.OfClass(typeof(RoofType))
.Cast<RoofType>()
.FirstOrDefault(a => null != a);
var lvl
= new FilteredElementCollector(doc)
.OfClass(typeof(Level))
.Cast<Level>()
.FirstOrDefault(a => null != a);
double x = 1;
var origin = new XYZ(x, 0, 0);
var vx = XYZ.BasisY;
var vy = XYZ.BasisZ;
var sp = SketchPlane.Create(doc,
//new Autodesk.Revit.DB.Plane( vx, vy, origin ) // 2016
Plane.CreateByOriginAndBasis(origin, vx, vy)); // 2017
//Plane.CreateByOriginAndBasis( origin, vy, vx ) ); // 2019
var ca = new CurveArray();
// This stair shape causes NewExtrusionRoof to
// throw an exception in Revit 2019.1.
var pts = new[]
{
new(x, 1, 0),
new XYZ(x, 1, 1),
new XYZ(x, 2, 1),
new XYZ(x, 2, 2),
new XYZ(x, 3, 2),
new XYZ(x, 3, 3),
new XYZ(x, 4, 3),
new XYZ(x, 4, 4)
};
// Try a simple and closed rectangular shape.
// This throws an invalid operation exception
// saying "Invalid profile."
pts = new[]
{
new(x, 1, 0),
new XYZ(x, 1, 1),
new XYZ(x, 2, 1),
new XYZ(x, 2, 0)
};
var n = pts.Length;
for (var i = 1; i < n; ++i)
ca.Append(Line.CreateBound(
pts[i - 1], pts[i]));
ca.Append(Line.CreateBound(
pts[n - 1], pts[0]));
doc.Create.NewModelCurveArray(ca, sp);
var v = doc.ActiveView;
var rp
= doc.Create.NewReferencePlane2(
origin, origin + vx, origin + vy, v);
rp.Name = "MyRoofPlane";
var er
= doc.Create.NewExtrusionRoof(
ca, rp, lvl, fs, 0, 3);
Debug.Print($"Extrusion roof element id: {er.Id}");
tx.Commit();
return Result.Succeeded;
}
#region Revit Online Help sample code from the section on Roofs
private void f(Document doc)
{
// Before invoking this sample, select some walls
// to add a roof over. Make sure there is a level
// named "Roof" in the document.
var level
= new FilteredElementCollector(doc)
.OfClass(typeof(Level))
.Where(e =>
!string.IsNullOrEmpty(e.Name)
&& e.Name.Equals("Roof"))
.FirstOrDefault() as Level;
var roofType
= new FilteredElementCollector(doc)
.OfClass(typeof(RoofType))
.FirstOrDefault() as RoofType;
// Get the handle of the application
var application = doc.Application;
// Define the footprint for the roof based on user selection
var footprint = application.Create
.NewCurveArray();
var uidoc = new UIDocument(doc);
var selectedIds
= uidoc.Selection.GetElementIds();
if (selectedIds.Count != 0)
foreach (var id in selectedIds)
{
var element = doc.GetElement(id);
switch (element)
{
case Wall wall:
{
var wallCurve = wall.Location as LocationCurve;
footprint.Append(wallCurve.Curve);
continue;
}
case ModelCurve modelCurve:
footprint.Append(modelCurve.GeometryCurve);
break;
}
}
else
throw new Exception(
"Please select a curve loop, wall loop or "
+ "combination of walls and curves to "
+ "create a footprint roof.");
var footPrintToModelCurveMapping
= new ModelCurveArray();
var footprintRoof
= doc.Create.NewFootPrintRoof(
footprint, level, roofType,
out footPrintToModelCurveMapping);
var iterator
= footPrintToModelCurveMapping.ForwardIterator();
iterator.Reset();
while (iterator.MoveNext())
{
var modelCurve = iterator.Current as ModelCurve;
footprintRoof.set_DefinesSlope(modelCurve, true);
footprintRoof.set_SlopeAngle(modelCurve, 0.5);
}
}
#endregion // Revit Online Help sample code from the section on Roofs
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>SmartCampaignSetting</c> resource.</summary>
public sealed partial class SmartCampaignSettingName : gax::IResourceName, sys::IEquatable<SmartCampaignSettingName>
{
/// <summary>The possible contents of <see cref="SmartCampaignSettingName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>.
/// </summary>
CustomerCampaign = 1,
}
private static gax::PathTemplate s_customerCampaign = new gax::PathTemplate("customers/{customer_id}/smartCampaignSettings/{campaign_id}");
/// <summary>Creates a <see cref="SmartCampaignSettingName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="SmartCampaignSettingName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static SmartCampaignSettingName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SmartCampaignSettingName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SmartCampaignSettingName"/> with the pattern
/// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// A new instance of <see cref="SmartCampaignSettingName"/> constructed from the provided ids.
/// </returns>
public static SmartCampaignSettingName FromCustomerCampaign(string customerId, string campaignId) =>
new SmartCampaignSettingName(ResourceNameType.CustomerCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SmartCampaignSettingName"/> with pattern
/// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SmartCampaignSettingName"/> with pattern
/// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>.
/// </returns>
public static string Format(string customerId, string campaignId) => FormatCustomerCampaign(customerId, campaignId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SmartCampaignSettingName"/> with pattern
/// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SmartCampaignSettingName"/> with pattern
/// <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>.
/// </returns>
public static string FormatCustomerCampaign(string customerId, string campaignId) =>
s_customerCampaign.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="SmartCampaignSettingName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="smartCampaignSettingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SmartCampaignSettingName"/> if successful.</returns>
public static SmartCampaignSettingName Parse(string smartCampaignSettingName) =>
Parse(smartCampaignSettingName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SmartCampaignSettingName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="smartCampaignSettingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="SmartCampaignSettingName"/> if successful.</returns>
public static SmartCampaignSettingName Parse(string smartCampaignSettingName, bool allowUnparsed) =>
TryParse(smartCampaignSettingName, allowUnparsed, out SmartCampaignSettingName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SmartCampaignSettingName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="smartCampaignSettingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SmartCampaignSettingName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string smartCampaignSettingName, out SmartCampaignSettingName result) =>
TryParse(smartCampaignSettingName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SmartCampaignSettingName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="smartCampaignSettingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SmartCampaignSettingName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string smartCampaignSettingName, bool allowUnparsed, out SmartCampaignSettingName result)
{
gax::GaxPreconditions.CheckNotNull(smartCampaignSettingName, nameof(smartCampaignSettingName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaign.TryParseName(smartCampaignSettingName, out resourceName))
{
result = FromCustomerCampaign(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(smartCampaignSettingName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SmartCampaignSettingName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SmartCampaignSettingName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/smartCampaignSettings/{campaign_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
public SmartCampaignSettingName(string customerId, string campaignId) : this(ResourceNameType.CustomerCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCampaign: return s_customerCampaign.Expand(CustomerId, CampaignId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as SmartCampaignSettingName);
/// <inheritdoc/>
public bool Equals(SmartCampaignSettingName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SmartCampaignSettingName a, SmartCampaignSettingName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SmartCampaignSettingName a, SmartCampaignSettingName b) => !(a == b);
}
public partial class SmartCampaignSetting
{
/// <summary>
/// <see cref="SmartCampaignSettingName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal SmartCampaignSettingName ResourceNameAsSmartCampaignSettingName
{
get => string.IsNullOrEmpty(ResourceName) ? null : SmartCampaignSettingName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
}
}
| |
#region Copyright
//
// Copyright (c) 2015
// by Satrabel
//
#endregion
#region Using Statements
using System;
using System.Linq;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Common;
using DotNetNuke.Framework.JavaScriptLibraries;
using DotNetNuke.Framework;
using System.Web.UI.WebControls;
using DotNetNuke.Services.Localization;
using System.IO;
using Satrabel.OpenContent.Components;
using Newtonsoft.Json.Linq;
using System.Globalization;
using DotNetNuke.Common.Utilities;
using Satrabel.OpenContent.Components.Json;
using Satrabel.OpenContent.Components.Manifest;
using Satrabel.OpenContent.Components.Lucene.Config;
using Satrabel.OpenContent.Components.Datasource;
#endregion
namespace Satrabel.OpenContent
{
public partial class EditData : PortalModuleBase
{
private const string cData = "Data";
private const string cSettings = "Settings";
private const string cFilter = "Filter";
#region Event Handlers
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
cmdSave.Click += cmdSave_Click;
cmdCancel.Click += cmdCancel_Click;
cmdImport.Click += cmdImport_Click;
//ServicesFramework.Instance.RequestAjaxScriptSupport();
//ServicesFramework.Instance.RequestAjaxAntiForgerySupport();
sourceList.SelectedIndexChanged += sourceList_SelectedIndexChanged;
ddlVersions.SelectedIndexChanged += ddlVersions_SelectedIndexChanged;
}
private void cmdImport_Click(object sender, EventArgs e)
{
OpenContentSettings settings = this.OpenContentSettings();
switch (sourceList.SelectedValue)
{
case cData:
{
txtSource.Text = File.ReadAllText(settings.TemplateDir.PhysicalFullDirectory + "\\data.json");
}
break;
}
}
private void ddlVersions_SelectedIndexChanged(object sender, EventArgs e)
{
OpenContentSettings settings = this.OpenContentSettings();
int ModId = settings.IsOtherModule ? settings.ModuleId : ModuleId;
var ds = DataSourceManager.GetDataSource("OpenContent");
var dsContext = new DataSourceContext()
{
ModuleId = ModId,
TemplateFolder = settings.TemplateDir.FolderPath,
Single = true
};
var dsItem = ds.Get(dsContext, null);
if (dsItem != null)
{
var ticks = long.Parse(ddlVersions.SelectedValue);
var ver = ds.GetVersion(dsContext, dsItem, new DateTime(ticks));
//var ver = data.Versions.Single(v => v.CreatedOnDate == d);
txtSource.Text = ver.ToString();
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsPostBack)
{
InitEditor();
}
}
private void InitEditor()
{
LoadFiles();
DisplayFile(cData);
}
private void DisplayFile(string selectedDataType)
{
cmdImport.Visible = false;
string json = string.Empty;
switch (selectedDataType)
{
case cData:
{
TemplateManifest template = null;
OpenContentSettings settings = this.OpenContentSettings();
int ModId = settings.IsOtherModule ? settings.ModuleId : ModuleId;
if (settings.TemplateAvailable)
{
template = settings.Template;
}
var ds = DataSourceManager.GetDataSource(settings.Manifest.DataSource);
var dsContext = new DataSourceContext()
{
ModuleId = ModId,
TemplateFolder = settings.TemplateDir.FolderPath,
Config = settings.Manifest.DataSourceConfig
};
if (template != null && template.IsListTemplate)
{
string itemId = Request.QueryString["id"];
if (!string.IsNullOrEmpty(itemId))
{
var dsItem = ds.Get(dsContext, itemId);
if (dsItem != null)
{
json = dsItem.Data.ToString();
var versions = ds.GetVersions(dsContext, dsItem);
if (versions != null)
foreach (var ver in versions)
{
ddlVersions.Items.Add(new ListItem()
{
//Text = ver.CreatedOnDate.ToShortDateString() + " " + ver.CreatedOnDate.ToShortTimeString(),
//Value = ver.CreatedOnDate.Ticks.ToString()
Text = ver["text"].ToString(),
Value = ver["ticks"].ToString()
});
}
}
}
else
{
var dataList = ds.GetAll(dsContext, null);
if (dataList != null)
{
JArray lst = new JArray();
foreach (var item in dataList.Items)
{
lst.Add(item.Data);
}
json = lst.ToString();
}
}
}
else
{
dsContext.Single = true;
var dsItem = ds.Get(dsContext, null);
if (dsItem != null)
{
json = dsItem.Data.ToString();
var versions = ds.GetVersions(dsContext, dsItem);
if (versions != null)
foreach (var ver in versions)
{
ddlVersions.Items.Add(new ListItem()
{
//Text = ver.CreatedOnDate.ToShortDateString() + " " + ver.CreatedOnDate.ToShortTimeString(),
//Value = ver.CreatedOnDate.Ticks.ToString()
Text = ver["text"].ToString(),
Value = ver["ticks"].ToString()
});
}
}
}
cmdImport.Visible = string.IsNullOrEmpty(json) && File.Exists(settings.TemplateDir.PhysicalFullDirectory + "\\data.json");
}
break;
case cSettings:
json = ModuleContext.Settings["data"] as string;
break;
case cFilter:
json = ModuleContext.Settings["query"] as string;
break;
default:
{
OpenContentSettings settings = this.OpenContentSettings();
int ModId = settings.IsOtherModule ? settings.ModuleId : ModuleId;
var manifest = settings.Manifest;
string key = selectedDataType;
var dataManifest = manifest.AdditionalData[key];
string scope = AdditionalDataUtils.GetScope(dataManifest, PortalSettings.PortalId, PortalSettings.ActiveTab.TabID, ModId, this.TabModuleId);
var dc = new AdditionalDataController();
var data = dc.GetData(scope, dataManifest.StorageKey ?? key);
json = data == null ? "" : data.Json;
break;
}
}
txtSource.Text = json;
}
private void LoadFiles()
{
TemplateManifest template = ModuleContext.OpenContentSettings().Template;
sourceList.Items.Clear();
sourceList.Items.Add(new ListItem(cData, cData));
sourceList.Items.Add(new ListItem(cSettings, cSettings));
sourceList.Items.Add(new ListItem(cFilter, cFilter));
if (template.Manifest.AdditionalData != null)
{
foreach (var addData in template.Manifest.AdditionalData)
{
string title = string.IsNullOrEmpty(addData.Value.Title) ? addData.Key : addData.Value.Title;
sourceList.Items.Add(new ListItem(title, addData.Key));
}
}
}
protected void cmdSave_Click(object sender, EventArgs e)
{
if (sourceList.SelectedValue == cData)
{
SaveData();
}
else if (sourceList.SelectedValue == cSettings)
{
SaveSettings();
}
else if (sourceList.SelectedValue == cFilter)
{
SaveFilter();
}
else
{
SaveAdditionalData(sourceList.SelectedValue);
}
Response.Redirect(Globals.NavigateURL(), true);
}
private void SaveAdditionalData(string key)
{
OpenContentSettings settings = this.OpenContentSettings();
int ModId = settings.IsOtherModule ? settings.ModuleId : ModuleId;
var manifest = settings.Manifest;
var dataManifest = manifest.AdditionalData[key];
string scope = AdditionalDataUtils.GetScope(dataManifest, PortalSettings.PortalId, PortalSettings.ActiveTab.TabID, ModId, this.TabModuleId);
var dc = new AdditionalDataController();
var data = dc.GetData(scope, dataManifest.StorageKey ?? key);
if (data == null)
{
data = new AdditionalDataInfo()
{
CreatedByUserId = UserId,
CreatedOnDate = DateTime.Now,
DataKey = key,
Json = txtSource.Text,
LastModifiedByUserId = UserId,
LastModifiedOnDate = DateTime.Now,
Scope = scope
};
dc.AddData(data);
}
else
{
data.Json = txtSource.Text;
data.LastModifiedByUserId = UserId;
data.LastModifiedOnDate = DateTime.Now;
dc.UpdateData(data);
}
}
private void SaveFilter()
{
ModuleController mc = new ModuleController();
if (!string.IsNullOrEmpty(txtSource.Text))
mc.UpdateModuleSetting(ModuleId, "query", txtSource.Text);
}
private void SaveData()
{
TemplateManifest template = null;
OpenContentSettings settings = this.OpenContentSettings();
int ModId = settings.IsOtherModule ? settings.ModuleId : ModuleId;
bool index = false;
if (settings.TemplateAvailable)
{
template = settings.Template;
index = settings.Template.Manifest.Index;
}
/*
FieldConfig indexConfig = null;
if (index)
{
indexConfig = OpenContentUtils.GetIndexConfig(settings.Template.Key.TemplateDir);
}
*/
var ds = DataSourceManager.GetDataSource(settings.Manifest.DataSource);
var dsContext = new DataSourceContext()
{
ModuleId = ModId,
TemplateFolder = settings.TemplateDir.FolderPath,
Index = index,
UserId = UserInfo.UserID,
Config = settings.Manifest.DataSourceConfig
};
if (template != null && template.IsListTemplate)
{
string itemId = Request.QueryString["id"];
if (!string.IsNullOrEmpty(itemId))
{
var dsItem = ds.Get(dsContext, itemId);
if (string.IsNullOrEmpty(txtSource.Text))
{
if (dsItem != null)
{
ds.Delete(dsContext, dsItem);
}
}
else
{
var json = txtSource.Text.ToJObject("Saving txtSource");
if (dsItem == null)
{
ds.Add(dsContext, json);
}
else
{
ds.Update(dsContext, dsItem, json);
}
if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.String)
{
string ModuleTitle = json["ModuleTitle"].ToString();
OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
}
else if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.Object)
{
string ModuleTitle = json["ModuleTitle"][DnnUtils.GetCurrentCultureCode()].ToString();
OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
}
}
}
else
{
JArray lst = null;
if (!string.IsNullOrEmpty(txtSource.Text))
{
lst = JArray.Parse(txtSource.Text);
}
var dataList = ds.GetAll(dsContext, null).Items;
foreach (var item in dataList)
{
ds.Delete(dsContext, item);
}
if (lst != null)
{
foreach (JObject json in lst)
{
ds.Add(dsContext, json);
}
}
}
}
else
{
dsContext.Single = true;
var dsItem = ds.Get(dsContext, null);
if (string.IsNullOrEmpty(txtSource.Text))
{
if (dsItem != null)
{
ds.Delete(dsContext, dsItem);
}
}
else
{
var json = txtSource.Text.ToJObject("Saving txtSource");
if (dsItem == null)
{
ds.Add(dsContext, json);
}
else
{
ds.Update(dsContext, dsItem, json);
}
if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.String)
{
string ModuleTitle = json["ModuleTitle"].ToString();
OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
}
else if (json["ModuleTitle"] != null && json["ModuleTitle"].Type == JTokenType.Object)
{
string ModuleTitle = json["ModuleTitle"][DnnUtils.GetCurrentCultureCode()].ToString();
OpenContentUtils.UpdateModuleTitle(ModuleContext.Configuration, ModuleTitle);
}
}
}
}
private void SaveSettings()
{
ModuleController mc = new ModuleController();
if (string.IsNullOrEmpty(txtSource.Text))
mc.DeleteModuleSetting(ModuleId, "data");
else
mc.UpdateModuleSetting(ModuleId, "data", txtSource.Text);
}
protected void cmdCancel_Click(object sender, EventArgs e)
{
Response.Redirect(Globals.NavigateURL(), true);
}
private void sourceList_SelectedIndexChanged(object sender, EventArgs e)
{
phVersions.Visible = sourceList.SelectedValue == cData;
DisplayFile(sourceList.SelectedValue);
}
#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.Drawing.Imaging
{
/// <summary>
/// Specifies the methods available in a metafile to read and write graphic commands.
/// </summary>
public enum EmfPlusRecordType
{
WmfRecordBase = 0x00010000,
WmfSetBkColor = WmfRecordBase | 0x201,
WmfSetBkMode = WmfRecordBase | 0x102,
WmfSetMapMode = WmfRecordBase | 0x103,
WmfSetROP2 = WmfRecordBase | 0x104,
WmfSetRelAbs = WmfRecordBase | 0x105,
WmfSetPolyFillMode = WmfRecordBase | 0x106,
WmfSetStretchBltMode = WmfRecordBase | 0x107,
WmfSetTextCharExtra = WmfRecordBase | 0x108,
WmfSetTextColor = WmfRecordBase | 0x209,
WmfSetTextJustification = WmfRecordBase | 0x20A,
WmfSetWindowOrg = WmfRecordBase | 0x20B,
WmfSetWindowExt = WmfRecordBase | 0x20C,
WmfSetViewportOrg = WmfRecordBase | 0x20D,
WmfSetViewportExt = WmfRecordBase | 0x20E,
WmfOffsetWindowOrg = WmfRecordBase | 0x20F,
WmfScaleWindowExt = WmfRecordBase | 0x410,
WmfOffsetViewportOrg = WmfRecordBase | 0x211,
WmfScaleViewportExt = WmfRecordBase | 0x412,
WmfLineTo = WmfRecordBase | 0x213,
WmfMoveTo = WmfRecordBase | 0x214,
WmfExcludeClipRect = WmfRecordBase | 0x415,
WmfIntersectClipRect = WmfRecordBase | 0x416,
WmfArc = WmfRecordBase | 0x817,
WmfEllipse = WmfRecordBase | 0x418,
WmfFloodFill = WmfRecordBase | 0x419,
WmfPie = WmfRecordBase | 0x81A,
WmfRectangle = WmfRecordBase | 0x41B,
WmfRoundRect = WmfRecordBase | 0x61C,
WmfPatBlt = WmfRecordBase | 0x61D,
WmfSaveDC = WmfRecordBase | 0x01E,
WmfSetPixel = WmfRecordBase | 0x41F,
WmfOffsetCilpRgn = WmfRecordBase | 0x220,
WmfTextOut = WmfRecordBase | 0x521,
WmfBitBlt = WmfRecordBase | 0x922,
WmfStretchBlt = WmfRecordBase | 0xB23,
WmfPolygon = WmfRecordBase | 0x324,
WmfPolyline = WmfRecordBase | 0x325,
WmfEscape = WmfRecordBase | 0x626,
WmfRestoreDC = WmfRecordBase | 0x127,
WmfFillRegion = WmfRecordBase | 0x228,
WmfFrameRegion = WmfRecordBase | 0x429,
WmfInvertRegion = WmfRecordBase | 0x12A,
WmfPaintRegion = WmfRecordBase | 0x12B,
WmfSelectClipRegion = WmfRecordBase | 0x12C,
WmfSelectObject = WmfRecordBase | 0x12D,
WmfSetTextAlign = WmfRecordBase | 0x12E,
WmfChord = WmfRecordBase | 0x830,
WmfSetMapperFlags = WmfRecordBase | 0x231,
WmfExtTextOut = WmfRecordBase | 0xA32,
WmfSetDibToDev = WmfRecordBase | 0xD33,
WmfSelectPalette = WmfRecordBase | 0x234,
WmfRealizePalette = WmfRecordBase | 0x035,
WmfAnimatePalette = WmfRecordBase | 0x436,
WmfSetPalEntries = WmfRecordBase | 0x037,
WmfPolyPolygon = WmfRecordBase | 0x538,
WmfResizePalette = WmfRecordBase | 0x139,
WmfDibBitBlt = WmfRecordBase | 0x940,
WmfDibStretchBlt = WmfRecordBase | 0xb41,
WmfDibCreatePatternBrush = WmfRecordBase | 0x142,
WmfStretchDib = WmfRecordBase | 0xf43,
WmfExtFloodFill = WmfRecordBase | 0x548,
WmfSetLayout = WmfRecordBase | 0x149, // META_SETLAYOUT
WmfDeleteObject = WmfRecordBase | 0x1f0,
WmfCreatePalette = WmfRecordBase | 0x0f7,
WmfCreatePatternBrush = WmfRecordBase | 0x1f9,
WmfCreatePenIndirect = WmfRecordBase | 0x2fa,
WmfCreateFontIndirect = WmfRecordBase | 0x2fb,
WmfCreateBrushIndirect = WmfRecordBase | 0x2fc,
WmfCreateRegion = WmfRecordBase | 0x6ff,
// Since we have to enumerate GDI records right along with GDI+ records,
// we list all the GDI records here so that they can be part of the
// same enumeration type which is used in the enumeration callback.
EmfHeader = 1,
EmfPolyBezier = 2,
EmfPolygon = 3,
EmfPolyline = 4,
EmfPolyBezierTo = 5,
EmfPolyLineTo = 6,
EmfPolyPolyline = 7,
EmfPolyPolygon = 8,
EmfSetWindowExtEx = 9,
EmfSetWindowOrgEx = 10,
EmfSetViewportExtEx = 11,
EmfSetViewportOrgEx = 12,
EmfSetBrushOrgEx = 13,
EmfEof = 14,
EmfSetPixelV = 15,
EmfSetMapperFlags = 16,
EmfSetMapMode = 17,
EmfSetBkMode = 18,
EmfSetPolyFillMode = 19,
EmfSetROP2 = 20,
EmfSetStretchBltMode = 21,
EmfSetTextAlign = 22,
EmfSetColorAdjustment = 23,
EmfSetTextColor = 24,
EmfSetBkColor = 25,
EmfOffsetClipRgn = 26,
EmfMoveToEx = 27,
EmfSetMetaRgn = 28,
EmfExcludeClipRect = 29,
EmfIntersectClipRect = 30,
EmfScaleViewportExtEx = 31,
EmfScaleWindowExtEx = 32,
EmfSaveDC = 33,
EmfRestoreDC = 34,
EmfSetWorldTransform = 35,
EmfModifyWorldTransform = 36,
EmfSelectObject = 37,
EmfCreatePen = 38,
EmfCreateBrushIndirect = 39,
EmfDeleteObject = 40,
EmfAngleArc = 41,
EmfEllipse = 42,
EmfRectangle = 43,
EmfRoundRect = 44,
EmfRoundArc = 45,
EmfChord = 46,
EmfPie = 47,
EmfSelectPalette = 48,
EmfCreatePalette = 49,
EmfSetPaletteEntries = 50,
EmfResizePalette = 51,
EmfRealizePalette = 52,
EmfExtFloodFill = 53,
EmfLineTo = 54,
EmfArcTo = 55,
EmfPolyDraw = 56,
EmfSetArcDirection = 57,
EmfSetMiterLimit = 58,
EmfBeginPath = 59,
EmfEndPath = 60,
EmfCloseFigure = 61,
EmfFillPath = 62,
EmfStrokeAndFillPath = 63,
EmfStrokePath = 64,
EmfFlattenPath = 65,
EmfWidenPath = 66,
EmfSelectClipPath = 67,
EmfAbortPath = 68,
EmfReserved069 = 69,
EmfGdiComment = 70,
EmfFillRgn = 71,
EmfFrameRgn = 72,
EmfInvertRgn = 73,
EmfPaintRgn = 74,
EmfExtSelectClipRgn = 75,
EmfBitBlt = 76,
EmfStretchBlt = 77,
EmfMaskBlt = 78,
EmfPlgBlt = 79,
EmfSetDIBitsToDevice = 80,
EmfStretchDIBits = 81,
EmfExtCreateFontIndirect = 82,
EmfExtTextOutA = 83,
EmfExtTextOutW = 84,
EmfPolyBezier16 = 85,
EmfPolygon16 = 86,
EmfPolyline16 = 87,
EmfPolyBezierTo16 = 88,
EmfPolylineTo16 = 89,
EmfPolyPolyline16 = 90,
EmfPolyPolygon16 = 91,
EmfPolyDraw16 = 92,
EmfCreateMonoBrush = 93,
EmfCreateDibPatternBrushPt = 94,
EmfExtCreatePen = 95,
EmfPolyTextOutA = 96,
EmfPolyTextOutW = 97,
EmfSetIcmMode = 98, // EMR_SETICMMODE,
EmfCreateColorSpace = 99, // EMR_CREATECOLORSPACE,
EmfSetColorSpace = 100, // EMR_SETCOLORSPACE,
EmfDeleteColorSpace = 101, // EMR_DELETECOLORSPACE,
EmfGlsRecord = 102, // EMR_GLSRECORD,
EmfGlsBoundedRecord = 103, // EMR_GLSBOUNDEDRECORD,
EmfPixelFormat = 104, // EMR_PIXELFORMAT,
EmfDrawEscape = 105, // EMR_RESERVED_105,
EmfExtEscape = 106, // EMR_RESERVED_106,
EmfStartDoc = 107, // EMR_RESERVED_107,
EmfSmallTextOut = 108, // EMR_RESERVED_108,
EmfForceUfiMapping = 109, // EMR_RESERVED_109,
EmfNamedEscpae = 110, // EMR_RESERVED_110,
EmfColorCorrectPalette = 111, // EMR_COLORCORRECTPALETTE,
EmfSetIcmProfileA = 112, // EMR_SETICMPROFILEA,
EmfSetIcmProfileW = 113, // EMR_SETICMPROFILEW,
EmfAlphaBlend = 114, // EMR_ALPHABLEND,
EmfSetLayout = 115, // EMR_SETLAYOUT,
EmfTransparentBlt = 116, // EMR_TRANSPARENTBLT,
EmfReserved117 = 117,
EmfGradientFill = 118, // EMR_GRADIENTFILL,
EmfSetLinkedUfis = 119, // EMR_RESERVED_119,
EmfSetTextJustification = 120, // EMR_RESERVED_120,
EmfColorMatchToTargetW = 121, // EMR_COLORMATCHTOTARGETW,
EmfCreateColorSpaceW = 122, // EMR_CREATECOLORSPACEW,
EmfMax = 122,
EmfMin = 1,
// That is the END of the GDI EMF records.
// Now we start the list of EMF+ records. We leave quite
// a bit of room here for the addition of any new GDI
// records that may be added later.
EmfPlusRecordBase = 0x00004000,
Invalid = EmfPlusRecordBase,
Header,
EndOfFile,
Comment,
GetDC, // the application grabbed the metafile dc
MultiFormatStart,
MultiFormatSection,
MultiFormatEnd,
// For all Persistent Objects
Object,
// Drawing Records
Clear,
FillRects,
DrawRects,
FillPolygon,
DrawLines,
FillEllipse,
DrawEllipse,
FillPie,
DrawPie,
DrawArc,
FillRegion,
FillPath,
DrawPath,
FillClosedCurve,
DrawClosedCurve,
DrawCurve,
DrawBeziers,
DrawImage,
DrawImagePoints,
DrawString,
// Graphics State Records
SetRenderingOrigin,
SetAntiAliasMode,
SetTextRenderingHint,
SetTextContrast,
SetInterpolationMode,
SetPixelOffsetMode,
SetCompositingMode,
SetCompositingQuality,
Save,
Restore,
BeginContainer,
BeginContainerNoParams,
EndContainer,
SetWorldTransform,
ResetWorldTransform,
MultiplyWorldTransform,
TranslateWorldTransform,
ScaleWorldTransform,
RotateWorldTransform,
SetPageTransform,
ResetClip,
SetClipRect,
SetClipPath,
SetClipRegion,
OffsetClip,
DrawDriverString,
Total,
Max = Total - 1,
Min = Header
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Avro.IO;
namespace Avro.Generic
{
public delegate void Writer<T>(T t);
/// <summary>
/// A typesafe wrapper around DefaultWriter. While a specific object of DefaultWriter
/// allows the client to serialize a generic type, an object of this class allows
/// only a single type of object to be serialized through it.
/// </summary>
/// <typeparam name="T">The type of object to be serialized.</typeparam>
public class GenericWriter<T> : DatumWriter<T>
{
private readonly DefaultWriter writer;
public GenericWriter(Schema schema) : this(new DefaultWriter(schema))
{
}
public Schema Schema { get { return writer.Schema; } }
public GenericWriter(DefaultWriter writer)
{
this.writer = writer;
}
/// <summary>
/// Serializes the given object using this writer's schema.
/// </summary>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder to use for serializing</param>
public void Write(T value, Encoder encoder)
{
writer.Write(value, encoder);
}
}
/// <summary>
/// A General purpose writer for serializing objects into a Stream using
/// Avro. This class implements a default way of serializing objects. But
/// one can derive a class from this and override different methods to
/// acheive results that are different from the default implementation.
/// </summary>
public class DefaultWriter
{
public Schema Schema { get; private set; }
/// <summary>
/// Constructs a generic writer for the given schema.
/// </summary>
/// <param name="schema">The schema for the object to be serialized</param>
public DefaultWriter(Schema schema)
{
this.Schema = schema;
}
public void Write<T>(T value, Encoder encoder)
{
Write(Schema, value, encoder);
}
/// <summary>
/// Examines the schema and dispatches the actual work to one
/// of the other methods of this class. This allows the derived
/// classes to override specific methods and get custom results.
/// </summary>
/// <param name="schema">The schema to use for serializing</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder to use during serialization</param>
public virtual void Write(Schema schema, object value, Encoder encoder)
{
switch (schema.Tag)
{
case Schema.Type.Null:
WriteNull(value, encoder);
break;
case Schema.Type.Boolean:
Write<bool>(value, schema.Tag, encoder.WriteBoolean);
break;
case Schema.Type.Int:
Write<int>(value, schema.Tag, encoder.WriteInt);
break;
case Schema.Type.Long:
Write<long>(value, schema.Tag, encoder.WriteLong);
break;
case Schema.Type.Float:
Write<float>(value, schema.Tag, encoder.WriteFloat);
break;
case Schema.Type.Double:
Write<double>(value, schema.Tag, encoder.WriteDouble);
break;
case Schema.Type.String:
Write<string>(value, schema.Tag, encoder.WriteString);
break;
case Schema.Type.Bytes:
Write<byte[]>(value, schema.Tag, encoder.WriteBytes);
break;
case Schema.Type.Record:
WriteRecord(schema as RecordSchema, value, encoder);
break;
case Schema.Type.Enumeration:
WriteEnum(schema as EnumSchema, value, encoder);
break;
case Schema.Type.Fixed:
WriteFixed(schema as FixedSchema, value, encoder);
break;
case Schema.Type.Array:
WriteArray(schema as ArraySchema, value, encoder);
break;
case Schema.Type.Map:
WriteMap(schema as MapSchema, value, encoder);
break;
case Schema.Type.Union:
WriteUnion(schema as UnionSchema, value, encoder);
break;
default:
error(schema, value);
break;
}
}
/// <summary>
/// Serializes a "null"
/// </summary>
/// <param name="value">The object to be serialized using null schema</param>
/// <param name="encoder">The encoder to use while serialization</param>
protected virtual void WriteNull(object value, Encoder encoder)
{
if (value != null) throw TypeMismatch(value, "null", "null");
}
/// <summary>
/// A generic method to serialize primitive Avro types.
/// </summary>
/// <typeparam name="S">Type of the C# type to be serialized</typeparam>
/// <param name="value">The value to be serialized</param>
/// <param name="tag">The schema type tag</param>
/// <param name="writer">The writer which should be used to write the given type.</param>
protected virtual void Write<S>(object value, Schema.Type tag, Writer<S> writer)
{
if (!(value is S)) throw TypeMismatch(value, tag.ToString(), typeof(S).ToString());
writer((S)value);
}
/// <summary>
/// Serialized a record using the given RecordSchema. It uses GetField method
/// to extract the field value from the given object.
/// </summary>
/// <param name="schema">The RecordSchema to use for serialization</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The Encoder for serialization</param>
protected virtual void WriteRecord(RecordSchema schema, object value, Encoder encoder)
{
EnsureRecordObject(schema, value);
foreach (Field field in schema)
{
try
{
object obj = GetField(value, field.Name, field.Pos);
Write(field.Schema, obj, encoder);
}
catch (Exception ex)
{
throw new AvroException(ex.Message + " in field " + field.Name);
}
}
}
protected virtual void EnsureRecordObject(RecordSchema s, object value)
{
if (value == null || !(value is GenericRecord) || !((value as GenericRecord).Schema.Equals(s)))
{
throw TypeMismatch(value, "record", "GenericRecord");
}
}
/// <summary>
/// Extracts the field value from the given object. In this default implementation,
/// value should be of type GenericRecord.
/// </summary>
/// <param name="value">The record value from which the field needs to be extracted</param>
/// <param name="fieldName">The name of the field in the record</param>
/// <param name="fieldPos">The position of field in the record</param>
/// <returns></returns>
protected virtual object GetField(object value, string fieldName, int fieldPos)
{
GenericRecord d = value as GenericRecord;
return d[fieldName];
}
/// <summary>
/// Serializes an enumeration. The default implementation expectes the value to be string whose
/// value is the name of the enumeration.
/// </summary>
/// <param name="es">The EnumSchema for serialization</param>
/// <param name="value">Value to be written</param>
/// <param name="encoder">Encoder for serialization</param>
protected virtual void WriteEnum(EnumSchema es, object value, Encoder encoder)
{
if (value == null || !(value is GenericEnum) || !((value as GenericEnum).Schema.Equals(es)))
throw TypeMismatch(value, "enum", "GenericEnum");
encoder.WriteEnum(es.Ordinal((value as GenericEnum).Value));
}
/// <summary>
/// Serialized an array. The default implementation calls EnsureArrayObject() to ascertain that the
/// given value is an array. It then calls GetArrayLength() and GetArrayElement()
/// to access the members of the array and then serialize them.
/// </summary>
/// <param name="schema">The ArraySchema for serialization</param>
/// <param name="value">The value being serialized</param>
/// <param name="encoder">The encoder for serialization</param>
protected virtual void WriteArray(ArraySchema schema, object value, Encoder encoder)
{
EnsureArrayObject(value);
long l = GetArrayLength(value);
encoder.WriteArrayStart();
encoder.SetItemCount(l);
for (long i = 0; i < l; i++)
{
encoder.StartItem();
Write(schema.ItemSchema, GetArrayElement(value, i), encoder);
}
encoder.WriteArrayEnd();
}
/// <summary>
/// Checks if the given object is an array. If it is a valid array, this function returns normally. Otherwise,
/// it throws an exception. The default implementation checks if the value is an array.
/// </summary>
/// <param name="value"></param>
protected virtual void EnsureArrayObject(object value)
{
if (value == null || !(value is Array)) throw TypeMismatch(value, "array", "Array");
}
/// <summary>
/// Returns the length of an array. The default implementation requires the object
/// to be an array of objects and returns its length. The defaul implementation
/// gurantees that EnsureArrayObject() has been called on the value before this
/// function is called.
/// </summary>
/// <param name="value">The object whose array length is required</param>
/// <returns>The array length of the given object</returns>
protected virtual long GetArrayLength(object value)
{
return (value as Array).Length;
}
/// <summary>
/// Returns the element at the given index from the given array object. The default implementation
/// requires that the value is an object array and returns the element in that array. The defaul implementation
/// gurantees that EnsureArrayObject() has been called on the value before this
/// function is called.
/// </summary>
/// <param name="value">The array object</param>
/// <param name="index">The index to look for</param>
/// <returns>The array element at the index</returns>
protected virtual object GetArrayElement(object value, long index)
{
return (value as Array).GetValue(index);
}
/// <summary>
/// Serialized a map. The default implementation first ensure that the value is indeed a map and then uses
/// GetMapSize() and GetMapElements() to access the contents of the map.
/// </summary>
/// <param name="schema">The MapSchema for serialization</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder for serialization</param>
protected virtual void WriteMap(MapSchema schema, object value, Encoder encoder)
{
EnsureMapObject(value);
IDictionary<string, object> vv = (IDictionary<string, object>)value;
encoder.WriteMapStart();
encoder.SetItemCount(GetMapSize(value));
foreach (KeyValuePair<string, object> obj in GetMapValues(vv))
{
encoder.StartItem();
encoder.WriteString(obj.Key);
Write(schema.ValueSchema, obj.Value, encoder);
}
encoder.WriteMapEnd();
}
/// <summary>
/// Checks if the given object is a map. If it is a valid map, this function returns normally. Otherwise,
/// it throws an exception. The default implementation checks if the value is an IDictionary<string, object>.
/// </summary>
/// <param name="value"></param>
protected virtual void EnsureMapObject(object value)
{
if (value == null || !(value is IDictionary<string, object>)) throw TypeMismatch(value, "map", "IDictionary<string, object>");
}
/// <summary>
/// Returns the size of the map object. The default implementation gurantees that EnsureMapObject has been
/// successfully called with the given value. The default implementation requires the value
/// to be an IDictionary<string, object> and returns the number of elements in it.
/// </summary>
/// <param name="value">The map object whose size is desired</param>
/// <returns>The size of the given map object</returns>
protected virtual long GetMapSize(object value)
{
return (value as IDictionary<string, object>).Count;
}
/// <summary>
/// Returns the contents of the given map object. The default implementation guarantees that EnsureMapObject
/// has been called with the given value. The defualt implementation of this method requires that
/// the value is an IDictionary<string, object> and returns its contents.
/// </summary>
/// <param name="value">The map object whose size is desired</param>
/// <returns>The contents of the given map object</returns>
protected virtual IEnumerable<KeyValuePair<string, object>> GetMapValues(object value)
{
return value as IDictionary<string, object>;
}
/// <summary>
/// Resolves the given value against the given UnionSchema and serializes the object against
/// the resolved schema member. The default implementation of this method uses
/// ResolveUnion to find the member schema within the UnionSchema.
/// </summary>
/// <param name="us">The UnionSchema to resolve against</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder for serialization</param>
protected virtual void WriteUnion(UnionSchema us, object value, Encoder encoder)
{
int index = ResolveUnion(us, value);
encoder.WriteUnionIndex(index);
Write(us[index], value, encoder);
}
/// <summary>
/// Finds the branch within the given UnionSchema that matches the given object. The default implementation
/// calls Matches() method in the order of branches within the UnionSchema. If nothing matches, throws
/// an exception.
/// </summary>
/// <param name="us">The UnionSchema to resolve against</param>
/// <param name="obj">The object that should be used in matching</param>
/// <returns></returns>
protected virtual int ResolveUnion(UnionSchema us, object obj)
{
for (int i = 0; i < us.Count; i++)
{
if (Matches(us[i], obj)) return i;
}
throw new AvroException("Cannot find a match for " + obj.GetType() + " in " + us);
}
/// <summary>
/// Serialized a fixed object. The default implementation requires that the value is
/// a GenericFixed object with an identical schema as es.
/// </summary>
/// <param name="es">The schema for serialization</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder for serialization</param>
protected virtual void WriteFixed(FixedSchema es, object value, Encoder encoder)
{
if (value == null || !(value is GenericFixed) || !(value as GenericFixed).Schema.Equals(es))
{
throw TypeMismatch(value, "fixed", "GenericFixed");
}
GenericFixed ba = (GenericFixed)value;
encoder.WriteFixed(ba.Value);
}
protected AvroException TypeMismatch(object obj, string schemaType, string type)
{
return new AvroException(type + " required to write against " + schemaType + " schema but found " + (null == obj ? "null" : obj.GetType().ToString()) );
}
private void error(Schema schema, Object value)
{
throw new AvroTypeException("Not a " + schema + ": " + value);
}
/*
* FIXME: This method of determining the Union branch has problems. If the data is IDictionary<string, object>
* if there are two branches one with record schema and the other with map, it choose the first one. Similarly if
* the data is byte[] and there are fixed and bytes schemas as branches, it choose the first one that matches.
* Also it does not recognize the arrays of primitive types.
*/
protected virtual bool Matches(Schema sc, object obj)
{
if (obj == null && sc.Tag != Avro.Schema.Type.Null) return false;
switch (sc.Tag)
{
case Schema.Type.Null:
return obj == null;
case Schema.Type.Boolean:
return obj is bool;
case Schema.Type.Int:
return obj is int;
case Schema.Type.Long:
return obj is long;
case Schema.Type.Float:
return obj is float;
case Schema.Type.Double:
return obj is double;
case Schema.Type.Bytes:
return obj is byte[];
case Schema.Type.String:
return obj is string;
case Schema.Type.Record:
//return obj is GenericRecord && (obj as GenericRecord).Schema.Equals(s);
return obj is GenericRecord && (obj as GenericRecord).Schema.SchemaName.Equals((sc as RecordSchema).SchemaName);
case Schema.Type.Enumeration:
//return obj is GenericEnum && (obj as GenericEnum).Schema.Equals(s);
return obj is GenericEnum && (obj as GenericEnum).Schema.SchemaName.Equals((sc as EnumSchema).SchemaName);
case Schema.Type.Array:
return obj is Array && !(obj is byte[]);
case Schema.Type.Map:
return obj is IDictionary<string, object>;
case Schema.Type.Union:
return false; // Union directly within another union not allowed!
case Schema.Type.Fixed:
//return obj is GenericFixed && (obj as GenericFixed).Schema.Equals(s);
return obj is GenericFixed && (obj as GenericFixed).Schema.SchemaName.Equals((sc as FixedSchema).SchemaName);
default:
throw new AvroException("Unknown schema type: " + sc.Tag);
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UMA;
namespace UMACharacterSystem
{
//refrenced by 'SlotMaker.cs' which is itself never refrenced
/*public enum WardrobeSlot
{
None = 0,
Face = 1,
Hair = 2,
Complexion = 3,
Eyebrows = 4,
Beard = 5,
Ears,
Helmet,
Shoulders,
Chest,
Arms,
Hands,
Waist,
Legs,
Feet
}*/
//not used any more now we set things based on race
/*public enum Sex
{
Unisex = 0,
Male = 1,
Female = 2
}*/
//The following classes are used by the pUMATextRecipe extension but also need to be available in RecipeEditor
public enum recipeTypeOpts { Standard, WardrobeItem, DynamicCharacterAvatar, WardrobeCollection }
[System.Serializable]
public class WardrobeRecipeThumb
{
public string race = "";
public string filename = "";
public Sprite thumb = null;
public WardrobeRecipeThumb()
{
}
public WardrobeRecipeThumb(string n_race)
{
race = n_race;
}
public WardrobeRecipeThumb(string n_race, Sprite n_thumb)
{
race = n_race;
filename = n_thumb.name;
thumb = n_thumb;
}
}
[System.Serializable]
public class WardrobeSettings
{
public string slot;
public string recipe;
public WardrobeSettings()
{
}
public WardrobeSettings(string _slot, string _recipe)
{
slot = _slot;
recipe = _recipe;
}
}
[System.Serializable]
public class WardrobeSet
{
public string targetRace = "";
public List<WardrobeSettings> wardrobeSet = new List<WardrobeSettings>();
public WardrobeSet() { }
public WardrobeSet(string race)
{
targetRace = race;
wardrobeSet = new List<WardrobeSettings>();
}
public WardrobeSet(string race, List<WardrobeSettings> settings)
{
targetRace = race;
wardrobeSet = settings;
}
}
[System.Serializable]
public class WardrobeCollectionList
{
public List<WardrobeSet> sets = new List<WardrobeSet>();
public List<WardrobeSettings> this[string key]
{
get
{
return GetValue(key);
}
set
{
SetValue(key, value);
}
}
public void Clear()
{
sets = new List<WardrobeSet>();
}
public bool Contains(string race)
{
bool contained = false;
for (int i = 0; i < sets.Count; i++)
{
if (sets[i].targetRace == race)
{
contained = true;
break;
}
}
return contained;
}
public void Add(string race)
{
if (!Contains(race))
sets.Add(new WardrobeSet(race));
}
public void Add(string race, List<WardrobeSettings> settings)
{
if (!Contains(race))
sets.Add(new WardrobeSet(race, settings));
}
public void Remove(string race)
{
if (Contains(race))
{
var newSets = new List<WardrobeSet>(sets.Count - 1);
for (int i = 0; i < sets.Count; i++)
{
if (sets[i].targetRace != race)
{
newSets.Add(new WardrobeSet(sets[i].targetRace, sets[i].wardrobeSet));
}
}
sets = newSets;
}
}
public List<string> GetAllRacesInCollection()
{
List<string> ret = new List<string>();
for (int i = 0; i < sets.Count; i++)
{
ret.Add(sets[i].targetRace);
}
return ret;
}
public List<string> GetAllRecipeNamesInCollection(string forRace = "")
{
var collectionNames = new List<string>();
for (int i = 0; i < sets.Count; i++)
{
if (forRace != "" && sets[i].targetRace != forRace)
continue;
for (int si = 0; si < sets[i].wardrobeSet.Count; si++)
{
if (sets[i].wardrobeSet[si].recipe != "")
{
collectionNames.Add(sets[i].wardrobeSet[si].recipe);
}
}
}
return collectionNames;
}
protected List<WardrobeSettings> GetValue(string key)
{
for (int i = 0; i < sets.Count; i++)
{
if (sets[i].targetRace == key)
{
return sets[i].wardrobeSet;
}
}
return new List<WardrobeSettings>();
}
protected void SetValue(string key, List<WardrobeSettings> value)
{
for (int i = 0; i < sets.Count; i++)
{
if (sets[i].targetRace == key)
{
sets[i].wardrobeSet = value;
}
}
}
}
}
| |
// Copyright (c) 2006-2011 Frank Laub
// 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.
// 3. The name of the author may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Text;
using System.Runtime.InteropServices;
using OpenSSL.Core;
namespace OpenSSL.Crypto
{
#region MessageDigest
/// <summary>
/// Wraps the EVP_MD object
/// </summary>
public class MessageDigest : Base
{
private EVP_MD raw;
/// <summary>
/// Creates a EVP_MD struct
/// </summary>
/// <param name="ptr"></param>
/// <param name="owner"></param>
internal MessageDigest(IntPtr ptr, bool owner) : base(ptr, owner)
{
this.raw = (EVP_MD)Marshal.PtrToStructure(this.ptr, typeof(EVP_MD));
}
/// <summary>
/// Prints MessageDigest
/// </summary>
/// <param name="bio"></param>
public override void Print(BIO bio)
{
bio.Write("MessageDigest");
}
/// <summary>
/// Not implemented, these objects should never be disposed.
/// </summary>
protected override void OnDispose() {
throw new NotImplementedException();
}
/// <summary>
/// Calls EVP_get_digestbyname()
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static MessageDigest CreateByName(string name) {
byte[] buf = Encoding.ASCII.GetBytes(name);
IntPtr ptr = Native.EVP_get_digestbyname(buf);
if (ptr == IntPtr.Zero)
return null;
return new MessageDigest(ptr, false);
}
/// <summary>
/// Calls OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH)
/// </summary>
public static string[] AllNamesSorted
{
get { return new NameCollector(Native.OBJ_NAME_TYPE_MD_METH, true).Result.ToArray(); }
}
/// <summary>
/// Calls OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH)
/// </summary>
public static string[] AllNames
{
get { return new NameCollector(Native.OBJ_NAME_TYPE_MD_METH, false).Result.ToArray(); }
}
#region EVP_MD
[StructLayout(LayoutKind.Sequential)]
struct EVP_MD
{
public int type;
public int pkey_type;
public int md_size;
public uint flags;
public IntPtr init;
public IntPtr update;
public IntPtr final;
public IntPtr copy;
public IntPtr cleanup;
public IntPtr sign;
public IntPtr verify;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
public int[] required_pkey_type;
public int block_size;
public int ctx_size;
}
#endregion
#region MessageDigests
/// <summary>
/// EVP_md_null()
/// </summary>
public static MessageDigest Null = new MessageDigest(Native.EVP_md_null(), false);
/// <summary>
/// EVP_md4()
/// </summary>
public static MessageDigest MD4 = new MessageDigest(Native.EVP_md4(), false);
/// <summary>
/// EVP_md5()
/// </summary>
public static MessageDigest MD5 = new MessageDigest(Native.EVP_md5(), false);
/// <summary>
/// EVP_sha()
/// </summary>
public static MessageDigest SHA = new MessageDigest(Native.EVP_sha(), false);
/// <summary>
/// EVP_sha1()
/// </summary>
public static MessageDigest SHA1 = new MessageDigest(Native.EVP_sha1(), false);
/// <summary>
/// EVP_sha224()
/// </summary>
public static MessageDigest SHA224 = new MessageDigest(Native.EVP_sha224(), false);
/// <summary>
/// EVP_sha256()
/// </summary>
public static MessageDigest SHA256 = new MessageDigest(Native.EVP_sha256(), false);
/// <summary>
/// EVP_sha384()
/// </summary>
public static MessageDigest SHA384 = new MessageDigest(Native.EVP_sha384(), false);
/// <summary>
/// EVP_sha512()
/// </summary>
public static MessageDigest SHA512 = new MessageDigest(Native.EVP_sha512(), false);
/// <summary>
/// EVP_dss()
/// </summary>
public static MessageDigest DSS = new MessageDigest(Native.EVP_dss(), false);
/// <summary>
/// EVP_dss1()
/// </summary>
public static MessageDigest DSS1 = new MessageDigest(Native.EVP_dss1(), false);
/// <summary>
/// EVP_ripemd160()
/// </summary>
public static MessageDigest RipeMD160 = new MessageDigest(Native.EVP_ripemd160(), false);
/// <summary>
/// EVP_ecdsa()
/// </summary>
public static MessageDigest ECDSA = new MessageDigest(Native.EVP_ecdsa(), false);
#endregion
#region Properties
/// <summary>
/// Returns the block_size field
/// </summary>
public int BlockSize
{
get { return this.raw.block_size; }
}
/// <summary>
/// Returns the md_size field
/// </summary>
public int Size
{
get { return this.raw.md_size; }
}
/// <summary>
/// Returns the type field using OBJ_nid2ln()
/// </summary>
public string LongName
{
get { return Native.OBJ_nid2ln(this.raw.type); }
}
/// <summary>
/// Returns the type field using OBJ_nid2sn()
/// </summary>
public string Name
{
get { return Native.OBJ_nid2sn(this.raw.type); }
}
#endregion
}
#endregion
#region EVP_MD_CTX
[StructLayout(LayoutKind.Sequential)]
struct EVP_MD_CTX
{
public IntPtr digest;
public IntPtr engine;
public uint flags;
public IntPtr md_data;
public IntPtr pctx;
public IntPtr update;
}
#endregion
/// <summary>
/// Wraps the EVP_MD_CTX object
/// </summary>
public class MessageDigestContext : Base
{
private MessageDigest md;
/// <summary>
/// Calls BIO_get_md_ctx() then BIO_get_md()
/// </summary>
/// <param name="bio"></param>
public MessageDigestContext(BIO bio)
: base(Native.ExpectNonNull(Native.BIO_get_md_ctx(bio.Handle)), false)
{
this.md = new MessageDigest(Native.ExpectNonNull(Native.BIO_get_md(bio.Handle)), false);
}
/// <summary>
/// Calls EVP_MD_CTX_create() then EVP_MD_CTX_init()
/// </summary>
/// <param name="md"></param>
public MessageDigestContext(MessageDigest md)
: base(Native.EVP_MD_CTX_create(), true)
{
Native.EVP_MD_CTX_init(this.ptr);
this.md = md;
}
/// <summary>
/// Prints the long name
/// </summary>
/// <param name="bio"></param>
public override void Print(BIO bio)
{
bio.Write("MessageDigestContext: " + this.md.LongName);
}
#region Methods
/// <summary>
/// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_DigestFinal_ex()
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public byte[] Digest(byte[] msg)
{
byte[] digest = new byte[this.md.Size];
uint len = (uint)digest.Length;
Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero));
Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length));
Native.ExpectSuccess(Native.EVP_DigestFinal_ex(this.ptr, digest, ref len));
return digest;
}
/// <summary>
/// Calls EVP_DigestInit_ex()
/// </summary>
public void Init()
{
Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero));
}
/// <summary>
/// Calls EVP_DigestUpdate()
/// </summary>
/// <param name="msg"></param>
public void Update(byte[] msg)
{
Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length));
}
/// <summary>
/// Calls EVP_DigestFinal_ex()
/// </summary>
/// <returns></returns>
public byte[] DigestFinal()
{
byte[] digest = new byte[this.md.Size];
uint len = (uint)digest.Length;
Native.ExpectSuccess(Native.EVP_DigestFinal_ex(this.ptr, digest, ref len));
return digest;
}
/// <summary>
/// Calls EVP_SignFinal()
/// </summary>
/// <param name="pkey"></param>
/// <returns></returns>
public byte[] SignFinal(CryptoKey pkey)
{
byte[] sig = new byte[pkey.Size];
uint len = (uint)sig.Length;
Native.ExpectSuccess(Native.EVP_SignFinal(this.ptr, sig, ref len, pkey.Handle));
return sig;
}
/// <summary>
/// Calls EVP_VerifyFinal()
/// </summary>
/// <param name="sig"></param>
/// <param name="pkey"></param>
/// <returns></returns>
public bool VerifyFinal(byte[] sig, CryptoKey pkey)
{
int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(this.ptr, sig, (uint)sig.Length, pkey.Handle));
return ret == 1;
}
/// <summary>
/// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_SignFinal()
/// </summary>
/// <param name="msg"></param>
/// <param name="pkey"></param>
/// <returns></returns>
public byte[] Sign(byte[] msg, CryptoKey pkey)
{
byte[] sig = new byte[pkey.Size];
uint len = (uint)sig.Length;
Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero));
Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length));
Native.ExpectSuccess(Native.EVP_SignFinal(this.ptr, sig, ref len, pkey.Handle));
byte[] ret = new byte[len];
Buffer.BlockCopy(sig, 0, ret, 0, (int)len);
return ret;
}
/// <summary>
/// Calls EVP_SignFinal()
/// </summary>
/// <param name="md"></param>
/// <param name="bio"></param>
/// <param name="pkey"></param>
/// <returns></returns>
public static byte[] Sign(MessageDigest md, BIO bio, CryptoKey pkey)
{
BIO bmd = BIO.MessageDigest(md);
bmd.Push(bio);
while (true)
{
ArraySegment<byte> bytes = bmd.ReadBytes(1024 * 4);
if (bytes.Count == 0)
break;
}
MessageDigestContext ctx = new MessageDigestContext(bmd);
byte[] sig = new byte[pkey.Size];
uint len = (uint)sig.Length;
Native.ExpectSuccess(Native.EVP_SignFinal(ctx.Handle, sig, ref len, pkey.Handle));
byte[] ret = new byte[len];
Buffer.BlockCopy(sig, 0, ret, 0, (int)len);
return ret;
}
/// <summary>
/// Calls EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_VerifyFinal()
/// </summary>
/// <param name="msg"></param>
/// <param name="sig"></param>
/// <param name="pkey"></param>
/// <returns></returns>
public bool Verify(byte[] msg, byte[] sig, CryptoKey pkey)
{
Native.ExpectSuccess(Native.EVP_DigestInit_ex(this.ptr, this.md.Handle, IntPtr.Zero));
Native.ExpectSuccess(Native.EVP_DigestUpdate(this.ptr, msg, (uint)msg.Length));
int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(this.ptr, sig, (uint)sig.Length, pkey.Handle));
return ret == 1;
}
/// <summary>
/// Calls EVP_VerifyFinal()
/// </summary>
/// <param name="md"></param>
/// <param name="bio"></param>
/// <param name="sig"></param>
/// <param name="pkey"></param>
/// <returns></returns>
public static bool Verify(MessageDigest md, BIO bio, byte[] sig, CryptoKey pkey)
{
BIO bmd = BIO.MessageDigest(md);
bmd.Push(bio);
while (true)
{
ArraySegment<byte> bytes = bmd.ReadBytes(1024 * 4);
if (bytes.Count == 0)
break;
}
MessageDigestContext ctx = new MessageDigestContext(bmd);
int ret = Native.ExpectSuccess(Native.EVP_VerifyFinal(ctx.Handle, sig, (uint)sig.Length, pkey.Handle));
return ret == 1;
}
#endregion
#region IDisposable Members
/// <summary>
/// Calls EVP_MD_CTX_cleanup() and EVP_MD_CTX_destroy()
/// </summary>
protected override void OnDispose() {
Native.EVP_MD_CTX_cleanup(this.ptr);
Native.EVP_MD_CTX_destroy(this.ptr);
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AnimatedSpice.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using Google.GData.Client;
namespace Google.GData.Extensions
{
/// <summary>
/// Extensible type used in many places.
/// </summary>
public abstract class ExtensionBase : IExtensionElementFactory, IVersionAware
{
private SortedList attributeNamespaces;
/// <summary>
/// this holds the attribute list for an extension element
/// </summary>
private SortedList attributes;
private List<XmlNode> unknownChildren;
/// <summary>
/// constructor
/// </summary>
/// <param name="name">the xml name</param>
/// <param name="prefix">the xml prefix</param>
/// <param name="ns">the xml namespace</param>
protected ExtensionBase(string name, string prefix, string ns)
{
XmlName = name;
XmlPrefix = prefix;
XmlNameSpace = ns;
}
internal VersionInformation VersionInfo { get; } = new VersionInformation();
/// <summary>accesses the Attribute list. The keys are the attribute names
/// the values the attribute values</summary>
/// <returns> </returns>
public SortedList Attributes
{
get { return getAttributes(); }
}
/// <summary>accesses the Attribute list. The keys are the attribute names
/// the values the attribute values</summary>
/// <returns> </returns>
public SortedList AttributeNamespaces
{
get { return getAttributeNamespaces(); }
}
/// <summary>
/// returns the major protocol version number this element
/// is working against.
/// </summary>
/// <returns></returns>
public int ProtocolMajor
{
get { return VersionInfo.ProtocolMajor; }
set
{
VersionInfo.ProtocolMajor = value;
VersionInfoChanged();
}
}
/// <summary>
/// returns the minor protocol version number this element
/// is working against.
/// </summary>
/// <returns></returns>
public int ProtocolMinor
{
get { return VersionInfo.ProtocolMinor; }
set
{
VersionInfo.ProtocolMinor = value;
VersionInfoChanged();
}
}
/// <summary>
/// virtual to be overloaded by subclasses which are interested in reacting on versioninformation
/// changes
/// </summary>
protected virtual void VersionInfoChanged()
{
}
/// <summary>
/// method for subclasses who need to change a namespace for parsing/persistence during runtime
/// </summary>
/// <param name="ns"></param>
protected void SetXmlNamespace(string ns)
{
XmlNameSpace = ns;
}
/// <summary>
/// returns the attributes list
/// </summary>
/// <returns>SortedList</returns>
internal SortedList getAttributes()
{
if (attributes == null)
{
attributes = new SortedList();
}
return attributes;
}
/// <summary>
/// returns the attribute namespace list
/// </summary>
/// <returns>SortedList</returns>
internal SortedList getAttributeNamespaces()
{
if (attributeNamespaces == null)
{
attributeNamespaces = new SortedList();
}
return attributeNamespaces;
}
#region overloaded for persistence
/// <summary>Returns the constant representing this XML element.</summary>
public string XmlName { get; }
/// <summary>Returns the constant representing this XML element.</summary>
public string XmlNameSpace { get; private set; }
/// <summary>Returns the constant representing this XML element.</summary>
public string XmlPrefix { get; }
/// <summary>
/// debugging helper
/// </summary>
/// <returns></returns>
public override string ToString()
{
return base.ToString() + " for: " + XmlNameSpace + "- " + XmlName;
}
/// <summary>
/// returns the list of childnodes that are unknown to the extension
/// used for example for the GD:ExtendedProperty
/// </summary>
/// <returns></returns>
public List<XmlNode> ChildNodes
{
get
{
if (unknownChildren == null)
{
unknownChildren = new List<XmlNode>();
}
return unknownChildren;
}
}
/// <summary>Parses an xml node to create an instance of this object.</summary>
/// <param name="node">the xml parses node, can be NULL</param>
/// <param name="parser">the xml parser to use if we need to dive deeper</param>
/// <returns>the created IExtensionElement object</returns>
public virtual IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser)
{
Tracing.TraceCall();
ExtensionBase e = null;
if (node != null)
{
object localname = node.LocalName;
if (!localname.Equals(XmlName) ||
!node.NamespaceURI.Equals(XmlNameSpace))
{
return null;
}
}
// memberwise close is fine here, as everything is identical beside the value
e = MemberwiseClone() as ExtensionBase;
e.InitInstance(this);
e.ProcessAttributes(node);
e.ProcessChildNodes(node, parser);
return e;
}
/// <summary>
/// used to copy the unknown childnodes for later saving
/// </summary>
public virtual void ProcessChildNodes(XmlNode node, AtomFeedParser parser)
{
if (node != null && node.HasChildNodes)
{
XmlNode childNode = node.FirstChild;
while (childNode != null)
{
if (childNode.NodeType == XmlNodeType.Element)
{
ChildNodes.Add(childNode);
}
childNode = childNode.NextSibling;
}
}
}
/// <summary>
/// used to copy the attribute lists over
/// </summary>
/// <param name="factory"></param>
protected void InitInstance(ExtensionBase factory)
{
attributes = null;
attributeNamespaces = null;
unknownChildren = null;
for (int i = 0; i < factory.getAttributes().Count; i++)
{
string name = factory.getAttributes().GetKey(i) as string;
string value = factory.getAttributes().GetByIndex(i) as string;
getAttributes().Add(name, value);
}
}
/// <summary>
/// default method override to handle attribute processing
/// the base implementation does process the attributes list
/// and reads all that are in there.
/// </summary>
/// <param name="node">XmlNode with attributes</param>
public virtual void ProcessAttributes(XmlNode node)
{
if (node != null && node.Attributes != null)
{
for (int i = 0; i < node.Attributes.Count; i++)
{
getAttributes()[node.Attributes[i].LocalName] = node.Attributes[i].Value;
}
}
}
/// <summary>
/// Persistence method for the EnumConstruct object
/// </summary>
/// <param name="writer">the xmlwriter to write into</param>
public virtual void Save(XmlWriter writer)
{
writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace);
if (attributes != null)
{
for (int i = 0; i < getAttributes().Count; i++)
{
if (getAttributes().GetByIndex(i) != null)
{
string name = getAttributes().GetKey(i) as string;
string value = Utilities.ConvertToXSDString(getAttributes().GetByIndex(i));
string ns = getAttributeNamespaces()[name] as string;
if (Utilities.IsPersistable(name) && Utilities.IsPersistable(value))
{
if (ns == null)
{
writer.WriteAttributeString(name, value);
}
else
{
writer.WriteAttributeString(name, ns, value);
}
}
}
}
}
SaveInnerXml(writer);
foreach (XmlNode node in ChildNodes)
{
if (node != null)
{
node.WriteTo(writer);
}
}
writer.WriteEndElement();
}
/// <summary>
/// a subclass that want's to save addtional XML would need to overload this
/// the default implementation does nothing
/// </summary>
/// <param name="writer"></param>
public virtual void SaveInnerXml(XmlWriter writer)
{
}
#endregion
}
}
| |
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 SysTipoEfector class.
/// </summary>
[Serializable]
public partial class SysTipoEfectorCollection : ActiveList<SysTipoEfector, SysTipoEfectorCollection>
{
public SysTipoEfectorCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>SysTipoEfectorCollection</returns>
public SysTipoEfectorCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
SysTipoEfector 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 Sys_TipoEfector table.
/// </summary>
[Serializable]
public partial class SysTipoEfector : ActiveRecord<SysTipoEfector>, IActiveRecord
{
#region .ctors and Default Settings
public SysTipoEfector()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public SysTipoEfector(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public SysTipoEfector(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public SysTipoEfector(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("Sys_TipoEfector", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdTipoEfector = new TableSchema.TableColumn(schema);
colvarIdTipoEfector.ColumnName = "idTipoEfector";
colvarIdTipoEfector.DataType = DbType.Int32;
colvarIdTipoEfector.MaxLength = 0;
colvarIdTipoEfector.AutoIncrement = true;
colvarIdTipoEfector.IsNullable = false;
colvarIdTipoEfector.IsPrimaryKey = true;
colvarIdTipoEfector.IsForeignKey = false;
colvarIdTipoEfector.IsReadOnly = false;
colvarIdTipoEfector.DefaultSetting = @"";
colvarIdTipoEfector.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTipoEfector);
TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema);
colvarNombre.ColumnName = "nombre";
colvarNombre.DataType = DbType.AnsiString;
colvarNombre.MaxLength = 50;
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("Sys_TipoEfector",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdTipoEfector")]
[Bindable(true)]
public int IdTipoEfector
{
get { return GetColumnValue<int>(Columns.IdTipoEfector); }
set { SetColumnValue(Columns.IdTipoEfector, 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)
{
SysTipoEfector item = new SysTipoEfector();
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 varIdTipoEfector,string varNombre)
{
SysTipoEfector item = new SysTipoEfector();
item.IdTipoEfector = varIdTipoEfector;
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 IdTipoEfectorColumn
{
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 IdTipoEfector = @"idTipoEfector";
public static string Nombre = @"nombre";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using SteamKit2;
using SteamTrade.Exceptions;
namespace SteamTrade
{
public class TradeManager
{
private const int MaxGapTimeDefault = 15;
private const int MaxTradeTimeDefault = 180;
private const int TradePollingIntervalDefault = 800;
private readonly string ApiKey;
private readonly SteamWeb SteamWeb;
private DateTime tradeStartTime;
private DateTime lastOtherActionTime;
private DateTime lastTimeoutMessage;
private Task<Inventory> myInventoryTask;
private Task<Inventory> otherInventoryTask;
/// <summary>
/// Initializes a new instance of the <see cref="SteamTrade.TradeManager"/> class.
/// </summary>
/// <param name='apiKey'>
/// The Steam Web API key. Cannot be null.
/// </param>
/// <param name="steamWeb">
/// The SteamWeb instances for this bot
/// </param>
public TradeManager (string apiKey, SteamWeb steamWeb)
{
if (apiKey == null)
throw new ArgumentNullException ("apiKey");
if (steamWeb == null)
throw new ArgumentNullException ("steamWeb");
SetTradeTimeLimits (MaxTradeTimeDefault, MaxGapTimeDefault, TradePollingIntervalDefault);
ApiKey = apiKey;
SteamWeb = steamWeb;
}
#region Public Properties
/// <summary>
/// Gets or the maximum trading time the bot will take in seconds.
/// </summary>
/// <value>
/// The maximum trade time.
/// </value>
public int MaxTradeTimeSec
{
get;
private set;
}
/// <summary>
/// Gets or the maxmium amount of time the bot will wait between actions.
/// </summary>
/// <value>
/// The maximum action gap.
/// </value>
public int MaxActionGapSec
{
get;
private set;
}
/// <summary>
/// Gets the Trade polling interval in milliseconds.
/// </summary>
public int TradePollingInterval
{
get;
private set;
}
/// <summary>
/// Gets the inventory of the bot.
/// </summary>
/// <value>
/// The bot's inventory fetched via Steam Web API.
/// </value>
public Inventory MyInventory
{
get
{
if(myInventoryTask == null)
return null;
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
/// <summary>
/// Gets the inventory of the other trade partner.
/// </summary>
/// <value>
/// The other trade partner's inventory fetched via Steam Web API.
/// </value>
public Inventory OtherInventory
{
get
{
if(otherInventoryTask == null)
return null;
otherInventoryTask.Wait();
return otherInventoryTask.Result;
}
}
/// <summary>
/// Gets or sets a value indicating whether the trade thread running.
/// </summary>
/// <value>
/// <c>true</c> if the trade thread running; otherwise, <c>false</c>.
/// </value>
public bool IsTradeThreadRunning
{
get;
internal set;
}
#endregion Public Properties
#region Public Events
/// <summary>
/// Occurs when the trade times out because either the user didn't complete an
/// action in a set amount of time, or they took too long with the whole trade.
/// </summary>
public EventHandler OnTimeout;
#endregion Public Events
#region Public Methods
/// <summary>
/// Sets the trade time limits.
/// </summary>
/// <param name='maxTradeTime'>
/// Max trade time in seconds.
/// </param>
/// <param name='maxActionGap'>
/// Max gap between user action in seconds.
/// </param>
/// <param name='pollingInterval'>The trade polling interval in milliseconds.</param>
public void SetTradeTimeLimits (int maxTradeTime, int maxActionGap, int pollingInterval)
{
MaxTradeTimeSec = maxTradeTime;
MaxActionGapSec = maxActionGap;
TradePollingInterval = pollingInterval;
}
/// <summary>
/// Creates a trade object and returns it for use.
/// Call <see cref="InitializeTrade"/> before using this method.
/// </summary>
/// <returns>
/// The trade object to use to interact with the Steam trade.
/// </returns>
/// <param name='me'>
/// The <see cref="SteamID"/> of the bot.
/// </param>
/// <param name='other'>
/// The <see cref="SteamID"/> of the other trade partner.
/// </param>
/// <remarks>
/// If the needed inventories are <c>null</c> then they will be fetched.
/// </remarks>
public Trade CreateTrade (SteamID me, SteamID other)
{
if (otherInventoryTask == null || myInventoryTask == null)
InitializeTrade (me, other);
var t = new Trade (me, other, SteamWeb, myInventoryTask, otherInventoryTask);
t.OnClose += delegate
{
IsTradeThreadRunning = false;
};
return t;
}
/// <summary>
/// Stops the trade thread.
/// </summary>
/// <remarks>
/// Also, nulls out the inventory objects so they have to be fetched
/// again if a new trade is started.
/// </remarks>
public void StopTrade ()
{
// TODO: something to check that trade was the Trade returned from CreateTrade
otherInventoryTask = null;
myInventoryTask = null;
IsTradeThreadRunning = false;
}
/// <summary>
/// Fetchs the inventories of both the bot and the other user as well as the TF2 item schema.
/// </summary>
/// <param name='me'>
/// The <see cref="SteamID"/> of the bot.
/// </param>
/// <param name='other'>
/// The <see cref="SteamID"/> of the other trade partner.
/// </param>
/// <remarks>
/// This should be done anytime a new user is traded with or the inventories are out of date. It should
/// be done sometime before calling <see cref="CreateTrade"/>.
/// </remarks>
public void InitializeTrade (SteamID me, SteamID other)
{
// fetch other player's inventory from the Steam API.
otherInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(other.ConvertToUInt64(), ApiKey, SteamWeb));
//if (OtherInventory == null)
//{
// throw new InventoryFetchException (other);
//}
// fetch our inventory from the Steam API.
myInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(me.ConvertToUInt64(), ApiKey, SteamWeb));
// check that the schema was already successfully fetched
if (Trade.CurrentSchema == null)
Trade.CurrentSchema = Schema.FetchSchema (ApiKey);
if (Trade.CurrentSchema == null)
throw new TradeException ("Could not download the latest item schema.");
}
#endregion Public Methods
/// <summary>
/// Starts the actual trade-polling thread.
/// </summary>
public void StartTradeThread (Trade trade)
{
// initialize data to use in thread
tradeStartTime = DateTime.Now;
lastOtherActionTime = DateTime.Now;
lastTimeoutMessage = DateTime.Now.AddSeconds(-1000);
var pollThread = new Thread (() =>
{
IsTradeThreadRunning = true;
DebugPrint ("Trade thread starting.");
// main thread loop for polling
try
{
while(IsTradeThreadRunning)
{
bool action = trade.Poll();
if(action)
lastOtherActionTime = DateTime.Now;
if(trade.OtherUserCancelled || trade.HasTradeCompletedOk || CheckTradeTimeout(trade))
{
IsTradeThreadRunning = false;
break;
}
Thread.Sleep(TradePollingInterval);
}
}
catch(Exception ex)
{
// TODO: find a new way to do this w/o the trade events
//if (OnError != null)
// OnError("Error Polling Trade: " + e);
// ok then we should stop polling...
IsTradeThreadRunning = false;
DebugPrint("[TRADEMANAGER] general error caught: " + ex);
trade.FireOnErrorEvent("Unknown error occurred: " + ex.ToString());
}
finally
{
DebugPrint("Trade thread shutting down.");
try
{
try //Yikes, that's a lot of nested 'try's. Is there some way to clean this up?
{
if(trade.HasTradeCompletedOk)
trade.FireOnSuccessEvent();
}
finally
{
//Make sure OnClose is always fired after OnSuccess, even if OnSuccess throws an exception
//(which it NEVER should, but...)
trade.FireOnCloseEvent();
}
}
catch(Exception ex)
{
trade.FireOnErrorEvent("Unknown error occurred DURING CLEANUP(!?): " + ex.ToString());
}
}
});
pollThread.Start();
}
private bool CheckTradeTimeout (Trade trade)
{
// User has accepted the trade. Disregard time out.
if (trade.OtherUserAccepted)
return false;
var now = DateTime.Now;
DateTime actionTimeout = lastOtherActionTime.AddSeconds (MaxActionGapSec);
int untilActionTimeout = (int)Math.Round ((actionTimeout - now).TotalSeconds);
DebugPrint (String.Format ("{0} {1}", actionTimeout, untilActionTimeout));
DateTime tradeTimeout = tradeStartTime.AddSeconds (MaxTradeTimeSec);
int untilTradeTimeout = (int)Math.Round ((tradeTimeout - now).TotalSeconds);
double secsSinceLastTimeoutMessage = (now - lastTimeoutMessage).TotalSeconds;
if (untilActionTimeout <= 0 || untilTradeTimeout <= 0)
{
DebugPrint ("timed out...");
if (OnTimeout != null)
{
OnTimeout (this, null);
}
trade.CancelTrade ();
return true;
}
else if (untilActionTimeout <= 20 && secsSinceLastTimeoutMessage >= 10)
{
try
{
trade.SendMessage("Are You AFK? The trade will be canceled in " + untilActionTimeout + " seconds if you don't do something.");
}
catch { }
lastTimeoutMessage = now;
}
return false;
}
[Conditional ("DEBUG_TRADE_MANAGER")]
private static void DebugPrint (string output)
{
// I don't really want to add the Logger as a dependecy to TradeManager so I
// print using the console directly. To enable this for debugging put this:
// #define DEBUG_TRADE_MANAGER
// at the first line of this file.
System.Console.WriteLine (output);
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Library
///<para>SObject Name: ContentWorkspace</para>
///<para>Custom Object: False</para>
///</summary>
public class SfContentWorkspace : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "ContentWorkspace"; }
}
///<summary>
/// Library ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Name
/// <para>Name: Name</para>
/// <para>SF Type: string</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
///<summary>
/// Description
/// <para>Name: Description</para>
/// <para>SF Type: textarea</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
///<summary>
/// Tag Model
/// <para>Name: TagModel</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "tagModel")]
[Updateable(false), Createable(false)]
public string TagModel { get; set; }
///<summary>
/// Created By ID
/// <para>Name: CreatedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdById")]
[Updateable(false), Createable(false)]
public string CreatedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: CreatedBy</para>
///</summary>
[JsonProperty(PropertyName = "createdBy")]
[Updateable(false), Createable(false)]
public SfUser CreatedBy { get; set; }
///<summary>
/// Created Date
/// <para>Name: CreatedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "createdDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? CreatedDate { get; set; }
///<summary>
/// Last Modified By ID
/// <para>Name: LastModifiedById</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedById")]
[Updateable(false), Createable(false)]
public string LastModifiedById { get; set; }
///<summary>
/// ReferenceTo: User
/// <para>RelationshipName: LastModifiedBy</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public SfUser LastModifiedBy { get; set; }
///<summary>
/// System Modstamp
/// <para>Name: SystemModstamp</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "systemModstamp")]
[Updateable(false), Createable(false)]
public DateTimeOffset? SystemModstamp { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Record Type ID
/// <para>Name: DefaultRecordTypeId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "defaultRecordTypeId")]
[Updateable(false), Createable(false)]
public string DefaultRecordTypeId { get; set; }
///<summary>
/// Restrict Record Types
/// <para>Name: IsRestrictContentTypes</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRestrictContentTypes")]
[Updateable(false), Createable(false)]
public bool? IsRestrictContentTypes { get; set; }
///<summary>
/// Restrict Linked Record Types
/// <para>Name: IsRestrictLinkedContentTypes</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isRestrictLinkedContentTypes")]
[Updateable(false), Createable(false)]
public bool? IsRestrictLinkedContentTypes { get; set; }
///<summary>
/// Library Type
/// <para>Name: WorkspaceType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "workspaceType")]
[Updateable(false), Createable(false)]
public string WorkspaceType { get; set; }
///<summary>
/// Add Creator Membership
/// <para>Name: ShouldAddCreatorMembership</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "shouldAddCreatorMembership")]
[Updateable(false), Createable(true)]
public bool? ShouldAddCreatorMembership { get; set; }
///<summary>
/// Last Activity
/// <para>Name: LastWorkspaceActivityDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastWorkspaceActivityDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastWorkspaceActivityDate { get; set; }
///<summary>
/// Content Folder ID
/// <para>Name: RootContentFolderId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "rootContentFolderId")]
[Updateable(false), Createable(false)]
public string RootContentFolderId { get; set; }
///<summary>
/// Namespace Prefix
/// <para>Name: NamespacePrefix</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "namespacePrefix")]
[Updateable(false), Createable(false)]
public string NamespacePrefix { get; set; }
///<summary>
/// Unique Name
/// <para>Name: DeveloperName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "developerName")]
public string DeveloperName { get; set; }
///<summary>
/// Asset File ID
/// <para>Name: WorkspaceImageId</para>
/// <para>SF Type: reference</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "workspaceImageId")]
public string WorkspaceImageId { get; set; }
///<summary>
/// ReferenceTo: ContentAsset
/// <para>RelationshipName: WorkspaceImage</para>
///</summary>
[JsonProperty(PropertyName = "workspaceImage")]
[Updateable(false), Createable(false)]
public SfContentAsset WorkspaceImage { get; set; }
}
}
| |
#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.Threading.Tasks;
using Grpc.Core.Logging;
using Grpc.Core.Profiling;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Manages client side native call lifecycle.
/// </summary>
internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse>
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>();
readonly CallInvocationDetails<TRequest, TResponse> details;
readonly INativeCall injectedNativeCall; // for testing
// Completion of a pending unary response if not null.
TaskCompletionSource<TResponse> unaryResponseTcs;
// Completion of a streaming response call if not null.
TaskCompletionSource<object> streamingResponseCallFinishedTcs;
// TODO(jtattermusch): this field could be lazy-initialized (only if someone requests the response headers).
// Response headers set here once received.
TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>();
// Set after status is received. Used for both unary and streaming response calls.
ClientSideStatus? finishedStatus;
public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails)
: base(callDetails.RequestMarshaller.Serializer, callDetails.ResponseMarshaller.Deserializer)
{
this.details = callDetails.WithOptions(callDetails.Options.Normalize());
this.initialMetadataSent = true; // we always send metadata at the very beginning of the call.
}
/// <summary>
/// This constructor should only be used for testing.
/// </summary>
public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails)
{
this.injectedNativeCall = injectedNativeCall;
}
// TODO: this method is not Async, so it shouldn't be in AsyncCall class, but
// it is reusing fair amount of code in this class, so we are leaving it here.
/// <summary>
/// Blocking unary request - unary response call.
/// </summary>
public TResponse UnaryCall(TRequest msg)
{
var profiler = Profilers.ForCurrentThread();
using (profiler.NewScope("AsyncCall.UnaryCall"))
using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.CreateSync())
{
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(cq);
halfcloseRequested = true;
readingDone = true;
}
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
using (var ctx = BatchContextSafeHandle.Create())
{
call.StartUnary(ctx, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
var ev = cq.Pluck(ctx.Handle);
bool success = (ev.success != 0);
try
{
using (profiler.NewScope("AsyncCall.UnaryCall.HandleBatch"))
{
HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata());
}
}
catch (Exception e)
{
Logger.Error(e, "Exception occured while invoking completion delegate.");
}
}
// Once the blocking call returns, the result should be available synchronously.
// Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException.
return unaryResponseTcs.Task.GetAwaiter().GetResult();
}
}
/// <summary>
/// Starts a unary request - unary response call.
/// </summary>
public Task<TResponse> UnaryCallAsync(TRequest msg)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
halfcloseRequested = true;
readingDone = true;
byte[] payload = UnsafeSerialize(msg);
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartUnary(HandleUnaryResponse, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a streamed request - unary response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public Task<TResponse> ClientStreamingCallAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
readingDone = true;
unaryResponseTcs = new TaskCompletionSource<TResponse>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartClientStreaming(HandleUnaryResponse, metadataArray, details.Options.Flags);
}
return unaryResponseTcs.Task;
}
}
/// <summary>
/// Starts a unary request - streamed response call.
/// </summary>
public void StartServerStreamingCall(TRequest msg)
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
halfcloseRequested = true;
byte[] payload = UnsafeSerialize(msg);
streamingResponseCallFinishedTcs = new TaskCompletionSource<object>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartServerStreaming(HandleFinished, payload, GetWriteFlagsForCall(), metadataArray, details.Options.Flags);
}
call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders);
}
}
/// <summary>
/// Starts a streaming request - streaming response call.
/// Use StartSendMessage and StartSendCloseFromClient to stream requests.
/// </summary>
public void StartDuplexStreamingCall()
{
lock (myLock)
{
GrpcPreconditions.CheckState(!started);
started = true;
Initialize(details.Channel.CompletionQueue);
streamingResponseCallFinishedTcs = new TaskCompletionSource<object>();
using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers))
{
call.StartDuplexStreaming(HandleFinished, metadataArray, details.Options.Flags);
}
call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders);
}
}
/// <summary>
/// Sends a streaming request. Only one pending send action is allowed at any given time.
/// </summary>
public Task SendMessageAsync(TRequest msg, WriteFlags writeFlags)
{
return SendMessageInternalAsync(msg, writeFlags);
}
/// <summary>
/// Receives a streaming response. Only one pending read action is allowed at any given time.
/// </summary>
public Task<TResponse> ReadMessageAsync()
{
return ReadMessageInternalAsync();
}
/// <summary>
/// Sends halfclose, indicating client is done with streaming requests.
/// Only one pending send action is allowed at any given time.
/// </summary>
public Task SendCloseFromClientAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckState(started);
var earlyResult = CheckSendPreconditionsClientSide();
if (earlyResult != null)
{
return earlyResult;
}
if (disposed || finished)
{
// In case the call has already been finished by the serverside,
// the halfclose has already been done implicitly, so just return
// completed task here.
halfcloseRequested = true;
return TaskUtils.CompletedTask;
}
call.StartSendCloseFromClient(HandleSendFinished);
halfcloseRequested = true;
streamingWriteTcs = new TaskCompletionSource<object>();
return streamingWriteTcs.Task;
}
}
/// <summary>
/// Get the task that completes once if streaming response call finishes with ok status and throws RpcException with given status otherwise.
/// </summary>
public Task StreamingResponseCallFinishedTask
{
get
{
return streamingResponseCallFinishedTcs.Task;
}
}
/// <summary>
/// Get the task that completes once response headers are received.
/// </summary>
public Task<Metadata> ResponseHeadersAsync
{
get
{
return responseHeadersTcs.Task;
}
}
/// <summary>
/// Gets the resulting status if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Status GetStatus()
{
lock (myLock)
{
GrpcPreconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished.");
return finishedStatus.Value.Status;
}
}
/// <summary>
/// Gets the trailing metadata if the call has already finished.
/// Throws InvalidOperationException otherwise.
/// </summary>
public Metadata GetTrailers()
{
lock (myLock)
{
GrpcPreconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished.");
return finishedStatus.Value.Trailers;
}
}
public CallInvocationDetails<TRequest, TResponse> Details
{
get
{
return this.details;
}
}
protected override void OnAfterReleaseResources()
{
details.Channel.RemoveCallReference(this);
}
protected override bool IsClient
{
get { return true; }
}
protected override Exception GetRpcExceptionClientOnly()
{
return new RpcException(finishedStatus.Value.Status);
}
protected override Task CheckSendAllowedOrEarlyResult()
{
var earlyResult = CheckSendPreconditionsClientSide();
if (earlyResult != null)
{
return earlyResult;
}
if (finishedStatus.HasValue)
{
// throwing RpcException if we already received status on client
// side makes the most sense.
// Note that this throws even for StatusCode.OK.
// Writing after the call has finished is not a programming error because server can close
// the call anytime, so don't throw directly, but let the write task finish with an error.
var tcs = new TaskCompletionSource<object>();
tcs.SetException(new RpcException(finishedStatus.Value.Status));
return tcs.Task;
}
return null;
}
private Task CheckSendPreconditionsClientSide()
{
GrpcPreconditions.CheckState(!halfcloseRequested, "Request stream has already been completed.");
GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time.");
if (cancelRequested)
{
// Return a cancelled task.
var tcs = new TaskCompletionSource<object>();
tcs.SetCanceled();
return tcs.Task;
}
return null;
}
private void Initialize(CompletionQueueSafeHandle cq)
{
var call = CreateNativeCall(cq);
details.Channel.AddCallReference(this);
InitializeInternal(call);
RegisterCancellationCallback();
}
private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq)
{
if (injectedNativeCall != null)
{
return injectedNativeCall; // allows injecting a mock INativeCall in tests.
}
var parentCall = details.Options.PropagationToken != null ? details.Options.PropagationToken.ParentCall : CallSafeHandle.NullInstance;
var credentials = details.Options.Credentials;
using (var nativeCredentials = credentials != null ? credentials.ToNativeCredentials() : null)
{
var result = details.Channel.Handle.CreateCall(
parentCall, ContextPropagationToken.DefaultMask, cq,
details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value), nativeCredentials);
return result;
}
}
// Make sure that once cancellationToken for this call is cancelled, Cancel() will be called.
private void RegisterCancellationCallback()
{
var token = details.Options.CancellationToken;
if (token.CanBeCanceled)
{
token.Register(() => this.Cancel());
}
}
/// <summary>
/// Gets WriteFlags set in callDetails.Options.WriteOptions
/// </summary>
private WriteFlags GetWriteFlagsForCall()
{
var writeOptions = details.Options.WriteOptions;
return writeOptions != null ? writeOptions.Flags : default(WriteFlags);
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders)
{
// TODO(jtattermusch): handle success==false
responseHeadersTcs.SetResult(responseHeaders);
}
/// <summary>
/// Handler for unary response completion.
/// </summary>
private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders)
{
// NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
// success will be always set to true.
TaskCompletionSource<object> delayedStreamingWriteTcs = null;
TResponse msg = default(TResponse);
var deserializeException = TryDeserialize(receivedMessage, out msg);
lock (myLock)
{
finished = true;
if (deserializeException != null && receivedStatus.Status.StatusCode == StatusCode.OK)
{
receivedStatus = new ClientSideStatus(DeserializeResponseFailureStatus, receivedStatus.Trailers);
}
finishedStatus = receivedStatus;
if (isStreamingWriteCompletionDelayed)
{
delayedStreamingWriteTcs = streamingWriteTcs;
streamingWriteTcs = null;
}
ReleaseResourcesIfPossible();
}
responseHeadersTcs.SetResult(responseHeaders);
if (delayedStreamingWriteTcs != null)
{
delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly());
}
var status = receivedStatus.Status;
if (status.StatusCode != StatusCode.OK)
{
unaryResponseTcs.SetException(new RpcException(status));
return;
}
unaryResponseTcs.SetResult(msg);
}
/// <summary>
/// Handles receive status completion for calls with streaming response.
/// </summary>
private void HandleFinished(bool success, ClientSideStatus receivedStatus)
{
// NOTE: because this event is a result of batch containing GRPC_OP_RECV_STATUS_ON_CLIENT,
// success will be always set to true.
TaskCompletionSource<object> delayedStreamingWriteTcs = null;
lock (myLock)
{
finished = true;
finishedStatus = receivedStatus;
if (isStreamingWriteCompletionDelayed)
{
delayedStreamingWriteTcs = streamingWriteTcs;
streamingWriteTcs = null;
}
ReleaseResourcesIfPossible();
}
if (delayedStreamingWriteTcs != null)
{
delayedStreamingWriteTcs.SetException(GetRpcExceptionClientOnly());
}
var status = receivedStatus.Status;
if (status.StatusCode != StatusCode.OK)
{
streamingResponseCallFinishedTcs.SetException(new RpcException(status));
return;
}
streamingResponseCallFinishedTcs.SetResult(null);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="IISUnsafeMethods.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Hosting {
using System;
using System.Configuration;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
[
System.Runtime.InteropServices.ComVisible(false),
System.Security.SuppressUnmanagedCodeSecurityAttribute()
]
// contains only method decls and data, so no instantiation
internal unsafe static class UnsafeIISMethods {
const string _IIS_NATIVE_DLL = ModName.MGDENG_FULL_NAME;
static internal readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[DllImport(_IIS_NATIVE_DLL)]
internal unsafe static extern int MgdGetRequestBasics(
IntPtr pRequestContext,
out int pContentType,
out int pContentTotalLength,
out IntPtr pPathTranslated,
out int pcchPathTranslated,
out IntPtr pCacheUrl,
out int pcchCacheUrl,
out IntPtr pHttpMethod,
out IntPtr pCookedUrl);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetHeaderChanges(
IntPtr pRequestContext,
bool fResponse,
out IntPtr knownHeaderSnapshot,
out int unknownHeaderSnapshotCount,
out IntPtr unknownHeaderSnapshotNames,
out IntPtr unknownHeaderSnapshotValues,
out IntPtr diffKnownIndicies,
out int diffUnknownCount,
out IntPtr diffUnknownIndicies);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetServerVarChanges(
IntPtr pRequestContext,
out int count,
out IntPtr names,
out IntPtr values,
out int diffCount,
out IntPtr diffIndicies);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetServerVariableW(
IntPtr pHandler,
string pszVarName,
out IntPtr ppBuffer,
out int pcchBufferSize);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetServerVariableA(
IntPtr pHandler,
string pszVarName,
out IntPtr ppBuffer,
out int pcchBufferSize);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern IntPtr MgdGetStopListeningEventHandle();
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdSetBadRequestStatus(
IntPtr pHandler);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdSetManagedHttpContext(
IntPtr pHandler,
IntPtr pManagedHttpContext);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdSetStatusW(
IntPtr pRequestContext,
int dwStatusCode,
int dwSubStatusCode,
string pszReason,
string pszErrorDescription /* optional, can be null */,
bool fTrySkipCustomErrors);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdSetKnownHeader(
IntPtr pRequestContext,
bool fRequest,
bool fReplace,
ushort uHeaderIndex,
byte[] value,
ushort valueSize);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdSetUnknownHeader(
IntPtr pRequestContext,
bool fRequest,
bool fReplace,
byte [] header,
byte [] value,
ushort valueSize);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdFlushCore(
IntPtr pRequestContext,
bool keepConnected,
int numBodyFragments,
IntPtr[] bodyFragments,
int[] bodyFragmentLengths,
int[] fragmentsNative);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdSetKernelCachePolicy(
IntPtr pHandler,
int secondsToLive);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdFlushKernelCache(
string cacheKey);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdDisableKernelCache(
IntPtr pHandler);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdDisableUserCache(
IntPtr pHandler);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdRegisterEventSubscription(
IntPtr pAppContext,
string pszModuleName,
[MarshalAs(UnmanagedType.U4)]
RequestNotification requestNotifications,
[MarshalAs(UnmanagedType.U4)]
RequestNotification postRequestNotifications,
string pszModuleType,
string pszModulePrecondition,
IntPtr moduleSpecificData,
bool useHighPriority);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdIndicateCompletion(
IntPtr pHandler,
[MarshalAs(UnmanagedType.U4)]
ref RequestNotificationStatus notificationStatus );
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdInsertEntityBody(
IntPtr pHandler,
byte[] buffer,
int offset,
int count);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdPostCompletion(
IntPtr pHandler,
[MarshalAs(UnmanagedType.U4)]
RequestNotificationStatus notificationStatus );
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdReadEntityBody(
IntPtr pHandler,
byte[] pBuffer,
int dwOffset,
int dwBytesToRead,
bool fAsync,
out int pBytesRead,
out IntPtr ppAsyncReceiveBuffer );
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetCorrelationIdHeader(
IntPtr pHandler,
out IntPtr correlationId,
out ushort correlationIdLength,
out bool base64BinaryFormat);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetUserToken(
IntPtr pHandler,
out IntPtr pToken );
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetVirtualToken(
IntPtr pHandler,
out IntPtr pToken );
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern bool MgdIsClientConnected(
IntPtr pHandler);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern bool MgdIsHandlerExecutionDenied(
IntPtr pHandler);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's sole caller.")]
internal static extern void MgdAbortConnection(
IntPtr pHandler);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern void MgdCloseConnection(
IntPtr pHandler);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetHandlerTypeString(
IntPtr pHandler,
out IntPtr ppszTypeString,
out int pcchTypeString);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetApplicationInfo(
IntPtr pHandler,
out IntPtr pVirtualPath,
out int cchVirtualPath,
out IntPtr pPhysPath,
out int cchPhysPath);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetUriPath(
IntPtr pHandler,
out IntPtr ppPath,
out int pcchPath,
bool fIncludePathInfo,
bool fUseParentContext);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetPreloadedContent(
IntPtr pHandler,
byte[] pBuffer,
int lOffset,
int cbLen,
out int pcbReceived);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetPreloadedSize(
IntPtr pHandler,
out int pcbAvailable);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetPrincipal(
IntPtr pHandler,
int dwRequestingAppDomainId,
out IntPtr pToken,
out IntPtr ppAuthType,
ref int pcchAuthType,
out IntPtr ppUserName,
ref int pcchUserName,
out IntPtr pManagedPrincipal);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdIsInRole(
IntPtr pHandler,
string pszRoleName,
out bool pfIsInRole);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern IntPtr MgdAllocateRequestMemory(
IntPtr pHandler,
int cbSize);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdAppDomainShutdown(
IntPtr appContext );
// Buffer pool methods
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern IntPtr /* W3_MGD_BUFFER_POOL* */
MgdGetBufferPool(int cbBufferSize);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern IntPtr /* PBYTE * */
MgdGetBuffer(IntPtr pPool);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern IntPtr /* W3_MGD_BUFFER_POOL* */
MgdReturnBuffer(IntPtr pBuffer);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int /* DWORD */
MgdGetLocalPort(IntPtr context);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int /* DWORD */
MgdGetRemotePort(IntPtr context);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetUserAgent(
IntPtr pRequestContext,
out IntPtr pBuffer,
out int cbBufferSize);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetCookieHeader(
IntPtr pRequestContext,
out IntPtr pBuffer,
out int cbBufferSize);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdRewriteUrl(
IntPtr pRequestContext,
string pszUrl,
bool fResetQueryString );
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetMaxConcurrentRequestsPerCPU();
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetMaxConcurrentThreadsPerCPU();
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdSetMaxConcurrentRequestsPerCPU(int value);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdSetMaxConcurrentThreadsPerCPU(int value);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetCurrentModuleName(
IntPtr pHandler,
out IntPtr pBuffer,
out int cbBufferSize);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetCurrentNotification(
IntPtr pRequestContext);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdDisableNotifications(
IntPtr pRequestContext,
[MarshalAs(UnmanagedType.U4)]
RequestNotification notifications,
[MarshalAs(UnmanagedType.U4)]
RequestNotification postNotifications);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdSuppressSendResponseNotifications(
IntPtr pRequestContext);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetNextNotification(
IntPtr pRequestContext,
[MarshalAs(UnmanagedType.U4)]
RequestNotificationStatus dwStatus);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdClearResponse(
IntPtr pRequestContext,
bool fClearEntity,
bool fClearHeaders);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdCreateNativeConfigSystem(
out IntPtr ppConfigSystem);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdReleaseNativeConfigSystem(
IntPtr pConfigSystem);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetRequestTraceGuid(
IntPtr pRequestContext,
out Guid traceContextId);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetStatusChanges(
IntPtr pRequestContext,
out ushort statusCode,
out ushort subStatusCode,
out IntPtr pBuffer,
out ushort cbBufferSize);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetResponseChunks(
IntPtr pRequestContext,
ref int fragmentCount,
IntPtr[] bodyFragments,
int[] bodyFragmentLengths,
int[] fragmentChunkType);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdEtwGetTraceConfig(
IntPtr pRequestContext,
out bool providerEnabled,
out int flags,
out int level);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdEmitSimpleTrace(
IntPtr pRequestContext,
int type,
string eventData);
[DllImport(_IIS_NATIVE_DLL, CharSet = CharSet.Unicode)]
internal static extern int MgdEmitWebEventTrace(
IntPtr pRequestContext,
int webEventType,
int fieldCount,
string[] fieldNames,
int[] fieldTypes,
string[] fieldData);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdSetRequestPrincipal(
IntPtr pRequestContext,
string userName,
string authType,
IntPtr token);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern bool MgdCanDisposeManagedContext(
IntPtr pRequestContext,
[MarshalAs(UnmanagedType.U4)]
RequestNotificationStatus dwStatus);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern bool MgdIsLastNotification(
IntPtr pRequestContext,
[MarshalAs(UnmanagedType.U4)]
RequestNotificationStatus dwStatus);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern bool MgdIsWithinApp(
IntPtr pConfigSystem,
string siteName,
string appPath,
string virtualPath);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetSiteNameFromId(
IntPtr pConfigSystem,
[MarshalAs(UnmanagedType.U4)]
uint siteId,
out IntPtr bstrSiteName,
out int cchSiteName);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetAppPathForPath(
IntPtr pConfigSystem,
[MarshalAs(UnmanagedType.U4)]
uint siteId,
string virtualPath,
out IntPtr bstrPath,
out int cchPath);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetMemoryLimitKB(
out long limit);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetMimeMapCollection(
IntPtr pConfigSystem,
IntPtr appContext,
out IntPtr pMimeMapCollection,
out int count);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetModuleCollection(
IntPtr pConfigSystem,
IntPtr appContext,
out IntPtr pModuleCollection,
out int count);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetNextMimeMap(
IntPtr pMimeMapCollection,
uint dwIndex,
out IntPtr bstrFileExtension,
out int cchFileExtension,
out IntPtr bstrMimeType,
out int cchMimeType);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetNextModule(
IntPtr pModuleCollection,
ref uint dwIndex,
out IntPtr bstrModuleName,
out int cchModuleName,
out IntPtr bstrModuleType,
out int cchModuleType,
out IntPtr bstrModulePrecondition,
out int cchModulePrecondition);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetVrPathCreds(
IntPtr pConfigSystem,
string siteName,
string virtualPath,
out IntPtr bstrUserName,
out int cchUserName,
out IntPtr bstrPassword,
out int cchPassword);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetAppCollection(
IntPtr pConfigSystem,
string siteName,
string virtualPath,
out IntPtr bstrPath,
out int cchPath,
out IntPtr pAppCollection,
out int count);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetNextVPath(
IntPtr pAppCollection,
uint dwIndex,
out IntPtr bstrPath,
out int cchPath);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdInitNativeConfig();
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdTerminateNativeConfig();
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdMapPathDirect(
IntPtr pConfigSystem,
string siteName,
string virtualPath,
out IntPtr bstrPhysicalPath,
out int cchPath);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdMapHandler(
IntPtr pHandler,
string method,
string virtualPath,
out IntPtr ppszTypeString,
out int pcchTypeString,
bool convertNativeStaticFileModule,
bool ignoreWildcardMappings);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdReMapHandler(
IntPtr pHandler,
string pszVirtualPath,
out IntPtr ppszTypeString,
out int pcchTypeString,
out bool pfHandlerExists);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdSetRemapHandler(
IntPtr pHandler,
string pszName,
string ppszType);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdSetScriptMapForRemapHandler(
IntPtr pHandler);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdSetNativeConfiguration(
IntPtr nativeConfig);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.U4)]
internal static extern uint MgdResolveSiteName(
IntPtr pConfigSystem,
string siteName);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdSetResponseFilter(
IntPtr context);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetFileChunkInfo(
IntPtr context,
int chunkOffset,
out long offset,
out long length);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdReadChunkHandle(
IntPtr context,
IntPtr FileHandle,
long startOffset,
ref int length,
IntPtr chunkEntity);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdExplicitFlush(
IntPtr context,
bool async,
out bool completedSynchronously);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdSetServerVariableW(
IntPtr context,
string variableName,
string variableValue);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdExecuteUrl(
IntPtr context,
string url,
bool resetQuerystring,
bool preserveForm,
byte[] entityBody,
uint entityBodySize,
string method,
int numHeaders,
string[] headersNames,
string[] headersValues,
bool preserveUser);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetClientCertificate(
IntPtr pHandler,
out IntPtr ppbClientCert,
out int pcbClientCert,
out IntPtr ppbClientCertIssuer,
out int pcbClientCertIssuer,
out IntPtr ppbClientCertPublicKey,
out int pcbClientCertPublicKey,
out uint pdwCertEncodingType,
out long ftNotBefore,
out long ftNotAfter);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern int MgdGetChannelBindingToken(
IntPtr pHandler,
out IntPtr ppbToken,
out int pcbTokenSize);
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdGetCurrentNotificationInfo(
IntPtr pHandler,
out int currentModuleIndex,
out bool isPostNotification,
out int currentNotification);
[DllImport(_IIS_NATIVE_DLL)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's sole caller.")]
internal static extern int MgdAcceptWebSocket(
IntPtr pHandler);
[DllImport(_IIS_NATIVE_DLL)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's sole caller.")]
internal static extern int MgdGetWebSocketContext(
IntPtr pHandler,
out IntPtr ppWebSocketContext);
[DllImport(_IIS_NATIVE_DLL, CharSet=CharSet.Unicode)]
internal static extern int MgdGetAnonymousUserToken(
IntPtr pHandler,
out IntPtr pToken );
[DllImport(_IIS_NATIVE_DLL)]
internal static extern void MgdGetIISVersionInformation(
[Out] out uint pdwVersion,
[Out] out bool pfIsIntegratedMode);
[DllImport(_IIS_NATIVE_DLL)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")]
internal static extern int MgdConfigureAsyncDisconnectNotification(
[In] IntPtr pHandler,
[In] bool fEnable,
[Out] out bool pfIsClientConnected);
[DllImport(_IIS_NATIVE_DLL)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")]
internal static extern int MgdGetIsChildContext(
[In] IntPtr pHandler,
[Out] out bool pfIsChildContext);
[DllImport(_IIS_NATIVE_DLL)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")]
internal static extern int MgdGetConfigProperty(
[In, MarshalAs(UnmanagedType.BStr)] string appConfigMetabasePath,
[In, MarshalAs(UnmanagedType.BStr)] string sectionName,
[In, MarshalAs(UnmanagedType.BStr)] string propertyName,
[Out, MarshalAs(UnmanagedType.Struct)] out object value); // marshaled as VARIANT
[DllImport(_IIS_NATIVE_DLL)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")]
internal static extern int MgdPushPromise(
[In] IntPtr context,
[In, MarshalAs(UnmanagedType.LPWStr)] string path,
[In, MarshalAs(UnmanagedType.LPWStr)] string queryString,
[In, MarshalAs(UnmanagedType.LPStr)] string method,
[In] int numHeaders,
[In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPStr)] string[] headersNames,
[In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] headersValues);
[DllImport(_IIS_NATIVE_DLL)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")]
internal static extern bool MgdIsAppPoolShuttingDown();
[DllImport(_IIS_NATIVE_DLL)]
[SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage", Justification = "We carefully control this method's callers.")]
internal static extern int MgdGetTlsTokenBindingIdentifiers(
[In] IntPtr pHandler,
[In, Out] ref IntPtr tokenBindingHandle,
[Out] out IntPtr providedToken,
[Out] out uint providedTokenSize,
[Out] out IntPtr referredToken,
[Out] out uint referredTokenSize);
}
}
| |
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
namespace Meziantou.Framework;
public static partial class ProcessExtensions
{
#if NETCOREAPP3_1_OR_GREATER
[Obsolete("Already implemented in .NET 3.1")]
public static void Kill(Process process!!, bool entireProcessTree = false)
{
process.Kill(entireProcessTree);
}
#else
public static void Kill(this Process process!!, bool entireProcessTree = false)
{
if (!entireProcessTree)
{
process.Kill();
return;
}
if (!IsWindows())
throw new PlatformNotSupportedException("Only supported on Windows");
var childProcesses = GetDescendantProcesses(process);
if (!process.HasExited)
{
process.Kill();
}
foreach (var childProcess in childProcesses)
{
if (!childProcess.HasExited)
{
if (!childProcess.HasExited)
{
childProcess.Kill();
}
}
}
}
#endif
[SupportedOSPlatform("windows")]
public static IReadOnlyList<Process> GetDescendantProcesses(this Process process!!)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
throw new PlatformNotSupportedException("Only supported on Windows");
var children = new List<Process>();
GetChildProcesses(process, children, int.MaxValue, 0);
return children;
}
[SupportedOSPlatform("windows")]
public static IReadOnlyList<Process> GetChildProcesses(this Process process!!)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
throw new PlatformNotSupportedException("Only supported on Windows");
var children = new List<Process>();
GetChildProcesses(process, children, 1, 0);
return children;
}
[SupportedOSPlatform("windows")]
public static IEnumerable<int> GetAncestorProcessIds(this Process process!!)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
throw new PlatformNotSupportedException("Only supported on Windows");
return GetAncestorProcessIdsIterator();
IEnumerable<int> GetAncestorProcessIdsIterator()
{
var returnedProcesses = new HashSet<int>();
var processId = process.Id;
var processes = GetProcesses().ToList();
var found = true;
while (found)
{
found = false;
foreach (var entry in processes)
{
if (entry.ProcessId == processId)
{
if (returnedProcesses.Add(entry.ParentProcessId))
{
yield return entry.ParentProcessId;
processId = entry.ParentProcessId;
found = true;
}
}
}
if (!found)
yield break;
}
}
}
[SupportedOSPlatform("windows")]
public static IEnumerable<Process> GetAncestorProcesses(this Process process!!)
{
return GetAncestorProcesses();
IEnumerable<Process> GetAncestorProcesses()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
throw new PlatformNotSupportedException("Only supported on Windows");
foreach (var entry in GetAncestorProcessIdsIterator())
{
Process? p = null;
try
{
p = entry.ToProcess();
if (p == null || p.StartTime > process.StartTime)
continue;
}
catch (ArgumentException)
{
// process might have exited since the snapshot, ignore it
}
if (p != null)
{
yield return p;
}
}
IEnumerable<ProcessEntry> GetAncestorProcessIdsIterator()
{
var returnedProcesses = new HashSet<int>();
var processId = process.Id;
var processes = GetProcesses().ToList();
var found = true;
while (found)
{
found = false;
foreach (var entry in processes)
{
if (entry.ProcessId == processId)
{
if (returnedProcesses.Add(entry.ParentProcessId))
{
yield return entry;
processId = entry.ParentProcessId;
found = true;
}
}
}
if (!found)
yield break;
}
}
}
}
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
public static int? GetParentProcessId(this Process process!!)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var processId = process.Id;
foreach (var entry in GetProcesses())
{
if (entry.ProcessId == processId)
{
return entry.ParentProcessId;
}
}
}
else
{
var processId = process.Id;
try
{
using var stream = File.OpenRead("/proc/" + processId.ToStringInvariant() + "/status");
using var sr = new StreamReader(stream);
string? line;
while ((line = sr.ReadLine()) != null)
{
const string Prefix = "PPid:";
if (line.StartsWith(Prefix, StringComparison.Ordinal))
{
if (int.TryParse(line[Prefix.Length..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var ppid))
return ppid;
}
}
}
catch (FileNotFoundException)
{
}
catch (DirectoryNotFoundException)
{
}
}
return null;
}
[SupportedOSPlatform("windows")]
[SupportedOSPlatform("linux")]
public static Process? GetParentProcess(this Process process)
{
var parentProcessId = GetParentProcessId(process);
if (parentProcessId == null)
return null;
var parentProcess = Process.GetProcessById(parentProcessId.Value);
if (parentProcess == null || parentProcess.StartTime > process.StartTime)
return null;
return parentProcess;
}
[SupportedOSPlatform("windows")]
public static IEnumerable<ProcessEntry> GetProcesses()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
throw new PlatformNotSupportedException("Only supported on Windows");
using var snapShotHandle = CreateToolhelp32Snapshot(SnapshotFlags.TH32CS_SNAPPROCESS, 0);
var entry = new ProcessEntry32
{
dwSize = (uint)Marshal.SizeOf(typeof(ProcessEntry32)),
};
var result = Process32First(snapShotHandle, ref entry);
while (result != 0)
{
yield return new ProcessEntry(entry.th32ProcessID, entry.th32ParentProcessID);
result = Process32Next(snapShotHandle, ref entry);
}
}
[SupportedOSPlatform("windows")]
private static void GetChildProcesses(Process process, List<Process> children, int maxDepth, int currentDepth)
{
var entries = new List<ProcessEntry>(100);
foreach (var entry in GetProcesses())
{
entries.Add(entry);
}
GetChildProcesses(entries, process, children, maxDepth, currentDepth);
}
private static void GetChildProcesses(List<ProcessEntry> entries, Process process, List<Process> children, int maxDepth, int currentDepth)
{
var processId = process.Id;
foreach (var entry in entries)
{
if (entry.ParentProcessId == processId)
{
try
{
var child = entry.ToProcess();
if (child == null || child.StartTime < process.StartTime)
continue;
children.Add(child);
if (currentDepth < maxDepth)
{
GetChildProcesses(entries, child, children, maxDepth, currentDepth + 1);
}
}
catch (ArgumentException)
{
// process might have exited since the snapshot, ignore it
}
}
}
}
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int Process32First(SnapshotSafeHandle handle, ref ProcessEntry32 entry);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int Process32Next(SnapshotSafeHandle handle, ref ProcessEntry32 entry);
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms682489.aspx
[DllImport("kernel32.dll", SetLastError = true)]
private static extern SnapshotSafeHandle CreateToolhelp32Snapshot(SnapshotFlags dwFlags, uint th32ProcessID);
private const int MAX_PATH = 260;
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684839.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct ProcessEntry32
{
#pragma warning disable IDE1006 // Naming Styles
public uint dwSize;
public uint cntUsage;
public int th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public int th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string szExeFile;
#pragma warning restore IDE1006 // Naming Styles
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms682489.aspx
private enum SnapshotFlags : uint
{
TH32CS_SNAPHEAPLIST = 0x00000001,
TH32CS_SNAPPROCESS = 0x00000002,
TH32CS_SNAPTHREAD = 0x00000004,
TH32CS_SNAPMODULE = 0x00000008,
TH32CS_SNAPMODULE32 = 0x00000010,
TH32CS_INHERIT = 0x80000000,
}
private sealed class SnapshotSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public SnapshotSafeHandle()
: base(ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
}
| |
using EPiServer.Commerce.Catalog.ContentTypes;
using EPiServer.Commerce.Catalog.Linking;
using EPiServer.Commerce.Marketing;
using EPiServer.Commerce.Order;
using EPiServer.Reference.Commerce.Site.Features.AddressBook.Services;
using EPiServer.Reference.Commerce.Site.Features.Cart.Extensions;
using EPiServer.Reference.Commerce.Site.Features.Cart.ViewModels;
using EPiServer.Reference.Commerce.Site.Features.Market.Services;
using EPiServer.Reference.Commerce.Site.Features.Product.Services;
using EPiServer.Reference.Commerce.Site.Features.Shared.Models;
using EPiServer.Reference.Commerce.Site.Features.Shared.Services;
using EPiServer.Reference.Commerce.Site.Infrastructure.Facades;
using EPiServer.ServiceLocation;
using Mediachase.Commerce;
using Mediachase.Commerce.Catalog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EPiServer.Reference.Commerce.Site.Features.Cart.Services
{
[ServiceConfiguration(typeof(ICartService), Lifecycle = ServiceInstanceScope.Singleton)]
public class CartService : ICartService
{
private readonly IProductService _productService;
private readonly IPricingService _pricingService;
private readonly IOrderGroupFactory _orderGroupFactory;
private readonly CustomerContextFacade _customerContext;
private readonly IPlacedPriceProcessor _placedPriceProcessor;
private readonly IInventoryProcessor _inventoryProcessor;
private readonly ILineItemValidator _lineItemValidator;
private readonly IPromotionEngine _promotionEngine;
private readonly IOrderRepository _orderRepository;
private readonly IAddressBookService _addressBookService;
private readonly ICurrentMarket _currentMarket;
private readonly ICurrencyService _currencyService;
private readonly ReferenceConverter _referenceConverter;
private readonly IContentLoader _contentLoader;
private readonly IRelationRepository _relationRepository;
public CartService(
IProductService productService,
IPricingService pricingService,
IOrderGroupFactory orderGroupFactory,
CustomerContextFacade customerContext,
IPlacedPriceProcessor placedPriceProcessor,
IInventoryProcessor inventoryProcessor,
ILineItemValidator lineItemValidator,
IOrderRepository orderRepository,
IPromotionEngine promotionEngine,
IAddressBookService addressBookService,
ICurrentMarket currentMarket,
ICurrencyService currencyService,
ReferenceConverter referenceConverter,
IContentLoader contentLoader,
IRelationRepository relationRepository)
{
_productService = productService;
_pricingService = pricingService;
_orderGroupFactory = orderGroupFactory;
_customerContext = customerContext;
_placedPriceProcessor = placedPriceProcessor;
_inventoryProcessor = inventoryProcessor;
_lineItemValidator = lineItemValidator;
_promotionEngine = promotionEngine;
_orderRepository = orderRepository;
_addressBookService = addressBookService;
_currentMarket = currentMarket;
_currencyService = currencyService;
_referenceConverter = referenceConverter;
_contentLoader = contentLoader;
_relationRepository = relationRepository;
}
public void ChangeCartItem(ICart cart, int shipmentId, string code, decimal quantity, string size, string newSize)
{
if (quantity > 0)
{
if (size == newSize)
{
ChangeQuantity(cart, shipmentId, code, quantity);
}
else
{
var newCode = _productService.GetSiblingVariantCodeBySize(code, newSize);
UpdateLineItemSku(cart, shipmentId, code, newCode, quantity);
}
}
else
{
RemoveLineItem(cart, shipmentId, code);
}
}
public string DefaultCartName
{
get { return "Default"; }
}
public string DefaultWishListName
{
get { return "WishList"; }
}
public void RecreateLineItemsBasedOnShipments(ICart cart, IEnumerable<CartItemViewModel> cartItems, IEnumerable<AddressModel> addresses)
{
var form = cart.GetFirstForm();
var items = cartItems
.GroupBy(x => new { x.AddressId, x.Code, x.IsGift })
.Select(x => new
{
Code = x.Key.Code,
AddressId = x.Key.AddressId,
Quantity = x.Count(),
IsGift = x.Key.IsGift
});
foreach (var shipment in form.Shipments)
{
shipment.LineItems.Clear();
}
form.Shipments.Clear();
foreach (var address in addresses)
{
var shipment = cart.CreateShipment(_orderGroupFactory);
form.Shipments.Add(shipment);
shipment.ShippingAddress = _addressBookService.ConvertToAddress(address, cart);
foreach (var item in items.Where(x => x.AddressId == address.AddressId))
{
var lineItem = cart.CreateLineItem(item.Code, _orderGroupFactory);
lineItem.IsGift = item.IsGift;
lineItem.Quantity = item.Quantity;
shipment.LineItems.Add(lineItem);
}
}
ValidateCart(cart);
}
public void MergeShipments(ICart cart)
{
if (cart == null || !cart.GetAllLineItems().Any())
{
return;
}
var form = cart.GetFirstForm();
var keptShipment = cart.GetFirstShipment();
var removedShipments = form.Shipments.Skip(1).ToList();
var movedLineItems = removedShipments.SelectMany(x => x.LineItems).ToList();
removedShipments.ForEach(x => x.LineItems.Clear());
removedShipments.ForEach(x => cart.GetFirstForm().Shipments.Remove(x));
foreach (var item in movedLineItems)
{
var existingLineItem = keptShipment.LineItems.SingleOrDefault(x => x.Code == item.Code);
if (existingLineItem != null)
{
existingLineItem.Quantity += item.Quantity;
continue;
}
keptShipment.LineItems.Add(item);
}
ValidateCart(cart);
}
public AddToCartResult AddToCart(ICart cart, string code, decimal quantity)
{
var result = new AddToCartResult();
var contentLink = _referenceConverter.GetContentLink(code);
var entryContent = _contentLoader.Get<EntryContentBase>(contentLink);
if (entryContent is BundleContent)
{
foreach (var relation in _relationRepository.GetRelationsBySource<BundleEntry>(contentLink))
{
var entry = _contentLoader.Get<EntryContentBase>(relation.Target);
var recursiveResult = AddToCart(cart, entry.Code, relation.Quantity ?? 1);
if (recursiveResult.EntriesAddedToCart)
{
result.EntriesAddedToCart = true;
}
foreach (var message in recursiveResult.ValidationMessages)
{
result.ValidationMessages.Add(message);
}
}
return result;
}
var lineItem = cart.GetAllLineItems().FirstOrDefault(x => x.Code == code);
if (lineItem == null)
{
lineItem = cart.CreateLineItem(code, _orderGroupFactory);
lineItem.DisplayName = entryContent.DisplayName;
lineItem.Quantity = quantity;
cart.AddLineItem(lineItem, _orderGroupFactory);
}
else
{
var shipment = cart.GetFirstShipment();
cart.UpdateLineItemQuantity(shipment, lineItem, lineItem.Quantity + quantity);
}
var validationIssues = ValidateCart(cart);
AddValidationMessagesToResult(result, lineItem, validationIssues);
return result;
}
public void SetCartCurrency(ICart cart, Currency currency)
{
if (currency.IsEmpty || currency == cart.Currency)
{
return;
}
cart.Currency = currency;
foreach (var lineItem in cart.GetAllLineItems())
{
// If there is an item which has no price in the new currency, a NullReference exception will be thrown.
// Mixing currencies in cart is not allowed.
// It's up to site's managers to ensure that all items have prices in allowed currency.
lineItem.PlacedPrice = _pricingService.GetPrice(lineItem.Code, cart.Market.MarketId, currency).Value.Amount;
}
ValidateCart(cart);
}
public Dictionary<ILineItem, List<ValidationIssue>> ValidateCart(ICart cart)
{
if (cart.Name.Equals(DefaultWishListName))
{
return new Dictionary<ILineItem, List<ValidationIssue>>();
}
var validationIssues = new Dictionary<ILineItem, List<ValidationIssue>>();
cart.ValidateOrRemoveLineItems((item, issue) => validationIssues.AddValidationIssues(item, issue), _lineItemValidator);
cart.UpdatePlacedPriceOrRemoveLineItems(_customerContext.GetContactById(cart.CustomerId), (item, issue) => validationIssues.AddValidationIssues(item, issue), _placedPriceProcessor);
cart.UpdateInventoryOrRemoveLineItems((item, issue) => validationIssues.AddValidationIssues(item, issue), _inventoryProcessor);
cart.ApplyDiscounts(_promotionEngine, new PromotionEngineSettings());
return validationIssues;
}
public Dictionary<ILineItem, List<ValidationIssue>> RequestInventory(ICart cart)
{
var validationIssues = new Dictionary<ILineItem, List<ValidationIssue>>();
cart.AdjustInventoryOrRemoveLineItems((item, issue) => validationIssues.AddValidationIssues(item, issue), _inventoryProcessor);
return validationIssues;
}
public ICart LoadCart(string name)
{
var cart = _orderRepository.LoadCart<ICart>(_customerContext.CurrentContactId, name, _currentMarket);
if (cart != null)
{
SetCartCurrency(cart, _currencyService.GetCurrentCurrency());
var validationIssues = ValidateCart(cart);
// After validate, if there is any change in cart, saving cart.
if (validationIssues.Any())
{
_orderRepository.Save(cart);
}
}
return cart;
}
public ICart LoadOrCreateCart(string name)
{
var cart = _orderRepository.LoadOrCreateCart<ICart>(_customerContext.CurrentContactId, name, _currentMarket);
if (cart != null)
{
SetCartCurrency(cart, _currencyService.GetCurrentCurrency());
}
return cart;
}
public bool AddCouponCode(ICart cart, string couponCode)
{
var couponCodes = cart.GetFirstForm().CouponCodes;
if (couponCodes.Any(c => c.Equals(couponCode, StringComparison.OrdinalIgnoreCase)))
{
return false;
}
couponCodes.Add(couponCode);
var rewardDescriptions = cart.ApplyDiscounts(_promotionEngine, new PromotionEngineSettings());
var appliedCoupons = rewardDescriptions
.Where(r => r.AppliedCoupon != null)
.Select(r => r.AppliedCoupon);
var couponApplied = appliedCoupons.Any(c => c.Equals(couponCode, StringComparison.OrdinalIgnoreCase));
if (!couponApplied)
{
couponCodes.Remove(couponCode);
}
return couponApplied;
}
public void RemoveCouponCode(ICart cart, string couponCode)
{
cart.GetFirstForm().CouponCodes.Remove(couponCode);
cart.ApplyDiscounts(_promotionEngine, new PromotionEngineSettings());
}
private void RemoveLineItem(ICart cart, int shipmentId, string code)
{
//gets the shipment for shipment id or for wish list shipment id as a parameter is always equal zero( wish list).
var shipment = cart.GetFirstForm().Shipments.First(s => s.ShipmentId == shipmentId || shipmentId == 0);
var lineItem = shipment.LineItems.FirstOrDefault(l => l.Code == code);
if (lineItem != null)
{
shipment.LineItems.Remove(lineItem);
}
if (!shipment.LineItems.Any())
{
cart.GetFirstForm().Shipments.Remove(shipment);
}
ValidateCart(cart);
}
private static void AddValidationMessagesToResult(AddToCartResult result, ILineItem lineItem, Dictionary<ILineItem, List<ValidationIssue>> validationIssues)
{
foreach (var validationIssue in validationIssues)
{
var warning = new StringBuilder();
warning.Append(string.Format("Line Item with code {0} ", lineItem.Code));
validationIssue.Value.Aggregate(warning, (current, issue) => current.Append(issue));
result.ValidationMessages.Add(warning.ToString());
}
if (!validationIssues.HasItemBeenRemoved(lineItem))
{
result.EntriesAddedToCart = true;
}
}
private void UpdateLineItemSku(ICart cart, int shipmentId, string oldCode, string newCode, decimal quantity)
{
RemoveLineItem(cart, shipmentId, oldCode);
//merge same sku's
var newLineItem = GetFirstLineItem(cart, newCode);
if (newLineItem != null)
{
var shipment = cart.GetFirstForm().Shipments.First(s => s.ShipmentId == shipmentId || shipmentId == 0);
cart.UpdateLineItemQuantity(shipment, newLineItem, newLineItem.Quantity + quantity);
}
else
{
newLineItem = cart.CreateLineItem(newCode, _orderGroupFactory);
newLineItem.Quantity = quantity;
cart.AddLineItem(newLineItem, _orderGroupFactory);
var price = _pricingService.GetCurrentPrice(newCode);
if (price.HasValue)
{
newLineItem.PlacedPrice = price.Value.Amount;
}
}
ValidateCart(cart);
}
private void ChangeQuantity(ICart cart, int shipmentId, string code, decimal quantity)
{
if (quantity == 0)
{
RemoveLineItem(cart, shipmentId, code);
}
var shipment = cart.GetFirstForm().Shipments.First(s => s.ShipmentId == shipmentId);
var lineItem = shipment.LineItems.FirstOrDefault(x => x.Code == code);
if (lineItem == null)
{
return;
}
cart.UpdateLineItemQuantity(shipment, lineItem, quantity);
ValidateCart(cart);
}
private ILineItem GetFirstLineItem(IOrderGroup cart, string code)
{
return cart.GetAllLineItems().FirstOrDefault(x => x.Code == code);
}
}
}
| |
//Uncomment the next line to enable debugging (also uncomment it in AstarPath.cs)
//#define ProfileAstar //@SHOWINEDITOR
//#define UNITY_PRO_PROFILER //@SHOWINEDITOR Requires ProfileAstar, profiles section of astar code which will show up in the Unity Pro Profiler.
using System.Collections.Generic;
using System;
using UnityEngine;
using Pathfinding;
namespace Pathfinding {
public class AstarProfiler
{
public class ProfilePoint
{
//public DateTime lastRecorded;
//public TimeSpan totalTime;
public System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
public int totalCalls;
public long tmpBytes;
public long totalBytes;
}
private static Dictionary<string, ProfilePoint> profiles = new Dictionary<string, ProfilePoint>();
private static DateTime startTime = DateTime.UtcNow;
public static ProfilePoint[] fastProfiles;
public static string[] fastProfileNames;
private AstarProfiler()
{
}
[System.Diagnostics.Conditional ("ProfileAstar")]
public static void InitializeFastProfile (string[] profileNames) {
fastProfileNames = new string[profileNames.Length+2];
Array.Copy (profileNames,fastProfileNames, profileNames.Length);
fastProfileNames[fastProfileNames.Length-2] = "__Control1__";
fastProfileNames[fastProfileNames.Length-1] = "__Control2__";
fastProfiles = new ProfilePoint[fastProfileNames.Length];
for (int i=0;i<fastProfiles.Length;i++) fastProfiles[i] = new ProfilePoint();
}
[System.Diagnostics.Conditional ("ProfileAstar")]
public static void StartFastProfile(int tag)
{
//profiles.TryGetValue(tag, out point);
fastProfiles[tag].watch.Start();//lastRecorded = DateTime.UtcNow;
}
[System.Diagnostics.Conditional ("ProfileAstar")]
public static void EndFastProfile(int tag)
{
/*if (!profiles.ContainsKey(tag))
{
Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")");
return;
}*/
ProfilePoint point = fastProfiles[tag];
point.totalCalls++;
point.watch.Stop ();
//DateTime now = DateTime.UtcNow;
//point.totalTime += now - point.lastRecorded;
//fastProfiles[tag] = point;
}
[System.Diagnostics.Conditional ("UNITY_PRO_PROFILER")]
public static void EndProfile () {
Profiler.EndSample ();
}
[System.Diagnostics.Conditional ("ProfileAstar")]
public static void StartProfile(string tag)
{
//Console.WriteLine ("Profile Start - " + tag);
ProfilePoint point;
profiles.TryGetValue(tag, out point);
if (point == null) {
point = new ProfilePoint();
profiles[tag] = point;
}
point.tmpBytes = System.GC.GetTotalMemory (false);
point.watch.Start();
//point.lastRecorded = DateTime.UtcNow;
//Debug.Log ("Starting " + tag);
}
[System.Diagnostics.Conditional ("ProfileAstar")]
public static void EndProfile(string tag)
{
if (!profiles.ContainsKey(tag))
{
Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")");
return;
}
//Console.WriteLine ("Profile End - " + tag);
//DateTime now = DateTime.UtcNow;
ProfilePoint point = profiles[tag];
//point.totalTime += now - point.lastRecorded;
++point.totalCalls;
point.watch.Stop();
point.totalBytes += System.GC.GetTotalMemory (false) - point.tmpBytes;
//profiles[tag] = point;
//Debug.Log ("Ending " + tag);
}
[System.Diagnostics.Conditional ("ProfileAstar")]
public static void Reset()
{
profiles.Clear();
startTime = DateTime.UtcNow;
if (fastProfiles != null) {
for (int i=0;i<fastProfiles.Length;i++) {
fastProfiles[i] = new ProfilePoint ();
}
}
}
[System.Diagnostics.Conditional ("ProfileAstar")]
public static void PrintFastResults()
{
StartFastProfile (fastProfiles.Length-2);
for (int i=0;i<1000;i++) {
StartFastProfile (fastProfiles.Length-1);
EndFastProfile (fastProfiles.Length-1);
}
EndFastProfile (fastProfiles.Length-2);
double avgOverhead = fastProfiles[fastProfiles.Length-2].watch.Elapsed.TotalMilliseconds / 1000.0;
TimeSpan endTime = DateTime.UtcNow - startTime;
System.Text.StringBuilder output = new System.Text.StringBuilder();
output.Append("============================\n\t\t\t\tProfile results:\n============================\n");
output.Append ("Name | Total Time | Total Calls | Avg/Call | Bytes");
//foreach(KeyValuePair<string, ProfilePoint> pair in profiles)
for (int i=0;i<fastProfiles.Length;i++)
{
string name = fastProfileNames[i];
ProfilePoint value = fastProfiles[i];
int totalCalls = value.totalCalls;
double totalTime = value.watch.Elapsed.TotalMilliseconds - avgOverhead*totalCalls;
if (totalCalls < 1) continue;
output.Append ("\n").Append(name.PadLeft(10)).Append("| ");
output.Append (totalTime.ToString("0.0 ").PadLeft (10)).Append(value.watch.Elapsed.TotalMilliseconds.ToString("(0.0)").PadLeft(10)).Append ("| ");
output.Append (totalCalls.ToString().PadLeft (10)).Append ("| ");
output.Append ((totalTime / totalCalls).ToString("0.000").PadLeft(10));
/* output.Append("\nProfile");
output.Append(name);
output.Append(" took \t");
output.Append(totalTime.ToString("0.0"));
output.Append(" ms to complete over ");
output.Append(totalCalls);
output.Append(" iteration");
if (totalCalls != 1) output.Append("s");
output.Append(", averaging \t");
output.Append((totalTime / totalCalls).ToString("0.000"));
output.Append(" ms per call"); */
}
output.Append("\n\n============================\n\t\tTotal runtime: ");
output.Append(endTime.TotalSeconds.ToString("F3"));
output.Append(" seconds\n============================");
Debug.Log(output.ToString());
}
[System.Diagnostics.Conditional ("ProfileAstar")]
public static void PrintResults()
{
TimeSpan endTime = DateTime.UtcNow - startTime;
System.Text.StringBuilder output = new System.Text.StringBuilder();
output.Append("============================\n\t\t\t\tProfile results:\n============================\n");
int maxLength = 5;
foreach(KeyValuePair<string, ProfilePoint> pair in profiles)
{
maxLength = Math.Max (pair.Key.Length,maxLength);
}
output.Append (" Name ".PadRight (maxLength)).
Append("|").Append(" Total Time ".PadRight(20)).
Append("|").Append(" Total Calls ".PadRight(20)).
Append("|").Append(" Avg/Call ".PadRight(20));
foreach(KeyValuePair<string, ProfilePoint> pair in profiles)
{
double totalTime = pair.Value.watch.Elapsed.TotalMilliseconds;
int totalCalls = pair.Value.totalCalls;
if (totalCalls < 1) continue;
string name = pair.Key;
output.Append ("\n").Append(name.PadRight(maxLength)).Append("| ");
output.Append (totalTime.ToString("0.0").PadRight (20)).Append ("| ");
output.Append (totalCalls.ToString().PadRight (20)).Append ("| ");
output.Append ((totalTime / totalCalls).ToString("0.000").PadRight(20));
output.Append (Pathfinding.AstarMath.FormatBytesBinary ((int)pair.Value.totalBytes).PadLeft(10));
/*output.Append("\nProfile ");
output.Append(pair.Key);
output.Append(" took ");
output.Append(totalTime.ToString("0"));
output.Append(" ms to complete over ");
output.Append(totalCalls);
output.Append(" iteration");
if (totalCalls != 1) output.Append("s");
output.Append(", averaging ");
output.Append((totalTime / totalCalls).ToString("0.0"));
output.Append(" ms per call");*/
}
output.Append("\n\n============================\n\t\tTotal runtime: ");
output.Append(endTime.TotalSeconds.ToString("F3"));
output.Append(" seconds\n============================");
Debug.Log(output.ToString());
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System
{
using System;
using System.Reflection;
////using System.Reflection.Emit;
////using System.Text;
using System.Collections;
using System.Globalization;
using System.Runtime.CompilerServices;
////using System.Runtime.Versioning;
[Microsoft.Zelig.Internals.WellKnownType( "System_Enum" )]
[Serializable]
public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible
{
#region Private Static Data Members
//// private const int maxHashElements = 100; // to trim the working set
//// private const String enumSeperator = ", ";
//// private static char[] enumSeperatorCharArray = new char[] { ',' };
//// private static Type intType = typeof( int );
//// private static Type stringType = typeof( String );
//// private static Hashtable fieldInfoHash = Hashtable.Synchronized( new Hashtable() );
#endregion
#region Private Static Methods
//// private static void ValidateEnumType( Type enumType)
//// {
//// if(enumType == null)
//// {
//// throw new ArgumentNullException( "enumType" );
//// }
////
//// if(!(enumType is RuntimeType))
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "enumType" );
//// }
////
//// if(!enumType.IsEnum)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeEnum" ), "enumType" );
//// }
//// }
//// private static FieldInfo GetValueField( Type type )
//// {
//// FieldInfo[] flds;
////
//// flds = type.GetFields( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
////
//// if((flds == null) || (flds.Length != 1))
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_EnumMustHaveUnderlyingValueField" ) );
//// }
////
//// return flds[0];
//// }
////
//// private static HashEntry GetHashEntry( Type enumType )
//// {
//// HashEntry hashEntry = (HashEntry)fieldInfoHash[enumType];
////
//// if(hashEntry == null)
//// {
//// // To reduce the workingset we clear the hashtable when a threshold number of elements are inserted.
//// if(fieldInfoHash.Count > maxHashElements)
//// {
//// fieldInfoHash.Clear();
//// }
////
//// ulong[] values = null;
//// String[] names = null;
////
//// BCLDebug.Assert( enumType.BaseType == typeof( Enum ), "Base type must of type Enum" );
//// if(enumType.BaseType == typeof( Enum ))
//// {
//// InternalGetEnumValues( enumType, ref values, ref names );
//// }
//// // If we switch over to EnumBuilder, this code path will be required.
//// else
//// {
//// // fall back on reflection for odd cases
//// FieldInfo[] flds = enumType.GetFields( BindingFlags.Static | BindingFlags.Public );
////
//// values = new ulong[flds.Length];
//// names = new String[flds.Length];
//// for(int i = 0; i < flds.Length; i++)
//// {
//// names[i] = flds[i].Name;
//// values[i] = ToUInt64( flds[i].GetValue( null ) );
//// }
////
//// // Insertion Sort these values in ascending order.
//// // We use this O(n^2) algorithm, but it turns out that most of the time the elements are already in sorted order and
//// // the common case performance will be faster than quick sorting this.
//// for(int i = 1; i < values.Length; i++)
//// {
//// int j = i;
//// String tempStr = names[i];
//// ulong val = values[i];
//// bool exchanged = false;
////
//// // Since the elements are sorted we only need to do one comparision, we keep the check for j inside the loop.
//// while(values[j - 1] > val)
//// {
//// names [j] = names [j - 1];
//// values[j] = values[j - 1];
////
//// j--;
////
//// exchanged = true;
//// if(j == 0)
//// {
//// break;
//// }
//// }
////
//// if(exchanged)
//// {
//// names [j] = tempStr;
//// values[j] = val;
//// }
//// }
//// }
////
//// hashEntry = new HashEntry( names, values );
////
//// fieldInfoHash[enumType] = hashEntry;
//// }
////
//// return hashEntry;
//// }
////
//// private static String InternalGetValueAsString( Type enumType, Object value )
//// {
//// //Don't ask for the private fields. Only .value is private and we don't need that.
//// HashEntry hashEntry = GetHashEntry ( enumType );
//// Type eT = GetUnderlyingType( enumType );
////
//// // Lets break this up based upon the size. We'll do part as an 64bit value
//// // and part as the 32bit values.
//// if(eT == intType || eT == typeof( short ) || eT == typeof( long ) || eT == typeof( ushort ) || eT == typeof( byte ) || eT == typeof( sbyte ) || eT == typeof( uint ) || eT == typeof( ulong ))
//// {
//// ulong val = ToUInt64( value );
//// int index = BinarySearch( hashEntry.values, val );
////
//// if(index >= 0)
//// {
//// return hashEntry.names[index];
//// }
//// }
////
//// return null;
//// }
////
//// private static String InternalFormattedHexString( Object value )
//// {
//// TypeCode typeCode = Convert.GetTypeCode( value );
////
//// switch(typeCode)
//// {
//// case TypeCode.SByte:
//// {
//// Byte result = (byte)(sbyte)value;
////
//// return result.ToString( "X2", null );
//// }
////
//// case TypeCode.Byte:
//// {
//// Byte result = (byte)value;
////
//// return result.ToString( "X2", null );
//// }
////
//// case TypeCode.Int16:
//// {
//// UInt16 result = (UInt16)(Int16)value;
////
//// return result.ToString( "X4", null );
//// }
////
//// case TypeCode.UInt16:
//// {
//// UInt16 result = (UInt16)value;
////
//// return result.ToString( "X4", null );
//// }
////
//// case TypeCode.UInt32:
//// {
//// UInt32 result = (UInt32)value;
////
//// return result.ToString( "X8", null );
//// }
////
//// case TypeCode.Int32:
//// {
//// UInt32 result = (UInt32)(int)value;
////
//// return result.ToString( "X8", null );
//// }
////
//// case TypeCode.UInt64:
//// {
//// UInt64 result = (UInt64)value;
////
//// return result.ToString( "X16", null );
//// }
////
//// case TypeCode.Int64:
//// {
//// UInt64 result = (UInt64)(Int64)value;
////
//// return result.ToString( "X16", null );
//// }
////
//// // All unsigned types will be directly cast
//// default:
//// BCLDebug.Assert( false, "Invalid Object type in Format" );
//// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) );
//// }
//// }
////
//// private static String InternalFormat( Type eT, Object value )
//// {
//// if(!eT.IsDefined( typeof( System.FlagsAttribute ), false )) // Not marked with Flags attribute
//// {
//// // Try to see if its one of the enum values, then we return a String back else the value
//// String retval = InternalGetValueAsString( eT, value );
//// if(retval == null)
//// {
//// return value.ToString();
//// }
//// else
//// {
//// return retval;
//// }
//// }
//// else // These are flags OR'ed together (We treat everything as unsigned types)
//// {
//// return InternalFlagsFormat( eT, value );
//// }
//// }
////
//// private static String InternalFlagsFormat( Type eT, Object value )
//// {
//// ulong result = ToUInt64( value );
//// HashEntry hashEntry = GetHashEntry( eT );
////
//// // These values are sorted by value. Don't change this
//// String[] names = hashEntry.names;
//// ulong[] values = hashEntry.values;
////
//// int index = values.Length - 1;
//// StringBuilder retval = new StringBuilder();
//// bool firstTime = true;
//// ulong saveResult = result;
////
//// // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied
//// // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of
//// // items in an enum are sufficiently small and not worth the optimization.
//// while(index >= 0)
//// {
//// if((index == 0) && (values[index] == 0))
//// {
//// break;
//// }
////
//// if((result & values[index]) == values[index])
//// {
//// result -= values[index];
////
//// if(!firstTime)
//// {
//// retval.Insert( 0, enumSeperator );
//// }
////
//// retval.Insert( 0, names[index] );
//// firstTime = false;
//// }
////
//// index--;
//// }
////
//// // We were unable to represent this number as a bitwise or of valid flags
//// if(result != 0)
//// {
//// return value.ToString();
//// }
////
//// // For the case when we have zero
//// if(saveResult == 0)
//// {
//// if(values[0] == 0)
//// {
//// return names[0]; // Zero was one of the enum values.
//// }
//// else
//// {
//// return "0";
//// }
//// }
//// else
//// {
//// return retval.ToString(); // Return the string representation
//// }
//// }
////
//// private static ulong ToUInt64( Object value )
//// {
//// // Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception.
//// // This is need since the Convert functions do overflow checks.
//// TypeCode typeCode = Convert.GetTypeCode( value );
//// ulong result;
////
//// switch(typeCode)
//// {
//// case TypeCode.SByte:
//// case TypeCode.Int16:
//// case TypeCode.Int32:
//// case TypeCode.Int64:
//// result = (UInt64)Convert.ToInt64( value, CultureInfo.InvariantCulture );
//// break;
////
//// case TypeCode.Byte:
//// case TypeCode.UInt16:
//// case TypeCode.UInt32:
//// case TypeCode.UInt64:
//// result = Convert.ToUInt64( value, CultureInfo.InvariantCulture );
//// break;
////
//// default:
//// // All unsigned types will be directly cast
//// BCLDebug.Assert( false, "Invalid Object type in ToUInt64" );
//// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) );
//// }
//// return result;
//// }
////
//// private static int BinarySearch( ulong[] array, ulong value )
//// {
//// int lo = 0;
//// int hi = array.Length - 1;
////
//// while(lo <= hi)
//// {
//// int i = (lo + hi) >> 1;
//// ulong temp = array[i];
////
//// if(value == temp) return i;
////
//// if(temp < value)
//// {
//// lo = i + 1;
//// }
//// else
//// {
//// hi = i - 1;
//// }
//// }
////
//// return ~lo;
//// }
//// [ResourceExposure( ResourceScope.None )]
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern int InternalCompareTo( Object o1, Object o2 );
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private static extern Type InternalGetUnderlyingType( Type enumType );
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private static extern void InternalGetEnumValues( Type enumType, ref ulong[] values, ref String[] names );
#endregion
#region Public Static Methods
public static Object Parse( Type enumType, String value )
{
return Parse( enumType, value, false );
}
[MethodImpl( MethodImplOptions.InternalCall )]
public static extern Object Parse( Type enumType, String value, bool ignoreCase );
//// {
//// ValidateEnumType( enumType );
////
//// if(value == null)
//// {
//// throw new ArgumentNullException( "value" );
//// }
////
//// value = value.Trim();
//// if(value.Length == 0)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustContainEnumInfo" ) );
//// }
////
//// // We have 2 code paths here. One if they are values else if they are Strings.
//// // values will have the first character as as number or a sign.
//// ulong result = 0;
////
//// if(Char.IsDigit( value[0] ) || value[0] == '-' || value[0] == '+')
//// {
//// Type underlyingType = GetUnderlyingType( enumType );
//// Object temp;
////
//// try
//// {
//// temp = Convert.ChangeType( value, underlyingType, CultureInfo.InvariantCulture );
////
//// return ToObject( enumType, temp );
//// }
//// catch(FormatException)
//// { // We need to Parse this a String instead. There are cases
//// // when you tlbimp enums that can have values of the form "3D".
//// // Don't fix this code.
//// }
//// }
////
//// String[] values = value.Split( enumSeperatorCharArray );
////
//// // Find the field.Lets assume that these are always static classes because the class is
//// // an enum.
//// HashEntry hashEntry = GetHashEntry( enumType );
//// String[] names = hashEntry.names;
////
//// for(int i = 0; i < values.Length; i++)
//// {
//// values[i] = values[i].Trim(); // We need to remove whitespace characters
////
//// bool success = false;
////
//// for(int j = 0; j < names.Length; j++)
//// {
//// if(ignoreCase)
//// {
//// if(String.Compare( names[j], values[i], StringComparison.OrdinalIgnoreCase ) != 0)
//// {
//// continue;
//// }
//// }
//// else
//// {
//// if(!names[j].Equals( values[i] ))
//// {
//// continue;
//// }
//// }
////
//// ulong item = hashEntry.values[j];
////
//// result |= item;
//// success = true;
//// break;
//// }
////
//// if(!success)
//// {
//// // Not found, throw an argument exception.
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumValueNotFound" ), value ) );
//// }
//// }
////
//// return ToObject( enumType, result );
//// }
public static Type GetUnderlyingType( Type enumType )
{
throw new NotImplementedException();
//// ////// Make this function working for EnumBuilder. JScript uses it.
//// ////if(enumType is EnumBuilder)
//// ////{
//// //// return ((EnumBuilder)enumType).UnderlyingSystemType;
//// ////}
////
//// ValidateEnumType( enumType );
////
//// return InternalGetUnderlyingType( enumType );
}
public static Array GetValues( Type enumType )
{
throw new NotImplementedException();
//// ValidateEnumType( enumType );
////
//// // Get all of the values
//// ulong[] values = GetHashEntry( enumType ).values;
////
//// // Create a generic Array
//// Array ret = Array.CreateInstance( enumType, values.Length );
////
//// for(int i = 0; i < values.Length; i++)
//// {
//// Object val = ToObject( enumType, values[i] );
////
//// ret.SetValue( val, i );
//// }
////
//// return ret;
}
//// public static String GetName( Type enumType, Object value )
//// {
//// ValidateEnumType( enumType );
////
//// if(value == null)
//// {
//// throw new ArgumentNullException( "value" );
//// }
////
//// Type valueType = value.GetType();
////
//// if(valueType.IsEnum || valueType == intType || valueType == typeof( short ) || valueType == typeof( ushort ) || valueType == typeof( byte ) || valueType == typeof( sbyte ) || valueType == typeof( uint ) || valueType == typeof( long ) || valueType == typeof( ulong ))
//// {
//// return InternalGetValueAsString( enumType, value );
//// }
////
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeEnumBaseTypeOrEnum" ), "value" );
//// }
////
//// public static String[] GetNames( Type enumType )
//// {
//// ValidateEnumType( enumType );
////
//// // Get all of the Field names
//// String[] ret = GetHashEntry( enumType ).names;
////
//// // Make a copy since we can't hand out the same array since users can modify them
//// String[] retVal = new String[ret.Length];
////
//// Array.Copy( ret, retVal, ret.Length );
////
//// return retVal;
//// }
////
//// public static Object ToObject( Type enumType, Object value )
//// {
//// if(value == null)
//// {
//// throw new ArgumentNullException( "value" );
//// }
////
//// // Delegate rest of error checking to the other functions
//// TypeCode typeCode = Convert.GetTypeCode( value );
////
//// switch(typeCode)
//// {
//// case TypeCode.Int32:
//// return ToObject( enumType, (int)value );
////
//// case TypeCode.SByte:
//// return ToObject( enumType, (sbyte)value );
////
//// case TypeCode.Int16:
//// return ToObject( enumType, (short)value );
////
//// case TypeCode.Int64:
//// return ToObject( enumType, (long)value );
////
//// case TypeCode.UInt32:
//// return ToObject( enumType, (uint)value );
////
//// case TypeCode.Byte:
//// return ToObject( enumType, (byte)value );
////
//// case TypeCode.UInt16:
//// return ToObject( enumType, (ushort)value );
////
//// case TypeCode.UInt64:
//// return ToObject( enumType, (ulong)value );
////
//// default:
//// // All unsigned types will be directly cast
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeEnumBaseTypeOrEnum" ), "value" );
//// }
//// }
////
//// public static bool IsDefined( Type enumType, Object value )
//// {
//// ValidateEnumType( enumType );
////
//// if(value == null)
//// {
//// throw new ArgumentNullException( "value" );
//// }
////
//// // Check if both of them are of the same type
//// Type valueType = value.GetType();
////
//// if(!(valueType is RuntimeType))
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "valueType" );
//// }
////
//// Type underlyingType = GetUnderlyingType( enumType );
////
//// // If the value is an Enum then we need to extract the underlying value from it
//// if(valueType.IsEnum)
//// {
//// Type valueUnderlyingType = GetUnderlyingType( valueType );
////
//// if(valueType != enumType)
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumAndObjectMustBeSameType" ), valueType.ToString(), enumType.ToString() ) );
//// }
////
//// valueType = valueUnderlyingType;
//// }
//// else
//// {
//// // The value must be of the same type as the Underlying type of the Enum
//// if((valueType != underlyingType) && (valueType != stringType))
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumUnderlyingTypeAndObjectMustBeSameType" ), valueType.ToString(), underlyingType.ToString() ) );
//// }
//// }
////
//// // If String is passed in
//// if(valueType == stringType)
//// {
//// // Get all of the Fields
//// String[] names = GetHashEntry( enumType ).names;
////
//// for(int i = 0; i < names.Length; i++)
//// {
//// if(names[i].Equals( (string)value ))
//// {
//// return true;
//// }
//// }
////
//// return false;
//// }
////
//// ulong[] values = GetHashEntry( enumType ).values;
////
//// // Look at the 8 possible enum base classes
//// if(valueType == intType || valueType == typeof( short ) || valueType == typeof( ushort ) || valueType == typeof( byte ) || valueType == typeof( sbyte ) || valueType == typeof( uint ) || valueType == typeof( long ) || valueType == typeof( ulong ))
//// {
//// ulong val = ToUInt64( value );
////
//// return (BinarySearch( values, val ) >= 0);
//// }
////
//// BCLDebug.Assert( false, "Unknown enum type" );
//// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) );
//// }
////
//// public static String Format( Type enumType, Object value, String format )
//// {
//// ValidateEnumType( enumType );
////
//// if(value == null)
//// {
//// throw new ArgumentNullException( "value" );
//// }
////
//// if(format == null)
//// {
//// throw new ArgumentNullException( "format" );
//// }
////
//// // Check if both of them are of the same type
//// Type valueType = value.GetType();
////
//// if(!(valueType is RuntimeType))
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "valueType" );
//// }
////
//// Type underlyingType = GetUnderlyingType( enumType );
////
//// // If the value is an Enum then we need to extract the underlying value from it
//// if(valueType.IsEnum)
//// {
//// Type valueUnderlyingType = GetUnderlyingType( valueType );
////
//// if(valueType != enumType)
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumAndObjectMustBeSameType" ), valueType.ToString(), enumType.ToString() ) );
//// }
////
//// valueType = valueUnderlyingType;
//// value = ((Enum)value).GetValue();
//// }
//// // The value must be of the same type as the Underlying type of the Enum
//// else if(valueType != underlyingType)
//// {
//// throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType" ), valueType.ToString(), underlyingType.ToString() ) );
//// }
////
//// if(format.Length != 1)
//// {
//// // all acceptable format string are of length 1
//// throw new FormatException( Environment.GetResourceString( "Format_InvalidEnumFormatSpecification" ) );
//// }
////
//// char formatCh = format[0];
////
//// if(formatCh == 'D' || formatCh == 'd')
//// {
//// return value.ToString();
//// }
////
//// if(formatCh == 'X' || formatCh == 'x')
//// {
//// // Retrieve the value from the field.
//// return InternalFormattedHexString( value );
//// }
////
//// if(formatCh == 'G' || formatCh == 'g')
//// {
//// return InternalFormat( enumType, value );
//// }
////
//// if(formatCh == 'F' || formatCh == 'f')
//// {
//// return InternalFlagsFormat( enumType, value );
//// }
////
//// throw new FormatException( Environment.GetResourceString( "Format_InvalidEnumFormatSpecification" ) );
//// }
////
#endregion
#region Definitions
//// private class HashEntry
//// {
//// // Each entry contains a list of sorted pair of enum field names and values, sorted by values
//// public HashEntry( String[] names, ulong[] values )
//// {
//// this.names = names;
//// this.values = values;
//// }
////
//// public String[] names;
//// public ulong[] values;
//// }
#endregion
#region Private Methods
private Object GetValue()
{
throw new NotImplementedException();
//// return InternalGetValue();
}
//// private String ToHexString()
//// {
//// Type eT = this.GetType();
//// FieldInfo thisField = GetValueField( eT );
////
//// // Retrieve the value from the field.
//// return InternalFormattedHexString( ((RtFieldInfo)thisField).InternalGetValue( this, false ) );
//// //return InternalFormattedHexString(((RuntimeFieldInfo)thisField).GetValue(this));
//// }
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private extern Object InternalGetValue();
////
#endregion
#region Object Overrides
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// public extern override bool Equals( Object obj );
//// ////FCIMPL2(FC_BOOL_RET, ReflectionEnum::InternalEquals, Object *pRefThis, Object* pRefTarget)
//// ////{
//// //// FCALL_CONTRACT;
//// ////
//// //// VALIDATEOBJECT(pRefThis);
//// //// BOOL ret = false;
//// //// if (pRefTarget == NULL) {
//// //// FC_RETURN_BOOL(ret);
//// //// }
//// ////
//// //// if( pRefThis == pRefTarget)
//// //// FC_RETURN_BOOL(true);
//// ////
//// //// //Make sure we are comparing same type.
//// //// MethodTable* pMTThis = pRefThis->GetMethodTable();
//// //// _ASSERTE(!pMTThis->IsArray()); // bunch of assumptions about arrays wrong.
//// //// if ( pMTThis != pRefTarget->GetMethodTable()) {
//// //// FC_RETURN_BOOL(ret);
//// //// }
//// ////
//// //// void * pThis = pRefThis->UnBox();
//// //// void * pTarget = pRefTarget->UnBox();
//// //// switch (pMTThis->GetNumInstanceFieldBytes()) {
//// //// case 1:
//// //// ret = (*(UINT8*)pThis == *(UINT8*)pTarget);
//// //// break;
//// //// case 2:
//// //// ret = (*(UINT16*)pThis == *(UINT16*)pTarget);
//// //// break;
//// //// case 4:
//// //// ret = (*(UINT32*)pThis == *(UINT32*)pTarget);
//// //// break;
//// //// case 8:
//// //// ret = (*(UINT64*)pThis == *(UINT64*)pTarget);
//// //// break;
//// //// default:
//// //// // should not reach here.
//// //// UNREACHABLE_MSG("Incorrect Enum Type size!");
//// //// break;
//// //// }
//// ////
//// //// FC_RETURN_BOOL(ret);
//// ////}
//// ////FCIMPLEND
////
//// public override int GetHashCode()
//// {
//// return GetValue().GetHashCode();
//// }
////
//// public override String ToString()
//// {
//// // Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned.
//// // For PASCAL style enums who's values do not map directly the decimal value of the field is returned.
//// // For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant
//// //(a pure power of 2), then the OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of
//// // pure powers of 2 OR-ed together, you return a hex value
//// Type eT = this.GetType();
//// FieldInfo thisField = GetValueField( eT );
////
//// // Retrieve the value from the field.
//// Object value = ((RtFieldInfo)thisField).InternalGetValue( this, false );
////
//// //Object value = ((RuntimeFieldInfo)thisField).GetValueInternal(this);
//// return InternalFormat( eT, value );
//// }
#endregion
#region IFormattable
[Obsolete( "The provider argument is not used. Please use ToString(String)." )]
public String ToString( String format, IFormatProvider provider )
{
return ToString( format );
}
#endregion
#region IComparable
public int CompareTo( Object target )
{
const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match
const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported unerlying type
if(this == null)
{
throw new NullReferenceException();
}
int ret = InternalCompareTo( this, target );
if(ret < retIncompatibleMethodTables)
{
// -1, 0 and 1 are the normal return codes
return ret;
}
else if(ret == retIncompatibleMethodTables)
{
Type thisType = this.GetType();
Type targetType = target.GetType();
#if EXCEPTION_STRINGS
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Arg_EnumAndObjectMustBeSameType" ), targetType.ToString(), thisType.ToString() ) );
#else
throw new ArgumentException();
#endif
}
else
{
// assert valid return code (3)
BCLDebug.Assert( ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid" );
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) );
#else
throw new InvalidOperationException();
#endif
}
}
#endregion
#region Public Methods
public String ToString( String format )
{
return ToString();
//// if(format == null || format.Length == 0)
//// {
//// format = "G";
//// }
////
//// if(String.Compare( format, "G", StringComparison.OrdinalIgnoreCase ) == 0)
//// {
//// return ToString();
//// // return InternalFormat(this.GetType(), this.GetValue());
//// }
////
//// if(String.Compare( format, "D", StringComparison.OrdinalIgnoreCase ) == 0)
//// {
//// return this.GetValue().ToString();
//// }
////
//// if(String.Compare( format, "X", StringComparison.OrdinalIgnoreCase ) == 0)
//// {
//// return this.ToHexString();
//// }
////
//// if(String.Compare( format, "F", StringComparison.OrdinalIgnoreCase ) == 0)
//// {
//// return InternalFlagsFormat( this.GetType(), this.GetValue() );
//// }
////
//// throw new FormatException( Environment.GetResourceString( "Format_InvalidEnumFormatSpecification" ) );
}
[Obsolete( "The provider argument is not used. Please use ToString()." )]
public String ToString( IFormatProvider provider )
{
return ToString();
}
#endregion
#region IConvertible
public TypeCode GetTypeCode()
{
Type enumType = this.GetType();
Type underlyingType = GetUnderlyingType( enumType );
if(underlyingType == typeof( Int32 ))
{
return TypeCode.Int32;
}
if(underlyingType == typeof( sbyte ))
{
return TypeCode.SByte;
}
if(underlyingType == typeof( Int16 ))
{
return TypeCode.Int16;
}
if(underlyingType == typeof( Int64 ))
{
return TypeCode.Int64;
}
if(underlyingType == typeof( UInt32 ))
{
return TypeCode.UInt32;
}
if(underlyingType == typeof( byte ))
{
return TypeCode.Byte;
}
if(underlyingType == typeof( UInt16 ))
{
return TypeCode.UInt16;
}
if(underlyingType == typeof( UInt64 ))
{
return TypeCode.UInt64;
}
BCLDebug.Assert( false, "Unknown underlying type." );
#if EXCEPTION_STRINGS
throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_UnknownEnumType" ) );
#else
throw new InvalidOperationException();
#endif
}
/// <internalonly/>
bool IConvertible.ToBoolean( IFormatProvider provider )
{
return Convert.ToBoolean( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
char IConvertible.ToChar( IFormatProvider provider )
{
return Convert.ToChar( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
sbyte IConvertible.ToSByte( IFormatProvider provider )
{
return Convert.ToSByte( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
byte IConvertible.ToByte( IFormatProvider provider )
{
return Convert.ToByte( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
short IConvertible.ToInt16( IFormatProvider provider )
{
return Convert.ToInt16( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
ushort IConvertible.ToUInt16( IFormatProvider provider )
{
return Convert.ToUInt16( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
int IConvertible.ToInt32( IFormatProvider provider )
{
return Convert.ToInt32( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
uint IConvertible.ToUInt32( IFormatProvider provider )
{
return Convert.ToUInt32( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
long IConvertible.ToInt64( IFormatProvider provider )
{
return Convert.ToInt64( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
ulong IConvertible.ToUInt64( IFormatProvider provider )
{
return Convert.ToUInt64( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
float IConvertible.ToSingle( IFormatProvider provider )
{
return Convert.ToSingle( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
double IConvertible.ToDouble( IFormatProvider provider )
{
return Convert.ToDouble( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
Decimal IConvertible.ToDecimal( IFormatProvider provider )
{
return Convert.ToDecimal( GetValue(), CultureInfo.CurrentCulture );
}
/// <internalonly/>
DateTime IConvertible.ToDateTime( IFormatProvider provider )
{
#if EXCEPTION_STRINGS
throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "Enum", "DateTime" ) );
#else
throw new InvalidCastException();
#endif
}
/// <internalonly/>
Object IConvertible.ToType( Type type, IFormatProvider provider )
{
return Convert.DefaultToType( (IConvertible)this, type, provider );
}
#endregion
#region ToObject
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImpl( MethodImplOptions.InternalCall )]
//// private static extern Object InternalBoxEnum( Type enumType, long value );
//// ////FCIMPL2_IV(Object*, ReflectionEnum::InternalBoxEnum, ReflectClassBaseObject* target, INT64 value) {
//// //// FCALL_CONTRACT;
//// ////
//// //// VALIDATEOBJECT(target);
//// //// OBJECTREF ret = NULL;
//// ////
//// //// MethodTable* pMT = target->GetType().AsMethodTable();
//// //// HELPER_METHOD_FRAME_BEGIN_RET_0();
//// ////
//// //// ret = pMT->Box(ArgSlotEndianessFixup((ARG_SLOT*)&value, pMT->GetNumInstanceFieldBytes()), FALSE);
//// ////
//// //// HELPER_METHOD_FRAME_END();
//// //// return OBJECTREFToObject(ret);
//// ////}
//// ////FCIMPLEND
////
////
////
//// [CLSCompliant( false )]
//// public static Object ToObject( Type enumType, sbyte value )
//// {
//// ValidateEnumType( enumType );
////
//// return InternalBoxEnum( enumType, value );
//// }
////
//// public static Object ToObject( Type enumType, short value )
//// {
//// ValidateEnumType( enumType );
////
//// return InternalBoxEnum( enumType, value );
//// }
////
//// public static Object ToObject( Type enumType, int value )
//// {
//// ValidateEnumType( enumType );
////
//// return InternalBoxEnum( enumType, value );
//// }
////
//// public static Object ToObject( Type enumType, byte value )
//// {
//// ValidateEnumType( enumType );
////
//// return InternalBoxEnum( enumType, value );
//// }
////
//// [CLSCompliant( false )]
//// public static Object ToObject( Type enumType, ushort value )
//// {
//// ValidateEnumType( enumType );
////
//// return InternalBoxEnum( enumType, value );
//// }
////
//// [CLSCompliant( false )]
//// public static Object ToObject( Type enumType, uint value )
//// {
//// ValidateEnumType( enumType );
////
//// return InternalBoxEnum( enumType, value );
//// }
////
//// public static Object ToObject( Type enumType, long value )
//// {
//// ValidateEnumType( enumType );
////
//// return InternalBoxEnum( enumType, value );
//// }
////
//// [CLSCompliant( false )]
//// public static Object ToObject( Type enumType, ulong value )
//// {
//// ValidateEnumType( enumType );
////
//// return InternalBoxEnum( enumType, unchecked( (long)value ) );
//// }
#endregion
}
}
| |
//
// Sqlite.cs
//
// Authors:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2010 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Hyena;
namespace Hyena.Data.Sqlite
{
public class Connection : IDisposable
{
IntPtr ptr;
internal IntPtr Ptr { get { return ptr; } }
internal List<Statement> Statements = new List<Statement> ();
public string DbPath { get; private set; }
public long LastInsertRowId {
get { return Native.sqlite3_last_insert_rowid (Ptr); }
}
public Connection (string dbPath)
{
DbPath = dbPath;
CheckError (Native.sqlite3_open (Native.GetUtf8Bytes (dbPath), out ptr));
if (ptr == IntPtr.Zero)
throw new Exception ("Unable to open connection");
Native.sqlite3_extended_result_codes (ptr, 1);
AddFunction<BinaryFunction> ();
AddFunction<CollationKeyFunction> ();
AddFunction<SearchKeyFunction> ();
AddFunction<Md5Function> ();
}
public void Dispose ()
{
if (ptr != IntPtr.Zero) {
lock (Statements) {
var stmts = Statements.ToArray ();
if (stmts.Length > 0)
Hyena.Log.DebugFormat ("Connection disposing of {0} remaining statements", stmts.Length);
foreach (var stmt in stmts) {
stmt.Dispose ();
}
}
CheckError (Native.sqlite3_close (ptr));
ptr = IntPtr.Zero;
}
}
~Connection ()
{
Dispose ();
}
internal void CheckError (int errorCode)
{
CheckError (errorCode, "");
}
internal void CheckError (int errorCode, string sql)
{
if (errorCode == 0 || errorCode == 100 || errorCode == 101)
return;
string errmsg = Native.sqlite3_errmsg16 (Ptr).PtrToString ();
if (sql != null) {
errmsg = String.Format ("{0} (SQL: {1})", errmsg, sql);
}
throw new SqliteException (errorCode, errmsg);
}
public Statement CreateStatement (string sql)
{
return new Statement (this, sql);
}
public QueryReader Query (string sql)
{
return new Statement (this, sql) { ReaderDisposes = true }.Query ();
}
public T Query<T> (string sql)
{
using (var stmt = new Statement (this, sql)) {
return stmt.Query<T> ();
}
}
public void Execute (string sql)
{
// TODO
// * The application must insure that the 1st parameter to sqlite3_exec() is a valid and open database connection.
// * The application must not close database connection specified by the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
// * The application must not modify the SQL statement text passed into the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
CheckError (Native.sqlite3_exec (Ptr, Native.GetUtf8Bytes (sql), IntPtr.Zero, IntPtr.Zero, IntPtr.Zero), sql);
}
// We need to keep a managed ref to the function objects we create so
// they won't get GC'd
List<SqliteFunction> functions = new List<SqliteFunction> ();
const int UTF16 = 4;
public void AddFunction<T> () where T : SqliteFunction
{
var type = typeof (T);
var pr = (SqliteFunctionAttribute)type.GetCustomAttributes (typeof (SqliteFunctionAttribute), false).First ();
var f = (SqliteFunction) Activator.CreateInstance (typeof (T));
f._InvokeFunc = (pr.FuncType == FunctionType.Scalar) ? new SqliteCallback(f.ScalarCallback) : null;
f._StepFunc = (pr.FuncType == FunctionType.Aggregate) ? new SqliteCallback(f.StepCallback) : null;
f._FinalFunc = (pr.FuncType == FunctionType.Aggregate) ? new SqliteFinalCallback(f.FinalCallback) : null;
f._CompareFunc = (pr.FuncType == FunctionType.Collation) ? new SqliteCollation(f.CompareCallback) : null;
if (pr.FuncType != FunctionType.Collation) {
CheckError (Native.sqlite3_create_function16 (
ptr, pr.Name, pr.Arguments, UTF16, IntPtr.Zero,
f._InvokeFunc, f._StepFunc, f._FinalFunc
));
} else {
CheckError (Native.sqlite3_create_collation16 (
ptr, pr.Name, UTF16, IntPtr.Zero, f._CompareFunc
));
}
functions.Add (f);
}
public void RemoveFunction<T> () where T : SqliteFunction
{
var type = typeof (T);
var pr = (SqliteFunctionAttribute)type.GetCustomAttributes (typeof (SqliteFunctionAttribute), false).First ();
if (pr.FuncType != FunctionType.Collation) {
CheckError (Native.sqlite3_create_function16 (
ptr, pr.Name, pr.Arguments, UTF16, IntPtr.Zero,
null, null, null
));
} else {
CheckError (Native.sqlite3_create_collation16 (
ptr, pr.Name, UTF16, IntPtr.Zero, null
));
}
var func = functions.FirstOrDefault (f => f is T);
if (func != null) {
functions.Remove (func);
}
}
}
public class SqliteException : Exception
{
public int ErrorCode { get; private set; }
public SqliteException (int errorCode, string message) : base (String.Format ("Sqlite error {0}: {1}", errorCode, message))
{
ErrorCode = errorCode;
}
}
public interface IDataReader : IDisposable
{
bool Read ();
object this[int i] { get; }
object this[string columnName] { get; }
T Get<T> (int i);
T Get<T> (string columnName);
object Get (int i, Type asType);
int FieldCount { get; }
string [] FieldNames { get; }
}
public class Statement : IDisposable, IEnumerable<IDataReader>
{
IntPtr ptr;
Connection connection;
bool bound;
QueryReader reader;
bool disposed;
internal bool Reading { get; set; }
internal IntPtr Ptr { get { return ptr; } }
internal bool Bound { get { return bound; } }
internal Connection Connection { get { return connection; } }
public bool IsDisposed { get { return disposed; } }
public string CommandText { get; private set; }
public int ParameterCount { get; private set; }
public bool ReaderDisposes { get; internal set; }
internal event EventHandler Disposed;
internal Statement (Connection connection, string sql)
{
CommandText = sql;
this.connection = connection;
IntPtr pzTail = IntPtr.Zero;
CheckError (Native.sqlite3_prepare16_v2 (connection.Ptr, sql, -1, out ptr, out pzTail));
lock (Connection.Statements) {
Connection.Statements.Add (this);
}
if (pzTail != IntPtr.Zero && Marshal.ReadByte (pzTail) != 0) {
Dispose ();
throw new ArgumentException ("sql", String.Format ("This sqlite binding does not support multiple commands in one statement:\n {0}", sql));
}
ParameterCount = Native.sqlite3_bind_parameter_count (ptr);
reader = new QueryReader () { Statement = this };
}
internal void CheckReading ()
{
CheckDisposed ();
if (!Reading) {
throw new InvalidOperationException ("Statement is not readable");
}
}
internal void CheckDisposed ()
{
if (disposed) {
throw new InvalidOperationException ("Statement is disposed");
}
}
public void Dispose ()
{
if (disposed)
return;
disposed = true;
if (ptr != IntPtr.Zero) {
// Don't check for error here, because if the most recent evaluation had an error finalize will return it too
// See http://sqlite.org/c3ref/finalize.html
Native.sqlite3_finalize (ptr);
ptr = IntPtr.Zero;
lock (Connection.Statements) {
Connection.Statements.Remove (this);
}
var h = Disposed;
if (h != null) {
h (this, EventArgs.Empty);
}
}
}
~Statement ()
{
Dispose ();
}
object [] null_val = new object [] { null };
public Statement Bind (params object [] vals)
{
Reset ();
if (vals == null && ParameterCount == 1)
vals = null_val;
if (vals == null || vals.Length != ParameterCount || ParameterCount == 0)
throw new ArgumentException ("vals", String.Format ("Statement has {0} parameters", ParameterCount));
for (int i = 1; i <= vals.Length; i++) {
int code = 0;
object o = SqliteUtils.ToDbFormat (vals[i - 1]);
if (o == null)
code = Native.sqlite3_bind_null (Ptr, i);
else if (o is double)
code = Native.sqlite3_bind_double (Ptr, i, (double)o);
else if (o is float)
code = Native.sqlite3_bind_double (Ptr, i, (double)(float)o);
else if (o is int)
code = Native.sqlite3_bind_int (Ptr, i, (int)o);
else if (o is uint)
code = Native.sqlite3_bind_int (Ptr, i, (int)(uint)o);
else if (o is long)
code = Native.sqlite3_bind_int64 (Ptr, i, (long)o);
else if (o is ulong)
code = Native.sqlite3_bind_int64 (Ptr, i, (long)(ulong)o);
else if (o is byte[]) {
byte [] bytes = o as byte[];
code = Native.sqlite3_bind_blob (Ptr, i, bytes, bytes.Length, (IntPtr)(-1));
} else {
// C# strings are UTF-16, so 2 bytes per char
// -1 for the last arg is the TRANSIENT destructor type so that sqlite will make its own copy of the string
string str = (o as string) ?? o.ToString ();
code = Native.sqlite3_bind_text16 (Ptr, i, str, str.Length * 2, (IntPtr)(-1));
}
CheckError (code);
}
bound = true;
return this;
}
internal void CheckError (int code)
{
connection.CheckError (code, CommandText);
}
private void Reset ()
{
CheckDisposed ();
if (Reading) {
throw new InvalidOperationException ("Can't reset statement while it's being read; make sure to Dispose any IDataReaders");
}
CheckError (Native.sqlite3_reset (ptr));
}
public IEnumerator<IDataReader> GetEnumerator ()
{
Reset ();
while (reader.Read ()) {
yield return reader;
}
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
public Statement Execute ()
{
Reset ();
using (reader) {
reader.Read ();
}
return this;
}
public T Query<T> ()
{
Reset ();
using (reader) {
return reader.Read () ? reader.Get<T> (0) : (T) SqliteUtils.FromDbFormat <T> (null);
}
}
public QueryReader Query ()
{
Reset ();
return reader;
}
}
public class QueryReader : IDataReader
{
Dictionary<string, int> columns;
int column_count = -1;
internal Statement Statement { get; set; }
IntPtr Ptr { get { return Statement.Ptr; } }
public void Dispose ()
{
Statement.Reading = false;
if (Statement.ReaderDisposes) {
Statement.Dispose ();
}
}
public int FieldCount {
get {
if (column_count == -1) {
Statement.CheckDisposed ();
column_count = Native.sqlite3_column_count (Ptr);
}
return column_count;
}
}
string [] field_names;
public string [] FieldNames {
get {
if (field_names == null) {
field_names = Columns.Keys.OrderBy (f => Columns[f]).ToArray ();
}
return field_names;
}
}
public bool Read ()
{
Statement.CheckDisposed ();
if (Statement.ParameterCount > 0 && !Statement.Bound)
throw new InvalidOperationException ("Statement not bound");
int code = Native.sqlite3_step (Ptr);
if (code == ROW) {
Statement.Reading = true;
return true;
} else {
Statement.Reading = false;
Statement.CheckError (code);
return false;
}
}
public object this[int i] {
get {
Statement.CheckReading ();
int type = Native.sqlite3_column_type (Ptr, i);
switch (type) {
case SQLITE_INTEGER:
return Native.sqlite3_column_int64 (Ptr, i);
case SQLITE_FLOAT:
return Native.sqlite3_column_double (Ptr, i);
case SQLITE3_TEXT:
return Native.sqlite3_column_text16 (Ptr, i).PtrToString ();
case SQLITE_BLOB:
int num_bytes = Native.sqlite3_column_bytes (Ptr, i);
if (num_bytes == 0)
return null;
byte [] bytes = new byte[num_bytes];
Marshal.Copy (Native.sqlite3_column_blob (Ptr, i), bytes, 0, num_bytes);
return bytes;
case SQLITE_NULL:
return null;
default:
throw new Exception (String.Format ("Column is of unknown type {0}", type));
}
}
}
public object this[string columnName] {
get { return this[GetColumnIndex (columnName)]; }
}
public T Get<T> (int i)
{
return (T) Get (i, typeof(T));
}
public object Get (int i, Type asType)
{
return GetAs (this[i], asType);
}
internal static object GetAs (object o, Type type)
{
if (o != null && o.GetType () == type)
return o;
if (o == null)
o = null;
else if (type == typeof(int))
o = (int)(long)o;
else if (type == typeof(uint))
o = (uint)(long)o;
else if (type == typeof(ulong))
o = (ulong)(long)o;
else if (type == typeof(float))
o = (float)(double)o;
if (o != null && o.GetType () == type)
return o;
return SqliteUtils.FromDbFormat (type, o);
}
public T Get<T> (string columnName)
{
return Get<T> (GetColumnIndex (columnName));
}
private Dictionary<string, int> Columns {
get {
if (columns == null) {
columns = new Dictionary<string, int> ();
for (int i = 0; i < FieldCount; i++) {
columns[Native.sqlite3_column_name16 (Ptr, i).PtrToString ()] = i;
}
}
return columns;
}
}
private int GetColumnIndex (string columnName)
{
Statement.CheckReading ();
int col = 0;
if (!Columns.TryGetValue (columnName, out col))
throw new ArgumentException ("columnName");
return col;
}
const int SQLITE_INTEGER = 1;
const int SQLITE_FLOAT = 2;
const int SQLITE3_TEXT = 3;
const int SQLITE_BLOB = 4;
const int SQLITE_NULL = 5;
const int ROW = 100;
const int DONE = 101;
}
internal static class Native
{
const string SQLITE_DLL = "sqlite3";
// Connection functions
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_open(byte [] utf8DbPath, out IntPtr db);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_close(IntPtr db);
[DllImport(SQLITE_DLL)]
internal static extern long sqlite3_last_insert_rowid (IntPtr db);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_busy_timeout(IntPtr db, int ms);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode)]
internal static extern IntPtr sqlite3_errmsg16(IntPtr db);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode)]
internal static extern int sqlite3_create_function16(IntPtr db, string strName, int nArgs, int eTextRep, IntPtr app, SqliteCallback func, SqliteCallback funcstep, SqliteFinalCallback funcfinal);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_aggregate_count(IntPtr context);
[DllImport(SQLITE_DLL)]
internal static extern IntPtr sqlite3_aggregate_context(IntPtr context, int nBytes);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode)]
internal static extern int sqlite3_create_collation16(IntPtr db, string strName, int eTextRep, IntPtr ctx, SqliteCollation fcompare);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_extended_result_codes (IntPtr db, int onoff);
// Statement functions
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode)]
internal static extern int sqlite3_prepare16_v2(IntPtr db, string pSql, int nBytes, out IntPtr stmt, out IntPtr ptrRemain);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_step(IntPtr stmt);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_column_count(IntPtr stmt);
[DllImport(SQLITE_DLL)]
internal static extern IntPtr sqlite3_column_name16(IntPtr stmt, int index);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_column_type(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL)]
internal static extern IntPtr sqlite3_column_blob(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_column_bytes(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL)]
internal static extern double sqlite3_column_double(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL)]
internal static extern long sqlite3_column_int64(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL)]
internal static extern IntPtr sqlite3_column_text16(IntPtr stmt, int iCol);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_finalize(IntPtr stmt);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_reset(IntPtr stmt);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_exec(IntPtr db, byte [] sql, IntPtr callback, IntPtr cbArg, IntPtr errPtr);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_bind_parameter_index(IntPtr stmt, byte [] paramName);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_bind_parameter_count(IntPtr stmt);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_bind_blob(IntPtr stmt, int param, byte[] val, int nBytes, IntPtr destructorType);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_bind_double(IntPtr stmt, int param, double val);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_bind_int(IntPtr stmt, int param, int val);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_bind_int64(IntPtr stmt, int param, long val);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_bind_null(IntPtr stmt, int param);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode)]
internal static extern int sqlite3_bind_text16 (IntPtr stmt, int param, string val, int numBytes, IntPtr destructorType);
//DllImport(SQLITE_DLL)]
//internal static extern int sqlite3_bind_zeroblob(IntPtr stmt, int, int n);
// Context functions
[DllImport(SQLITE_DLL)]
internal static extern void sqlite3_result_blob(IntPtr context, byte[] value, int nSize, IntPtr pvReserved);
[DllImport(SQLITE_DLL)]
internal static extern void sqlite3_result_double(IntPtr context, double value);
[DllImport(SQLITE_DLL)]
internal static extern void sqlite3_result_error(IntPtr context, byte[] strErr, int nLen);
[DllImport(SQLITE_DLL)]
internal static extern void sqlite3_result_int(IntPtr context, int value);
[DllImport(SQLITE_DLL)]
internal static extern void sqlite3_result_int64(IntPtr context, Int64 value);
[DllImport(SQLITE_DLL)]
internal static extern void sqlite3_result_null(IntPtr context);
[DllImport(SQLITE_DLL)]
internal static extern void sqlite3_result_text(IntPtr context, byte[] value, int nLen, IntPtr pvReserved);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode)]
internal static extern void sqlite3_result_error16(IntPtr context, string strName, int nLen);
[DllImport(SQLITE_DLL, CharSet = CharSet.Unicode)]
internal static extern void sqlite3_result_text16(IntPtr context, string strName, int nLen, IntPtr pvReserved);
// Value methods
[DllImport(SQLITE_DLL)]
internal static extern IntPtr sqlite3_value_blob(IntPtr p);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_value_bytes(IntPtr p);
[DllImport(SQLITE_DLL)]
internal static extern double sqlite3_value_double(IntPtr p);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_value_int(IntPtr p);
[DllImport(SQLITE_DLL)]
internal static extern Int64 sqlite3_value_int64(IntPtr p);
[DllImport(SQLITE_DLL)]
internal static extern int sqlite3_value_type(IntPtr p);
[DllImport(SQLITE_DLL)]
internal static extern IntPtr sqlite3_value_text16(IntPtr p);
internal static string PtrToString (this IntPtr ptr)
{
return System.Runtime.InteropServices.Marshal.PtrToStringUni (ptr);
}
internal static byte [] GetUtf8Bytes (string str)
{
return Encoding.UTF8.GetBytes (str + '\0');
}
}
}
| |
// <copyright file="LeaderboardManager.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if UNITY_ANDROID
namespace GooglePlayGames.Native.PInvoke
{
using System;
using System.Runtime.InteropServices;
using GooglePlayGames.BasicApi;
using GooglePlayGames.OurUtils;
using C = GooglePlayGames.Native.Cwrapper.LeaderboardManager;
using Types = GooglePlayGames.Native.Cwrapper.Types;
using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus;
using UnityEngine.SocialPlatforms;
internal class LeaderboardManager
{
private readonly GameServices mServices;
internal LeaderboardManager(GameServices services)
{
mServices = Misc.CheckNotNull(services);
}
internal int LeaderboardMaxResults
{
get
{
return 25;
}
}
internal void SubmitScore(string leaderboardId, long score, string metadata)
{
Misc.CheckNotNull(leaderboardId, "leaderboardId");
Logger.d("Native Submitting score: " + score +
" for lb " + leaderboardId + " with metadata: " + metadata);
C.LeaderboardManager_SubmitScore(mServices.AsHandle(), leaderboardId,
(ulong)score, metadata ?? "");
}
internal void ShowAllUI(Action<Status.UIStatus> callback)
{
Misc.CheckNotNull(callback);
C.LeaderboardManager_ShowAllUI(mServices.AsHandle(), Callbacks.InternalShowUICallback,
Callbacks.ToIntPtr(callback));
}
internal void ShowUI(string leaderboardId,
LeaderboardTimeSpan span, Action<Status.UIStatus> callback)
{
Misc.CheckNotNull(callback);
C.LeaderboardManager_ShowUI(mServices.AsHandle(), leaderboardId,
(Types.LeaderboardTimeSpan)span,
Callbacks.InternalShowUICallback,
Callbacks.ToIntPtr(callback));
}
/// <summary>
/// Loads the leaderboard data. This is the "top level" call
/// to load leaderboard data. A token for fetching scores is created
/// based on the parameters.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="start">Start of scores location</param>
/// <param name="rowCount">Row count.</param>
/// <param name="collection">Collection social or public</param>
/// <param name="timeSpan">Time span of leaderboard</param>
/// <param name="playerId">Player identifier.</param>
/// <param name="callback">Callback.</param>
public void LoadLeaderboardData(string leaderboardId,
LeaderboardStart start,
int rowCount,
LeaderboardCollection collection,
LeaderboardTimeSpan timeSpan,
string playerId, Action<LeaderboardScoreData> callback)
{
//Create a token we'll use to load scores later.
NativeScorePageToken nativeToken = new NativeScorePageToken(
C.LeaderboardManager_ScorePageToken(
mServices.AsHandle(),
leaderboardId,
(Types.LeaderboardStart)start,
(Types.LeaderboardTimeSpan)timeSpan,
(Types.LeaderboardCollection)collection));
ScorePageToken token = new ScorePageToken(nativeToken, leaderboardId,
collection, timeSpan);
// First fetch the leaderboard to get the title
C.LeaderboardManager_Fetch(mServices.AsHandle(),
Types.DataSource.CACHE_OR_NETWORK,
leaderboardId,
InternalFetchCallback,
Callbacks.ToIntPtr<FetchResponse>((rsp) =>
HandleFetch(token, rsp, playerId, rowCount, callback),
FetchResponse.FromPointer));
}
[AOT.MonoPInvokeCallback(typeof(C.FetchCallback))]
private static void InternalFetchCallback(IntPtr response, IntPtr data)
{
Callbacks.PerformInternalCallback("LeaderboardManager#InternalFetchCallback",
Callbacks.Type.Temporary, response, data);
}
/// <summary>
/// Handles the fetch of a specific leaderboard definition. This
/// is called with the expectation that the leaderboard summary and
/// scores are also needed.
/// </summary>
/// <param name="token">token for the current fetching request.</param>
/// <param name="response">Response.</param>
/// <param name="selfPlayerId">Self player identifier.</param>
/// <param name="maxResults">Number of scores to return.</param>
/// <param name="callback">Callback.</param>
internal void HandleFetch(ScorePageToken token,
FetchResponse response,
string selfPlayerId,
int maxResults,
Action<LeaderboardScoreData> callback)
{
LeaderboardScoreData data =
new LeaderboardScoreData(
token.LeaderboardId, (ResponseStatus)response.GetStatus());
if (response.GetStatus() != Status.ResponseStatus.VALID &&
response.GetStatus() != Status.ResponseStatus.VALID_BUT_STALE)
{
Logger.w("Error returned from fetch: " + response.GetStatus());
callback(data);
return;
}
data.Title = response.Leaderboard().Title();
data.Id = token.LeaderboardId;
// now fetch the summary of the leaderboard.
C.LeaderboardManager_FetchScoreSummary(mServices.AsHandle(),
Types.DataSource.CACHE_OR_NETWORK,
token.LeaderboardId,
(Types.LeaderboardTimeSpan)token.TimeSpan,
(Types.LeaderboardCollection)token.Collection,
InternalFetchSummaryCallback,
Callbacks.ToIntPtr<FetchScoreSummaryResponse>((rsp) =>
HandleFetchScoreSummary(data, rsp, selfPlayerId, maxResults, token, callback),
FetchScoreSummaryResponse.FromPointer)
);
}
[AOT.MonoPInvokeCallback(typeof(C.FetchScoreSummaryCallback))]
private static void InternalFetchSummaryCallback(IntPtr response, IntPtr data)
{
Callbacks.PerformInternalCallback("LeaderboardManager#InternalFetchSummaryCallback",
Callbacks.Type.Temporary, response, data);
}
internal void HandleFetchScoreSummary(LeaderboardScoreData data,
FetchScoreSummaryResponse response,
string selfPlayerId, int maxResults,
ScorePageToken token, Action<LeaderboardScoreData> callback)
{
if (response.GetStatus() != Status.ResponseStatus.VALID &&
response.GetStatus() != Status.ResponseStatus.VALID_BUT_STALE)
{
Logger.w("Error returned from fetchScoreSummary: " + response);
data.Status = (ResponseStatus)response.GetStatus();
callback(data);
return;
}
NativeScoreSummary summary = response.GetScoreSummary();
data.ApproximateCount = summary.ApproximateResults();
data.PlayerScore = summary.LocalUserScore().AsScore(data.Id, selfPlayerId);
// if the maxResults is 0, no scores are needed, so we are done.
if (maxResults <= 0)
{
callback(data);
return;
}
LoadScorePage(data, maxResults, token, callback);
}
/// <summary>
/// Loads the score page. This is used to page through the rows
/// of leaderboard scores.
/// </summary>
/// <param name="data">Data - partially completed result data, can be null</param>
/// <param name="maxResults">Max results to return</param>
/// <param name="token">Token to use for getting the score page,</param>
/// <param name="callback">Callback.</param>
public void LoadScorePage(LeaderboardScoreData data,
int maxResults, ScorePageToken token,
Action<LeaderboardScoreData> callback)
{
if (data == null)
{
data = new LeaderboardScoreData(token.LeaderboardId);
}
NativeScorePageToken nativeToken = (NativeScorePageToken)token.InternalObject;
C.LeaderboardManager_FetchScorePage(mServices.AsHandle(),
Types.DataSource.CACHE_OR_NETWORK,
nativeToken.AsPointer(),
(uint)maxResults,
InternalFetchScorePage,
Callbacks.ToIntPtr<FetchScorePageResponse>((rsp) => {
HandleFetchScorePage(data, token, rsp, callback);
}, FetchScorePageResponse.FromPointer)
);
}
[AOT.MonoPInvokeCallback(typeof(C.FetchScorePageCallback))]
private static void InternalFetchScorePage(IntPtr response, IntPtr data)
{
Callbacks.PerformInternalCallback("LeaderboardManager#InternalFetchScorePage",
Callbacks.Type.Temporary, response, data);
}
internal void HandleFetchScorePage(LeaderboardScoreData data,
ScorePageToken token,
FetchScorePageResponse rsp, Action<LeaderboardScoreData> callback)
{
data.Status = (ResponseStatus)rsp.GetStatus();
// add the scores that match the criteria
if (rsp.GetStatus() != Status.ResponseStatus.VALID &&
rsp.GetStatus() != Status.ResponseStatus.VALID_BUT_STALE)
{
callback(data);
}
NativeScorePage page = rsp.GetScorePage();
if (!page.Valid())
{
callback(data);
}
if (page.HasNextScorePage())
{
data.NextPageToken = new ScorePageToken(
page.GetNextScorePageToken(),
token.LeaderboardId,
token.Collection,
token.TimeSpan);
}
if (page.HasPrevScorePage())
{
data.PrevPageToken = new ScorePageToken(
page.GetPreviousScorePageToken(),
token.LeaderboardId,
token.Collection,
token.TimeSpan);
}
foreach (NativeScoreEntry ent in page)
{
data.AddScore(ent.AsScore(data.Id));
}
callback(data);
}
}
internal class FetchScorePageResponse : BaseReferenceHolder
{
internal FetchScorePageResponse(IntPtr selfPointer) : base(selfPointer)
{
}
protected override void CallDispose(HandleRef selfPointer)
{
C.LeaderboardManager_FetchScorePageResponse_Dispose(SelfPtr());
}
internal Status.ResponseStatus GetStatus()
{
return C.LeaderboardManager_FetchScorePageResponse_GetStatus(SelfPtr());
}
internal NativeScorePage GetScorePage()
{
return NativeScorePage.FromPointer(
C.LeaderboardManager_FetchScorePageResponse_GetData(SelfPtr()));
}
internal static FetchScorePageResponse FromPointer(IntPtr pointer)
{
if (pointer.Equals(IntPtr.Zero))
{
return null;
}
return new FetchScorePageResponse(pointer);
}
}
internal class FetchResponse : BaseReferenceHolder
{
internal FetchResponse(IntPtr selfPointer) : base(selfPointer)
{
}
protected override void CallDispose(HandleRef selfPointer)
{
C.LeaderboardManager_FetchResponse_Dispose(SelfPtr());
}
internal NativeLeaderboard Leaderboard()
{
return NativeLeaderboard.FromPointer(
C.LeaderboardManager_FetchResponse_GetData(SelfPtr()));
}
internal Status.ResponseStatus GetStatus()
{
return C.LeaderboardManager_FetchResponse_GetStatus(SelfPtr());
}
internal static FetchResponse FromPointer(IntPtr pointer)
{
if (pointer.Equals(IntPtr.Zero))
{
return null;
}
return new FetchResponse(pointer);
}
}
internal class FetchScoreSummaryResponse : BaseReferenceHolder
{
internal FetchScoreSummaryResponse(IntPtr selfPointer) : base(selfPointer)
{
}
protected override void CallDispose(HandleRef selfPointer)
{
C.LeaderboardManager_FetchScoreSummaryResponse_Dispose(selfPointer);
}
internal Status.ResponseStatus GetStatus()
{
return C.LeaderboardManager_FetchScoreSummaryResponse_GetStatus(SelfPtr());
}
internal NativeScoreSummary GetScoreSummary()
{
return NativeScoreSummary.FromPointer(
C.LeaderboardManager_FetchScoreSummaryResponse_GetData(SelfPtr()
));
}
internal static FetchScoreSummaryResponse FromPointer(IntPtr pointer)
{
if (pointer.Equals(IntPtr.Zero))
{
return null;
}
return new FetchScoreSummaryResponse(pointer);
}
}
}
#endif
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HalftoneFilter.cs" company="James Jackson-South">
// Copyright (c) James Jackson-South.
// Licensed under the Apache License, Version 2.0.
// </copyright>
// <summary>
// The halftone filter applies a classical CMYK filter to the given image.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ImageProcessor.Imaging.Filters.Artistic
{
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Threading.Tasks;
using ImageProcessor.Imaging.Colors;
using ImageProcessor.Imaging.Helpers;
/// <summary>
/// The halftone filter applies a classical CMYK filter to the given image.
/// </summary>
public class HalftoneFilter
{
/// <summary>
/// Initializes a new instance of the <see cref="HalftoneFilter"/> class.
/// </summary>
public HalftoneFilter()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HalftoneFilter"/> class.
/// </summary>
/// <param name="distance">
/// The distance.
/// </param>
public HalftoneFilter(int distance) => this.Distance = distance;
/// <summary>
/// Gets or sets the angle of the cyan component in degrees.
/// </summary>
public float CyanAngle { get; set; } = 15f;
/// <summary>
/// Gets or sets the angle of the magenta component in degrees.
/// </summary>
public float MagentaAngle { get; set; } = 75f;
/// <summary>
/// Gets or sets the angle of the yellow component in degrees.
/// </summary>
public float YellowAngle { get; set; }
/// <summary>
/// Gets or sets the angle of the keyline black component in degrees.
/// </summary>
public float KeylineAngle { get; set; } = 45f;
/// <summary>
/// Gets or sets the distance between component points.
/// </summary>
public int Distance { get; set; } = 4;
/// <summary>
/// Applies the halftone filter.
/// </summary>
/// <param name="source">
/// The <see cref="Bitmap"/> to apply the filter to.
/// </param>
/// <returns>
/// The <see cref="Bitmap"/> with the filter applied.
/// </returns>
public Bitmap ApplyFilter(Bitmap source)
{
// TODO: Make this class implement an interface?
Bitmap padded = null;
Bitmap cyan = null;
Bitmap magenta = null;
Bitmap yellow = null;
Bitmap keyline = null;
Bitmap newImage = null;
try
{
int sourceWidth = source.Width;
int sourceHeight = source.Height;
int width = source.Width + this.Distance;
int height = source.Height + this.Distance;
// Draw a slightly larger image, flipping the top/left pixels to prevent
// jagged edge of output.
padded = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
padded.SetResolution(source.HorizontalResolution, source.VerticalResolution);
using (var graphicsPadded = Graphics.FromImage(padded))
{
graphicsPadded.Clear(Color.White);
var destinationRectangle = new Rectangle(0, 0, sourceWidth + this.Distance, source.Height + this.Distance);
using (var tb = new TextureBrush(source))
{
tb.WrapMode = WrapMode.TileFlipXY;
tb.TranslateTransform(this.Distance, this.Distance);
graphicsPadded.FillRectangle(tb, destinationRectangle);
}
}
// Calculate min and max widths/heights.
Rectangle rotatedBounds = this.GetBoundingRectangle(width, height);
int minY = -(rotatedBounds.Height + height);
int maxY = rotatedBounds.Height + height;
int minX = -(rotatedBounds.Width + width);
int maxX = rotatedBounds.Width + width;
Point center = Point.Empty;
// Yellow oversaturates the output.
int offset = this.Distance;
float yellowMultiplier = this.Distance * 1.587f;
float magentaMultiplier = this.Distance * 2.176f;
float multiplier = this.Distance * 2.2f;
float max = this.Distance * (float)Math.Sqrt(2);
float magentaMax = this.Distance * (float)Math.Sqrt(1.4545);
// Bump up the keyline max so that black looks black.
float keylineMax = max * (float)Math.Sqrt(2);
// Color sampled process colours from Wikipedia pages.
// Keyline brush is declared separately.
Brush cyanBrush = new SolidBrush(Color.FromArgb(0, 183, 235));
Brush magentaBrush = new SolidBrush(Color.FromArgb(255, 0, 144));
Brush yellowBrush = new SolidBrush(Color.FromArgb(255, 239, 0));
// Create our images.
cyan = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
magenta = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
yellow = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
keyline = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
newImage = new Bitmap(sourceWidth, sourceHeight, PixelFormat.Format32bppPArgb);
// Ensure the correct resolution is set.
cyan.SetResolution(source.HorizontalResolution, source.VerticalResolution);
magenta.SetResolution(source.HorizontalResolution, source.VerticalResolution);
yellow.SetResolution(source.HorizontalResolution, source.VerticalResolution);
keyline.SetResolution(source.HorizontalResolution, source.VerticalResolution);
newImage.SetResolution(source.HorizontalResolution, source.VerticalResolution);
// Check bounds against this.
var rectangle = new Rectangle(0, 0, width, height);
using (var graphicsCyan = Graphics.FromImage(cyan))
using (var graphicsMagenta = Graphics.FromImage(magenta))
using (var graphicsYellow = Graphics.FromImage(yellow))
using (var graphicsKeyline = Graphics.FromImage(keyline))
{
// Set the quality properties.
graphicsCyan.PixelOffsetMode = PixelOffsetMode.Half;
graphicsMagenta.PixelOffsetMode = PixelOffsetMode.Half;
graphicsYellow.PixelOffsetMode = PixelOffsetMode.Half;
graphicsKeyline.PixelOffsetMode = PixelOffsetMode.Half;
graphicsCyan.SmoothingMode = SmoothingMode.AntiAlias;
graphicsMagenta.SmoothingMode = SmoothingMode.AntiAlias;
graphicsYellow.SmoothingMode = SmoothingMode.AntiAlias;
graphicsKeyline.SmoothingMode = SmoothingMode.AntiAlias;
graphicsCyan.CompositingQuality = CompositingQuality.HighQuality;
graphicsMagenta.CompositingQuality = CompositingQuality.HighQuality;
graphicsYellow.CompositingQuality = CompositingQuality.HighQuality;
graphicsKeyline.CompositingQuality = CompositingQuality.HighQuality;
// Set up the canvas.
graphicsCyan.Clear(Color.White);
graphicsMagenta.Clear(Color.White);
graphicsYellow.Clear(Color.White);
graphicsKeyline.Clear(Color.White);
// This is too slow. The graphics object can't be called within a parallel
// loop so we have to do it old school. :(
using (var sourceBitmap = new FastBitmap(padded))
{
for (int y = minY; y < maxY; y += offset)
{
for (int x = minX; x < maxX; x += offset)
{
Color color;
CmykColor cmykColor;
float brushWidth;
// Cyan
Point rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.CyanAngle, center);
int angledX = rotatedPoint.X;
int angledY = rotatedPoint.Y;
if (rectangle.Contains(new Point(angledX, angledY)))
{
color = sourceBitmap.GetPixel(angledX, angledY);
cmykColor = color;
brushWidth = Math.Min((cmykColor.C / 100f) * multiplier, max);
graphicsCyan.FillEllipse(cyanBrush, angledX, angledY, brushWidth, brushWidth);
}
// Magenta
rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.MagentaAngle, center);
angledX = rotatedPoint.X;
angledY = rotatedPoint.Y;
if (rectangle.Contains(new Point(angledX, angledY)))
{
color = sourceBitmap.GetPixel(angledX, angledY);
cmykColor = color;
brushWidth = Math.Min((cmykColor.M / 100f) * magentaMultiplier, magentaMax);
graphicsMagenta.FillEllipse(magentaBrush, angledX, angledY, brushWidth, brushWidth);
}
// Yellow
rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.YellowAngle, center);
angledX = rotatedPoint.X;
angledY = rotatedPoint.Y;
if (rectangle.Contains(new Point(angledX, angledY)))
{
color = sourceBitmap.GetPixel(angledX, angledY);
cmykColor = color;
brushWidth = Math.Min((cmykColor.Y / 100f) * yellowMultiplier, max);
graphicsYellow.FillEllipse(yellowBrush, angledX, angledY, brushWidth, brushWidth);
}
// Keyline
rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.KeylineAngle, center);
angledX = rotatedPoint.X;
angledY = rotatedPoint.Y;
if (rectangle.Contains(new Point(angledX, angledY)))
{
color = sourceBitmap.GetPixel(angledX, angledY);
cmykColor = color;
brushWidth = Math.Min((cmykColor.K / 100f) * multiplier, keylineMax);
// Just using black is too dark.
Brush keylineBrush = new SolidBrush(CmykColor.FromCmykColor(0, 0, 0, cmykColor.K));
graphicsKeyline.FillEllipse(keylineBrush, angledX, angledY, brushWidth, brushWidth);
}
}
}
}
// Set our white background.
using (var graphics = Graphics.FromImage(newImage))
{
graphics.Clear(Color.White);
}
// Blend the colors now to mimic adaptive blending.
using (var cyanBitmap = new FastBitmap(cyan))
using (var magentaBitmap = new FastBitmap(magenta))
using (var yellowBitmap = new FastBitmap(yellow))
using (var keylineBitmap = new FastBitmap(keyline))
using (var destinationBitmap = new FastBitmap(newImage))
{
Parallel.For(
offset,
height,
y =>
{
for (int x = offset; x < width; x++)
{
// ReSharper disable AccessToDisposedClosure
Color cyanPixel = cyanBitmap.GetPixel(x, y);
Color magentaPixel = magentaBitmap.GetPixel(x, y);
Color yellowPixel = yellowBitmap.GetPixel(x, y);
Color keylinePixel = keylineBitmap.GetPixel(x, y);
// Negate the offset.
int xBack = x - offset;
int yBack = y - offset;
CmykColor blended = cyanPixel.AddAsCmykColor(magentaPixel, yellowPixel, keylinePixel);
if (rectangle.Contains(new Point(xBack, yBack)))
{
destinationBitmap.SetPixel(xBack, yBack, blended);
}
// ReSharper restore AccessToDisposedClosure
}
});
}
}
padded.Dispose();
cyan.Dispose();
magenta.Dispose();
yellow.Dispose();
keyline.Dispose();
source.Dispose();
source = newImage;
}
catch
{
padded?.Dispose();
cyan?.Dispose();
magenta?.Dispose();
yellow?.Dispose();
keyline?.Dispose();
newImage?.Dispose();
}
return source;
}
/// <summary>
/// Gets the bounding rectangle of the image based on the rotating angles.
/// </summary>
/// <param name="width">
/// The width of the image.
/// </param>
/// <param name="height">
/// The height of the image.
/// </param>
/// <returns>
/// The <see cref="Rectangle"/>.
/// </returns>
private Rectangle GetBoundingRectangle(int width, int height)
{
int maxWidth = 0;
int maxHeight = 0;
foreach (float angle in new List<float> { this.CyanAngle, this.MagentaAngle, this.YellowAngle, this.KeylineAngle })
{
Size rotatedSize = ImageMaths.GetBoundingRotatedRectangle(width, height, angle).Size;
maxWidth = Math.Max(maxWidth, rotatedSize.Width);
maxHeight = Math.Max(maxHeight, rotatedSize.Height);
}
return new Rectangle(0, 0, maxWidth, maxHeight);
}
}
}
| |
// 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.Data.Odbc;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
internal static partial class Interop
{
internal static partial class Odbc
{
//
// ODBC32
//
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLAllocHandle(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/IntPtr InputHandle,
/*SQLHANDLE* */out IntPtr OutputHandle);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLAllocHandle(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/OdbcHandle InputHandle,
/*SQLHANDLE* */out IntPtr OutputHandle);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLBindCol(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/UInt16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_C TargetType,
/*SQLPOINTER*/HandleRef TargetValue,
/*SQLLEN*/IntPtr BufferLength,
/*SQLLEN* */IntPtr StrLen_or_Ind);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLBindCol(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/UInt16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_C TargetType,
/*SQLPOINTER*/IntPtr TargetValue,
/*SQLLEN*/IntPtr BufferLength,
/*SQLLEN* */IntPtr StrLen_or_Ind);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLBindParameter(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/UInt16 ParameterNumber,
/*SQLSMALLINT*/Int16 ParamDirection,
/*SQLSMALLINT*/ODBC32.SQL_C SQLCType,
/*SQLSMALLINT*/Int16 SQLType,
/*SQLULEN*/IntPtr cbColDef,
/*SQLSMALLINT*/IntPtr ibScale,
/*SQLPOINTER*/HandleRef rgbValue,
/*SQLLEN*/IntPtr BufferLength,
/*SQLLEN* */HandleRef StrLen_or_Ind);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLCancel(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLCloseCursor(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLColAttributeW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/Int16 ColumnNumber,
/*SQLUSMALLINT*/Int16 FieldIdentifier,
/*SQLPOINTER*/CNativeBuffer CharacterAttribute,
/*SQLSMALLINT*/Int16 BufferLength,
/*SQLSMALLINT* */out Int16 StringLength,
/*SQLPOINTER*/out IntPtr NumericAttribute);
// note: in sql.h this is defined differently for the 64Bit platform.
// However, for us the code is not different for SQLPOINTER or SQLLEN ...
// frome sql.h:
// #ifdef _WIN64
// SQLRETURN SQL_API SQLColAttribute (SQLHSTMT StatementHandle,
// SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier,
// SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength,
// SQLSMALLINT *StringLength, SQLLEN *NumericAttribute);
// #else
// SQLRETURN SQL_API SQLColAttribute (SQLHSTMT StatementHandle,
// SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier,
// SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength,
// SQLSMALLINT *StringLength, SQLPOINTER NumericAttribute);
// #endif
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLColumnsW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string ColumnName,
/*SQLSMALLINT*/Int16 NameLen4);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLDisconnect(
/*SQLHDBC*/IntPtr ConnectionHandle);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLDriverConnectW(
/*SQLHDBC*/OdbcConnectionHandle hdbc,
/*SQLHWND*/IntPtr hwnd,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string connectionstring,
/*SQLSMALLINT*/Int16 cbConnectionstring,
/*SQLCHAR* */IntPtr connectionstringout,
/*SQLSMALLINT*/Int16 cbConnectionstringoutMax,
/*SQLSMALLINT* */out Int16 cbConnectionstringout,
/*SQLUSMALLINT*/Int16 fDriverCompletion);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLEndTran(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/IntPtr Handle,
/*SQLSMALLINT*/Int16 CompletionType);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLExecDirectW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string StatementText,
/*SQLINTEGER*/Int32 TextLength);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLExecute(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLFetch(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLFreeHandle(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHSTMT*/IntPtr StatementHandle);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLFreeStmt(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/ODBC32.STMT Option);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetConnectAttrW(
/*SQLHBDC*/OdbcConnectionHandle ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/byte[] Value,
/*SQLINTEGER*/Int32 BufferLength,
/*SQLINTEGER* */out Int32 StringLength);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetData(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/UInt16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_C TargetType,
/*SQLPOINTER*/CNativeBuffer TargetValue,
/*SQLLEN*/IntPtr BufferLength, // sql.h differs from MSDN
/*SQLLEN* */out IntPtr StrLen_or_Ind);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetDescFieldW(
/*SQLHSTMT*/OdbcDescriptorHandle StatementHandle,
/*SQLUSMALLINT*/Int16 RecNumber,
/*SQLUSMALLINT*/ODBC32.SQL_DESC FieldIdentifier,
/*SQLPOINTER*/CNativeBuffer ValuePointer,
/*SQLINTEGER*/Int32 BufferLength,
/*SQLINTEGER* */out Int32 StringLength);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetDiagRecW(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/OdbcHandle Handle,
/*SQLSMALLINT*/Int16 RecNumber,
/*SQLCHAR* */ StringBuilder rchState,
/*SQLINTEGER* */out Int32 NativeError,
/*SQLCHAR* */StringBuilder MessageText,
/*SQLSMALLINT*/Int16 BufferLength,
/*SQLSMALLINT* */out Int16 TextLength);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetDiagFieldW(
/*SQLSMALLINT*/ ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/ OdbcHandle Handle,
/*SQLSMALLINT*/ Int16 RecNumber,
/*SQLSMALLINT*/ Int16 DiagIdentifier,
[MarshalAs(UnmanagedType.LPWStr)]
/*SQLPOINTER*/ StringBuilder rchState,
/*SQLSMALLINT*/ Int16 BufferLength,
/*SQLSMALLINT* */ out Int16 StringLength);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetFunctions(
/*SQLHBDC*/OdbcConnectionHandle hdbc,
/*SQLUSMALLINT*/ODBC32.SQL_API fFunction,
/*SQLUSMALLINT* */out Int16 pfExists);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetInfoW(
/*SQLHBDC*/OdbcConnectionHandle hdbc,
/*SQLUSMALLINT*/ODBC32.SQL_INFO fInfoType,
/*SQLPOINTER*/byte[] rgbInfoValue,
/*SQLSMALLINT*/Int16 cbInfoValueMax,
/*SQLSMALLINT* */out Int16 pcbInfoValue);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetInfoW(
/*SQLHBDC*/OdbcConnectionHandle hdbc,
/*SQLUSMALLINT*/ODBC32.SQL_INFO fInfoType,
/*SQLPOINTER*/byte[] rgbInfoValue,
/*SQLSMALLINT*/Int16 cbInfoValueMax,
/*SQLSMALLINT* */IntPtr pcbInfoValue);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetStmtAttrW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/out IntPtr Value,
/*SQLINTEGER*/Int32 BufferLength,
/*SQLINTEGER*/out Int32 StringLength);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLGetTypeInfo(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLSMALLINT*/Int16 fSqlType);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLMoreResults(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLNumResultCols(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLSMALLINT* */out Int16 ColumnCount);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLPrepareW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string StatementText,
/*SQLINTEGER*/Int32 TextLength);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLPrimaryKeysW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */ string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLProcedureColumnsW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string ProcName,
/*SQLSMALLINT*/Int16 NameLen3,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string ColumnName,
/*SQLSMALLINT*/Int16 NameLen4);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLProceduresW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string ProcName,
/*SQLSMALLINT*/Int16 NameLen3);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLRowCount(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLLEN* */out IntPtr RowCount);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW(
/*SQLHBDC*/OdbcConnectionHandle ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/System.Transactions.IDtcTransaction Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW(
/*SQLHBDC*/OdbcConnectionHandle ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/string Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW(
/*SQLHBDC*/OdbcConnectionHandle ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/IntPtr Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW( // used only for AutoCommitOn
/*SQLHBDC*/IntPtr ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/IntPtr Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetDescFieldW(
/*SQLHSTMT*/OdbcDescriptorHandle StatementHandle,
/*SQLSMALLINT*/Int16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_DESC FieldIdentifier,
/*SQLPOINTER*/HandleRef CharacterAttribute,
/*SQLINTEGER*/Int32 BufferLength);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetDescFieldW(
/*SQLHSTMT*/OdbcDescriptorHandle StatementHandle,
/*SQLSMALLINT*/Int16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_DESC FieldIdentifier,
/*SQLPOINTER*/IntPtr CharacterAttribute,
/*SQLINTEGER*/Int32 BufferLength);
[DllImport(Interop.Libraries.Odbc32)]
// user can set SQL_ATTR_CONNECTION_POOLING attribute with envHandle = null, this attribute is process-level attribute
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetEnvAttr(
/*SQLHENV*/OdbcEnvironmentHandle EnvironmentHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/IntPtr Value,
/*SQLINTEGER*/ODBC32.SQL_IS StringLength);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSetStmtAttrW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLINTEGER*/Int32 Attribute,
/*SQLPOINTER*/IntPtr Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLSpecialColumnsW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/ODBC32.SQL_SPECIALCOLS IdentifierType,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3,
/*SQLUSMALLINT*/ODBC32.SQL_SCOPE Scope,
/*SQLUSMALLINT*/ ODBC32.SQL_NULLABILITY Nullable);
[DllImport(Interop.Libraries.Odbc32, CharSet = CharSet.Unicode)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLStatisticsW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3,
/*SQLUSMALLINT*/Int16 Unique,
/*SQLUSMALLINT*/Int16 Reserved);
[DllImport(Interop.Libraries.Odbc32)]
internal static extern /*SQLRETURN*/ODBC32.RetCode SQLTablesW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableType,
/*SQLSMALLINT*/Int16 NameLen4);
}
}
| |
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK;
using OpenTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Sprites;
using osu.Game.Users;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;
using osu.Game.Overlays.MedalSplash;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input;
using OpenTK.Input;
using System.Linq;
using osu.Framework.Graphics.Shapes;
using System;
using osu.Framework.MathUtils;
namespace osu.Game.Overlays
{
public class MedalOverlay : FocusedOverlayContainer
{
public const float DISC_SIZE = 400;
private const float border_width = 5;
private readonly Medal medal;
private readonly Box background;
private readonly Container backgroundStrip, particleContainer;
private readonly BackgroundStrip leftStrip, rightStrip;
private readonly CircularContainer disc;
private readonly Sprite innerSpin, outerSpin;
private DrawableMedal drawableMedal;
private SampleChannel getSample;
public MedalOverlay(Medal medal)
{
this.medal = medal;
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(60),
},
outerSpin = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(DISC_SIZE + 500),
Alpha = 0f,
},
backgroundStrip = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = border_width,
Alpha = 0f,
Children = new[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.CentreRight,
Width = 0.5f,
Padding = new MarginPadding { Right = DISC_SIZE / 2 },
Children = new[]
{
leftStrip = new BackgroundStrip(0f, 1f)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
},
},
new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.CentreLeft,
Width = 0.5f,
Padding = new MarginPadding { Left = DISC_SIZE / 2 },
Children = new[]
{
rightStrip = new BackgroundStrip(1f, 0f),
},
},
},
},
particleContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Alpha = 0f,
},
disc = new CircularContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Alpha = 0f,
Masking = true,
AlwaysPresent = true,
BorderColour = Color4.White,
BorderThickness = border_width,
Size = new Vector2(DISC_SIZE),
Scale = new Vector2(0.8f),
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.FromHex(@"05262f"),
},
new Triangles
{
RelativeSizeAxes = Axes.Both,
TriangleScale = 2,
ColourDark = OsuColour.FromHex(@"04222b"),
ColourLight = OsuColour.FromHex(@"052933"),
},
innerSpin = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(1.05f),
Alpha = 0.25f,
},
},
},
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, TextureStore textures, AudioManager audio)
{
getSample = audio.Sample.Get(@"MedalSplash/medal-get");
innerSpin.Texture = outerSpin.Texture = textures.Get(@"MedalSplash/disc-spin");
disc.EdgeEffect = leftStrip.EdgeEffect = rightStrip.EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Glow,
Colour = colours.Blue.Opacity(0.5f),
Radius = 50,
};
disc.Add(drawableMedal = new DrawableMedal(medal)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.Both,
});
}
protected override void LoadComplete()
{
base.LoadComplete();
Show();
}
protected override void Update()
{
base.Update();
particleContainer.Add(new MedalParticle(RNG.Next(0, 359)));
}
protected override bool OnClick(InputState state)
{
dismiss();
return true;
}
protected override void OnFocusLost(InputState state)
{
if (state.Keyboard.Keys.Contains(Key.Escape)) dismiss();
}
private const double initial_duration = 400;
private const double step_duration = 900;
protected override void PopIn()
{
base.PopIn();
this.FadeIn(200);
background.FlashColour(Color4.White.Opacity(0.25f), 400);
getSample.Play();
innerSpin.Spin(20000, RotationDirection.Clockwise);
outerSpin.Spin(40000, RotationDirection.Clockwise);
using (BeginDelayedSequence(200, true))
{
disc.FadeIn(initial_duration)
.ScaleTo(1f, initial_duration * 2, Easing.OutElastic);
particleContainer.FadeIn(initial_duration);
outerSpin.FadeTo(0.1f, initial_duration * 2);
using (BeginDelayedSequence(initial_duration + 200, true))
{
backgroundStrip.FadeIn(step_duration);
leftStrip.ResizeWidthTo(1f, step_duration, Easing.OutQuint);
rightStrip.ResizeWidthTo(1f, step_duration, Easing.OutQuint);
this.Animate().Schedule(() =>
{
if (drawableMedal.State != DisplayState.Full)
drawableMedal.State = DisplayState.Icon;
})
.Delay(step_duration).Schedule(() =>
{
if (drawableMedal.State != DisplayState.Full)
drawableMedal.State = DisplayState.MedalUnlocked;
})
.Delay(step_duration).Schedule(() =>
{
if (drawableMedal.State != DisplayState.Full)
drawableMedal.State = DisplayState.Full;
});
}
}
}
protected override void PopOut()
{
base.PopOut();
this.FadeOut(200);
}
private void dismiss()
{
if (drawableMedal.State != DisplayState.Full)
{
// if we haven't yet, play out the animation fully
drawableMedal.State = DisplayState.Full;
FinishTransforms(true);
return;
}
Hide();
Expire();
}
private class BackgroundStrip : Container
{
public BackgroundStrip(float start, float end)
{
RelativeSizeAxes = Axes.Both;
Width = 0f;
Colour = ColourInfo.GradientHorizontal(Color4.White.Opacity(start), Color4.White.Opacity(end));
Masking = true;
Children = new[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
}
};
}
}
private class MedalParticle : CircularContainer
{
private readonly float direction;
private Vector2 positionForOffset(float offset) => new Vector2((float)(offset * Math.Sin(direction)), (float)(offset * Math.Cos(direction)));
public MedalParticle(float direction)
{
this.direction = direction;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Position = positionForOffset(DISC_SIZE / 2);
Masking = true;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Glow,
Colour = colours.Blue.Opacity(0.5f),
Radius = 5,
};
this.MoveTo(positionForOffset(DISC_SIZE / 2 + 200), 500);
this.FadeOut(500);
Expire();
}
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Xml;
/// <summary>
/// Represents an abstract binding to an Exchange Service.
/// </summary>
public abstract class ExchangeServiceBase
{
#region Const members
private static readonly object lockObj = new object();
private readonly ExchangeVersion requestedServerVersion = ExchangeVersion.Exchange2013_SP1;
/// <summary>
/// Special HTTP status code that indicates that the account is locked.
/// </summary>
internal const HttpStatusCode AccountIsLocked = (HttpStatusCode)456;
/// <summary>
/// The binary secret.
/// </summary>
private static byte[] binarySecret;
#endregion
#region Static members
/// <summary>
/// Default UserAgent
/// </summary>
private static string defaultUserAgent = "ExchangeServicesClient/" + EwsUtilities.BuildVersion;
#endregion
#region Fields
/// <summary>
/// Occurs when the http response headers of a server call is captured.
/// </summary>
public event ResponseHeadersCapturedHandler OnResponseHeadersCaptured;
private ExchangeCredentials credentials;
private bool useDefaultCredentials;
private int timeout = 100000;
private bool traceEnabled;
private bool sendClientLatencies = true;
private TraceFlags traceFlags = TraceFlags.All;
private ITraceListener traceListener = new EwsTraceListener();
private bool preAuthenticate;
private string userAgent = ExchangeService.defaultUserAgent;
private bool acceptGzipEncoding = true;
private bool keepAlive = true;
private string connectionGroupName;
private string clientRequestId;
private bool returnClientRequestId;
private CookieContainer cookieContainer = new CookieContainer();
private TimeZoneInfo timeZone;
private TimeZoneDefinition timeZoneDefinition;
private ExchangeServerInfo serverInfo;
private IWebProxy webProxy;
private IDictionary<string, string> httpHeaders = new Dictionary<string, string>();
private IDictionary<string, string> httpResponseHeaders = new Dictionary<string, string>();
private IEwsHttpWebRequestFactory ewsHttpWebRequestFactory = new EwsHttpWebRequestFactory();
#endregion
#region Event handlers
/// <summary>
/// Calls the custom SOAP header serialization event handlers, if defined.
/// </summary>
/// <param name="writer">The XmlWriter to which to write the custom SOAP headers.</param>
internal void DoOnSerializeCustomSoapHeaders(XmlWriter writer)
{
EwsUtilities.Assert(
writer != null,
"ExchangeService.DoOnSerializeCustomSoapHeaders",
"writer is null");
if (this.OnSerializeCustomSoapHeaders != null)
{
this.OnSerializeCustomSoapHeaders(writer);
}
}
#endregion
#region Utilities
/// <summary>
/// Creates an HttpWebRequest instance and initializes it with the appropriate parameters,
/// based on the configuration of this service object.
/// </summary>
/// <param name="url">The URL that the HttpWebRequest should target.</param>
/// <param name="acceptGzipEncoding">If true, ask server for GZip compressed content.</param>
/// <param name="allowAutoRedirect">If true, redirection responses will be automatically followed.</param>
/// <returns>A initialized instance of HttpWebRequest.</returns>
internal IEwsHttpWebRequest PrepareHttpWebRequestForUrl(
Uri url,
bool acceptGzipEncoding,
bool allowAutoRedirect)
{
// Verify that the protocol is something that we can handle
if ((url.Scheme != Uri.UriSchemeHttp) && (url.Scheme != Uri.UriSchemeHttps))
{
throw new ServiceLocalException(string.Format(Strings.UnsupportedWebProtocol, url.Scheme));
}
IEwsHttpWebRequest request = this.HttpWebRequestFactory.CreateRequest(url);
request.PreAuthenticate = this.PreAuthenticate;
request.Timeout = this.Timeout;
this.SetContentType(request);
request.Method = "POST";
request.UserAgent = this.UserAgent;
request.AllowAutoRedirect = allowAutoRedirect;
request.CookieContainer = this.CookieContainer;
request.KeepAlive = this.keepAlive;
request.ConnectionGroupName = this.connectionGroupName;
if (acceptGzipEncoding)
{
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
}
if (!string.IsNullOrEmpty(this.clientRequestId))
{
request.Headers.Add("client-request-id", this.clientRequestId);
if (this.returnClientRequestId)
{
request.Headers.Add("return-client-request-id", "true");
}
}
if (this.webProxy != null)
{
request.Proxy = this.webProxy;
}
if (this.HttpHeaders.Count > 0)
{
this.HttpHeaders.ForEach((kv) => request.Headers.Add(kv.Key, kv.Value));
}
request.UseDefaultCredentials = this.UseDefaultCredentials;
if (!request.UseDefaultCredentials)
{
ExchangeCredentials serviceCredentials = this.Credentials;
if (serviceCredentials == null)
{
throw new ServiceLocalException(Strings.CredentialsRequired);
}
// Make sure that credentials have been authenticated if required
serviceCredentials.PreAuthenticate();
// Apply credentials to the request
serviceCredentials.PrepareWebRequest(request);
}
this.httpResponseHeaders.Clear();
return request;
}
internal virtual void SetContentType(IEwsHttpWebRequest request)
{
request.ContentType = "text/xml; charset=utf-8";
request.Accept = "text/xml";
}
/// <summary>
/// Processes an HTTP error response
/// </summary>
/// <param name="httpWebResponse">The HTTP web response.</param>
/// <param name="webException">The web exception.</param>
/// <param name="responseHeadersTraceFlag">The trace flag for response headers.</param>
/// <param name="responseTraceFlag">The trace flag for responses.</param>
/// <remarks>
/// This method doesn't handle 500 ISE errors. This is handled by the caller since
/// 500 ISE typically indicates that a SOAP fault has occurred and the handling of
/// a SOAP fault is currently service specific.
/// </remarks>
internal void InternalProcessHttpErrorResponse(
IEwsHttpWebResponse httpWebResponse,
WebException webException,
TraceFlags responseHeadersTraceFlag,
TraceFlags responseTraceFlag)
{
EwsUtilities.Assert(
httpWebResponse.StatusCode != HttpStatusCode.InternalServerError,
"ExchangeServiceBase.InternalProcessHttpErrorResponse",
"InternalProcessHttpErrorResponse does not handle 500 ISE errors, the caller is supposed to handle this.");
this.ProcessHttpResponseHeaders(responseHeadersTraceFlag, httpWebResponse);
// Deal with new HTTP error code indicating that account is locked.
// The "unlock" URL is returned as the status description in the response.
if (httpWebResponse.StatusCode == ExchangeServiceBase.AccountIsLocked)
{
string location = httpWebResponse.StatusDescription;
Uri accountUnlockUrl = null;
if (Uri.IsWellFormedUriString(location, UriKind.Absolute))
{
accountUnlockUrl = new Uri(location);
}
this.TraceMessage(responseTraceFlag, string.Format("Account is locked. Unlock URL is {0}", accountUnlockUrl));
throw new AccountIsLockedException(
string.Format(Strings.AccountIsLocked, accountUnlockUrl),
accountUnlockUrl,
webException);
}
}
/// <summary>
/// Processes an HTTP error response.
/// </summary>
/// <param name="httpWebResponse">The HTTP web response.</param>
/// <param name="webException">The web exception.</param>
internal abstract void ProcessHttpErrorResponse(IEwsHttpWebResponse httpWebResponse, WebException webException);
/// <summary>
/// Determines whether tracing is enabled for specified trace flag(s).
/// </summary>
/// <param name="traceFlags">The trace flags.</param>
/// <returns>True if tracing is enabled for specified trace flag(s).
/// </returns>
internal bool IsTraceEnabledFor(TraceFlags traceFlags)
{
return this.TraceEnabled && ((this.TraceFlags & traceFlags) != 0);
}
/// <summary>
/// Logs the specified string to the TraceListener if tracing is enabled.
/// </summary>
/// <param name="traceType">Kind of trace entry.</param>
/// <param name="logEntry">The entry to log.</param>
internal void TraceMessage(TraceFlags traceType, string logEntry)
{
if (this.IsTraceEnabledFor(traceType))
{
string traceTypeStr = traceType.ToString();
string logMessage = EwsUtilities.FormatLogMessage(traceTypeStr, logEntry);
this.TraceListener.Trace(traceTypeStr, logMessage);
}
}
/// <summary>
/// Logs the specified XML to the TraceListener if tracing is enabled.
/// </summary>
/// <param name="traceType">Kind of trace entry.</param>
/// <param name="stream">The stream containing XML.</param>
internal void TraceXml(TraceFlags traceType, MemoryStream stream)
{
if (this.IsTraceEnabledFor(traceType))
{
string traceTypeStr = traceType.ToString();
string logMessage = EwsUtilities.FormatLogMessageWithXmlContent(traceTypeStr, stream);
this.TraceListener.Trace(traceTypeStr, logMessage);
}
}
/// <summary>
/// Traces the HTTP request headers.
/// </summary>
/// <param name="traceType">Kind of trace entry.</param>
/// <param name="request">The request.</param>
internal void TraceHttpRequestHeaders(TraceFlags traceType, IEwsHttpWebRequest request)
{
if (this.IsTraceEnabledFor(traceType))
{
string traceTypeStr = traceType.ToString();
string headersAsString = EwsUtilities.FormatHttpRequestHeaders(request);
string logMessage = EwsUtilities.FormatLogMessage(traceTypeStr, headersAsString);
this.TraceListener.Trace(traceTypeStr, logMessage);
}
}
/// <summary>
/// Traces the HTTP response headers.
/// </summary>
/// <param name="traceType">Kind of trace entry.</param>
/// <param name="response">The response.</param>
internal void ProcessHttpResponseHeaders(TraceFlags traceType, IEwsHttpWebResponse response)
{
this.TraceHttpResponseHeaders(traceType, response);
this.SaveHttpResponseHeaders(response.Headers);
}
/// <summary>
/// Traces the HTTP response headers.
/// </summary>
/// <param name="traceType">Kind of trace entry.</param>
/// <param name="response">The response.</param>
private void TraceHttpResponseHeaders(TraceFlags traceType, IEwsHttpWebResponse response)
{
if (this.IsTraceEnabledFor(traceType))
{
string traceTypeStr = traceType.ToString();
string headersAsString = EwsUtilities.FormatHttpResponseHeaders(response);
string logMessage = EwsUtilities.FormatLogMessage(traceTypeStr, headersAsString);
this.TraceListener.Trace(traceTypeStr, logMessage);
}
}
/// <summary>
/// Save the HTTP response headers.
/// </summary>
/// <param name="headers">The response headers</param>
private void SaveHttpResponseHeaders(WebHeaderCollection headers)
{
this.httpResponseHeaders.Clear();
foreach (string key in headers.AllKeys)
{
string existingValue;
if (this.httpResponseHeaders.TryGetValue(key, out existingValue))
{
this.httpResponseHeaders[key] = existingValue + "," + headers[key];
}
else
{
this.httpResponseHeaders.Add(key, headers[key]);
}
}
if (this.OnResponseHeadersCaptured != null)
{
this.OnResponseHeadersCaptured(headers);
}
}
/// <summary>
/// Converts the universal date time string to local date time.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>DateTime</returns>
internal DateTime? ConvertUniversalDateTimeStringToLocalDateTime(string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
else
{
// Assume an unbiased date/time is in UTC. Convert to UTC otherwise.
DateTime dateTime = DateTime.Parse(
value,
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
if (this.TimeZone == TimeZoneInfo.Utc)
{
// This returns a DateTime with Kind.Utc
return dateTime;
}
else
{
DateTime localTime = EwsUtilities.ConvertTime(
dateTime,
TimeZoneInfo.Utc,
this.TimeZone);
if (EwsUtilities.IsLocalTimeZone(this.TimeZone))
{
// This returns a DateTime with Kind.Local
return new DateTime(localTime.Ticks, DateTimeKind.Local);
}
else
{
// This returns a DateTime with Kind.Unspecified
return localTime;
}
}
}
}
/// <summary>
/// Converts xs:dateTime string with either "Z", "-00:00" bias, or "" suffixes to
/// unspecified StartDate value ignoring the suffix.
/// </summary>
/// <param name="value">The string value to parse.</param>
/// <returns>The parsed DateTime value.</returns>
internal DateTime? ConvertStartDateToUnspecifiedDateTime(string value)
{
if (string.IsNullOrEmpty(value))
{
return null;
}
else
{
DateTimeOffset dateTimeOffset = DateTimeOffset.Parse(value, CultureInfo.InvariantCulture);
// Return only the date part with the kind==Unspecified.
return dateTimeOffset.Date;
}
}
/// <summary>
/// Converts the date time to universal date time string.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>String representation of DateTime.</returns>
internal string ConvertDateTimeToUniversalDateTimeString(DateTime value)
{
DateTime dateTime;
switch (value.Kind)
{
case DateTimeKind.Unspecified:
dateTime = EwsUtilities.ConvertTime(
value,
this.TimeZone,
TimeZoneInfo.Utc);
break;
case DateTimeKind.Local:
dateTime = EwsUtilities.ConvertTime(
value,
TimeZoneInfo.Local,
TimeZoneInfo.Utc);
break;
default:
// The date is already in UTC, no need to convert it.
dateTime = value;
break;
}
return dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture);
}
/// <summary>
/// Register the custom auth module to support non-ascii upn authentication if the server supports that
/// </summary>
internal void RegisterCustomBasicAuthModule()
{
if (this.RequestedServerVersion >= ExchangeVersion.Exchange2013_SP1)
{
BasicAuthModuleForUTF8.InstantiateIfNeeded();
}
}
/// <summary>
/// Sets the user agent to a custom value
/// </summary>
/// <param name="userAgent">User agent string to set on the service</param>
internal void SetCustomUserAgent(string userAgent)
{
this.userAgent = userAgent;
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ExchangeServiceBase"/> class.
/// </summary>
internal ExchangeServiceBase()
: this(TimeZoneInfo.Local)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExchangeServiceBase"/> class.
/// </summary>
/// <param name="timeZone">The time zone to which the service is scoped.</param>
internal ExchangeServiceBase(TimeZoneInfo timeZone)
{
this.timeZone = timeZone;
this.UseDefaultCredentials = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExchangeServiceBase"/> class.
/// </summary>
/// <param name="requestedServerVersion">The requested server version.</param>
internal ExchangeServiceBase(ExchangeVersion requestedServerVersion)
: this(requestedServerVersion, TimeZoneInfo.Local)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ExchangeServiceBase"/> class.
/// </summary>
/// <param name="requestedServerVersion">The requested server version.</param>
/// <param name="timeZone">The time zone to which the service is scoped.</param>
internal ExchangeServiceBase(ExchangeVersion requestedServerVersion, TimeZoneInfo timeZone)
: this(timeZone)
{
this.requestedServerVersion = requestedServerVersion;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExchangeServiceBase"/> class.
/// </summary>
/// <param name="service">The other service.</param>
/// <param name="requestedServerVersion">The requested server version.</param>
internal ExchangeServiceBase(ExchangeServiceBase service, ExchangeVersion requestedServerVersion)
: this(requestedServerVersion)
{
this.useDefaultCredentials = service.useDefaultCredentials;
this.credentials = service.credentials;
this.traceEnabled = service.traceEnabled;
this.traceListener = service.traceListener;
this.traceFlags = service.traceFlags;
this.timeout = service.timeout;
this.preAuthenticate = service.preAuthenticate;
this.userAgent = service.userAgent;
this.acceptGzipEncoding = service.acceptGzipEncoding;
this.keepAlive = service.keepAlive;
this.connectionGroupName = service.connectionGroupName;
this.timeZone = service.timeZone;
this.httpHeaders = service.httpHeaders;
this.ewsHttpWebRequestFactory = service.ewsHttpWebRequestFactory;
this.webProxy = service.webProxy;
}
/// <summary>
/// Initializes a new instance of the <see cref="ExchangeServiceBase"/> class from existing one.
/// </summary>
/// <param name="service">The other service.</param>
internal ExchangeServiceBase(ExchangeServiceBase service)
: this(service, service.RequestedServerVersion)
{
}
#endregion
#region Validation
/// <summary>
/// Validates this instance.
/// </summary>
internal virtual void Validate()
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the cookie container.
/// </summary>
/// <value>The cookie container.</value>
public CookieContainer CookieContainer
{
get { return this.cookieContainer; }
set { this.cookieContainer = value; }
}
/// <summary>
/// Gets the time zone this service is scoped to.
/// </summary>
internal TimeZoneInfo TimeZone
{
get { return this.timeZone; }
}
/// <summary>
/// Gets a time zone definition generated from the time zone info to which this service is scoped.
/// </summary>
internal TimeZoneDefinition TimeZoneDefinition
{
get
{
if (this.timeZoneDefinition == null)
{
this.timeZoneDefinition = new TimeZoneDefinition(this.TimeZone);
}
return this.timeZoneDefinition;
}
}
/// <summary>
/// Gets or sets a value indicating whether client latency info is push to server.
/// </summary>
public bool SendClientLatencies
{
get
{
return this.sendClientLatencies;
}
set
{
this.sendClientLatencies = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether tracing is enabled.
/// </summary>
public bool TraceEnabled
{
get
{
return this.traceEnabled;
}
set
{
this.traceEnabled = value;
if (this.traceEnabled && (this.traceListener == null))
{
this.traceListener = new EwsTraceListener();
}
}
}
/// <summary>
/// Gets or sets the trace flags.
/// </summary>
/// <value>The trace flags.</value>
public TraceFlags TraceFlags
{
get
{
return this.traceFlags;
}
set
{
this.traceFlags = value;
}
}
/// <summary>
/// Gets or sets the trace listener.
/// </summary>
/// <value>The trace listener.</value>
public ITraceListener TraceListener
{
get
{
return this.traceListener;
}
set
{
this.traceListener = value;
this.traceEnabled = value != null;
}
}
/// <summary>
/// Gets or sets the credentials used to authenticate with the Exchange Web Services. Setting the Credentials property
/// automatically sets the UseDefaultCredentials to false.
/// </summary>
public ExchangeCredentials Credentials
{
get
{
return this.credentials;
}
set
{
this.credentials = value;
this.useDefaultCredentials = false;
this.cookieContainer = new CookieContainer(); // Changing credentials resets the Cookie container
}
}
/// <summary>
/// Gets or sets a value indicating whether the credentials of the user currently logged into Windows should be used to
/// authenticate with the Exchange Web Services. Setting UseDefaultCredentials to true automatically sets the Credentials
/// property to null.
/// </summary>
public bool UseDefaultCredentials
{
get
{
return this.useDefaultCredentials;
}
set
{
this.useDefaultCredentials = value;
if (value)
{
this.credentials = null;
this.cookieContainer = new CookieContainer(); // Changing credentials resets the Cookie container
}
}
}
/// <summary>
/// Gets or sets the timeout used when sending HTTP requests and when receiving HTTP responses, in milliseconds.
/// Defaults to 100000.
/// </summary>
public int Timeout
{
get
{
return this.timeout;
}
set
{
if (value < 1)
{
throw new ArgumentException(Strings.TimeoutMustBeGreaterThanZero);
}
this.timeout = value;
}
}
/// <summary>
/// Gets or sets a value that indicates whether HTTP pre-authentication should be performed.
/// </summary>
public bool PreAuthenticate
{
get { return this.preAuthenticate; }
set { this.preAuthenticate = value; }
}
/// <summary>
/// Gets or sets a value indicating whether GZip compression encoding should be accepted.
/// </summary>
/// <remarks>
/// This value will tell the server that the client is able to handle GZip compression encoding. The server
/// will only send Gzip compressed content if it has been configured to do so.
/// </remarks>
public bool AcceptGzipEncoding
{
get { return this.acceptGzipEncoding; }
set { this.acceptGzipEncoding = value; }
}
/// <summary>
/// Gets the requested server version.
/// </summary>
/// <value>The requested server version.</value>
public ExchangeVersion RequestedServerVersion
{
get { return this.requestedServerVersion; }
}
/// <summary>
/// Gets or sets the user agent.
/// </summary>
/// <value>The user agent.</value>
public string UserAgent
{
get { return this.userAgent; }
set { this.userAgent = value + " (" + ExchangeService.defaultUserAgent + ")"; }
}
/// <summary>
/// Gets information associated with the server that processed the last request.
/// Will be null if no requests have been processed.
/// </summary>
public ExchangeServerInfo ServerInfo
{
get { return this.serverInfo; }
internal set { this.serverInfo = value; }
}
/// <summary>
/// Gets or sets the web proxy that should be used when sending requests to EWS.
/// Set this property to null to use the default web proxy.
/// </summary>
public IWebProxy WebProxy
{
get { return this.webProxy; }
set { this.webProxy = value; }
}
/// <summary>
/// Gets or sets if the request to the internet resource should contain a Connection HTTP header with the value Keep-alive
/// </summary>
public bool KeepAlive
{
get
{
return this.keepAlive;
}
set
{
this.keepAlive = value;
}
}
/// <summary>
/// Gets or sets the name of the connection group for the request.
/// </summary>
public string ConnectionGroupName
{
get
{
return this.connectionGroupName;
}
set
{
this.connectionGroupName = value;
}
}
/// <summary>
/// Gets or sets the request id for the request.
/// </summary>
public string ClientRequestId
{
get { return this.clientRequestId; }
set { this.clientRequestId = value; }
}
/// <summary>
/// Gets or sets a flag to indicate whether the client requires the server side to return the request id.
/// </summary>
public bool ReturnClientRequestId
{
get { return this.returnClientRequestId; }
set { this.returnClientRequestId = value; }
}
/// <summary>
/// Gets a collection of HTTP headers that will be sent with each request to EWS.
/// </summary>
public IDictionary<string, string> HttpHeaders
{
get { return this.httpHeaders; }
}
/// <summary>
/// Gets a collection of HTTP headers from the last response.
/// </summary>
public IDictionary<string, string> HttpResponseHeaders
{
get { return this.httpResponseHeaders; }
}
/// <summary>
/// Gets the session key.
/// </summary>
internal static byte[] SessionKey
{
get
{
// this has to be computed only once.
lock (ExchangeServiceBase.lockObj)
{
if (ExchangeServiceBase.binarySecret == null)
{
RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create();
ExchangeServiceBase.binarySecret = new byte[256 / 8];
randomNumberGenerator.GetNonZeroBytes(binarySecret);
}
return ExchangeServiceBase.binarySecret;
}
}
}
/// <summary>
/// Gets or sets the HTTP web request factory.
/// </summary>
internal IEwsHttpWebRequestFactory HttpWebRequestFactory
{
get { return this.ewsHttpWebRequestFactory; }
set
{
// If new value is null, reset to default factory.
this.ewsHttpWebRequestFactory = (value == null) ? new EwsHttpWebRequestFactory() : value;
}
}
/// <summary>
/// For testing: suppresses generation of the SOAP version header.
/// </summary>
internal bool SuppressXmlVersionHeader { get; set; }
#endregion
#region Events
/// <summary>
/// Provides an event that applications can implement to emit custom SOAP headers in requests that are sent to Exchange.
/// </summary>
public event CustomXmlSerializationDelegate OnSerializeCustomSoapHeaders;
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.Generic;
using System.Management.Automation.Internal;
using System.Text;
namespace System.Management.Automation.Provider
{
#region NavigationCmdletProvider
/// <summary>
/// The base class for a Cmdlet provider that expose a hierarchy of items and containers.
/// </summary>
///
/// <remarks>
/// The NavigationCmdletProvider class is a base class that provider can derive from
/// to implement a set of methods that allow
/// the use of a set of core commands against the data store that the provider
/// gives access to. By implementing this interface users can take advantage
/// the recursive commands, nested containers, and relative paths.
/// </remarks>
public abstract class NavigationCmdletProvider : ContainerCmdletProvider
{
#region Internal methods
/// <summary>
/// Internal wrapper for the MakePath protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
///
/// <param name="parent">
/// The parent segment of a path to be joined with the child.
/// </param>
///
/// <param name="child">
/// The child segment of a path to be joined with the parent.
/// </param>
///
/// <param name="context">
/// The context under which this method is being called.
/// </param>
///
/// <returns>
/// A string that represents the parent and child segments of the path
/// joined by a path separator.
/// </returns>
///
/// <remarks>
/// This method should use lexical joining of two path segments with a path
/// separator character. It should not validate the path as a legal fully
/// qualified path in the provider namespace as each parameter could be only
/// partial segments of a path and joined they may not generate a fully
/// qualified path.
/// Example: the file system provider may get "windows\system32" as the parent
/// parameter and "foo.dll" as the child parameter. The method should join these
/// with the "\" separator and return "windows\system32\foo.dll". Note that
/// the returned path is not a fully qualified file system path.
///
/// Also beware that the path segments may contain characters that are illegal
/// in the provider namespace. These characters are most likely being used
/// for globbing and should not be removed by the implementation of this method.
/// </remarks>
///
internal string MakePath(
string parent,
string child,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return MakePath(parent, child);
} // MakePath
/// <summary>
/// Internal wrapper for the GetParentPath protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
///
/// <param name="path">
/// A fully qualified provider specific path to an item. The item may or
/// may not exist.
/// </param>
///
/// <param name="root">
/// The fully qualified path to the root of a drive. This parameter may be null
/// or empty if a mounted drive is not in use for this operation. If this parameter
/// is not null or empty the result of the method should not be a path to a container
/// that is a parent or in a different tree than the root.
/// </param>
///
/// <param name="context">
/// The context under which this method is being called.
/// </param>
///
/// <returns>
/// The path of the parent of the path parameter.
/// </returns>
///
/// <remarks>
/// This should be a lexical splitting of the path on the path separator character
/// for the provider namespace. For example, the file system provider should look
/// for the last "\" and return everything to the left of the "\".
/// </remarks>
///
internal string GetParentPath(
string path,
string root,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return GetParentPath(path, root);
} // GetParentPath
/// <summary>
/// Internal wrapper for the NormalizeRelativePath method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
///
/// <param name="path">
/// A fully qualified provider specific path to an item. The item should exist
/// or the provider should write out an error.
/// </param>
///
/// <param name="basePath">
/// The path that the return value should be relative to.
/// </param>
///
/// <param name="context">
/// The context under which this method is being called.
/// </param>
///
/// <returns>
/// A normalized path that is relative to the basePath that was passed. The
/// provider should parse the path parameter, normalize the path, and then
/// return the normalized path relative to the basePath.
/// </returns>
///
/// <remarks>
/// This method does not have to be purely syntactical parsing of the path. It
/// is encouraged that the provider actually use the path to lookup in its store
/// and create a relative path that matches the casing, and standardized path syntax.
/// </remarks>
///
internal string NormalizeRelativePath(
string path,
string basePath,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return NormalizeRelativePath(path, basePath);
} // NormalizeRelativePath
/// <summary>
/// Internal wrapper for the GetChildName protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
///
/// <param name="path">
/// The fully qualified path to the item
/// </param>
///
/// <returns>
/// The leaf element in the path.
/// </returns>
///
/// <param name="context">
/// The context under which this method is being called.
/// </param>
///
/// <remarks>
/// This should be implemented as a split on the path separator. The characters
/// in the fullPath may not be legal characters in the namespace but may be
/// used in globing or regular expression matching. The provider should not error
/// unless there are no path separators in the fully qualified path.
/// </remarks>
///
internal string GetChildName(
string path,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return GetChildName(path);
} // GetChildName
/// <summary>
/// Internal wrapper for the IsItemContainer protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
///
/// <param name="path">
/// The path to the item to determine if it is a container.
/// </param>
///
/// <param name="context">
/// The context under which this method is being called.
/// </param>
///
/// <returns>
/// true if the item specified by path is a container, false otherwise.
/// </returns>
///
internal bool IsItemContainer(
string path,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
return IsItemContainer(path);
} // IsItemContainer
/// <summary>
/// Internal wrapper for the MoveItem protected method. It is called instead
/// of the protected method that is overridden by derived classes so that the
/// context of the command can be set.
/// </summary>
///
/// <param name="path">
/// The path to the item to be moved.
/// </param>
///
/// <param name="destination">
/// The path of the destination container.
/// </param>
///
/// <param name="context">
/// The context under which this method is being called.
/// </param>
///
/// <returns>
/// Nothing. All objects that are moved should be written to the WriteObject method.
/// </returns>
///
internal void MoveItem(
string path,
string destination,
CmdletProviderContext context)
{
Context = context;
// Call virtual method
MoveItem(path, destination);
} // MoveItem
/// <summary>
/// Gives the provider to attach additional parameters to
/// the move-item cmdlet.
/// </summary>
///
/// <param name="path">
/// If the path was specified on the command line, this is the path
/// to the item to get the dynamic parameters for.
/// </param>
///
/// <param name="destination">
/// The path of the destination container.
/// </param>
///
/// <param name="context">
/// The context under which this method is being called.
/// </param>
///
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
///
internal object MoveItemDynamicParameters(
string path,
string destination,
CmdletProviderContext context)
{
Context = context;
return MoveItemDynamicParameters(path, destination);
} // MoveItemDynamicParameters
#endregion Internal methods
#region protected methods
/// <summary>
/// Joins two strings with a path a provider specific path separator.
/// </summary>
///
/// <param name="parent">
/// The parent segment of a path to be joined with the child.
/// </param>
///
/// <param name="child">
/// The child segment of a path to be joined with the parent.
/// </param>
///
/// <returns>
/// A string that represents the parent and child segments of the path
/// joined by a path separator.
/// </returns>
///
/// <remarks>
/// This method should use lexical joining of two path segments with a path
/// separator character. It should not validate the path as a legal fully
/// qualified path in the provider namespace as each parameter could be only
/// partial segments of a path and joined they may not generate a fully
/// qualified path.
/// Example: the file system provider may get "windows\system32" as the parent
/// parameter and "foo.dll" as the child parameter. The method should join these
/// with the "\" separator and return "windows\system32\foo.dll". Note that
/// the returned path is not a fully qualified file system path.
///
/// Also beware that the path segments may contain characters that are illegal
/// in the provider namespace. These characters are most likely being used
/// for globbing and should not be removed by the implementation of this method.
/// </remarks>
protected virtual string MakePath(string parent, string child)
{
return MakePath(parent, child, childIsLeaf: false);
} // MakePath
/// <summary>
/// Joins two strings with a path a provider specific path separator.
/// </summary>
///
/// <param name="parent">
/// The parent segment of a path to be joined with the child.
/// </param>
///
/// <param name="child">
/// The child segment of a path to be joined with the parent.
/// </param>
///
/// <param name="childIsLeaf">
/// Indicate that the <paramref name="child"/> is the name of a child item that's guaranteed to exist
/// </param>
///
/// <remarks>
/// If the <paramref name="childIsLeaf"/> is True, then we don't normalize the child path, and would do
/// some checks to decide whether to normalize the parent path.
/// </remarks>
///
/// <returns></returns>
protected string MakePath(string parent, string child, bool childIsLeaf)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
string result = null;
if (parent == null &&
child == null)
{
// If both are null it is an error
throw PSTraceSource.NewArgumentException("parent");
}
else if (String.IsNullOrEmpty(parent) &&
String.IsNullOrEmpty(child))
{
// If both are empty, just return the empty string.
result = String.Empty;
}
else if (String.IsNullOrEmpty(parent) &&
!String.IsNullOrEmpty(child))
{
// If the parent is empty but the child is not, return the
// child
result = child.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);
}
else if (!String.IsNullOrEmpty(parent) &&
String.IsNullOrEmpty(child))
{
// If the child is empty but the parent is not, return the
// parent with the path separator appended.
// Append the default path separator
if (parent.EndsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.Ordinal))
{
result = parent;
}
else
{
result = parent + StringLiterals.DefaultPathSeparator;
}
}
else
{
// Both parts are not empty so join them
// 'childIsLeaf == true' indicates that 'child' is actually the name of a child item and
// guaranteed to exist. In this case, we don't normalize the child path.
if (childIsLeaf)
{
parent = NormalizePath(parent);
}
else
{
// Normalize the path so that only the default path separator is used as a
// separator even if the user types the alternate slash.
parent = parent.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);
child = child.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);
}
// Joins the paths
StringBuilder builder = new StringBuilder(parent, parent.Length + child.Length + 1);
if (parent.EndsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.Ordinal))
{
if (child.StartsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.Ordinal))
{
builder.Append(child, 1, child.Length - 1);
}
else
{
builder.Append(child);
}
}
else
{
if (child.StartsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.CurrentCulture))
{
if (parent.Length == 0)
{
builder.Append(child, 1, child.Length - 1);
}
else
{
builder.Append(child);
}
}
else
{
if (parent.Length > 0 && child.Length > 0)
{
builder.Append(StringLiterals.DefaultPathSeparator);
}
builder.Append(child);
}
}
result = builder.ToString();
}
return result;
}
}
/// <summary>
/// Removes the child segment of a path and returns the remaining parent
/// portion.
/// </summary>
///
/// <param name="path">
/// A fully qualified provider specific path to an item. The item may or
/// may not exist.
/// </param>
///
/// <param name="root">
/// The fully qualified path to the root of a drive. This parameter may be null
/// or empty if a mounted drive is not in use for this operation. If this parameter
/// is not null or empty the result of the method should not be a path to a container
/// that is a parent or in a different tree than the root.
/// </param>
///
/// <returns>
/// The path of the parent of the path parameter.
/// </returns>
///
/// <remarks>
/// This should be a lexical splitting of the path on the path separator character
/// for the provider namespace. For example, the file system provider should look
/// for the last "\" and return everything to the left of the "\".
/// </remarks>
protected virtual string GetParentPath(string path, string root)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
string parentPath = null;
// Verify the parameters
if (String.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentException("path");
}
if (root == null)
{
if (PSDriveInfo != null)
{
root = PSDriveInfo.Root;
}
}
// Normalize the path
path = NormalizePath(path);
path = path.TrimEnd(StringLiterals.DefaultPathSeparator);
string rootPath = String.Empty;
if (root != null)
{
rootPath = NormalizePath(root);
}
// Check to see if the path is equal to the root
// of the virtual drive
if (String.Compare(
path,
rootPath,
StringComparison.OrdinalIgnoreCase) == 0)
{
parentPath = String.Empty;
}
else
{
int lastIndex = path.LastIndexOf(StringLiterals.DefaultPathSeparator);
if (lastIndex != -1)
{
if (lastIndex == 0)
{
++lastIndex;
}
// Get the parent directory
parentPath = path.Substring(0, lastIndex);
}
else
{
parentPath = String.Empty;
}
}
return parentPath;
}
} // GetParentPath
/// <summary>
/// Normalizes the path that was passed in and returns the normalized path
/// as a relative path to the basePath that was passed.
/// </summary>
///
/// <param name="path">
/// A fully qualified provider specific path to an item. The item should exist
/// or the provider should write out an error.
/// </param>
///
/// <param name="basePath">
/// The path that the return value should be relative to.
/// </param>
///
/// <returns>
/// A normalized path that is relative to the basePath that was passed. The
/// provider should parse the path parameter, normalize the path, and then
/// return the normalized path relative to the basePath.
/// </returns>
///
/// <remarks>
/// This method does not have to be purely syntactical parsing of the path. It
/// is encouraged that the provider actually use the path to lookup in its store
/// and create a relative path that matches the casing, and standardized path syntax.
///
/// Note, the base class implementation uses GetParentPath, GetChildName, and MakePath
/// to normalize the path and then make it relative to basePath. All string comparisons
/// are done using StringComparison.InvariantCultureIgnoreCase.
/// </remarks>
protected virtual string NormalizeRelativePath(
string path,
string basePath)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return ContractRelativePath(path, basePath, false, Context);
}
} // NormalizeRelativePath
internal string ContractRelativePath(
string path,
string basePath,
bool allowNonExistingPaths,
CmdletProviderContext context)
{
Context = context;
if (path == null)
{
throw PSTraceSource.NewArgumentNullException("path");
}
if (path.Length == 0)
{
return String.Empty;
}
if (basePath == null)
{
basePath = String.Empty;
}
providerBaseTracer.WriteLine("basePath = {0}", basePath);
string result = path;
bool originalPathHadTrailingSlash = false;
string normalizedPath = path;
string normalizedBasePath = basePath;
// NTRAID#Windows 7-697922-2009/06/29-leeholm
// WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND
//
// This path normalization got moved here from the MakePath override in V2 to prevent
// over-normalization of paths. This was a net-improvement for providers that use the default
// implementations, but now incorrectly replaces forward slashes with back slashes during the call to
// GetParentPath and GetChildName. This breaks providers that are sensitive to slash direction, the only
// one we are aware of being the Active Directory provider. This change prevents this over-normalization
// from being done on AD paths.
//
// For more information, see Win7:695292. Do not change this code without closely working with the
// Active Directory team.
//
// WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND
if (!String.Equals(context.ProviderInstance.ProviderInfo.FullName,
@"Microsoft.ActiveDirectory.Management\ActiveDirectory", StringComparison.OrdinalIgnoreCase))
{
normalizedPath = NormalizePath(path);
normalizedBasePath = NormalizePath(basePath);
}
do // false loop
{
// Convert to the correct path separators and trim trailing separators
string originalPath = path;
Stack<string> tokenizedPathStack = null;
if (path.EndsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.OrdinalIgnoreCase))
{
path = path.TrimEnd(StringLiterals.DefaultPathSeparator);
originalPathHadTrailingSlash = true;
}
basePath = basePath.TrimEnd(StringLiterals.DefaultPathSeparator);
// See if the base and the path are already the same. We resolve this to
// ..\Leaf, since resolving "." to "." doesn't offer much information.
if (String.Equals(normalizedPath, normalizedBasePath, StringComparison.OrdinalIgnoreCase) &&
(!originalPath.EndsWith("" + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase)))
{
string childName = GetChildName(path);
result = MakePath("..", childName);
break;
}
// If the base path isn't really a base, then we resolve to a parent
// path (such as ../../foo)
if (!normalizedPath.StartsWith(normalizedBasePath, StringComparison.OrdinalIgnoreCase) &&
(basePath.Length > 0))
{
result = String.Empty;
string commonBase = GetCommonBase(normalizedPath, normalizedBasePath);
Stack<string> parentNavigationStack = TokenizePathToStack(normalizedBasePath, commonBase);
int parentPopCount = parentNavigationStack.Count;
if (String.IsNullOrEmpty(commonBase))
{
parentPopCount--;
}
for (int leafCounter = 0; leafCounter < parentPopCount; leafCounter++)
{
result = MakePath("..", result);
}
// This is true if we get passed a base path like:
// c:\directory1\directory2
// and an actual path of
// c:\directory1
// Which happens when the user is in c:\directory1\directory2
// and wants to resolve something like:
// ..\..\dir*
// In that case (as above,) we keep the ..\..\directory1
// instead of ".." as would usually be returned
if (!String.IsNullOrEmpty(commonBase))
{
if (String.Equals(normalizedPath, commonBase, StringComparison.OrdinalIgnoreCase) &&
(!normalizedPath.EndsWith("" + StringLiterals.DefaultPathSeparator, StringComparison.OrdinalIgnoreCase)))
{
string childName = GetChildName(path);
result = MakePath("..", result);
result = MakePath(result, childName);
}
else
{
string[] childNavigationItems = TokenizePathToStack(normalizedPath, commonBase).ToArray();
for (int leafCounter = 0; leafCounter < childNavigationItems.Length; leafCounter++)
{
result = MakePath(result, childNavigationItems[leafCounter]);
}
}
}
}
// Otherwise, we resolve to a child path (such as foo/bar)
else
{
tokenizedPathStack = TokenizePathToStack(path, basePath);
// Now we have to normalize the path
// by processing each token on the stack
Stack<string> normalizedPathStack;
try
{
normalizedPathStack = NormalizeThePath(tokenizedPathStack, path, basePath, allowNonExistingPaths);
}
catch (ArgumentException argumentException)
{
WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.InvalidArgument, null));
result = null;
break;
}
// Now that the path has been normalized, create the relative path
result = CreateNormalizedRelativePathFromStack(normalizedPathStack);
}
} while (false);
if (originalPathHadTrailingSlash)
{
result = result + StringLiterals.DefaultPathSeparator;
}
return result;
} // ContractRelativePath
/// <summary>
/// Get the common base path of two paths
/// </summary>
/// <param name="path1">One path</param>
/// <param name="path2">Another path</param>
private string GetCommonBase(string path1, string path2)
{
// Always see if the shorter path is a substring of the
// longer path. If it is not, take the child off of the longer
// path and compare again.
while (!String.Equals(path1, path2, StringComparison.OrdinalIgnoreCase))
{
if (path2.Length > path1.Length)
{
path2 = GetParentPath(path2, null);
}
else
{
path1 = GetParentPath(path1, null);
}
}
return path1;
}
/// <summary>
/// Gets the name of the leaf element in the specified path.
/// </summary>
///
/// <param name="path">
/// The fully qualified path to the item
/// </param>
///
/// <returns>
/// The leaf element in the path.
/// </returns>
///
/// <remarks>
/// This should be implemented as a split on the path separator. The characters
/// in the fullPath may not be legal characters in the namespace but may be
/// used in globing or regular expression matching. The provider should not error
/// unless there are no path separators in the fully qualified path.
/// </remarks>
protected virtual string GetChildName(string path)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
// Verify the parameters
if (String.IsNullOrEmpty(path))
{
throw PSTraceSource.NewArgumentException("path");
}
// Normalize the path
path = NormalizePath(path);
// Trim trailing back slashes
path = path.TrimEnd(StringLiterals.DefaultPathSeparator);
string result = null;
int separatorIndex = path.LastIndexOf(StringLiterals.DefaultPathSeparator);
// Since there was no path separator return the entire path
if (separatorIndex == -1)
{
result = path;
}
// If the full path existed, we must semantically evaluate the parent path
else if (ItemExists(path, Context))
{
string parentPath = GetParentPath(path, null);
// No parent, return the entire path
if (String.IsNullOrEmpty(parentPath))
result = path;
// If the parent path ends with the path separator, we can't split
// the path based on that
else if (parentPath.IndexOf(StringLiterals.DefaultPathSeparator) == (parentPath.Length - 1))
{
separatorIndex = path.IndexOf(parentPath, StringComparison.OrdinalIgnoreCase) + parentPath.Length;
result = path.Substring(separatorIndex);
}
else
{
separatorIndex = path.IndexOf(parentPath, StringComparison.OrdinalIgnoreCase) + parentPath.Length;
result = path.Substring(separatorIndex + 1);
}
}
// Otherwise, use lexical parsing
else
{
result = path.Substring(separatorIndex + 1);
}
return result;
}
} // GetChildName
/// <summary>
/// Determines if the item specified by the path is a container.
/// </summary>
///
/// <param name="path">
/// The path to the item to determine if it is a container.
/// </param>
///
/// <returns>
/// true if the item specified by path is a container, false otherwise.
/// </returns>
///
/// <remarks>
/// Providers override this method to give the user the ability to check
/// to see if a provider object is a container using the test-path -container cmdlet.
///
/// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/>
/// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path passed meets those
/// requirements by accessing the appropriate property from the base class.
///
/// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>.
/// </remarks>
protected virtual bool IsItemContainer(string path)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
throw
PSTraceSource.NewNotSupportedException(
SessionStateStrings.CmdletProvider_NotSupported);
}
}
/// <summary>
/// Moves the item specified by path to the specified destination.
/// </summary>
///
/// <param name="path">
/// The path to the item to be moved.
/// </param>
///
/// <param name="destination">
/// The path of the destination container.
/// </param>
///
/// <returns>
/// Nothing is returned, but all the objects that were moved should be written to the WriteItemObject method.
/// </returns>
///
/// <remarks>
/// Providers override this method to give the user the ability to move provider objects using
/// the move-item cmdlet.
///
/// Providers that declare <see cref="System.Management.Automation.Provider.ProviderCapabilities"/>
/// of ExpandWildcards, Filter, Include, or Exclude should ensure that the path and items being moved
/// meets those requirements by accessing the appropriate property from the base class.
///
/// By default overrides of this method should not move objects over existing items unless the Force
/// property is set to true. For instance, the FileSystem provider should not move c:\temp\foo.txt over
/// c:\bar.txt if c:\bar.txt already exists unless the Force parameter is true.
///
/// If <paramref name="destination"/> exists and is a container then Force isn't required and <paramref name="path"/>
/// should be moved into the <paramref name="destination"/> container as a child.
///
/// The default implementation of this method throws an <see cref="System.Management.Automation.PSNotSupportedException"/>.
/// </remarks>
protected virtual void MoveItem(
string path,
string destination)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
throw
PSTraceSource.NewNotSupportedException(
SessionStateStrings.CmdletProvider_NotSupported);
}
}
/// <summary>
/// Gives the provider an opportunity to attach additional parameters to
/// the move-item cmdlet.
/// </summary>
///
/// <param name="path">
/// If the path was specified on the command line, this is the path
/// to the item to get the dynamic parameters for.
/// </param>
///
/// <param name="destination">
/// The path of the destination container.
/// </param>
///
/// <returns>
/// Overrides of this method should return an object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class or a
/// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>.
///
/// The default implementation returns null. (no additional parameters)
/// </returns>
protected virtual object MoveItemDynamicParameters(
string path,
string destination)
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return null;
}
} // MoveItemDynamicParameters
#endregion Protected methods
#region private members
/// <summary>
/// When a path contains both forward slash and backslash, we may introduce some errors by
/// normalizing the path. This method does some smart checks to reduce the chances of making
/// those errors.
/// </summary>
///
/// <param name="path">
/// The path to normalize
/// </param>
///
/// <returns>
/// Normalized path or the original path
/// </returns>
private string NormalizePath(string path)
{
// If we have a mix of slashes, then we may introduce an error by normalizing the path.
// For example: path HKCU:\Test\/ is pointing to a subkey '/' of 'HKCU:\Test', if we
// normalize it, then we will get a wrong path.
bool pathHasForwardSlash = path.IndexOf(StringLiterals.AlternatePathSeparator) != -1;
bool pathHasBackSlash = path.IndexOf(StringLiterals.DefaultPathSeparator) != -1;
bool pathHasMixedSlashes = pathHasForwardSlash && pathHasBackSlash;
bool shouldNormalizePath = true;
string normalizedPath = path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator);
// There is a mix of slashes & the path is rooted & the path exists without normalization.
// In this case, we might want to skip the normalization to the path.
if (pathHasMixedSlashes && IsAbsolutePath(path) && ItemExists(path))
{
// 1. The path exists and ends with a forward slash, in this case, it's very possible the ending forward slash
// make sense to the underlying provider, so we skip normalization
// 2. The path exists, but not anymore after normalization, then we skip normalization
bool parentEndsWithForwardSlash = path.EndsWith(StringLiterals.AlternatePathSeparatorString, StringComparison.Ordinal);
if (parentEndsWithForwardSlash || !ItemExists(normalizedPath))
{
shouldNormalizePath = false;
}
}
return shouldNormalizePath ? normalizedPath : path;
}
/// <summary>
/// Test if the path is an absolute path
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private bool IsAbsolutePath(string path)
{
bool result = false;
if (LocationGlobber.IsAbsolutePath(path))
{
result = true;
}
else if (this.PSDriveInfo != null && !String.IsNullOrEmpty(this.PSDriveInfo.Root) &&
path.StartsWith(this.PSDriveInfo.Root, StringComparison.OrdinalIgnoreCase))
{
result = true;
}
return result;
}
/// <summary>
/// Tokenizes the specified path onto a stack
/// </summary>
///
/// <param name="path">
/// The path to tokenize.
/// </param>
///
/// <param name="basePath">
/// The base part of the path that should not be tokenized.
/// </param>
///
/// <returns>
/// A stack containing the tokenized path with leaf elements on the bottom
/// of the stack and the most ancestral parent at the top.
/// </returns>
///
private Stack<string> TokenizePathToStack(string path, string basePath)
{
Stack<string> tokenizedPathStack = new Stack<string>();
string tempPath = path;
string previousParent = path;
while (tempPath.Length > basePath.Length)
{
// Get the child name and push it onto the stack
// if its valid
string childName = GetChildName(tempPath);
if (String.IsNullOrEmpty(childName))
{
// Push the parent on and then stop
tokenizedPathStack.Push(tempPath);
break;
}
providerBaseTracer.WriteLine("tokenizedPathStack.Push({0})", childName);
tokenizedPathStack.Push(childName);
// Get the parent path and verify if we have to continue
// tokenizing
tempPath = GetParentPath(tempPath, basePath);
if (tempPath.Length >= previousParent.Length)
{
break;
}
previousParent = tempPath;
}
return tokenizedPathStack;
} // TokenizePathToStack
/// <summary>
/// Given the tokenized path, the relative path elements are removed.
/// </summary>
///
/// <param name="tokenizedPathStack">
/// A stack containing path elements where the leaf most element is at
/// the bottom of the stack and the most ancestral parent is on the top.
/// Generally this stack comes from TokenizePathToStack().
/// </param>
///
/// <param name="path">
/// The path being normalized. Just used for error reporting.
/// </param>
///
/// <param name="basePath">
/// The base path to make the path relative to. Just used for error reporting.
/// </param>
///
/// <param name="allowNonExistingPaths">
/// Determines whether to throw an exception on non-existing paths.
/// </param>
///
/// <returns>
/// A stack in reverse order with the path elements normalized and all relative
/// path tokens removed.
/// </returns>
///
private static Stack<string> NormalizeThePath(
Stack<string> tokenizedPathStack, string path,
string basePath, bool allowNonExistingPaths)
{
Stack<string> normalizedPathStack = new Stack<string>();
while (tokenizedPathStack.Count > 0)
{
string childName = tokenizedPathStack.Pop();
providerBaseTracer.WriteLine("childName = {0}", childName);
// Ignore the current directory token
if (childName.Equals(".", StringComparison.OrdinalIgnoreCase))
{
// Just ignore it and move on.
continue;
}
// Make sure we don't have
if (childName.Equals("..", StringComparison.OrdinalIgnoreCase))
{
if (normalizedPathStack.Count > 0)
{
// Pop the result and continue processing
string poppedName = normalizedPathStack.Pop();
providerBaseTracer.WriteLine("normalizedPathStack.Pop() : {0}", poppedName);
continue;
}
else
{
if (!allowNonExistingPaths)
{
PSArgumentException e =
(PSArgumentException)
PSTraceSource.NewArgumentException(
"path",
SessionStateStrings.NormalizeRelativePathOutsideBase,
path,
basePath);
throw e;
}
}
}
providerBaseTracer.WriteLine("normalizedPathStack.Push({0})", childName);
normalizedPathStack.Push(childName);
}
return normalizedPathStack;
} // NormalizeThePath
/// <summary>
/// Pops each leaf element of the stack and uses MakePath to generate the relative path
/// </summary>
///
/// <param name="normalizedPathStack">
/// The stack containing the leaf elements of the path.
/// </param>
///
/// <returns>
/// A path that is made up of the leaf elements on the given stack.
/// </returns>
///
/// <remarks>
/// The elements on the stack start from the leaf element followed by its parent
/// followed by its parent, etc. Each following element on the stack is the parent
/// of the one before it.
/// </remarks>
///
private string CreateNormalizedRelativePathFromStack(Stack<string> normalizedPathStack)
{
string leafElement = String.Empty;
while (normalizedPathStack.Count > 0)
{
if (String.IsNullOrEmpty(leafElement))
{
leafElement = normalizedPathStack.Pop();
}
else
{
string parentElement = normalizedPathStack.Pop();
leafElement = MakePath(parentElement, leafElement);
}
}
return leafElement;
} // CreateNormalizedRelativePathFromStack
#endregion private members
} // NavigationCmdletProvider
#endregion NavigationCmdletProvider
} // namespace System.Management.Automation
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
using Resources = Microsoft.AspNetCore.Mvc.Core.Resources;
namespace Microsoft.AspNetCore.Mvc.Infrastructure
{
internal class ControllerActionInvoker : ResourceInvoker, IActionInvoker
{
private readonly ControllerActionInvokerCacheEntry _cacheEntry;
private readonly ControllerContext _controllerContext;
private Dictionary<string, object?>? _arguments;
private ActionExecutingContextSealed? _actionExecutingContext;
private ActionExecutedContextSealed? _actionExecutedContext;
internal ControllerActionInvoker(
ILogger logger,
DiagnosticListener diagnosticListener,
IActionContextAccessor actionContextAccessor,
IActionResultTypeMapper mapper,
ControllerContext controllerContext,
ControllerActionInvokerCacheEntry cacheEntry,
IFilterMetadata[] filters)
: base(diagnosticListener, logger, actionContextAccessor, mapper, controllerContext, filters, controllerContext.ValueProviderFactories)
{
if (cacheEntry == null)
{
throw new ArgumentNullException(nameof(cacheEntry));
}
_cacheEntry = cacheEntry;
_controllerContext = controllerContext;
}
// Internal for testing
internal ControllerContext ControllerContext => _controllerContext;
protected override ValueTask ReleaseResources()
{
if (_instance != null && _cacheEntry.ControllerReleaser != null)
{
return _cacheEntry.ControllerReleaser(_controllerContext, _instance);
}
return default;
}
private Task Next(ref State next, ref Scope scope, ref object? state, ref bool isCompleted)
{
switch (next)
{
case State.ActionBegin:
{
var controllerContext = _controllerContext;
_cursor.Reset();
_logger.ExecutingControllerFactory(controllerContext);
_instance = _cacheEntry.ControllerFactory(controllerContext);
_logger.ExecutedControllerFactory(controllerContext);
_arguments = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
var task = BindArgumentsAsync();
if (task.Status != TaskStatus.RanToCompletion)
{
next = State.ActionNext;
return task;
}
goto case State.ActionNext;
}
case State.ActionNext:
{
var current = _cursor.GetNextFilter<IActionFilter, IAsyncActionFilter>();
if (current.FilterAsync != null)
{
if (_actionExecutingContext == null)
{
_actionExecutingContext = new ActionExecutingContextSealed(_controllerContext, _filters, _arguments!, _instance!);
}
state = current.FilterAsync;
goto case State.ActionAsyncBegin;
}
else if (current.Filter != null)
{
if (_actionExecutingContext == null)
{
_actionExecutingContext = new ActionExecutingContextSealed(_controllerContext, _filters, _arguments!, _instance!);
}
state = current.Filter;
goto case State.ActionSyncBegin;
}
else
{
goto case State.ActionInside;
}
}
case State.ActionAsyncBegin:
{
Debug.Assert(state != null);
Debug.Assert(_actionExecutingContext != null);
var filter = (IAsyncActionFilter)state;
var actionExecutingContext = _actionExecutingContext;
_diagnosticListener.BeforeOnActionExecution(actionExecutingContext, filter);
_logger.BeforeExecutingMethodOnFilter(
MvcCoreLoggerExtensions.ActionFilter,
nameof(IAsyncActionFilter.OnActionExecutionAsync),
filter);
var task = filter.OnActionExecutionAsync(actionExecutingContext, InvokeNextActionFilterAwaitedAsync);
if (task.Status != TaskStatus.RanToCompletion)
{
next = State.ActionAsyncEnd;
return task;
}
goto case State.ActionAsyncEnd;
}
case State.ActionAsyncEnd:
{
Debug.Assert(state != null);
Debug.Assert(_actionExecutingContext != null);
var filter = (IAsyncActionFilter)state;
if (_actionExecutedContext == null)
{
// If we get here then the filter didn't call 'next' indicating a short circuit.
_logger.ActionFilterShortCircuited(filter);
_actionExecutedContext = new ActionExecutedContextSealed(
_controllerContext,
_filters,
_instance!)
{
Canceled = true,
Result = _actionExecutingContext.Result,
};
}
_diagnosticListener.AfterOnActionExecution(_actionExecutedContext, filter);
_logger.AfterExecutingMethodOnFilter(
MvcCoreLoggerExtensions.ActionFilter,
nameof(IAsyncActionFilter.OnActionExecutionAsync),
filter);
goto case State.ActionEnd;
}
case State.ActionSyncBegin:
{
Debug.Assert(state != null);
Debug.Assert(_actionExecutingContext != null);
var filter = (IActionFilter)state;
var actionExecutingContext = _actionExecutingContext;
_diagnosticListener.BeforeOnActionExecuting(actionExecutingContext, filter);
_logger.BeforeExecutingMethodOnFilter(
MvcCoreLoggerExtensions.ActionFilter,
nameof(IActionFilter.OnActionExecuting),
filter);
filter.OnActionExecuting(actionExecutingContext);
_diagnosticListener.AfterOnActionExecuting(actionExecutingContext, filter);
_logger.AfterExecutingMethodOnFilter(
MvcCoreLoggerExtensions.ActionFilter,
nameof(IActionFilter.OnActionExecuting),
filter);
if (actionExecutingContext.Result != null)
{
// Short-circuited by setting a result.
_logger.ActionFilterShortCircuited(filter);
_actionExecutedContext = new ActionExecutedContextSealed(
_actionExecutingContext,
_filters,
_instance!)
{
Canceled = true,
Result = _actionExecutingContext.Result,
};
goto case State.ActionEnd;
}
var task = InvokeNextActionFilterAsync();
if (task.Status != TaskStatus.RanToCompletion)
{
next = State.ActionSyncEnd;
return task;
}
goto case State.ActionSyncEnd;
}
case State.ActionSyncEnd:
{
Debug.Assert(state != null);
Debug.Assert(_actionExecutingContext != null);
Debug.Assert(_actionExecutedContext != null);
var filter = (IActionFilter)state;
var actionExecutedContext = _actionExecutedContext;
_diagnosticListener.BeforeOnActionExecuted(actionExecutedContext, filter);
_logger.BeforeExecutingMethodOnFilter(
MvcCoreLoggerExtensions.ActionFilter,
nameof(IActionFilter.OnActionExecuted),
filter);
filter.OnActionExecuted(actionExecutedContext);
_diagnosticListener.AfterOnActionExecuted(actionExecutedContext, filter);
_logger.AfterExecutingMethodOnFilter(
MvcCoreLoggerExtensions.ActionFilter,
nameof(IActionFilter.OnActionExecuted),
filter);
goto case State.ActionEnd;
}
case State.ActionInside:
{
var task = InvokeActionMethodAsync();
if (task.Status != TaskStatus.RanToCompletion)
{
next = State.ActionEnd;
return task;
}
goto case State.ActionEnd;
}
case State.ActionEnd:
{
if (scope == Scope.Action)
{
if (_actionExecutedContext == null)
{
_actionExecutedContext = new ActionExecutedContextSealed(_controllerContext, _filters, _instance!)
{
Result = _result,
};
}
isCompleted = true;
return Task.CompletedTask;
}
var actionExecutedContext = _actionExecutedContext;
Rethrow(actionExecutedContext);
if (actionExecutedContext != null)
{
_result = actionExecutedContext.Result;
}
isCompleted = true;
return Task.CompletedTask;
}
default:
throw new InvalidOperationException();
}
}
private Task InvokeNextActionFilterAsync()
{
try
{
var next = State.ActionNext;
var state = (object?)null;
var scope = Scope.Action;
var isCompleted = false;
while (!isCompleted)
{
var lastTask = Next(ref next, ref scope, ref state, ref isCompleted);
if (!lastTask.IsCompletedSuccessfully)
{
return Awaited(this, lastTask, next, scope, state, isCompleted);
}
}
}
catch (Exception exception)
{
_actionExecutedContext = new ActionExecutedContextSealed(_controllerContext, _filters, _instance!)
{
ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception),
};
}
Debug.Assert(_actionExecutedContext != null);
return Task.CompletedTask;
static async Task Awaited(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object? state, bool isCompleted)
{
try
{
await lastTask;
while (!isCompleted)
{
await invoker.Next(ref next, ref scope, ref state, ref isCompleted);
}
}
catch (Exception exception)
{
invoker._actionExecutedContext = new ActionExecutedContextSealed(invoker._controllerContext, invoker._filters, invoker._instance!)
{
ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception),
};
}
Debug.Assert(invoker._actionExecutedContext != null);
}
}
private Task<ActionExecutedContext> InvokeNextActionFilterAwaitedAsync()
{
Debug.Assert(_actionExecutingContext != null);
if (_actionExecutingContext.Result != null)
{
// If we get here, it means that an async filter set a result AND called next(). This is forbidden.
return Throw();
}
var task = InvokeNextActionFilterAsync();
if (!task.IsCompletedSuccessfully)
{
return Awaited(this, task);
}
Debug.Assert(_actionExecutedContext != null);
return Task.FromResult<ActionExecutedContext>(_actionExecutedContext);
static async Task<ActionExecutedContext> Awaited(ControllerActionInvoker invoker, Task task)
{
await task;
Debug.Assert(invoker._actionExecutedContext != null);
return invoker._actionExecutedContext;
}
#pragma warning disable CS1998
static async Task<ActionExecutedContext> Throw()
{
var message = Resources.FormatAsyncActionFilter_InvalidShortCircuit(
typeof(IAsyncActionFilter).Name,
nameof(ActionExecutingContext.Result),
typeof(ActionExecutingContext).Name,
typeof(ActionExecutionDelegate).Name);
throw new InvalidOperationException(message);
}
#pragma warning restore CS1998
}
private Task InvokeActionMethodAsync()
{
if (_diagnosticListener.IsEnabled() || _logger.IsEnabled(LogLevel.Trace))
{
return Logged(this);
}
var objectMethodExecutor = _cacheEntry.ObjectMethodExecutor;
var actionMethodExecutor = _cacheEntry.ActionMethodExecutor;
var orderedArguments = PrepareArguments(_arguments, objectMethodExecutor);
var actionResultValueTask = actionMethodExecutor.Execute(_mapper, objectMethodExecutor, _instance!, orderedArguments);
if (actionResultValueTask.IsCompletedSuccessfully)
{
_result = actionResultValueTask.Result;
}
else
{
return Awaited(this, actionResultValueTask);
}
return Task.CompletedTask;
static async Task Awaited(ControllerActionInvoker invoker, ValueTask<IActionResult> actionResultValueTask)
{
invoker._result = await actionResultValueTask;
}
static async Task Logged(ControllerActionInvoker invoker)
{
var controllerContext = invoker._controllerContext;
var objectMethodExecutor = invoker._cacheEntry.ObjectMethodExecutor;
var controller = invoker._instance;
var arguments = invoker._arguments;
var actionMethodExecutor = invoker._cacheEntry.ActionMethodExecutor;
var orderedArguments = PrepareArguments(arguments, objectMethodExecutor);
var diagnosticListener = invoker._diagnosticListener;
var logger = invoker._logger;
IActionResult? result = null;
try
{
diagnosticListener.BeforeControllerActionMethod(
controllerContext,
arguments,
controller);
logger.ActionMethodExecuting(controllerContext, orderedArguments);
var stopwatch = ValueStopwatch.StartNew();
var actionResultValueTask = actionMethodExecutor.Execute(invoker._mapper, objectMethodExecutor, controller!, orderedArguments);
if (actionResultValueTask.IsCompletedSuccessfully)
{
result = actionResultValueTask.Result;
}
else
{
result = await actionResultValueTask;
}
invoker._result = result;
logger.ActionMethodExecuted(controllerContext, result, stopwatch.GetElapsedTime());
}
finally
{
diagnosticListener.AfterControllerActionMethod(
controllerContext,
arguments,
controllerContext,
result);
}
}
}
/// <remarks><see cref="ResourceInvoker.InvokeFilterPipelineAsync"/> for details on what the
/// variables in this method represent.</remarks>
protected override Task InvokeInnerFilterAsync()
{
try
{
var next = State.ActionBegin;
var scope = Scope.Invoker;
var state = (object?)null;
var isCompleted = false;
while (!isCompleted)
{
var lastTask = Next(ref next, ref scope, ref state, ref isCompleted);
if (!lastTask.IsCompletedSuccessfully)
{
return Awaited(this, lastTask, next, scope, state, isCompleted);
}
}
return Task.CompletedTask;
}
catch (Exception ex)
{
// Wrap non task-wrapped exceptions in a Task,
// as this isn't done automatically since the method is not async.
return Task.FromException(ex);
}
static async Task Awaited(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object? state, bool isCompleted)
{
await lastTask;
while (!isCompleted)
{
await invoker.Next(ref next, ref scope, ref state, ref isCompleted);
}
}
}
private static void Rethrow(ActionExecutedContextSealed? context)
{
if (context == null)
{
return;
}
if (context.ExceptionHandled)
{
return;
}
if (context.ExceptionDispatchInfo != null)
{
context.ExceptionDispatchInfo.Throw();
}
if (context.Exception != null)
{
throw context.Exception;
}
}
private Task BindArgumentsAsync()
{
// Perf: Avoid allocating async state machines where possible. We only need the state
// machine if you need to bind properties or arguments.
var actionDescriptor = _controllerContext.ActionDescriptor;
if (actionDescriptor.BoundProperties.Count == 0 &&
actionDescriptor.Parameters.Count == 0)
{
return Task.CompletedTask;
}
Debug.Assert(_cacheEntry.ControllerBinderDelegate != null);
return _cacheEntry.ControllerBinderDelegate(_controllerContext, _instance!, _arguments!);
}
private static object?[]? PrepareArguments(
IDictionary<string, object?>? actionParameters,
ObjectMethodExecutor actionMethodExecutor)
{
var declaredParameterInfos = actionMethodExecutor.MethodParameters;
var count = declaredParameterInfos.Length;
if (count == 0)
{
return null;
}
Debug.Assert(actionParameters != null, "Expect arguments to be initialized.");
var arguments = new object?[count];
for (var index = 0; index < count; index++)
{
var parameterInfo = declaredParameterInfos[index];
if (!actionParameters.TryGetValue(parameterInfo.Name!, out var value))
{
value = actionMethodExecutor.GetDefaultValueForParameter(index);
}
arguments[index] = value;
}
return arguments;
}
private enum Scope
{
Invoker,
Action,
}
private enum State
{
ActionBegin,
ActionNext,
ActionAsyncBegin,
ActionAsyncEnd,
ActionSyncBegin,
ActionSyncEnd,
ActionInside,
ActionEnd,
}
private sealed class ActionExecutingContextSealed : ActionExecutingContext
{
public ActionExecutingContextSealed(ActionContext actionContext, IList<IFilterMetadata> filters, IDictionary<string, object?> actionArguments, object controller) : base(actionContext, filters, actionArguments, controller) { }
}
private sealed class ActionExecutedContextSealed : ActionExecutedContext
{
public ActionExecutedContextSealed(ActionContext actionContext, IList<IFilterMetadata> filters, object controller) : base(actionContext, filters, controller) { }
}
}
}
| |
namespace KabMan.Client
{
partial class frmServerDetailCreate
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmServerDetailCreate));
this.barManager1 = new DevExpress.XtraBars.BarManager(this.components);
this.bar1 = new DevExpress.XtraBars.Bar();
this.btnSpeichern = new DevExpress.XtraBars.BarButtonItem();
this.btnSchliessen = new DevExpress.XtraBars.BarButtonItem();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.btnListeLoeschen = new DevExpress.XtraEditors.SimpleButton();
this.btnErstellen = new DevExpress.XtraEditors.SimpleButton();
this.txtVTPort = new DevExpress.XtraEditors.TextEdit();
this.txtKabelTrunkMulti = new DevExpress.XtraEditors.TextEdit();
this.txtBlechPosition = new DevExpress.XtraEditors.TextEdit();
this.txtKabelURMLC = new DevExpress.XtraEditors.TextEdit();
this.gridControl1 = new DevExpress.XtraGrid.GridControl();
this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView();
this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn4 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn5 = new DevExpress.XtraGrid.Columns.GridColumn();
this.lkpSAN = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
this.gridView2 = new DevExpress.XtraGrid.Views.Grid.GridView();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem6 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem7 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlGroup2 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem3 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem4 = new DevExpress.XtraLayout.LayoutControlItem();
this.layoutControlItem5 = new DevExpress.XtraLayout.LayoutControlItem();
this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.txtVTPort.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtKabelTrunkMulti.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtBlechPosition.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtKabelURMLC.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.lkpSAN)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.gridView2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit();
this.SuspendLayout();
//
// barManager1
//
this.barManager1.AllowCustomization = false;
this.barManager1.AllowQuickCustomization = false;
this.barManager1.AllowShowToolbarsPopup = false;
this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.bar1});
this.barManager1.DockControls.Add(this.barDockControlTop);
this.barManager1.DockControls.Add(this.barDockControlBottom);
this.barManager1.DockControls.Add(this.barDockControlLeft);
this.barManager1.DockControls.Add(this.barDockControlRight);
this.barManager1.Form = this;
this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.btnSchliessen,
this.btnSpeichern});
this.barManager1.MaxItemId = 2;
//
// bar1
//
this.bar1.BarName = "Tools";
this.bar1.DockCol = 0;
this.bar1.DockRow = 0;
this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.btnSpeichern, true),
new DevExpress.XtraBars.LinkPersistInfo(this.btnSchliessen, true)});
this.bar1.OptionsBar.AllowQuickCustomization = false;
this.bar1.OptionsBar.DrawDragBorder = false;
this.bar1.OptionsBar.UseWholeRow = true;
resources.ApplyResources(this.bar1, "bar1");
//
// btnSpeichern
//
resources.ApplyResources(this.btnSpeichern, "btnSpeichern");
this.btnSpeichern.Id = 1;
this.btnSpeichern.Name = "btnSpeichern";
this.btnSpeichern.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnSpeichern_ItemClick);
//
// btnSchliessen
//
resources.ApplyResources(this.btnSchliessen, "btnSchliessen");
this.btnSchliessen.Glyph = global::KabMan.Client.Properties.Resources.exit;
this.btnSchliessen.Id = 0;
this.btnSchliessen.Name = "btnSchliessen";
this.btnSchliessen.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.btnSchliessen_ItemClick);
//
// layoutControl1
//
this.layoutControl1.AllowCustomizationMenu = false;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.btnListeLoeschen);
this.layoutControl1.Controls.Add(this.btnErstellen);
this.layoutControl1.Controls.Add(this.txtVTPort);
this.layoutControl1.Controls.Add(this.txtKabelTrunkMulti);
this.layoutControl1.Controls.Add(this.txtBlechPosition);
this.layoutControl1.Controls.Add(this.txtKabelURMLC);
this.layoutControl1.Controls.Add(this.gridControl1);
resources.ApplyResources(this.layoutControl1, "layoutControl1");
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
//
// btnListeLoeschen
//
resources.ApplyResources(this.btnListeLoeschen, "btnListeLoeschen");
this.btnListeLoeschen.Name = "btnListeLoeschen";
this.btnListeLoeschen.StyleController = this.layoutControl1;
this.btnListeLoeschen.Click += new System.EventHandler(this.btnListeLoeschen_Click);
//
// btnErstellen
//
resources.ApplyResources(this.btnErstellen, "btnErstellen");
this.btnErstellen.Name = "btnErstellen";
this.btnErstellen.StyleController = this.layoutControl1;
this.btnErstellen.Click += new System.EventHandler(this.btnErstellen_Click);
//
// txtVTPort
//
resources.ApplyResources(this.txtVTPort, "txtVTPort");
this.txtVTPort.Name = "txtVTPort";
this.txtVTPort.StyleController = this.layoutControl1;
//
// txtKabelTrunkMulti
//
resources.ApplyResources(this.txtKabelTrunkMulti, "txtKabelTrunkMulti");
this.txtKabelTrunkMulti.Name = "txtKabelTrunkMulti";
this.txtKabelTrunkMulti.Properties.MaxLength = 5;
this.txtKabelTrunkMulti.StyleController = this.layoutControl1;
//
// txtBlechPosition
//
resources.ApplyResources(this.txtBlechPosition, "txtBlechPosition");
this.txtBlechPosition.Name = "txtBlechPosition";
this.txtBlechPosition.StyleController = this.layoutControl1;
//
// txtKabelURMLC
//
resources.ApplyResources(this.txtKabelURMLC, "txtKabelURMLC");
this.txtKabelURMLC.Name = "txtKabelURMLC";
this.txtKabelURMLC.Properties.MaxLength = 5;
this.txtKabelURMLC.StyleController = this.layoutControl1;
//
// gridControl1
//
resources.ApplyResources(this.gridControl1, "gridControl1");
this.gridControl1.MainView = this.gridView1;
this.gridControl1.Name = "gridControl1";
this.gridControl1.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] {
this.lkpSAN});
this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.gridView1,
this.gridView2});
//
// gridView1
//
this.gridView1.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.gridView1.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray;
this.gridView1.Appearance.ColumnFilterButton.Options.UseBackColor = true;
this.gridView1.Appearance.ColumnFilterButton.Options.UseBorderColor = true;
this.gridView1.Appearance.ColumnFilterButton.Options.UseForeColor = true;
this.gridView1.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.gridView1.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.gridView1.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.gridView1.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue;
this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true;
this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true;
this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true;
this.gridView1.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.gridView1.Appearance.Empty.Options.UseBackColor = true;
this.gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.gridView1.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite;
this.gridView1.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.gridView1.Appearance.EvenRow.Options.UseBackColor = true;
this.gridView1.Appearance.EvenRow.Options.UseForeColor = true;
this.gridView1.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225)))));
this.gridView1.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.gridView1.Appearance.FilterCloseButton.Options.UseBackColor = true;
this.gridView1.Appearance.FilterCloseButton.Options.UseBorderColor = true;
this.gridView1.Appearance.FilterCloseButton.Options.UseForeColor = true;
this.gridView1.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135)))));
this.gridView1.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.gridView1.Appearance.FilterPanel.Options.UseBackColor = true;
this.gridView1.Appearance.FilterPanel.Options.UseForeColor = true;
this.gridView1.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58)))));
this.gridView1.Appearance.FixedLine.Options.UseBackColor = true;
this.gridView1.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225)))));
this.gridView1.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.FocusedCell.Options.UseBackColor = true;
this.gridView1.Appearance.FocusedCell.Options.UseForeColor = true;
this.gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy;
this.gridView1.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178)))));
this.gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.FocusedRow.Options.UseBackColor = true;
this.gridView1.Appearance.FocusedRow.Options.UseForeColor = true;
this.gridView1.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.FooterPanel.Options.UseBackColor = true;
this.gridView1.Appearance.FooterPanel.Options.UseBorderColor = true;
this.gridView1.Appearance.FooterPanel.Options.UseForeColor = true;
this.gridView1.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.GroupButton.Options.UseBackColor = true;
this.gridView1.Appearance.GroupButton.Options.UseBorderColor = true;
this.gridView1.Appearance.GroupButton.Options.UseForeColor = true;
this.gridView1.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.gridView1.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.gridView1.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.GroupFooter.Options.UseBackColor = true;
this.gridView1.Appearance.GroupFooter.Options.UseBorderColor = true;
this.gridView1.Appearance.GroupFooter.Options.UseForeColor = true;
this.gridView1.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165)))));
this.gridView1.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White;
this.gridView1.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.gridView1.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.GroupPanel.Options.UseBackColor = true;
this.gridView1.Appearance.GroupPanel.Options.UseFont = true;
this.gridView1.Appearance.GroupPanel.Options.UseForeColor = true;
this.gridView1.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray;
this.gridView1.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.GroupRow.Options.UseBackColor = true;
this.gridView1.Appearance.GroupRow.Options.UseForeColor = true;
this.gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.gridView1.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.HeaderPanel.Options.UseBackColor = true;
this.gridView1.Appearance.HeaderPanel.Options.UseBorderColor = true;
this.gridView1.Appearance.HeaderPanel.Options.UseFont = true;
this.gridView1.Appearance.HeaderPanel.Options.UseForeColor = true;
this.gridView1.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray;
this.gridView1.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.gridView1.Appearance.HideSelectionRow.Options.UseBackColor = true;
this.gridView1.Appearance.HideSelectionRow.Options.UseForeColor = true;
this.gridView1.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.HorzLine.Options.UseBackColor = true;
this.gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.OddRow.BackColor2 = System.Drawing.Color.White;
this.gridView1.Appearance.OddRow.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal;
this.gridView1.Appearance.OddRow.Options.UseBackColor = true;
this.gridView1.Appearance.OddRow.Options.UseForeColor = true;
this.gridView1.Appearance.Preview.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.Preview.ForeColor = System.Drawing.Color.Navy;
this.gridView1.Appearance.Preview.Options.UseBackColor = true;
this.gridView1.Appearance.Preview.Options.UseForeColor = true;
this.gridView1.Appearance.Row.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.Row.ForeColor = System.Drawing.Color.Black;
this.gridView1.Appearance.Row.Options.UseBackColor = true;
this.gridView1.Appearance.Row.Options.UseForeColor = true;
this.gridView1.Appearance.RowSeparator.BackColor = System.Drawing.Color.White;
this.gridView1.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.gridView1.Appearance.RowSeparator.Options.UseBackColor = true;
this.gridView1.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138)))));
this.gridView1.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White;
this.gridView1.Appearance.SelectedRow.Options.UseBackColor = true;
this.gridView1.Appearance.SelectedRow.Options.UseForeColor = true;
this.gridView1.Appearance.VertLine.BackColor = System.Drawing.Color.Silver;
this.gridView1.Appearance.VertLine.Options.UseBackColor = true;
this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.gridColumn1,
this.gridColumn2,
this.gridColumn3,
this.gridColumn4,
this.gridColumn5});
this.gridView1.GridControl = this.gridControl1;
this.gridView1.Name = "gridView1";
this.gridView1.OptionsCustomization.AllowFilter = false;
this.gridView1.OptionsMenu.EnableColumnMenu = false;
this.gridView1.OptionsMenu.EnableFooterMenu = false;
this.gridView1.OptionsMenu.EnableGroupPanelMenu = false;
this.gridView1.OptionsView.EnableAppearanceEvenRow = true;
this.gridView1.OptionsView.EnableAppearanceOddRow = true;
this.gridView1.OptionsView.ShowGroupPanel = false;
this.gridView1.OptionsView.ShowIndicator = false;
//
// gridColumn1
//
this.gridColumn1.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn1.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn1.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn1.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
resources.ApplyResources(this.gridColumn1, "gridColumn1");
this.gridColumn1.FieldName = "KabelURMLC";
this.gridColumn1.Name = "gridColumn1";
//
// gridColumn2
//
this.gridColumn2.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn2.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn2.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn2.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
resources.ApplyResources(this.gridColumn2, "gridColumn2");
this.gridColumn2.FieldName = "Blech";
this.gridColumn2.Name = "gridColumn2";
//
// gridColumn3
//
this.gridColumn3.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn3.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn3.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn3.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
resources.ApplyResources(this.gridColumn3, "gridColumn3");
this.gridColumn3.FieldName = "CableTrunkMulti";
this.gridColumn3.Name = "gridColumn3";
//
// gridColumn4
//
this.gridColumn4.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn4.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn4.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn4.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
resources.ApplyResources(this.gridColumn4, "gridColumn4");
this.gridColumn4.FieldName = "VTPort";
this.gridColumn4.Name = "gridColumn4";
//
// gridColumn5
//
this.gridColumn5.AppearanceCell.Options.UseTextOptions = true;
this.gridColumn5.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
this.gridColumn5.AppearanceHeader.Options.UseTextOptions = true;
this.gridColumn5.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
resources.ApplyResources(this.gridColumn5, "gridColumn5");
this.gridColumn5.ColumnEdit = this.lkpSAN;
this.gridColumn5.FieldName = "SanId";
this.gridColumn5.Name = "gridColumn5";
//
// lkpSAN
//
this.lkpSAN.Appearance.Options.UseTextOptions = true;
this.lkpSAN.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
resources.ApplyResources(this.lkpSAN, "lkpSAN");
this.lkpSAN.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
new DevExpress.XtraEditors.Controls.EditorButton(((DevExpress.XtraEditors.Controls.ButtonPredefines)(resources.GetObject("lkpSAN.Buttons"))))});
this.lkpSAN.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
new DevExpress.XtraEditors.Controls.LookUpColumnInfo("SAN", "SAN", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Center, DevExpress.Data.ColumnSortOrder.None)});
this.lkpSAN.Name = "lkpSAN";
//
// gridView2
//
this.gridView2.GridControl = this.gridControl1;
this.gridView2.Name = "gridView2";
//
// layoutControlGroup1
//
resources.ApplyResources(this.layoutControlGroup1, "layoutControlGroup1");
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1,
this.layoutControlItem6,
this.layoutControlItem7,
this.layoutControlGroup2,
this.emptySpaceItem1});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(632, 386);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.gridControl1;
resources.ApplyResources(this.layoutControlItem1, "layoutControlItem1");
this.layoutControlItem1.Location = new System.Drawing.Point(0, 80);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(630, 304);
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem1.TextToControlDistance = 0;
this.layoutControlItem1.TextVisible = false;
//
// layoutControlItem6
//
this.layoutControlItem6.Control = this.btnErstellen;
resources.ApplyResources(this.layoutControlItem6, "layoutControlItem6");
this.layoutControlItem6.Location = new System.Drawing.Point(539, 0);
this.layoutControlItem6.MaxSize = new System.Drawing.Size(91, 33);
this.layoutControlItem6.MinSize = new System.Drawing.Size(91, 33);
this.layoutControlItem6.Name = "layoutControlItem6";
this.layoutControlItem6.Size = new System.Drawing.Size(91, 33);
this.layoutControlItem6.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.layoutControlItem6.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem6.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem6.TextToControlDistance = 0;
this.layoutControlItem6.TextVisible = false;
//
// layoutControlItem7
//
this.layoutControlItem7.Control = this.btnListeLoeschen;
resources.ApplyResources(this.layoutControlItem7, "layoutControlItem7");
this.layoutControlItem7.Location = new System.Drawing.Point(539, 33);
this.layoutControlItem7.MaxSize = new System.Drawing.Size(91, 33);
this.layoutControlItem7.MinSize = new System.Drawing.Size(91, 33);
this.layoutControlItem7.Name = "layoutControlItem7";
this.layoutControlItem7.Size = new System.Drawing.Size(91, 33);
this.layoutControlItem7.SizeConstraintsType = DevExpress.XtraLayout.SizeConstraintsType.Custom;
this.layoutControlItem7.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem7.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem7.TextToControlDistance = 0;
this.layoutControlItem7.TextVisible = false;
//
// layoutControlGroup2
//
resources.ApplyResources(this.layoutControlGroup2, "layoutControlGroup2");
this.layoutControlGroup2.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem2,
this.layoutControlItem3,
this.layoutControlItem4,
this.layoutControlItem5});
this.layoutControlGroup2.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup2.Name = "layoutControlGroup2";
this.layoutControlGroup2.Size = new System.Drawing.Size(539, 80);
//
// layoutControlItem2
//
this.layoutControlItem2.Control = this.txtKabelURMLC;
resources.ApplyResources(this.layoutControlItem2, "layoutControlItem2");
this.layoutControlItem2.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem2.Name = "layoutControlItem2";
this.layoutControlItem2.Size = new System.Drawing.Size(95, 56);
this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Top;
this.layoutControlItem2.TextSize = new System.Drawing.Size(81, 20);
//
// layoutControlItem3
//
this.layoutControlItem3.Control = this.txtBlechPosition;
resources.ApplyResources(this.layoutControlItem3, "layoutControlItem3");
this.layoutControlItem3.Location = new System.Drawing.Point(95, 0);
this.layoutControlItem3.Name = "layoutControlItem3";
this.layoutControlItem3.Size = new System.Drawing.Size(137, 56);
this.layoutControlItem3.TextLocation = DevExpress.Utils.Locations.Top;
this.layoutControlItem3.TextSize = new System.Drawing.Size(81, 20);
//
// layoutControlItem4
//
this.layoutControlItem4.Control = this.txtKabelTrunkMulti;
resources.ApplyResources(this.layoutControlItem4, "layoutControlItem4");
this.layoutControlItem4.Location = new System.Drawing.Point(232, 0);
this.layoutControlItem4.Name = "layoutControlItem4";
this.layoutControlItem4.Size = new System.Drawing.Size(127, 56);
this.layoutControlItem4.TextLocation = DevExpress.Utils.Locations.Top;
this.layoutControlItem4.TextSize = new System.Drawing.Size(81, 20);
//
// layoutControlItem5
//
this.layoutControlItem5.Control = this.txtVTPort;
resources.ApplyResources(this.layoutControlItem5, "layoutControlItem5");
this.layoutControlItem5.Location = new System.Drawing.Point(359, 0);
this.layoutControlItem5.Name = "layoutControlItem5";
this.layoutControlItem5.Size = new System.Drawing.Size(174, 56);
this.layoutControlItem5.TextLocation = DevExpress.Utils.Locations.Top;
this.layoutControlItem5.TextSize = new System.Drawing.Size(81, 20);
//
// emptySpaceItem1
//
resources.ApplyResources(this.emptySpaceItem1, "emptySpaceItem1");
this.emptySpaceItem1.Location = new System.Drawing.Point(539, 66);
this.emptySpaceItem1.Name = "emptySpaceItem1";
this.emptySpaceItem1.Size = new System.Drawing.Size(91, 14);
this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0);
//
// frmServerDetailCreate
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.layoutControl1);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmServerDetailCreate";
this.Load += new System.EventHandler(this.frmServerDetailCreate_Load);
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.frmServerDetailCreate_KeyPress);
((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.txtVTPort.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtKabelTrunkMulti.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtBlechPosition.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtKabelURMLC.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.lkpSAN)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.gridView2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraBars.BarManager barManager1;
private DevExpress.XtraBars.Bar bar1;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraGrid.GridControl gridControl1;
private DevExpress.XtraGrid.Views.Grid.GridView gridView1;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn1;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn2;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn3;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn4;
private DevExpress.XtraGrid.Views.Grid.GridView gridView2;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraEditors.TextEdit txtVTPort;
private DevExpress.XtraEditors.TextEdit txtKabelTrunkMulti;
private DevExpress.XtraEditors.TextEdit txtBlechPosition;
private DevExpress.XtraEditors.TextEdit txtKabelURMLC;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem3;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem4;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem5;
private DevExpress.XtraEditors.SimpleButton btnErstellen;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem6;
private DevExpress.XtraEditors.SimpleButton btnListeLoeschen;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem7;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup2;
private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1;
private DevExpress.XtraBars.BarButtonItem btnSchliessen;
private DevExpress.XtraBars.BarButtonItem btnSpeichern;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn5;
private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit lkpSAN;
}
}
| |
//
// 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.Insights;
using Microsoft.Azure.Management.Insights;
using Microsoft.Azure.Management.Insights.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Insights
{
/// <summary>
/// Operations for managing agent diagnostic settings.
/// </summary>
internal partial class AgentDiagnosticSettingsOperations : IServiceOperations<InsightsManagementClient>, IAgentDiagnosticSettingsOperations
{
/// <summary>
/// Initializes a new instance of the AgentDiagnosticSettingsOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AgentDiagnosticSettingsOperations(InsightsManagementClient client)
{
this._client = client;
}
private InsightsManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Insights.InsightsManagementClient.
/// </summary>
public InsightsManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets the diagnostic settings.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource uri.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AgentDiagnosticSettingsGetResponse> GetAsync(string resourceUri, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
// Only valid for compute resources
if (!Util.IsComputeResourceProvider(resourceUri))
{
throw new ArgumentException("This is not a valid compute resource Id.", "resourceUri");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/diagnosticSettings/agent";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
// 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
AgentDiagnosticSettingsGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AgentDiagnosticSettingsGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
result.Location = locationInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
AgentDiagnosticSettings propertiesInstance = new AgentDiagnosticSettings();
result.Properties = propertiesInstance;
JToken nameValue2 = propertiesValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
propertiesInstance.Name = nameInstance2;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
JToken publicConfigurationValue = propertiesValue["publicConfiguration"];
if (publicConfigurationValue != null && publicConfigurationValue.Type != JTokenType.Null)
{
string typeName = ((string)publicConfigurationValue["odata.type"]);
}
}
}
}
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>
/// Puts the new diagnostic settings.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource uri.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Generic empty response. We only pass it to ensure json error
/// handling
/// </returns>
public async Task<EmptyResponse> PutAsync(string resourceUri, AgentDiagnosticSettgingsPutParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Only valid for compute resources
if (!Util.IsComputeResourceProvider(resourceUri))
{
throw new ArgumentException("This is not a valid compute resource Id.", "resourceUri");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PutAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + Uri.EscapeDataString(resourceUri);
url = url + "/diagnosticSettings/agent";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-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
httpRequest.Headers.Add("Accept", "application/json");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject agentDiagnosticSettgingsPutParametersValue = new JObject();
requestDoc = agentDiagnosticSettgingsPutParametersValue;
if (parameters.Properties != null)
{
JObject propertiesValue = new JObject();
agentDiagnosticSettgingsPutParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Name != null)
{
propertiesValue["name"] = parameters.Properties.Name;
}
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
if (parameters.Properties.PublicConfiguration != null)
{
JObject publicConfigurationValue = new JObject();
propertiesValue["publicConfiguration"] = publicConfigurationValue;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// 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 && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted)
{
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
EmptyResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new EmptyResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
}
}
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 Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace Lucene.Net.Support
{
/// <summary>
/// A C# emulation of the <a href="http://download.oracle.com/javase/1,5.0/docs/api/java/util/HashMap.html">Java Hashmap</a>
/// <para>
/// A <see cref="Dictionary{TKey, TValue}" /> is a close equivalent to the Java
/// Hashmap. One difference java implementation of the class is that
/// the Hashmap supports both null keys and values, where the C# Dictionary
/// only supports null values not keys. Also, <c>V Get(TKey)</c>
/// method in Java returns null if the key doesn't exist, instead of throwing
/// an exception. This implementation doesn't throw an exception when a key
/// doesn't exist, it will return null. This class is slower than using a
/// <see cref="Dictionary{TKey, TValue}"/>, because of extra checks that have to be
/// done on each access, to check for null.
/// </para>
/// <para>
/// <b>NOTE:</b> This class works best with nullable types. default(T) is returned
/// when a key doesn't exist in the collection (this being similar to how Java returns
/// null). Therefore, if the expected behavior of the java code is to execute code
/// based on if the key exists, when the key is an integer type, it will return 0 instead of null.
/// </para>
/// <remaks>
/// Consider also implementing IDictionary, IEnumerable, and ICollection
/// like <see cref="Dictionary{TKey, TValue}" /> does, so HashMap can be
/// used in substituted in place for the same interfaces it implements.
/// </remaks>
/// </summary>
/// <typeparam name="TKey">The type of keys in the dictionary</typeparam>
/// <typeparam name="TValue">The type of values in the dictionary</typeparam>
[Serializable]
public class HashMap<TKey, TValue> : IDictionary<TKey, TValue>
{
internal IEqualityComparer<TKey> _comparer;
internal IDictionary<TKey, TValue> _dict;
// Indicates if a null key has been assigned, used for iteration
private bool _hasNullValue;
// stores the value for the null key
private TValue _nullValue;
// Indicates the type of key is a non-nullable valuetype
private readonly bool _isValueType;
public HashMap()
: this(0)
{ }
public HashMap(IEqualityComparer<TKey> comparer)
: this(0, comparer)
{
}
public HashMap(int initialCapacity)
: this(initialCapacity, EqualityComparer<TKey>.Default)
{
}
public HashMap(int initialCapacity, IEqualityComparer<TKey> comparer)
: this(new Dictionary<TKey, TValue>(initialCapacity, comparer), comparer)
{
}
public HashMap(IEnumerable<KeyValuePair<TKey, TValue>> other)
: this(0)
{
foreach (var kvp in other)
{
Add(kvp.Key, kvp.Value);
}
}
internal HashMap(IDictionary<TKey, TValue> wrappedDict, IEqualityComparer<TKey> comparer)
{
_comparer = EqualityComparer<TKey>.Default;
_dict = wrappedDict;
_hasNullValue = false;
if (typeof(TKey).IsValueType)
{
_isValueType = Nullable.GetUnderlyingType(typeof(TKey)) == null;
}
}
public bool ContainsValue(TValue value)
{
if (!_isValueType && _hasNullValue && _nullValue.Equals(value))
return true;
return _dict.Values.Contains(value);
}
public TValue AddIfAbsent(TKey key, TValue value)
{
if (!ContainsKey(key))
{
Add(key, value);
return default(TValue);
}
return this[key];
}
#region Implementation of IEnumerable
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
if (!_isValueType && _hasNullValue)
{
yield return new KeyValuePair<TKey, TValue>(default(TKey), _nullValue);
}
foreach (var kvp in _dict)
{
yield return kvp;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion Implementation of IEnumerable
#region Implementation of ICollection<KeyValuePair<TKey,TValue>>
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
Add(item.Key, item.Value);
}
public void Clear()
{
_hasNullValue = false;
_nullValue = default(TValue);
_dict.Clear();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
if (!_isValueType && _comparer.Equals(item.Key, default(TKey)))
{
return _hasNullValue && EqualityComparer<TValue>.Default.Equals(item.Value, _nullValue);
}
return ((ICollection<KeyValuePair<TKey, TValue>>)_dict).Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<TKey, TValue>>)_dict).CopyTo(array, arrayIndex);
if (!_isValueType && _hasNullValue)
{
array[array.Length - 1] = new KeyValuePair<TKey, TValue>(default(TKey), _nullValue);
}
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
if (!_isValueType && _comparer.Equals(item.Key, default(TKey)))
{
if (!_hasNullValue)
return false;
_hasNullValue = false;
_nullValue = default(TValue);
return true;
}
return ((ICollection<KeyValuePair<TKey, TValue>>)_dict).Remove(item);
}
public int Count
{
get { return _dict.Count + (_hasNullValue ? 1 : 0); }
}
public bool IsReadOnly
{
get { return false; }
}
#endregion Implementation of ICollection<KeyValuePair<TKey,TValue>>
#region Implementation of IDictionary<TKey,TValue>
public bool ContainsKey(TKey key)
{
if (!_isValueType && _comparer.Equals(key, default(TKey)))
{
if (_hasNullValue)
{
return true;
}
return false;
}
return _dict.ContainsKey(key);
}
public virtual void Add(TKey key, TValue value)
{
if (!_isValueType && _comparer.Equals(key, default(TKey)))
{
_hasNullValue = true;
_nullValue = value;
}
else
{
_dict[key] = value;
}
}
public bool Remove(TKey key)
{
if (!_isValueType && _comparer.Equals(key, default(TKey)))
{
_hasNullValue = false;
_nullValue = default(TValue);
return true;
}
else
{
return _dict.Remove(key);
}
}
public bool TryGetValue(TKey key, out TValue value)
{
if (!_isValueType && _comparer.Equals(key, default(TKey)))
{
if (_hasNullValue)
{
value = _nullValue;
return true;
}
value = default(TValue);
return false;
}
else
{
return _dict.TryGetValue(key, out value);
}
}
public TValue this[TKey key]
{
get
{
if (!_isValueType && _comparer.Equals(key, default(TKey)))
{
if (!_hasNullValue)
{
return default(TValue);
}
return _nullValue;
}
return _dict.ContainsKey(key) ? _dict[key] : default(TValue);
}
set { Add(key, value); }
}
public ICollection<TKey> Keys
{
get
{
if (!_hasNullValue) return _dict.Keys;
// Using a List<T> to generate an ICollection<TKey>
// would incur a costly copy of the dict's KeyCollection
// use out own wrapper instead
return new NullKeyCollection(_dict);
}
}
public ICollection<TValue> Values
{
get
{
if (!_hasNullValue) return _dict.Values;
// Using a List<T> to generate an ICollection<TValue>
// would incur a costly copy of the dict's ValueCollection
// use out own wrapper instead
return new NullValueCollection(_dict, _nullValue);
}
}
#endregion Implementation of IDictionary<TKey,TValue>
#region NullValueCollection
/// <summary>
/// Wraps a dictionary and adds the value
/// represented by the null key
/// </summary>
private class NullValueCollection : ICollection<TValue>
{
private readonly TValue _nullValue;
private readonly IDictionary<TKey, TValue> _internalDict;
public NullValueCollection(IDictionary<TKey, TValue> dict, TValue nullValue)
{
_internalDict = dict;
_nullValue = nullValue;
}
#region Implementation of IEnumerable
public IEnumerator<TValue> GetEnumerator()
{
yield return _nullValue;
foreach (var val in _internalDict.Values)
{
yield return val;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion Implementation of IEnumerable
#region Implementation of ICollection<TValue>
public void CopyTo(TValue[] array, int arrayIndex)
{
throw new NotImplementedException("Implement as needed");
}
public int Count
{
get { return _internalDict.Count + 1; }
}
public bool IsReadOnly
{
get { return true; }
}
#region Explicit Interface Methods
void ICollection<TValue>.Add(TValue item)
{
throw new NotSupportedException();
}
void ICollection<TValue>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<TValue>.Contains(TValue item)
{
throw new NotSupportedException();
}
bool ICollection<TValue>.Remove(TValue item)
{
throw new NotSupportedException("Collection is read only!");
}
#endregion Explicit Interface Methods
#endregion Implementation of ICollection<TValue>
}
#endregion NullValueCollection
#region NullKeyCollection
/// <summary>
/// Wraps a dictionary's collection, adding in a
/// null key.
/// </summary>
private class NullKeyCollection : ICollection<TKey>
{
private readonly IDictionary<TKey, TValue> _internalDict;
public NullKeyCollection(IDictionary<TKey, TValue> dict)
{
_internalDict = dict;
}
public IEnumerator<TKey> GetEnumerator()
{
yield return default(TKey);
foreach (var key in _internalDict.Keys)
{
yield return key;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void CopyTo(TKey[] array, int arrayIndex)
{
throw new NotImplementedException("Implement this as needed");
}
public int Count
{
get { return _internalDict.Count + 1; }
}
public bool IsReadOnly
{
get { return true; }
}
#region Explicit Interface Definitions
bool ICollection<TKey>.Contains(TKey item)
{
throw new NotSupportedException();
}
void ICollection<TKey>.Add(TKey item)
{
throw new NotSupportedException();
}
void ICollection<TKey>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<TKey>.Remove(TKey item)
{
throw new NotSupportedException();
}
#endregion Explicit Interface Definitions
}
#endregion NullKeyCollection
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Domain.Shipping;
using Nop.Services.Events;
namespace Nop.Services.Orders
{
/// <summary>
/// Order service
/// </summary>
public partial class OrderService : IOrderService
{
#region Fields
private readonly IRepository<Order> _orderRepository;
private readonly IRepository<OrderItem> _orderItemRepository;
private readonly IRepository<OrderNote> _orderNoteRepository;
private readonly IRepository<Product> _productRepository;
private readonly IRepository<RecurringPayment> _recurringPaymentRepository;
private readonly IRepository<Customer> _customerRepository;
private readonly IRepository<ReturnRequest> _returnRequestRepository;
private readonly IEventPublisher _eventPublisher;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="orderRepository">Order repository</param>
/// <param name="orderItemRepository">Order item repository</param>
/// <param name="orderNoteRepository">Order note repository</param>
/// <param name="productRepository">Product repository</param>
/// <param name="recurringPaymentRepository">Recurring payment repository</param>
/// <param name="customerRepository">Customer repository</param>
/// <param name="returnRequestRepository">Return request repository</param>
/// <param name="eventPublisher">Event published</param>
public OrderService(IRepository<Order> orderRepository,
IRepository<OrderItem> orderItemRepository,
IRepository<OrderNote> orderNoteRepository,
IRepository<Product> productRepository,
IRepository<RecurringPayment> recurringPaymentRepository,
IRepository<Customer> customerRepository,
IRepository<ReturnRequest> returnRequestRepository,
IEventPublisher eventPublisher)
{
this._orderRepository = orderRepository;
this._orderItemRepository = orderItemRepository;
this._orderNoteRepository = orderNoteRepository;
this._productRepository = productRepository;
this._recurringPaymentRepository = recurringPaymentRepository;
this._customerRepository = customerRepository;
this._returnRequestRepository = returnRequestRepository;
this._eventPublisher = eventPublisher;
}
#endregion
#region Methods
#region Orders
/// <summary>
/// Gets an order
/// </summary>
/// <param name="orderId">The order identifier</param>
/// <returns>Order</returns>
public virtual Order GetOrderById(int orderId)
{
if (orderId == 0)
return null;
return _orderRepository.GetById(orderId);
}
/// <summary>
/// Get orders by identifiers
/// </summary>
/// <param name="orderIds">Order identifiers</param>
/// <returns>Order</returns>
public virtual IList<Order> GetOrdersByIds(int[] orderIds)
{
if (orderIds == null || orderIds.Length == 0)
return new List<Order>();
var query = from o in _orderRepository.Table
where orderIds.Contains(o.Id)
select o;
var orders = query.ToList();
//sort by passed identifiers
var sortedOrders = new List<Order>();
foreach (int id in orderIds)
{
var order = orders.Find(x => x.Id == id);
if (order != null)
sortedOrders.Add(order);
}
return sortedOrders;
}
/// <summary>
/// Gets an order
/// </summary>
/// <param name="orderGuid">The order identifier</param>
/// <returns>Order</returns>
public virtual Order GetOrderByGuid(Guid orderGuid)
{
if (orderGuid == Guid.Empty)
return null;
var query = from o in _orderRepository.Table
where o.OrderGuid == orderGuid
select o;
var order = query.FirstOrDefault();
return order;
}
/// <summary>
/// Deletes an order
/// </summary>
/// <param name="order">The order</param>
public virtual void DeleteOrder(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
order.Deleted = true;
UpdateOrder(order);
}
/// <summary>
/// Search orders
/// </summary>
/// <param name="storeId">Store identifier; 0 to load all orders</param>
/// <param name="vendorId">Vendor identifier; null to load all orders</param>
/// <param name="customerId">Customer identifier; 0 to load all orders</param>
/// <param name="productId">Product identifier which was purchased in an order; 0 to load all orders</param>
/// <param name="affiliateId">Affiliate identifier; 0 to load all orders</param>
/// <param name="warehouseId">Warehouse identifier, only orders with products from a specified warehouse will be loaded; 0 to load all orders</param>
/// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>
/// <param name="createdToUtc">Created date to (UTC); null to load all records</param>
/// <param name="os">Order status; null to load all orders</param>
/// <param name="ps">Order payment status; null to load all orders</param>
/// <param name="ss">Order shipment status; null to load all orders</param>
/// <param name="billingEmail">Billing email. Leave empty to load all records.</param>
/// <param name="orderGuid">Search by order GUID (Global unique identifier) or part of GUID. Leave empty to load all orders.</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <returns>Order collection</returns>
public virtual IPagedList<Order> SearchOrders(int storeId = 0,
int vendorId = 0, int customerId = 0,
int productId = 0, int affiliateId = 0, int warehouseId = 0,
DateTime? createdFromUtc = null, DateTime? createdToUtc = null,
OrderStatus? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null,
string billingEmail = null, string orderGuid = null,
int pageIndex = 0, int pageSize = int.MaxValue)
{
int? orderStatusId = null;
if (os.HasValue)
orderStatusId = (int)os.Value;
int? paymentStatusId = null;
if (ps.HasValue)
paymentStatusId = (int)ps.Value;
int? shippingStatusId = null;
if (ss.HasValue)
shippingStatusId = (int)ss.Value;
var query = _orderRepository.Table;
if (storeId > 0)
query = query.Where(o => o.StoreId == storeId);
if (vendorId > 0)
{
query = query
.Where(o => o.OrderItems
.Any(orderItem => orderItem.Product.VendorId == vendorId));
}
if (customerId > 0)
query = query.Where(o => o.CustomerId == customerId);
if (productId > 0)
{
query = query
.Where(o => o.OrderItems
.Any(orderItem => orderItem.Product.Id == productId));
}
if (warehouseId > 0)
{
query = query
.Where(o => o.OrderItems
.Any(orderItem => orderItem.Product.WarehouseId == warehouseId));
}
if (affiliateId > 0)
query = query.Where(o => o.AffiliateId == affiliateId);
if (createdFromUtc.HasValue)
query = query.Where(o => createdFromUtc.Value <= o.CreatedOnUtc);
if (createdToUtc.HasValue)
query = query.Where(o => createdToUtc.Value >= o.CreatedOnUtc);
if (orderStatusId.HasValue)
query = query.Where(o => orderStatusId.Value == o.OrderStatusId);
if (paymentStatusId.HasValue)
query = query.Where(o => paymentStatusId.Value == o.PaymentStatusId);
if (shippingStatusId.HasValue)
query = query.Where(o => shippingStatusId.Value == o.ShippingStatusId);
if (!String.IsNullOrEmpty(billingEmail))
query = query.Where(o => o.BillingAddress != null && !String.IsNullOrEmpty(o.BillingAddress.Email) && o.BillingAddress.Email.Contains(billingEmail));
query = query.Where(o => !o.Deleted);
query = query.OrderByDescending(o => o.CreatedOnUtc);
if (!String.IsNullOrEmpty(orderGuid))
{
//filter by GUID. Filter in BLL because EF doesn't support casting of GUID to string
var orders = query.ToList();
orders = orders.FindAll(o => o.OrderGuid.ToString().ToLowerInvariant().Contains(orderGuid.ToLowerInvariant()));
return new PagedList<Order>(orders, pageIndex, pageSize);
}
else
{
//database layer paging
return new PagedList<Order>(query, pageIndex, pageSize);
}
}
/// <summary>
/// Inserts an order
/// </summary>
/// <param name="order">Order</param>
public virtual void InsertOrder(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
_orderRepository.Insert(order);
//event notification
_eventPublisher.EntityInserted(order);
}
/// <summary>
/// Updates the order
/// </summary>
/// <param name="order">The order</param>
public virtual void UpdateOrder(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
_orderRepository.Update(order);
//event notification
_eventPublisher.EntityUpdated(order);
}
/// <summary>
/// Get an order by authorization transaction ID and payment method system name
/// </summary>
/// <param name="authorizationTransactionId">Authorization transaction ID</param>
/// <param name="paymentMethodSystemName">Payment method system name</param>
/// <returns>Order</returns>
public virtual Order GetOrderByAuthorizationTransactionIdAndPaymentMethod(string authorizationTransactionId,
string paymentMethodSystemName)
{
var query = _orderRepository.Table;
if (!String.IsNullOrWhiteSpace(authorizationTransactionId))
query = query.Where(o => o.AuthorizationTransactionId == authorizationTransactionId);
if (!String.IsNullOrWhiteSpace(paymentMethodSystemName))
query = query.Where(o => o.PaymentMethodSystemName == paymentMethodSystemName);
query = query.OrderByDescending(o => o.CreatedOnUtc);
var order = query.FirstOrDefault();
return order;
}
#endregion
#region Orders items
/// <summary>
/// Gets an order item
/// </summary>
/// <param name="orderItemId">Order item identifier</param>
/// <returns>Order item</returns>
public virtual OrderItem GetOrderItemById(int orderItemId)
{
if (orderItemId == 0)
return null;
return _orderItemRepository.GetById(orderItemId);
}
/// <summary>
/// Gets an item
/// </summary>
/// <param name="orderItemGuid">Order identifier</param>
/// <returns>Order item</returns>
public virtual OrderItem GetOrderItemByGuid(Guid orderItemGuid)
{
if (orderItemGuid == Guid.Empty)
return null;
var query = from orderItem in _orderItemRepository.Table
where orderItem.OrderItemGuid == orderItemGuid
select orderItem;
var item = query.FirstOrDefault();
return item;
}
/// <summary>
/// Gets all order items
/// </summary>
/// <param name="orderId">Order identifier; null to load all records</param>
/// <param name="customerId">Customer identifier; null to load all records</param>
/// <param name="createdFromUtc">Order created date from (UTC); null to load all records</param>
/// <param name="createdToUtc">Order created date to (UTC); null to load all records</param>
/// <param name="os">Order status; null to load all records</param>
/// <param name="ps">Order payment status; null to load all records</param>
/// <param name="ss">Order shipment status; null to load all records</param>
/// <param name="loadDownloableProductsOnly">Value indicating whether to load downloadable products only</param>
/// <returns>Order collection</returns>
public virtual IList<OrderItem> GetAllOrderItems(int? orderId,
int? customerId, DateTime? createdFromUtc, DateTime? createdToUtc,
OrderStatus? os, PaymentStatus? ps, ShippingStatus? ss,
bool loadDownloableProductsOnly)
{
int? orderStatusId = null;
if (os.HasValue)
orderStatusId = (int)os.Value;
int? paymentStatusId = null;
if (ps.HasValue)
paymentStatusId = (int)ps.Value;
int? shippingStatusId = null;
if (ss.HasValue)
shippingStatusId = (int)ss.Value;
var query = from orderItem in _orderItemRepository.Table
join o in _orderRepository.Table on orderItem.OrderId equals o.Id
join p in _productRepository.Table on orderItem.ProductId equals p.Id
where (!orderId.HasValue || orderId.Value == 0 || orderId == o.Id) &&
(!customerId.HasValue || customerId.Value == 0 || customerId == o.CustomerId) &&
(!createdFromUtc.HasValue || createdFromUtc.Value <= o.CreatedOnUtc) &&
(!createdToUtc.HasValue || createdToUtc.Value >= o.CreatedOnUtc) &&
(!orderStatusId.HasValue || orderStatusId == o.OrderStatusId) &&
(!paymentStatusId.HasValue || paymentStatusId.Value == o.PaymentStatusId) &&
(!shippingStatusId.HasValue || shippingStatusId.Value == o.ShippingStatusId) &&
(!loadDownloableProductsOnly || p.IsDownload) &&
!o.Deleted
orderby o.CreatedOnUtc descending, orderItem.Id
select orderItem;
var orderItems = query.ToList();
return orderItems;
}
/// <summary>
/// Delete an order item
/// </summary>
/// <param name="orderItem">The order item</param>
public virtual void DeleteOrderItem(OrderItem orderItem)
{
if (orderItem == null)
throw new ArgumentNullException("orderItem");
_orderItemRepository.Delete(orderItem);
//event notification
_eventPublisher.EntityDeleted(orderItem);
}
#endregion
#region Orders
/// <summary>
/// Gets an order note
/// </summary>
/// <param name="orderNoteId">The order note identifier</param>
/// <returns>Order note</returns>
public virtual OrderNote GetOrderNoteById(int orderNoteId)
{
if (orderNoteId == 0)
return null;
return _orderNoteRepository.GetById(orderNoteId);
}
/// <summary>
/// Deletes an order note
/// </summary>
/// <param name="orderNote">The order note</param>
public virtual void DeleteOrderNote(OrderNote orderNote)
{
if (orderNote == null)
throw new ArgumentNullException("orderNote");
_orderNoteRepository.Delete(orderNote);
//event notification
_eventPublisher.EntityDeleted(orderNote);
}
#endregion
#region Recurring payments
/// <summary>
/// Deletes a recurring payment
/// </summary>
/// <param name="recurringPayment">Recurring payment</param>
public virtual void DeleteRecurringPayment(RecurringPayment recurringPayment)
{
if (recurringPayment == null)
throw new ArgumentNullException("recurringPayment");
recurringPayment.Deleted = true;
UpdateRecurringPayment(recurringPayment);
}
/// <summary>
/// Gets a recurring payment
/// </summary>
/// <param name="recurringPaymentId">The recurring payment identifier</param>
/// <returns>Recurring payment</returns>
public virtual RecurringPayment GetRecurringPaymentById(int recurringPaymentId)
{
if (recurringPaymentId == 0)
return null;
return _recurringPaymentRepository.GetById(recurringPaymentId);
}
/// <summary>
/// Inserts a recurring payment
/// </summary>
/// <param name="recurringPayment">Recurring payment</param>
public virtual void InsertRecurringPayment(RecurringPayment recurringPayment)
{
if (recurringPayment == null)
throw new ArgumentNullException("recurringPayment");
_recurringPaymentRepository.Insert(recurringPayment);
//event notification
_eventPublisher.EntityInserted(recurringPayment);
}
/// <summary>
/// Updates the recurring payment
/// </summary>
/// <param name="recurringPayment">Recurring payment</param>
public virtual void UpdateRecurringPayment(RecurringPayment recurringPayment)
{
if (recurringPayment == null)
throw new ArgumentNullException("recurringPayment");
_recurringPaymentRepository.Update(recurringPayment);
//event notification
_eventPublisher.EntityUpdated(recurringPayment);
}
/// <summary>
/// Search recurring payments
/// </summary>
/// <param name="storeId">The store identifier; 0 to load all records</param>
/// <param name="customerId">The customer identifier; 0 to load all records</param>
/// <param name="initialOrderId">The initial order identifier; 0 to load all records</param>
/// <param name="initialOrderStatus">Initial order status identifier; null to load all records</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Recurring payment collection</returns>
public virtual IPagedList<RecurringPayment> SearchRecurringPayments(int storeId,
int customerId, int initialOrderId, OrderStatus? initialOrderStatus,
int pageIndex, int pageSize, bool showHidden = false)
{
int? initialOrderStatusId = null;
if (initialOrderStatus.HasValue)
initialOrderStatusId = (int)initialOrderStatus.Value;
var query1 = from rp in _recurringPaymentRepository.Table
join c in _customerRepository.Table on rp.InitialOrder.CustomerId equals c.Id
where
(!rp.Deleted) &&
(showHidden || !rp.InitialOrder.Deleted) &&
(showHidden || !c.Deleted) &&
(showHidden || rp.IsActive) &&
(customerId == 0 || rp.InitialOrder.CustomerId == customerId) &&
(storeId == 0 || rp.InitialOrder.StoreId == storeId) &&
(initialOrderId == 0 || rp.InitialOrder.Id == initialOrderId) &&
(!initialOrderStatusId.HasValue || initialOrderStatusId.Value == 0 || rp.InitialOrder.OrderStatusId == initialOrderStatusId.Value)
select rp.Id;
var query2 = from rp in _recurringPaymentRepository.Table
where query1.Contains(rp.Id)
orderby rp.StartDateUtc, rp.Id
select rp;
var recurringPayments = new PagedList<RecurringPayment>(query2, pageIndex, pageSize);
return recurringPayments;
}
#endregion
#region Return requests
/// <summary>
/// Deletes a return request
/// </summary>
/// <param name="returnRequest">Return request</param>
public virtual void DeleteReturnRequest(ReturnRequest returnRequest)
{
if (returnRequest == null)
throw new ArgumentNullException("returnRequest");
_returnRequestRepository.Delete(returnRequest);
//event notification
_eventPublisher.EntityDeleted(returnRequest);
}
/// <summary>
/// Gets a return request
/// </summary>
/// <param name="returnRequestId">Return request identifier</param>
/// <returns>Return request</returns>
public virtual ReturnRequest GetReturnRequestById(int returnRequestId)
{
if (returnRequestId == 0)
return null;
return _returnRequestRepository.GetById(returnRequestId);
}
/// <summary>
/// Search return requests
/// </summary>
/// <param name="storeId">Store identifier; 0 to load all entries</param>
/// <param name="customerId">Customer identifier; null to load all entries</param>
/// <param name="orderItemId">Order item identifier; 0 to load all entries</param>
/// <param name="rs">Return request status; null to load all entries</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <returns>Return requests</returns>
public virtual IPagedList<ReturnRequest> SearchReturnRequests(int storeId, int customerId,
int orderItemId, ReturnRequestStatus? rs, int pageIndex, int pageSize)
{
var query = _returnRequestRepository.Table;
if (storeId > 0)
query = query.Where(rr => storeId == rr.StoreId);
if (customerId > 0)
query = query.Where(rr => customerId == rr.CustomerId);
if (rs.HasValue)
{
int returnStatusId = (int)rs.Value;
query = query.Where(rr => rr.ReturnRequestStatusId == returnStatusId);
}
if (orderItemId > 0)
query = query.Where(rr => rr.OrderItemId == orderItemId);
query = query.OrderByDescending(rr => rr.CreatedOnUtc).ThenByDescending(rr=>rr.Id);
var returnRequests = new PagedList<ReturnRequest>(query, pageIndex, pageSize);
return returnRequests;
}
#endregion
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.Reflection;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// Factory for locating methods.
/// </summary>
internal class MethodFactory : INamedItemFactory<MethodInfo, MethodInfo>, INamedItemFactory<ReflectionHelpers.LateBoundMethod, MethodInfo>, IFactory
{
private readonly Dictionary<string, MethodInfo> _nameToMethodInfo = new Dictionary<string, MethodInfo>();
private readonly Dictionary<string, ReflectionHelpers.LateBoundMethod> _nameToLateBoundMethod = new Dictionary<string, ReflectionHelpers.LateBoundMethod>();
private readonly Func<Type, IList<KeyValuePair<string, MethodInfo>>> _methodExtractor;
/// <summary>
/// Initializes a new instance of the <see cref="MethodFactory"/> class.
/// </summary>
/// <param name="methodExtractor">Helper method to extract relevant methods from type</param>
public MethodFactory(Func<Type, IList<KeyValuePair<string, MethodInfo>>> methodExtractor)
{
_methodExtractor = methodExtractor;
}
/// <summary>
/// Scans the assembly for classes marked with expected class <see cref="Attribute"/>
/// and methods marked with expected <see cref="NameBaseAttribute"/> and adds them
/// to the factory.
/// </summary>
/// <param name="types">The types to scan.</param>
/// <param name="prefix">The prefix to use for names.</param>
public void ScanTypes(Type[] types, string prefix)
{
foreach (Type t in types)
{
try
{
if (t.IsClass() || t.IsAbstract())
{
RegisterType(t, prefix);
}
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Failed to add type '{0}'.", t.FullName);
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
/// <summary>
/// Registers the type.
/// </summary>
/// <param name="type">The type to register.</param>
/// <param name="itemNamePrefix">The item name prefix.</param>
public void RegisterType(Type type, string itemNamePrefix)
{
var extractedMethods = _methodExtractor(type);
if (extractedMethods?.Count > 0)
{
for (int i = 0; i < extractedMethods.Count; ++i)
{
RegisterDefinition(itemNamePrefix + extractedMethods[i].Key, extractedMethods[i].Value);
}
}
}
/// <summary>
/// Scans a type for relevant methods with their symbolic names
/// </summary>
/// <typeparam name="TClassAttributeType">Include types that are marked with this attribute</typeparam>
/// <typeparam name="TMethodAttributeType">Include methods that are marked with this attribute</typeparam>
/// <param name="type">Class Type to scan</param>
/// <returns>Collection of methods with their symbolic names</returns>
public static IList<KeyValuePair<string, MethodInfo>> ExtractClassMethods<TClassAttributeType, TMethodAttributeType>(Type type)
where TClassAttributeType : Attribute
where TMethodAttributeType : NameBaseAttribute
{
if (!type.IsDefined(typeof(TClassAttributeType), false))
return ArrayHelper.Empty<KeyValuePair<string, MethodInfo>>();
var conditionMethods = new List<KeyValuePair<string, MethodInfo>>();
foreach (MethodInfo mi in type.GetMethods())
{
var methodAttributes = (TMethodAttributeType[])mi.GetCustomAttributes(typeof(TMethodAttributeType), false);
foreach (var attr in methodAttributes)
{
conditionMethods.Add(new KeyValuePair<string, MethodInfo>(attr.Name, mi));
}
}
return conditionMethods;
}
/// <summary>
/// Clears contents of the factory.
/// </summary>
public void Clear()
{
_nameToMethodInfo.Clear();
lock (_nameToLateBoundMethod)
_nameToLateBoundMethod.Clear();
}
/// <summary>
/// Registers the definition of a single method.
/// </summary>
/// <param name="itemName">The method name.</param>
/// <param name="itemDefinition">The method info.</param>
public void RegisterDefinition(string itemName, MethodInfo itemDefinition)
{
_nameToMethodInfo[itemName] = itemDefinition;
lock (_nameToLateBoundMethod)
_nameToLateBoundMethod.Remove(itemName);
}
/// <summary>
/// Registers the definition of a single method.
/// </summary>
/// <param name="itemName">The method name.</param>
/// <param name="itemDefinition">The method info.</param>
/// <param name="lateBoundMethod">The precompiled method delegate.</param>
internal void RegisterDefinition(string itemName, MethodInfo itemDefinition, ReflectionHelpers.LateBoundMethod lateBoundMethod)
{
_nameToMethodInfo[itemName] = itemDefinition;
lock (_nameToLateBoundMethod)
_nameToLateBoundMethod[itemName] = lateBoundMethod;
}
/// <summary>
/// Tries to retrieve method by name.
/// </summary>
/// <param name="itemName">The method name.</param>
/// <param name="result">The result.</param>
/// <returns>A value of <c>true</c> if the method was found, <c>false</c> otherwise.</returns>
public bool TryCreateInstance(string itemName, out MethodInfo result)
{
return _nameToMethodInfo.TryGetValue(itemName, out result);
}
/// <summary>
/// Tries to retrieve method-delegate by name.
/// </summary>
/// <param name="itemName">The method name.</param>
/// <param name="result">The result.</param>
/// <returns>A value of <c>true</c> if the method was found, <c>false</c> otherwise.</returns>
public bool TryCreateInstance(string itemName, out ReflectionHelpers.LateBoundMethod result)
{
lock (_nameToLateBoundMethod)
{
if (_nameToLateBoundMethod.TryGetValue(itemName, out result))
{
return true;
}
}
if (_nameToMethodInfo.TryGetValue(itemName, out var methodInfo))
{
result = ReflectionHelpers.CreateLateBoundMethod(methodInfo);
lock (_nameToLateBoundMethod)
_nameToLateBoundMethod[itemName] = result;
return true;
}
return false;
}
/// <summary>
/// Retrieves method by name.
/// </summary>
/// <param name="itemName">Method name.</param>
/// <returns>MethodInfo object.</returns>
MethodInfo INamedItemFactory<MethodInfo, MethodInfo>.CreateInstance(string itemName)
{
if (TryCreateInstance(itemName, out MethodInfo result))
{
return result;
}
throw new NLogConfigurationException($"Unknown function: '{itemName}'");
}
/// <summary>
/// Retrieves method by name.
/// </summary>
/// <param name="itemName">Method name.</param>
/// <returns>Method delegate object.</returns>
public ReflectionHelpers.LateBoundMethod CreateInstance(string itemName)
{
if (TryCreateInstance(itemName, out ReflectionHelpers.LateBoundMethod result))
{
return result;
}
throw new NLogConfigurationException($"Unknown function: '{itemName}'");
}
/// <summary>
/// Tries to get method definition.
/// </summary>
/// <param name="itemName">The method name.</param>
/// <param name="result">The result.</param>
/// <returns>A value of <c>true</c> if the method was found, <c>false</c> otherwise.</returns>
public bool TryGetDefinition(string itemName, out MethodInfo result)
{
return _nameToMethodInfo.TryGetValue(itemName, out result);
}
}
}
| |
//
// PrimarySource.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Jobs;
using Hyena.Data;
using Hyena.Query;
using Hyena.Data.Sqlite;
using Hyena.Collections;
using Banshee.Base;
using Banshee.Preferences;
using Banshee.ServiceStack;
using Banshee.Configuration;
using Banshee.Sources;
using Banshee.Playlist;
using Banshee.SmartPlaylist;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Query;
namespace Banshee.Sources
{
public class TrackEventArgs : EventArgs
{
private DateTime when;
public DateTime When {
get { return when; }
}
private QueryField [] changed_fields;
public QueryField [] ChangedFields {
get { return changed_fields; }
}
public TrackEventArgs ()
{
when = DateTime.Now;
}
public TrackEventArgs (params QueryField [] fields) : this ()
{
changed_fields = fields;
}
}
public delegate bool TrackEqualHandler (DatabaseTrackInfo a, TrackInfo b);
public delegate object TrackExternalObjectHandler (DatabaseTrackInfo a);
public delegate string TrackArtworkIdHandler (DatabaseTrackInfo a);
public abstract class PrimarySource : DatabaseSource, IDisposable
{
#region Functions that let us override some behavior of our DatabaseTrackInfos
public TrackEqualHandler TrackEqualHandler { get; protected set; }
public TrackInfo.IsPlayingHandler TrackIsPlayingHandler { get; protected set; }
public TrackExternalObjectHandler TrackExternalObjectHandler { get; protected set; }
public TrackArtworkIdHandler TrackArtworkIdHandler { get; protected set; }
#endregion
protected ErrorSource error_source;
protected bool error_source_visible = false;
protected string remove_range_sql = @"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri)
SELECT ?, TrackID, " + BansheeQuery.UriField.Column + @"
FROM CoreTracks WHERE TrackID IN (SELECT {0});
DELETE FROM CoreTracks WHERE TrackID IN (SELECT {0})";
protected HyenaSqliteCommand remove_list_command = new HyenaSqliteCommand (String.Format (@"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri)
SELECT ?, TrackID, {0} FROM CoreTracks WHERE TrackID IN (SELECT ItemID FROM CoreCache WHERE ModelID = ?);
DELETE FROM CoreTracks WHERE TrackID IN (SELECT ItemID FROM CoreCache WHERE ModelID = ?)
", BansheeQuery.UriField.Column));
protected HyenaSqliteCommand prune_artists_albums_command = new HyenaSqliteCommand (@"
DELETE FROM CoreAlbums WHERE AlbumID NOT IN (SELECT AlbumID FROM CoreTracks);
DELETE FROM CoreArtists WHERE
NOT EXISTS (SELECT 1 FROM CoreTracks WHERE CoreTracks.ArtistID = CoreArtists.ArtistID)
AND NOT EXISTS (SELECT 1 FROM CoreAlbums WHERE CoreAlbums.ArtistID = CoreArtists.ArtistID)
");
protected HyenaSqliteCommand purge_tracks_command = new HyenaSqliteCommand (@"
DELETE FROM CoreTracks WHERE PrimarySourceId = ?
");
private SchemaEntry<bool> expanded_schema;
public SchemaEntry<bool> ExpandedSchema {
get { return expanded_schema; }
}
private int dbid;
public int DbId {
get {
if (dbid > 0) {
return dbid;
}
dbid = ServiceManager.DbConnection.Query<int> ("SELECT PrimarySourceID FROM CorePrimarySources WHERE StringID = ?", UniqueId);
if (dbid == 0) {
dbid = ServiceManager.DbConnection.Execute ("INSERT INTO CorePrimarySources (StringID, IsTemporary) VALUES (?, ?)", UniqueId, IsTemporary);
} else {
SavedCount = ServiceManager.DbConnection.Query<int> ("SELECT CachedCount FROM CorePrimarySources WHERE PrimarySourceID = ?", dbid);
IsTemporary = ServiceManager.DbConnection.Query<bool> ("SELECT IsTemporary FROM CorePrimarySources WHERE PrimarySourceID = ?", dbid);
}
if (dbid == 0) {
throw new ApplicationException ("dbid could not be resolved, this should never happen");
}
return dbid;
}
}
private bool supports_playlists = true;
public virtual bool SupportsPlaylists {
get { return supports_playlists; }
protected set { supports_playlists = value; }
}
public virtual bool PlaylistsReadOnly {
get { return false; }
}
public ErrorSource ErrorSource {
get {
if (error_source == null) {
error_source = new ErrorSource (Catalog.GetString ("Errors"));
ErrorSource.Updated += OnErrorSourceUpdated;
OnErrorSourceUpdated (null, null);
}
return error_source;
}
}
private bool is_local = false;
public bool IsLocal {
get { return is_local; }
protected set { is_local = value; }
}
private static SourceSortType[] sort_types = new SourceSortType[] {
SortNameAscending,
SortSizeAscending,
SortSizeDescending
};
public override SourceSortType[] ChildSortTypes {
get { return sort_types; }
}
public override SourceSortType DefaultChildSort {
get { return SortNameAscending; }
}
public delegate void TrackEventHandler (Source sender, TrackEventArgs args);
public event TrackEventHandler TracksAdded;
public event TrackEventHandler TracksChanged;
public event TrackEventHandler TracksDeleted;
private static Dictionary<int, PrimarySource> primary_sources = new Dictionary<int, PrimarySource> ();
public static PrimarySource GetById (int id)
{
return (primary_sources.ContainsKey (id)) ? primary_sources[id] : null;
}
public virtual string BaseDirectory {
get { return null; }
protected set { base_dir_with_sep = null; }
}
private string base_dir_with_sep;
public string BaseDirectoryWithSeparator {
get { return base_dir_with_sep ?? (base_dir_with_sep = BaseDirectory + System.IO.Path.DirectorySeparatorChar); }
}
protected PrimarySource (string generic_name, string name, string id, int order) : this (generic_name, name, id, order, false)
{
}
protected PrimarySource (string generic_name, string name, string id, int order, bool is_temp) : base (generic_name, name, id, order)
{
Properties.SetString ("SortChildrenActionLabel", Catalog.GetString ("Sort Playlists By"));
IsTemporary = is_temp;
PrimarySourceInitialize ();
}
protected PrimarySource () : base ()
{
}
// Translators: this is a noun, referring to the harddisk
private string storage_name = Catalog.GetString ("Drive");
public string StorageName {
get { return storage_name; }
protected set { storage_name = value; }
}
public override bool? AutoExpand {
get { return ExpandedSchema.Get (); }
}
public override bool Expanded {
get { return ExpandedSchema.Get (); }
set {
ExpandedSchema.Set (value);
base.Expanded = value;
}
}
public PathPattern PathPattern { get; private set; }
protected void SetFileNamePattern (PathPattern pattern)
{
PathPattern = pattern;
var file_system = PreferencesPage.FindOrAdd (new Section ("file-system", Catalog.GetString ("File Organization"), 5));
file_system.Add (new SchemaPreference<string> (pattern.FolderSchema, Catalog.GetString ("Folder hie_rarchy")));
file_system.Add (new SchemaPreference<string> (pattern.FileSchema, Catalog.GetString ("File _name")));
}
public virtual void Dispose ()
{
PurgeSelfIfTemporary ();
if (Application.ShuttingDown)
return;
DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null && track.PrimarySourceId == this.DbId) {
ServiceManager.PlayerEngine.Close ();
}
ClearChildSources ();
Remove ();
}
protected override void Initialize ()
{
base.Initialize ();
PrimarySourceInitialize ();
}
private void PrimarySourceInitialize ()
{
// Scope the tracks to this primary source
DatabaseTrackModel.AddCondition (String.Format ("CoreTracks.PrimarySourceID = {0}", DbId));
primary_sources[DbId] = this;
// If there was a crash, tracks can be left behind, for example in DaapSource.
// Temporary playlists are cleaned up by the PlaylistSource.LoadAll call below
if (IsTemporary && SavedCount > 0) {
PurgeTracks ();
}
// Load our playlists and smart playlists
foreach (PlaylistSource pl in PlaylistSource.LoadAll (this)) {
AddChildSource (pl);
}
int sp_count = 0;
foreach (SmartPlaylistSource pl in SmartPlaylistSource.LoadAll (this)) {
AddChildSource (pl);
sp_count++;
}
// Create default smart playlists if we haven't done it ever before, and if the
// user has zero smart playlists.
if (!HaveCreatedSmartPlaylists) {
if (sp_count == 0) {
foreach (SmartPlaylistDefinition def in DefaultSmartPlaylists) {
SmartPlaylistSource pl = def.ToSmartPlaylistSource (this);
pl.Save ();
AddChildSource (pl);
pl.RefreshAndReload ();
sp_count++;
}
}
// Only save it if we already had some smart playlists, or we actually created some (eg not
// if we didn't have any and the list of default ones is empty atm).
if (sp_count > 0)
HaveCreatedSmartPlaylists = true;
}
expanded_schema = new SchemaEntry<bool> (
String.Format ("sources.{0}", ParentConfigurationId), "expanded", true, "Is source expanded", "Is source expanded"
);
}
private bool HaveCreatedSmartPlaylists {
get { return DatabaseConfigurationClient.Client.Get<bool> ("HaveCreatedSmartPlaylists", UniqueId, false); }
set { DatabaseConfigurationClient.Client.Set<bool> ("HaveCreatedSmartPlaylists", UniqueId, value); }
}
public override void Save ()
{
ServiceManager.DbConnection.Execute (
"UPDATE CorePrimarySources SET CachedCount = ? WHERE PrimarySourceID = ?",
Count, DbId
);
}
public virtual void UpdateMetadata (DatabaseTrackInfo track)
{
}
public virtual void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
Log.WarningFormat ("CopyTrackTo not implemented for source {0}", this);
}
internal void NotifyTracksAdded ()
{
OnTracksAdded ();
}
internal void NotifyTracksChanged (params QueryField [] fields)
{
OnTracksChanged (fields);
}
// TODO replace this public method with a 'transaction'-like system
public void NotifyTracksChanged ()
{
OnTracksChanged ();
}
public void NotifyTracksDeleted ()
{
OnTracksDeleted ();
}
protected void OnErrorSourceUpdated (object o, EventArgs args)
{
lock (error_source) {
if (error_source.Count > 0 && !error_source_visible) {
error_source_visible = true;
AddChildSource (error_source);
} else if (error_source.Count <= 0 && error_source_visible) {
error_source_visible = false;
RemoveChildSource (error_source);
}
}
}
public virtual IEnumerable<SmartPlaylistDefinition> DefaultSmartPlaylists {
get { yield break; }
}
public virtual IEnumerable<SmartPlaylistDefinition> NonDefaultSmartPlaylists {
get { yield break; }
}
public IEnumerable<SmartPlaylistDefinition> PredefinedSmartPlaylists {
get {
foreach (SmartPlaylistDefinition def in DefaultSmartPlaylists)
yield return def;
foreach (SmartPlaylistDefinition def in NonDefaultSmartPlaylists)
yield return def;
}
}
public override bool CanSearch {
get { return true; }
}
protected override void OnTracksAdded ()
{
ThreadAssist.SpawnFromMain (delegate {
Reload ();
TrackEventHandler handler = TracksAdded;
if (handler != null) {
handler (this, new TrackEventArgs ());
}
});
}
protected override void OnTracksChanged (params QueryField [] fields)
{
ThreadAssist.SpawnFromMain (delegate {
if (NeedsReloadWhenFieldsChanged (fields)) {
Reload ();
} else {
InvalidateCaches ();
}
System.Threading.Thread.Sleep (150);
TrackEventHandler handler = TracksChanged;
if (handler != null) {
handler (this, new TrackEventArgs (fields));
}
});
}
protected override void OnTracksDeleted ()
{
ThreadAssist.SpawnFromMain (delegate {
PruneArtistsAlbums ();
Reload ();
TrackEventHandler handler = TracksDeleted;
if (handler != null) {
handler (this, new TrackEventArgs ());
}
SkipTrackIfRemoved ();
});
}
protected override void OnTracksRemoved ()
{
OnTracksDeleted ();
}
protected virtual void PurgeSelfIfTemporary ()
{
if (!IsTemporary) {
return;
}
PlaylistSource.ClearTemporary (this);
PurgeTracks ();
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
DELETE FROM CorePrimarySources WHERE PrimarySourceId = ?"),
DbId);
}
protected virtual void PurgeTracks ()
{
ServiceManager.DbConnection.Execute (purge_tracks_command, DbId);
}
protected override void RemoveTrackRange (DatabaseTrackListModel model, RangeCollection.Range range)
{
ServiceManager.DbConnection.Execute (
String.Format (remove_range_sql, model.TrackIdsSql),
DateTime.Now,
model.CacheId, range.Start, range.End - range.Start + 1,
model.CacheId, range.Start, range.End - range.Start + 1
);
}
public void DeleteAllTracks (AbstractPlaylistSource source)
{
if (source.PrimarySource != this) {
Log.WarningFormat ("Cannot delete all tracks from {0} via primary source {1}", source, this);
return;
}
if (source.Count < 1)
return;
var list = CachedList<DatabaseTrackInfo>.CreateFromModel (source.DatabaseTrackModel);
ThreadAssist.SpawnFromMain (delegate {
DeleteTrackList (list);
});
}
public override void DeleteTracks (DatabaseTrackListModel model, Selection selection)
{
if (model == null || model.Count < 1) {
return;
}
var list = CachedList<DatabaseTrackInfo>.CreateFromModelAndSelection (model, selection);
ThreadAssist.SpawnFromMain (delegate {
DeleteTrackList (list);
});
}
protected virtual void DeleteTrackList (CachedList<DatabaseTrackInfo> list)
{
is_deleting = true;
DeleteTrackJob.Total += list.Count;
List<DatabaseTrackInfo> skip_deletion = null;
// Remove from file system
foreach (DatabaseTrackInfo track in list) {
if (track == null) {
DeleteTrackJob.Completed++;
continue;
}
try {
DeleteTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
if (!DeleteTrack (track)) {
if (skip_deletion == null) {
skip_deletion = new List<DatabaseTrackInfo> ();
}
skip_deletion.Add (track);
}
} catch (Exception e) {
Log.Exception (e);
ErrorSource.AddMessage (e.Message, track.Uri.ToString ());
}
DeleteTrackJob.Completed++;
if (DeleteTrackJob.Completed % 10 == 0 && !DeleteTrackJob.IsFinished) {
OnTracksDeleted ();
}
}
is_deleting = false;
if (DeleteTrackJob.Total == DeleteTrackJob.Completed) {
delete_track_job.Finish ();
delete_track_job = null;
}
if (skip_deletion != null) {
list.Remove (skip_deletion);
skip_deletion.Clear ();
skip_deletion = null;
}
// Remove from database
if (list.Count > 0) {
ServiceManager.DbConnection.Execute (remove_list_command, DateTime.Now, list.CacheId, list.CacheId);
}
ThreadAssist.ProxyToMain (delegate {
OnTracksDeleted ();
OnUserNotifyUpdated ();
OnUpdated ();
});
}
protected virtual bool DeleteTrack (DatabaseTrackInfo track)
{
if (!track.Uri.IsLocalPath)
throw new Exception ("Cannot delete a non-local resource: " + track.Uri.Scheme);
try {
Banshee.IO.Utilities.DeleteFileTrimmingParentDirectories (track.Uri);
} catch (System.IO.FileNotFoundException) {
} catch (System.IO.DirectoryNotFoundException) {
}
return true;
}
public override bool AcceptsInputFromSource (Source source)
{
return base.AcceptsInputFromSource (source) && source.Parent != this
&& (source.Parent is PrimarySource || source is PrimarySource)
&& !(source.Parent is Banshee.Library.LibrarySource);
}
public override bool AddSelectedTracks (Source source, Selection selection)
{
if (!AcceptsInputFromSource (source))
return false;
DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel;
// Store a snapshot of the current selection
CachedList<DatabaseTrackInfo> cached_list = CachedList<DatabaseTrackInfo>.CreateFromModelAndSelection (model, selection);
if (ThreadAssist.InMainThread) {
System.Threading.ThreadPool.QueueUserWorkItem (AddTrackList, cached_list);
} else {
AddTrackList (cached_list);
}
return true;
}
public int GetTrackIdForUri (string uri)
{
return DatabaseTrackInfo.GetTrackIdForUri (new SafeUri (uri), DbId);
}
private bool is_adding;
public bool IsAdding {
get { return is_adding; }
}
private bool is_deleting;
public bool IsDeleting {
get { return is_deleting; }
}
protected virtual void AddTrackAndIncrementCount (DatabaseTrackInfo track)
{
AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
AddTrack (track);
IncrementAddedTracks ();
}
protected virtual void AddTrackList (object cached_list)
{
CachedList<DatabaseTrackInfo> list = cached_list as CachedList<DatabaseTrackInfo>;
is_adding = true;
AddTrackJob.Total += list.Count;
foreach (DatabaseTrackInfo track in list) {
if (AddTrackJob.IsCancelRequested) {
AddTrackJob.Finish ();
IncrementAddedTracks ();
break;
}
if (track == null) {
IncrementAddedTracks ();
continue;
}
try {
AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
AddTrackAndIncrementCount (track);
} catch (Exception e) {
IncrementAddedTracks ();
Log.Exception (e);
ErrorSource.AddMessage (e.Message, track.Uri.ToString ());
}
}
if (!AddTrackJob.IsFinished) {
AddTrackJob.Finish ();
}
add_track_job = null;
is_adding = false;
}
protected void IncrementAddedTracks ()
{
bool finished = false, notify = false;
lock (this) {
add_track_job.Completed++;
if (add_track_job.IsFinished) {
finished = true;
} else {
if (add_track_job.Completed % 10 == 0)
notify = true;
}
}
if (finished) {
is_adding = false;
}
if (notify || finished) {
OnTracksAdded ();
if (finished) {
ThreadAssist.ProxyToMain (OnUserNotifyUpdated);
}
}
}
private bool delay_add_job = true;
protected bool DelayAddJob {
get { return delay_add_job; }
set { delay_add_job = value; }
}
private bool delay_delete_job = true;
protected bool DelayDeleteJob {
get { return delay_delete_job; }
set { delay_delete_job = value; }
}
private BatchUserJob add_track_job;
protected BatchUserJob AddTrackJob {
get {
lock (this) {
if (add_track_job == null) {
add_track_job = new BatchUserJob (String.Format (Catalog.GetString (
"Adding {0} of {1} to {2}"), "{0}", "{1}", Name),
Properties.GetStringList ("Icon.Name"));
add_track_job.SetResources (Resource.Cpu, Resource.Database, Resource.Disk);
add_track_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped;
add_track_job.DelayShow = DelayAddJob;
add_track_job.CanCancel = true;
add_track_job.Register ();
}
}
return add_track_job;
}
}
private BatchUserJob delete_track_job;
protected BatchUserJob DeleteTrackJob {
get {
lock (this) {
if (delete_track_job == null) {
delete_track_job = new BatchUserJob (String.Format (Catalog.GetString (
"Deleting {0} of {1} From {2}"), "{0}", "{1}", Name),
Properties.GetStringList ("Icon.Name"));
delete_track_job.SetResources (Resource.Cpu, Resource.Database);
delete_track_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped;
delete_track_job.DelayShow = DelayDeleteJob;
delete_track_job.Register ();
}
}
return delete_track_job;
}
}
protected override void PruneArtistsAlbums ()
{
ServiceManager.DbConnection.Execute (prune_artists_albums_command);
base.PruneArtistsAlbums ();
DatabaseAlbumInfo.Reset ();
DatabaseArtistInfo.Reset ();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.Azure.Management.WebSites;
using Microsoft.Azure.Management.WebSites.Models;
using Microsoft.Rest;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Microsoft.Azure.Test.HttpRecorder;
using WebSites.Tests.Helpers;
using Xunit;
namespace WebSites.Tests.ScenarioTests
{
public class WebSiteScenarioTests : TestBase
{
private delegate void WebsiteTestDelegate(string webSiteName, string resourceGroupName, string webHostingPlanName, string location, WebSiteManagementClient webSitesClient, ResourceManagementClient resourcesClient);
[Fact]
public void CreateAndVerifyGetOnAWebsite()
{
RunWebsiteTestScenario(
(webSiteName, resourceGroupName, whpName, locationName, webSitesClient, resourcesClient) =>
{
var webSite = webSitesClient.WebApps.Get(resourceGroupName, webSiteName);
Assert.Equal(webSiteName, webSite.Name);
var serverfarmId = ResourceGroupHelper.GetServerFarmId(webSitesClient.SubscriptionId,
resourceGroupName, whpName);
Assert.Equal(serverfarmId, webSite.ServerFarmId, StringComparer.OrdinalIgnoreCase);
Assert.Equal("value1", webSite.Tags["tag1"]);
Assert.Equal("", webSite.Tags["tag2"]);
Assert.NotNull(webSite.HostNameSslStates);
Assert.NotEmpty(webSite.HostNameSslStates);
});
}
[Fact]
public void CreateAndVerifyListOfWebsites()
{
RunWebsiteTestScenario(
(webSiteName, resourceGroupName, whpName, locationName, webSitesClient, resourcesClient) =>
{
var webSites = webSitesClient.WebApps.ListByResourceGroup(resourceGroupName, null);
Assert.Equal(1, webSites.Count());
Assert.Equal(webSiteName, webSites.ToList()[0].Name);
var serverfarmId = ResourceGroupHelper.GetServerFarmId(webSitesClient.SubscriptionId,
resourceGroupName, whpName);
Assert.Equal(serverfarmId, webSites.ToList()[0].ServerFarmId, StringComparer.OrdinalIgnoreCase);
});
}
[Fact]
public void CreateAndDeleteWebsite()
{
RunWebsiteTestScenario(
(webSiteName, resourceGroupName, whpName, locationName, webSitesClient, resourcesClient) =>
{
#region Start/Stop website
webSitesClient.WebApps.Stop(resourceGroupName, webSiteName);
var getWebSiteResponse = webSitesClient.WebApps.Get(resourceGroupName, webSiteName);
Assert.NotNull(getWebSiteResponse);
Assert.Equal(getWebSiteResponse.State, "Stopped");
webSitesClient.WebApps.Start(resourceGroupName, webSiteName);
getWebSiteResponse = webSitesClient.WebApps.Get(resourceGroupName, webSiteName);
Assert.NotNull(getWebSiteResponse);
Assert.Equal(getWebSiteResponse.State, "Running");
#endregion Start/Stop website
webSitesClient.WebApps.Delete(resourceGroupName, webSiteName, null);
var webSites = webSitesClient.WebApps.ListByResourceGroup(resourceGroupName);
Assert.Equal(0, webSites.Count());
});
}
[Fact]
public void GetAndSetNonSensitiveSiteConfigs()
{
RunWebsiteTestScenario(
(siteName, resourceGroupName, whpName, locationName, webSitesClient, resourcesClient) =>
{
#region Get/Set PythonVersion
var configurationResponse = webSitesClient.WebApps.GetConfiguration(resourceGroupName,
siteName);
Assert.NotNull(configurationResponse);
Assert.True(string.IsNullOrEmpty(configurationResponse.PythonVersion));
var configurationParameters = new SiteConfigResource
{
PythonVersion = "3.4"
};
var operationResponse = webSitesClient.WebApps.UpdateConfiguration(resourceGroupName,
siteName, configurationParameters);
configurationResponse = webSitesClient.WebApps.GetConfiguration(resourceGroupName, siteName);
Assert.NotNull(configurationResponse);
Assert.Equal(configurationResponse.PythonVersion, configurationParameters.PythonVersion);
#endregion Get/Set PythonVersion
});
}
[Fact]
public void GetAndSetSensitiveSiteConfigs()
{
RunWebsiteTestScenario(
(siteName, resourceGroupName, whpName, locationName, webSitesClient, resourcesClient) =>
{
#region Get/Set Application settings
const string settingName = "Application Setting1", settingValue = "Setting Value 1";
var appSetting = new StringDictionary { Properties = new Dictionary<string, string> { { settingName, settingValue} } };
var appSettingsResponse = webSitesClient.WebApps.UpdateApplicationSettings(
resourceGroupName,
siteName,
appSetting);
Assert.NotNull(appSettingsResponse);
Assert.True(appSettingsResponse.Properties.Contains(new KeyValuePair<string, string>(settingName, settingValue)));
appSettingsResponse = webSitesClient.WebApps.ListApplicationSettings(resourceGroupName, siteName);
Assert.NotNull(appSettingsResponse);
Assert.True(appSettingsResponse.Properties.Contains(new KeyValuePair<string, string>(settingName, settingValue)));
#endregion Get/Set Application settings
#region Get/Set Metadata
const string metadataName = "Metadata 1", metadataValue = "Metadata Value 1";
var metadata = new StringDictionary { Properties = new Dictionary<string, string> { { metadataName, metadataValue } } };
var metadataResponse = webSitesClient.WebApps.UpdateMetadata(
resourceGroupName,
siteName,
metadata);
Assert.NotNull(metadataResponse);
Assert.True(metadataResponse.Properties.Contains(new KeyValuePair<string, string>(metadataName, metadataValue)));
metadataResponse = webSitesClient.WebApps.ListMetadata(resourceGroupName, siteName);
Assert.NotNull(metadataResponse);
Assert.True(metadataResponse.Properties.Contains(new KeyValuePair<string, string>(metadataName, metadataValue)));
#endregion Get/Set Metadata
#region Get/Set Connection strings
const string connectionStringName = "ConnectionString 1",
connectionStringValue = "ConnectionString Value 1";
var connStringValueTypePair = new ConnStringValueTypePair
{
Value = connectionStringValue,
Type = ConnectionStringType.MySql
};
var connectionStringResponse = webSitesClient.WebApps.UpdateConnectionStrings(
resourceGroupName,
siteName,
new ConnectionStringDictionary { Properties = new Dictionary<string, ConnStringValueTypePair> { { connectionStringName, connStringValueTypePair } } });
Assert.NotNull(connectionStringResponse);
Assert.True(connectionStringResponse.Properties.Contains(new KeyValuePair<string, ConnStringValueTypePair>(connectionStringName, connStringValueTypePair), new ConnectionStringComparer()));
connectionStringResponse = webSitesClient.WebApps.ListConnectionStrings(resourceGroupName, siteName);
Assert.NotNull(connectionStringResponse);
Assert.True(connectionStringResponse.Properties.Contains(new KeyValuePair<string, ConnStringValueTypePair>(connectionStringName, connStringValueTypePair), new ConnectionStringComparer()));
#endregion Get/Set Connection strings
#region Get Publishing credentials
var credentialsResponse = webSitesClient.WebApps.ListPublishingCredentials(resourceGroupName, siteName);
Assert.NotNull(credentialsResponse);
Assert.Equal("$" + siteName, credentialsResponse.PublishingUserName);
Assert.NotNull(credentialsResponse.PublishingPassword);
#endregion Get Publishing credentials
#region Get Publishing profile XML
var publishingProfileResponse = webSitesClient.WebApps.ListPublishingProfileXmlWithSecrets(resourceGroupName, siteName, new CsmPublishingProfileOptions() { Format = "WebDeploy" });
Assert.NotNull(publishingProfileResponse);
var doc = XDocument.Load(publishingProfileResponse, LoadOptions.None);
Assert.NotNull(doc);
#endregion Get Publishing profile XML
webSitesClient.WebApps.Delete(resourceGroupName, siteName, deleteMetrics: true);
webSitesClient.AppServicePlans.Delete(resourceGroupName, whpName);
});
}
[Fact]
public void GetAndSetSlotSettingsConfigs()
{
RunWebsiteTestScenario(
(siteName, resourceGroupName, whpName, locationName, webSitesClient, resourcesClient) =>
{
#region Get/Set slot settings
const string setting1Name = "AppSetting1", setting2Name = "AppSetting2";
const string connection1Name = "ConnString1", connection2Name = "ConnString2";
webSitesClient.WebApps.UpdateSlotConfigurationNames(
resourceGroupName,
siteName,
new SlotConfigNamesResource()
{
AppSettingNames = new List<string> { setting1Name, setting2Name },
ConnectionStringNames = new List<string> { connection1Name, connection2Name },
});
var response = webSitesClient.WebApps.ListSlotConfigurationNames(resourceGroupName, siteName);
Assert.NotNull(response);
Assert.NotNull(response.AppSettingNames);
var appSettingsNames = response.AppSettingNames;
Assert.Single(appSettingsNames.Where(a => a == setting1Name));
Assert.Single(appSettingsNames.Where(a => a == setting2Name));
Assert.NotNull(response.ConnectionStringNames);
var connectionStringNames = response.ConnectionStringNames;
Assert.Single(connectionStringNames.Where(a => a == connection1Name));
Assert.Single(connectionStringNames.Where(a => a == connection2Name));
#endregion Get/Set slot settings
webSitesClient.WebApps.Delete(resourceGroupName, siteName, deleteMetrics: true);
webSitesClient.AppServicePlans.Delete(resourceGroupName, whpName);
});
}
[Fact(Skip = "Failing on GitHubProxy GetWebHookInfo")]
public void LinkAndUnlinkSourceControlToWebsiteShouldSucceed()
{
/*
RunWebsiteTestScenario(
(webSiteName, resourceGroupName, whpName, locationName, webSitesClient, resourcesClient) =>
{
var gitHubSourceControl = new SourceControl()
{
SourceControlName = "GitHub",
Token = "36c7290f81fda5877d52d2fc3fbc7c31acd25051",
Location = locationName
};
webSitesClient.Provider.UpdateSourceControl(gitHubSourceControl.SourceControlName, gitHubSourceControl);
var siteSourceControlUpdateResponse =
webSitesClient.WebApps.UpdateSiteSourceControl(
resourceGroupName,
webSiteName,
new SiteSourceControl() { RepoUrl = "https://github.com/amitaptest/HelloKudu"});
Assert.Equal("https://github.com/amitaptest/HelloKudu", siteSourceControlUpdateResponse.RepoUrl);
var operationResponse =
webSitesClient.WebApps.DeleteSiteSourceControl(
resourceGroupName,
webSiteName);
});
*/
}
private void RunWebsiteTestScenario(WebsiteTestDelegate testAction, string skuTier = "Shared", string skuName = "D1",
[System.Runtime.CompilerServices.CallerMemberName]
string methodName= "testframework_failed")
{
using (var context = MockContext.Start(this.GetType(), methodName))
{
var webSitesClient = this.GetWebSiteManagementClient(context);
var resourcesClient = this.GetResourceManagementClient(context);
var webSiteName = TestUtilities.GenerateName("csmws");
var resourceGroupName = TestUtilities.GenerateName("csmrg");
var webHostingPlanName = TestUtilities.GenerateName("csmwhp");
var location = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites");
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
var serverFarm = webSitesClient.AppServicePlans.CreateOrUpdate(resourceGroupName, webHostingPlanName,
new AppServicePlan()
{
Location = location,
Sku = new SkuDescription()
{
Name = skuName,
Tier = skuTier
}
});
var webSite = webSitesClient.WebApps.CreateOrUpdate(resourceGroupName, webSiteName, new Site
{
Location = location,
Tags = new Dictionary<string, string> { { "tag1", "value1" }, { "tag2", "" } },
ServerFarmId = serverFarm.Id
});
Assert.Equal(webSiteName, webSite.Name);
Assert.Equal(serverFarm.Id, webSite.ServerFarmId, StringComparer.OrdinalIgnoreCase);
Assert.Equal("value1", webSite.Tags["tag1"]);
Assert.Equal("", webSite.Tags["tag2"]);
testAction(webSiteName, resourceGroupName, webHostingPlanName, location, webSitesClient, resourcesClient);
}
}
[Fact]
public void GetAndSetSiteLimits()
{
using (var context = MockContext.Start(this.GetType()))
{
var webSitesClient = this.GetWebSiteManagementClient(context);
var resourcesClient = this.GetResourceManagementClient(context);
var whpName = TestUtilities.GenerateName("cswhp");
var resourceGroupName = TestUtilities.GenerateName("csmrg");
var serverfarmId = ResourceGroupHelper.GetServerFarmId(webSitesClient.SubscriptionId,
resourceGroupName, whpName);
var locationName = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites");
var siteName = TestUtilities.GenerateName("csmws");
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = locationName
});
webSitesClient.AppServicePlans.CreateOrUpdate(resourceGroupName, whpName, new AppServicePlan()
{
Location = locationName,
Sku = new SkuDescription
{
Name = "D1",
Tier = "Shared",
Capacity = 1
}
});
var createResponse = webSitesClient.WebApps.CreateOrUpdate(resourceGroupName, siteName, new Site
{
Location = locationName,
ServerFarmId = serverfarmId
});
#region Get/Set Site limits
var expectedSitelimits = new SiteLimits()
{
MaxDiskSizeInMb = 512,
MaxMemoryInMb = 1024,
MaxPercentageCpu = 70.5
};
var siteConfig = new SiteConfigResource
{
Limits = expectedSitelimits
};
webSitesClient.WebApps.UpdateConfiguration(
resourceGroupName,
siteName,
siteConfig);
var siteGetConfigResponse = webSitesClient.WebApps.GetConfiguration(resourceGroupName, siteName);
Assert.NotNull(siteGetConfigResponse);
var limits = siteGetConfigResponse.Limits;
Assert.NotNull(limits);
Assert.Equal(expectedSitelimits.MaxDiskSizeInMb, limits.MaxDiskSizeInMb);
Assert.Equal(expectedSitelimits.MaxMemoryInMb, limits.MaxMemoryInMb);
Assert.Equal(expectedSitelimits.MaxPercentageCpu, limits.MaxPercentageCpu);
#endregion Get/Set Site limits
webSitesClient.WebApps.Delete(resourceGroupName, siteName, deleteMetrics: true);
webSitesClient.AppServicePlans.Delete(resourceGroupName, whpName);
}
}
[Fact(Skip = "Test failing due to test issue. Needs further investigation")]
//[Fact]
public void CloneSite()
{
RunWebsiteTestScenario(
(webSiteName, resourceGroupName, whpName, locationName, webSitesClient, resourcesClient) =>
{
string targetSiteName = TestUtilities.GenerateName("csmws");
string location = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites");
var webAppIdFormat = "/subscriptions/{0}/resourcegroups/{1}/providers/Microsoft.Web/sites/{2}";
var serverFarmIdFormat = "/subscriptions/{0}/resourcegroups/{1}/providers/Microsoft.Web/serverfarms/{2}";
var site = new Site()
{
Location = "West US",
ServerFarmId = string.Format(serverFarmIdFormat, webSitesClient.SubscriptionId, resourceGroupName, whpName),
CloningInfo = new CloningInfo()
{
SourceWebAppId = string.Format(webAppIdFormat, webSitesClient.SubscriptionId, resourceGroupName, webSiteName),
}
};
ServiceClientTracing.IsEnabled = true;
var operationResponse = webSitesClient.WebApps.CreateOrUpdate(resourceGroupName, targetSiteName, site);
ServiceClientTracing.IsEnabled = false;
}, "Premium", "P1");
}
private Guid ParseOperationIdFromLocation(string location)
{
var locationSplit = location.Split('/');
Assert.NotEmpty(locationSplit);
Guid operationId;
Assert.True(Guid.TryParse(locationSplit.Last(), out operationId));
return operationId;
}
private void WaitForOperationCompletion(double timeOutInSeconds, double timeIntervalInMilliSeconds, string operationName, Func<HttpStatusCode> operationToCall)
{
DateTime endTime = DateTime.Now.AddSeconds(timeOutInSeconds);
double interval = timeIntervalInMilliSeconds;
HttpStatusCode status = HttpStatusCode.Accepted;
while (status == HttpStatusCode.Accepted && DateTime.Now < endTime)
{
status = operationToCall();
if (DateTime.Now.AddMilliseconds(interval) > endTime)
{
interval = (endTime - DateTime.Now).TotalMilliseconds;
}
Thread.Sleep((int)interval);
}
switch (status)
{
case HttpStatusCode.Accepted:
throw new Exception(string.Format("Timed out waiting on operation {0} after {1} s", operationName, timeIntervalInMilliSeconds));
case HttpStatusCode.OK:
return;
default:
throw new Exception(string.Format("Operation {0} was not successful. Status {1}", operationName, status.ToString()));
}
}
}
class ConnectionStringComparer : IEqualityComparer<KeyValuePair<string, ConnStringValueTypePair>>
{
public bool Equals(KeyValuePair<string, ConnStringValueTypePair> x, KeyValuePair<string, ConnStringValueTypePair> y)
{
return string.Equals(x.Key, y.Key, StringComparison.OrdinalIgnoreCase) &&
string.Equals(x.Value.Value, y.Value.Value, StringComparison.OrdinalIgnoreCase) && x.Value.Type == y.Value.Type;
}
public int GetHashCode(KeyValuePair<string, ConnStringValueTypePair> obj)
{
return obj.Key.GetHashCode() ^ obj.Value.Type.GetHashCode() ^ obj.Value.Value.GetHashCode();
}
}
}
| |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Transports.InMemory
{
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Logging;
using Pipeline;
using Util;
/// <summary>
/// Support in-memory message queue that is not durable, but supports parallel delivery of messages
/// based on TPL usage.
/// </summary>
public class InMemoryTransport :
IReceiveTransport,
ISendTransport,
IDisposable
{
static readonly ILog _log = Logger.Get<InMemoryTransport>();
readonly ReceiveEndpointObservable _endpointObservable;
readonly Uri _inputAddress;
readonly ITaskParticipant _participant;
readonly ReceiveObservable _receiveObservable;
readonly LimitedConcurrencyLevelTaskScheduler _scheduler;
readonly SendObservable _sendObservable;
readonly TaskSupervisor _supervisor;
int _currentPendingDeliveryCount;
long _deliveryCount;
int _maxPendingDeliveryCount;
IPipe<ReceiveContext> _receivePipe;
public InMemoryTransport(Uri inputAddress, int concurrencyLimit)
{
_inputAddress = inputAddress;
_sendObservable = new SendObservable();
_receiveObservable = new ReceiveObservable();
_endpointObservable = new ReceiveEndpointObservable();
_supervisor = new TaskSupervisor($"{TypeMetadataCache<InMemoryTransport>.ShortName} - {_inputAddress}");
_participant = _supervisor.CreateParticipant($"{TypeMetadataCache<InMemoryTransport>.ShortName} - {_inputAddress}");
_scheduler = new LimitedConcurrencyLevelTaskScheduler(concurrencyLimit);
}
public void Dispose()
{
_participant.SetComplete();
TaskUtil.Await(() => _supervisor.Stop("Disposed"));
TaskUtil.Await(() => _supervisor.Completed);
}
public void Probe(ProbeContext context)
{
var scope = context.CreateScope("transport");
scope.Set(new
{
Address = _inputAddress
});
}
ReceiveTransportHandle IReceiveTransport.Start(IPipe<ReceiveContext> receivePipe)
{
try
{
_receivePipe = receivePipe;
TaskUtil.Await(() => _endpointObservable.Ready(new Ready(_inputAddress)));
_participant.SetReady();
return new Handle(_supervisor, _participant, this);
}
catch (Exception exception)
{
_participant.SetNotReady(exception);
throw;
}
}
public ConnectHandle ConnectReceiveObserver(IReceiveObserver observer)
{
return _receiveObservable.Connect(observer);
}
public ConnectHandle ConnectReceiveEndpointObserver(IReceiveEndpointObserver observer)
{
return _endpointObservable.Connect(observer);
}
async Task ISendTransport.Send<T>(T message, IPipe<SendContext<T>> pipe, CancellationToken cancelSend)
{
var context = new InMemorySendContext<T>(message, cancelSend);
try
{
await pipe.Send(context).ConfigureAwait(false);
var messageId = context.MessageId ?? NewId.NextGuid();
await _sendObservable.PreSend(context).ConfigureAwait(false);
var transportMessage = new InMemoryTransportMessage(messageId, context.Body, context.ContentType.MediaType, TypeMetadataCache<T>.ShortName);
#pragma warning disable 4014
Task.Factory.StartNew(() => DispatchMessage(transportMessage), _supervisor.StoppedToken, TaskCreationOptions.HideScheduler, _scheduler);
#pragma warning restore 4014
context.DestinationAddress.LogSent(context.MessageId?.ToString("N") ?? "", TypeMetadataCache<T>.ShortName);
await _sendObservable.PostSend(context).ConfigureAwait(false);
}
catch (Exception ex)
{
_log.Error($"SEND FAULT: {_inputAddress} {context.MessageId} {TypeMetadataCache<T>.ShortName}", ex);
await _sendObservable.SendFault(context, ex).ConfigureAwait(false);
throw;
}
}
async Task ISendTransport.Move(ReceiveContext context, IPipe<SendContext> pipe)
{
var messageId = GetMessageId(context);
byte[] body;
using (var bodyStream = context.GetBody())
{
body = await GetMessageBody(bodyStream).ConfigureAwait(false);
}
var messageType = "Unknown";
InMemoryTransportMessage receivedMessage;
if (context.TryGetPayload(out receivedMessage))
messageType = receivedMessage.MessageType;
var transportMessage = new InMemoryTransportMessage(messageId, body, context.ContentType.MediaType, messageType);
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Factory.StartNew(() => DispatchMessage(transportMessage), _supervisor.StoppedToken, TaskCreationOptions.HideScheduler, _scheduler);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
Task ISendTransport.Close()
{
// an in-memory send transport does not get disposed
return TaskUtil.Completed;
}
public ConnectHandle ConnectSendObserver(ISendObserver observer)
{
return _sendObservable.Connect(observer);
}
async Task DispatchMessage(InMemoryTransportMessage message)
{
await _supervisor.Ready.ConfigureAwait(false);
if (_supervisor.StoppedToken.IsCancellationRequested)
return;
if (_receivePipe == null)
throw new ArgumentException("ReceivePipe not configured");
var context = new InMemoryReceiveContext(_inputAddress, message, _receiveObservable);
Interlocked.Increment(ref _deliveryCount);
var current = Interlocked.Increment(ref _currentPendingDeliveryCount);
while (current > _maxPendingDeliveryCount)
Interlocked.CompareExchange(ref _maxPendingDeliveryCount, current, _maxPendingDeliveryCount);
try
{
await _receiveObservable.PreReceive(context).ConfigureAwait(false);
await _receivePipe.Send(context).ConfigureAwait(false);
await context.CompleteTask.ConfigureAwait(false);
await _receiveObservable.PostReceive(context).ConfigureAwait(false);
_inputAddress.LogReceived(message.MessageId.ToString("N"), message.MessageType);
}
catch (Exception ex)
{
_log.Error($"RCV FAULT: {message.MessageId}", ex);
await _receiveObservable.ReceiveFault(context, ex).ConfigureAwait(false);
message.DeliveryCount++;
}
finally
{
Interlocked.Decrement(ref _currentPendingDeliveryCount);
}
}
async Task<byte[]> GetMessageBody(Stream body)
{
using (var ms = new MemoryStream())
{
await body.CopyToAsync(ms).ConfigureAwait(false);
return ms.ToArray();
}
}
static Guid GetMessageId(ReceiveContext context)
{
object messageIdValue;
return context.TransportHeaders.TryGetHeader("MessageId", out messageIdValue)
? new Guid(messageIdValue.ToString())
: NewId.NextGuid();
}
class Handle :
ReceiveTransportHandle
{
readonly ITaskParticipant _participant;
readonly TaskSupervisor _supervisor;
readonly InMemoryTransport _transport;
public Handle(TaskSupervisor supervisor, ITaskParticipant participant, InMemoryTransport transport)
{
_supervisor = supervisor;
_participant = participant;
_transport = transport;
}
async Task ReceiveTransportHandle.Stop(CancellationToken cancellationToken)
{
_participant.SetComplete();
await _supervisor.Stop("Stopped").ConfigureAwait(false);
await _supervisor.Completed.ConfigureAwait(false);
await _transport._endpointObservable.Completed(new Completed(_transport._inputAddress, _transport._deliveryCount,
_transport._maxPendingDeliveryCount)).ConfigureAwait(false);
}
}
class Ready :
ReceiveEndpointReady
{
public Ready(Uri inputAddress)
{
InputAddress = inputAddress;
}
public Uri InputAddress { get; }
}
class Completed :
ReceiveEndpointCompleted
{
public Completed(Uri inputAddress, long deliveryCount, long concurrentDeliveryCount)
{
InputAddress = inputAddress;
DeliveryCount = deliveryCount;
ConcurrentDeliveryCount = concurrentDeliveryCount;
}
public Uri InputAddress { get; }
public long DeliveryCount { get; }
public long ConcurrentDeliveryCount { get; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Xml;
using System.Collections;
using System.Diagnostics;
namespace System.Runtime.Serialization
{
internal static class XmlFormatGeneratorStatics
{
private static MethodInfo s_writeStartElementMethod2;
internal static MethodInfo WriteStartElementMethod2
{
get
{
if (s_writeStartElementMethod2 == null)
{
s_writeStartElementMethod2 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
Debug.Assert(s_writeStartElementMethod2 != null);
}
return s_writeStartElementMethod2;
}
}
private static MethodInfo s_writeStartElementMethod3;
internal static MethodInfo WriteStartElementMethod3
{
get
{
if (s_writeStartElementMethod3 == null)
{
s_writeStartElementMethod3 = typeof(XmlWriterDelegator).GetMethod("WriteStartElement", Globals.ScanAllMembers, new Type[] { typeof(string), typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
Debug.Assert(s_writeStartElementMethod3 != null);
}
return s_writeStartElementMethod3;
}
}
private static MethodInfo s_writeEndElementMethod;
internal static MethodInfo WriteEndElementMethod
{
get
{
if (s_writeEndElementMethod == null)
{
s_writeEndElementMethod = typeof(XmlWriterDelegator).GetMethod("WriteEndElement", Globals.ScanAllMembers, Array.Empty<Type>());
Debug.Assert(s_writeEndElementMethod != null);
}
return s_writeEndElementMethod;
}
}
private static MethodInfo s_writeNamespaceDeclMethod;
internal static MethodInfo WriteNamespaceDeclMethod
{
get
{
if (s_writeNamespaceDeclMethod == null)
{
s_writeNamespaceDeclMethod = typeof(XmlWriterDelegator).GetMethod("WriteNamespaceDecl", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString) });
Debug.Assert(s_writeNamespaceDeclMethod != null);
}
return s_writeNamespaceDeclMethod;
}
}
private static PropertyInfo s_extensionDataProperty;
internal static PropertyInfo ExtensionDataProperty => s_extensionDataProperty ??
(s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData"));
private static ConstructorInfo s_dictionaryEnumeratorCtor;
internal static ConstructorInfo DictionaryEnumeratorCtor
{
get
{
if (s_dictionaryEnumeratorCtor == null)
s_dictionaryEnumeratorCtor = Globals.TypeOfDictionaryEnumerator.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator });
return s_dictionaryEnumeratorCtor;
}
}
private static MethodInfo s_ienumeratorMoveNextMethod;
internal static MethodInfo MoveNextMethod
{
get
{
if (s_ienumeratorMoveNextMethod == null)
{
s_ienumeratorMoveNextMethod = typeof(IEnumerator).GetMethod("MoveNext");
Debug.Assert(s_ienumeratorMoveNextMethod != null);
}
return s_ienumeratorMoveNextMethod;
}
}
private static MethodInfo s_ienumeratorGetCurrentMethod;
internal static MethodInfo GetCurrentMethod
{
get
{
if (s_ienumeratorGetCurrentMethod == null)
{
s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetGetMethod();
Debug.Assert(s_ienumeratorGetCurrentMethod != null);
}
return s_ienumeratorGetCurrentMethod;
}
}
private static MethodInfo s_getItemContractMethod;
internal static MethodInfo GetItemContractMethod
{
get
{
if (s_getItemContractMethod == null)
{
s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers).GetMethod;
Debug.Assert(s_getItemContractMethod != null);
}
return s_getItemContractMethod;
}
}
private static MethodInfo s_isStartElementMethod2;
internal static MethodInfo IsStartElementMethod2
{
get
{
if (s_isStartElementMethod2 == null)
{
s_isStartElementMethod2 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, new Type[] { typeof(XmlDictionaryString), typeof(XmlDictionaryString) });
Debug.Assert(s_isStartElementMethod2 != null);
}
return s_isStartElementMethod2;
}
}
private static MethodInfo s_isStartElementMethod0;
internal static MethodInfo IsStartElementMethod0
{
get
{
if (s_isStartElementMethod0 == null)
{
s_isStartElementMethod0 = typeof(XmlReaderDelegator).GetMethod("IsStartElement", Globals.ScanAllMembers, Array.Empty<Type>());
Debug.Assert(s_isStartElementMethod0 != null);
}
return s_isStartElementMethod0;
}
}
private static MethodInfo s_getUninitializedObjectMethod;
internal static MethodInfo GetUninitializedObjectMethod
{
get
{
if (s_getUninitializedObjectMethod == null)
{
s_getUninitializedObjectMethod = typeof(XmlFormatReaderGenerator).GetMethod("UnsafeGetUninitializedObject", Globals.ScanAllMembers, new Type[] { typeof(int) });
Debug.Assert(s_getUninitializedObjectMethod != null);
}
return s_getUninitializedObjectMethod;
}
}
private static MethodInfo s_onDeserializationMethod;
internal static MethodInfo OnDeserializationMethod
{
get
{
if (s_onDeserializationMethod == null)
s_onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization");
return s_onDeserializationMethod;
}
}
private static PropertyInfo s_nodeTypeProperty;
internal static PropertyInfo NodeTypeProperty
{
get
{
if (s_nodeTypeProperty == null)
{
s_nodeTypeProperty = typeof(XmlReaderDelegator).GetProperty("NodeType", Globals.ScanAllMembers);
Debug.Assert(s_nodeTypeProperty != null);
}
return s_nodeTypeProperty;
}
}
private static ConstructorInfo s_extensionDataObjectCtor;
internal static ConstructorInfo ExtensionDataObjectCtor => s_extensionDataObjectCtor ??
(s_extensionDataObjectCtor =
typeof (ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, new Type[] {}, null));
private static ConstructorInfo s_hashtableCtor;
internal static ConstructorInfo HashtableCtor
{
get
{
if (s_hashtableCtor == null)
s_hashtableCtor = Globals.TypeOfHashtable.GetConstructor(Globals.ScanAllMembers, Array.Empty<Type>());
return s_hashtableCtor;
}
}
private static MethodInfo s_getStreamingContextMethod;
internal static MethodInfo GetStreamingContextMethod
{
get
{
if (s_getStreamingContextMethod == null)
{
s_getStreamingContextMethod = typeof(XmlObjectSerializerContext).GetMethod("GetStreamingContext", Globals.ScanAllMembers);
Debug.Assert(s_getStreamingContextMethod != null);
}
return s_getStreamingContextMethod;
}
}
private static MethodInfo s_getCollectionMemberMethod;
internal static MethodInfo GetCollectionMemberMethod
{
get
{
if (s_getCollectionMemberMethod == null)
{
s_getCollectionMemberMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetCollectionMember", Globals.ScanAllMembers);
Debug.Assert(s_getCollectionMemberMethod != null);
}
return s_getCollectionMemberMethod;
}
}
private static MethodInfo s_storeCollectionMemberInfoMethod;
internal static MethodInfo StoreCollectionMemberInfoMethod
{
get
{
if (s_storeCollectionMemberInfoMethod == null)
{
s_storeCollectionMemberInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("StoreCollectionMemberInfo", Globals.ScanAllMembers, new Type[] { typeof(object) });
Debug.Assert(s_storeCollectionMemberInfoMethod != null);
}
return s_storeCollectionMemberInfoMethod;
}
}
private static MethodInfo s_resetCollectionMemberInfoMethod;
internal static MethodInfo ResetCollectionMemberInfoMethod
{
get
{
if (s_resetCollectionMemberInfoMethod == null)
{
s_resetCollectionMemberInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ResetCollectionMemberInfo", Globals.ScanAllMembers, new Type[] { });
Debug.Assert(s_resetCollectionMemberInfoMethod != null);
}
return s_resetCollectionMemberInfoMethod;
}
}
private static MethodInfo s_storeIsGetOnlyCollectionMethod;
internal static MethodInfo StoreIsGetOnlyCollectionMethod
{
get
{
if (s_storeIsGetOnlyCollectionMethod == null)
{
s_storeIsGetOnlyCollectionMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("StoreIsGetOnlyCollection", Globals.ScanAllMembers);
Debug.Assert(s_storeIsGetOnlyCollectionMethod != null);
}
return s_storeIsGetOnlyCollectionMethod;
}
}
private static MethodInfo s_resetIsGetOnlyCollection;
internal static MethodInfo ResetIsGetOnlyCollectionMethod
{
get
{
if (s_resetIsGetOnlyCollection == null)
{
s_resetIsGetOnlyCollection = typeof(XmlObjectSerializerWriteContext).GetMethod("ResetIsGetOnlyCollection", Globals.ScanAllMembers);
Debug.Assert(s_resetIsGetOnlyCollection != null);
}
return s_resetIsGetOnlyCollection;
}
}
private static MethodInfo s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod;
internal static MethodInfo ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod
{
get
{
if (s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod == null)
{
s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowNullValueReturnedForGetOnlyCollectionException", Globals.ScanAllMembers);
Debug.Assert(s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod != null);
}
return s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod;
}
}
private static MethodInfo s_throwArrayExceededSizeExceptionMethod;
internal static MethodInfo ThrowArrayExceededSizeExceptionMethod
{
get
{
if (s_throwArrayExceededSizeExceptionMethod == null)
{
s_throwArrayExceededSizeExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowArrayExceededSizeException", Globals.ScanAllMembers);
Debug.Assert(s_throwArrayExceededSizeExceptionMethod != null);
}
return s_throwArrayExceededSizeExceptionMethod;
}
}
private static MethodInfo s_incrementItemCountMethod;
internal static MethodInfo IncrementItemCountMethod
{
get
{
if (s_incrementItemCountMethod == null)
{
s_incrementItemCountMethod = typeof(XmlObjectSerializerContext).GetMethod("IncrementItemCount", Globals.ScanAllMembers);
Debug.Assert(s_incrementItemCountMethod != null);
}
return s_incrementItemCountMethod;
}
}
private static MethodInfo s_internalDeserializeMethod;
internal static MethodInfo InternalDeserializeMethod
{
get
{
if (s_internalDeserializeMethod == null)
{
s_internalDeserializeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("InternalDeserialize", Globals.ScanAllMembers, new Type[] { typeof(XmlReaderDelegator), typeof(int), typeof(RuntimeTypeHandle), typeof(string), typeof(string) });
Debug.Assert(s_internalDeserializeMethod != null);
}
return s_internalDeserializeMethod;
}
}
private static MethodInfo s_moveToNextElementMethod;
internal static MethodInfo MoveToNextElementMethod
{
get
{
if (s_moveToNextElementMethod == null)
{
s_moveToNextElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("MoveToNextElement", Globals.ScanAllMembers);
Debug.Assert(s_moveToNextElementMethod != null);
}
return s_moveToNextElementMethod;
}
}
private static MethodInfo s_getMemberIndexMethod;
internal static MethodInfo GetMemberIndexMethod
{
get
{
if (s_getMemberIndexMethod == null)
{
s_getMemberIndexMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndex", Globals.ScanAllMembers);
Debug.Assert(s_getMemberIndexMethod != null);
}
return s_getMemberIndexMethod;
}
}
private static MethodInfo s_getMemberIndexWithRequiredMembersMethod;
internal static MethodInfo GetMemberIndexWithRequiredMembersMethod
{
get
{
if (s_getMemberIndexWithRequiredMembersMethod == null)
{
s_getMemberIndexWithRequiredMembersMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetMemberIndexWithRequiredMembers", Globals.ScanAllMembers);
Debug.Assert(s_getMemberIndexWithRequiredMembersMethod != null);
}
return s_getMemberIndexWithRequiredMembersMethod;
}
}
private static MethodInfo s_throwRequiredMemberMissingExceptionMethod;
internal static MethodInfo ThrowRequiredMemberMissingExceptionMethod
{
get
{
if (s_throwRequiredMemberMissingExceptionMethod == null)
{
s_throwRequiredMemberMissingExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ThrowRequiredMemberMissingException", Globals.ScanAllMembers);
Debug.Assert(s_throwRequiredMemberMissingExceptionMethod != null);
}
return s_throwRequiredMemberMissingExceptionMethod;
}
}
private static MethodInfo s_skipUnknownElementMethod;
internal static MethodInfo SkipUnknownElementMethod
{
get
{
if (s_skipUnknownElementMethod == null)
{
s_skipUnknownElementMethod = typeof(XmlObjectSerializerReadContext).GetMethod("SkipUnknownElement", Globals.ScanAllMembers);
Debug.Assert(s_skipUnknownElementMethod != null);
}
return s_skipUnknownElementMethod;
}
}
private static MethodInfo s_readIfNullOrRefMethod;
internal static MethodInfo ReadIfNullOrRefMethod
{
get
{
if (s_readIfNullOrRefMethod == null)
{
s_readIfNullOrRefMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadIfNullOrRef", Globals.ScanAllMembers, new Type[] { typeof(XmlReaderDelegator), typeof(Type), typeof(bool) });
Debug.Assert(s_readIfNullOrRefMethod != null);
}
return s_readIfNullOrRefMethod;
}
}
private static MethodInfo s_readAttributesMethod;
internal static MethodInfo ReadAttributesMethod
{
get
{
if (s_readAttributesMethod == null)
{
s_readAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadAttributes", Globals.ScanAllMembers);
Debug.Assert(s_readAttributesMethod != null);
}
return s_readAttributesMethod;
}
}
private static MethodInfo s_resetAttributesMethod;
internal static MethodInfo ResetAttributesMethod
{
get
{
if (s_resetAttributesMethod == null)
{
s_resetAttributesMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ResetAttributes", Globals.ScanAllMembers);
Debug.Assert(s_resetAttributesMethod != null);
}
return s_resetAttributesMethod;
}
}
private static MethodInfo s_getObjectIdMethod;
internal static MethodInfo GetObjectIdMethod
{
get
{
if (s_getObjectIdMethod == null)
{
s_getObjectIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetObjectId", Globals.ScanAllMembers);
Debug.Assert(s_getObjectIdMethod != null);
}
return s_getObjectIdMethod;
}
}
private static MethodInfo s_getArraySizeMethod;
internal static MethodInfo GetArraySizeMethod
{
get
{
if (s_getArraySizeMethod == null)
{
s_getArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetArraySize", Globals.ScanAllMembers);
Debug.Assert(s_getArraySizeMethod != null);
}
return s_getArraySizeMethod;
}
}
private static MethodInfo s_addNewObjectMethod;
internal static MethodInfo AddNewObjectMethod
{
get
{
if (s_addNewObjectMethod == null)
{
s_addNewObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObject", Globals.ScanAllMembers);
Debug.Assert(s_addNewObjectMethod != null);
}
return s_addNewObjectMethod;
}
}
private static MethodInfo s_addNewObjectWithIdMethod;
internal static MethodInfo AddNewObjectWithIdMethod
{
get
{
if (s_addNewObjectWithIdMethod == null)
{
s_addNewObjectWithIdMethod = typeof(XmlObjectSerializerReadContext).GetMethod("AddNewObjectWithId", Globals.ScanAllMembers);
Debug.Assert(s_addNewObjectWithIdMethod != null);
}
return s_addNewObjectWithIdMethod;
}
}
private static MethodInfo s_getExistingObjectMethod;
internal static MethodInfo GetExistingObjectMethod
{
get
{
if (s_getExistingObjectMethod == null)
{
s_getExistingObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetExistingObject", Globals.ScanAllMembers);
Debug.Assert(s_getExistingObjectMethod != null);
}
return s_getExistingObjectMethod;
}
}
private static MethodInfo s_getRealObjectMethod;
internal static MethodInfo GetRealObjectMethod
{
get
{
if (s_getRealObjectMethod == null)
s_getRealObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetRealObject", Globals.ScanAllMembers);
return s_getRealObjectMethod;
}
}
private static MethodInfo s_ensureArraySizeMethod;
internal static MethodInfo EnsureArraySizeMethod
{
get
{
if (s_ensureArraySizeMethod == null)
{
s_ensureArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("EnsureArraySize", Globals.ScanAllMembers);
Debug.Assert(s_ensureArraySizeMethod != null);
}
return s_ensureArraySizeMethod;
}
}
private static MethodInfo s_trimArraySizeMethod;
internal static MethodInfo TrimArraySizeMethod
{
get
{
if (s_trimArraySizeMethod == null)
{
s_trimArraySizeMethod = typeof(XmlObjectSerializerReadContext).GetMethod("TrimArraySize", Globals.ScanAllMembers);
Debug.Assert(s_trimArraySizeMethod != null);
}
return s_trimArraySizeMethod;
}
}
private static MethodInfo s_checkEndOfArrayMethod;
internal static MethodInfo CheckEndOfArrayMethod
{
get
{
if (s_checkEndOfArrayMethod == null)
{
s_checkEndOfArrayMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CheckEndOfArray", Globals.ScanAllMembers);
Debug.Assert(s_checkEndOfArrayMethod != null);
}
return s_checkEndOfArrayMethod;
}
}
private static MethodInfo s_getArrayLengthMethod;
internal static MethodInfo GetArrayLengthMethod
{
get
{
if (s_getArrayLengthMethod == null)
{
s_getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length").GetMethod;
Debug.Assert(s_getArrayLengthMethod != null);
}
return s_getArrayLengthMethod;
}
}
private static MethodInfo s_createSerializationExceptionMethod;
internal static MethodInfo CreateSerializationExceptionMethod
{
get
{
if (s_createSerializationExceptionMethod == null)
{
s_createSerializationExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateSerializationException", Globals.ScanAllMembers, new Type[] { typeof(string) });
Debug.Assert(s_createSerializationExceptionMethod != null);
}
return s_createSerializationExceptionMethod;
}
}
private static MethodInfo s_readSerializationInfoMethod;
internal static MethodInfo ReadSerializationInfoMethod
{
get
{
if (s_readSerializationInfoMethod == null)
s_readSerializationInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadSerializationInfo", Globals.ScanAllMembers);
return s_readSerializationInfoMethod;
}
}
private static MethodInfo s_createUnexpectedStateExceptionMethod;
internal static MethodInfo CreateUnexpectedStateExceptionMethod
{
get
{
if (s_createUnexpectedStateExceptionMethod == null)
{
s_createUnexpectedStateExceptionMethod = typeof(XmlObjectSerializerReadContext).GetMethod("CreateUnexpectedStateException", Globals.ScanAllMembers, new Type[] { typeof(XmlNodeType), typeof(XmlReaderDelegator) });
Debug.Assert(s_createUnexpectedStateExceptionMethod != null);
}
return s_createUnexpectedStateExceptionMethod;
}
}
private static MethodInfo s_internalSerializeReferenceMethod;
internal static MethodInfo InternalSerializeReferenceMethod
{
get
{
if (s_internalSerializeReferenceMethod == null)
{
s_internalSerializeReferenceMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerializeReference", Globals.ScanAllMembers);
Debug.Assert(s_internalSerializeReferenceMethod != null);
}
return s_internalSerializeReferenceMethod;
}
}
private static MethodInfo s_internalSerializeMethod;
internal static MethodInfo InternalSerializeMethod
{
get
{
if (s_internalSerializeMethod == null)
{
s_internalSerializeMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("InternalSerialize", Globals.ScanAllMembers);
Debug.Assert(s_internalSerializeMethod != null);
}
return s_internalSerializeMethod;
}
}
private static MethodInfo s_writeNullMethod;
internal static MethodInfo WriteNullMethod
{
get
{
if (s_writeNullMethod == null)
{
s_writeNullMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteNull", Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), typeof(Type), typeof(bool) });
Debug.Assert(s_writeNullMethod != null);
}
return s_writeNullMethod;
}
}
private static MethodInfo s_incrementArrayCountMethod;
internal static MethodInfo IncrementArrayCountMethod
{
get
{
if (s_incrementArrayCountMethod == null)
{
s_incrementArrayCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementArrayCount", Globals.ScanAllMembers);
Debug.Assert(s_incrementArrayCountMethod != null);
}
return s_incrementArrayCountMethod;
}
}
private static MethodInfo s_incrementCollectionCountMethod;
internal static MethodInfo IncrementCollectionCountMethod
{
get
{
if (s_incrementCollectionCountMethod == null)
{
s_incrementCollectionCountMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCount", Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), typeof(ICollection) });
Debug.Assert(s_incrementCollectionCountMethod != null);
}
return s_incrementCollectionCountMethod;
}
}
private static MethodInfo s_incrementCollectionCountGenericMethod;
internal static MethodInfo IncrementCollectionCountGenericMethod
{
get
{
if (s_incrementCollectionCountGenericMethod == null)
{
s_incrementCollectionCountGenericMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("IncrementCollectionCountGeneric", Globals.ScanAllMembers);
Debug.Assert(s_incrementCollectionCountGenericMethod != null);
}
return s_incrementCollectionCountGenericMethod;
}
}
private static MethodInfo s_getDefaultValueMethod;
internal static MethodInfo GetDefaultValueMethod
{
get
{
if (s_getDefaultValueMethod == null)
{
s_getDefaultValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(nameof(XmlObjectSerializerWriteContext.GetDefaultValue), Globals.ScanAllMembers);
Debug.Assert(s_getDefaultValueMethod != null);
}
return s_getDefaultValueMethod;
}
}
internal static object GetDefaultValue(Type type)
{
return GetDefaultValueMethod.MakeGenericMethod(type).Invoke(null, Array.Empty<object>());
}
private static MethodInfo s_getNullableValueMethod;
internal static MethodInfo GetNullableValueMethod
{
get
{
if (s_getNullableValueMethod == null)
{
s_getNullableValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetNullableValue", Globals.ScanAllMembers);
Debug.Assert(s_getNullableValueMethod != null);
}
return s_getNullableValueMethod;
}
}
private static MethodInfo s_throwRequiredMemberMustBeEmittedMethod;
internal static MethodInfo ThrowRequiredMemberMustBeEmittedMethod
{
get
{
if (s_throwRequiredMemberMustBeEmittedMethod == null)
{
s_throwRequiredMemberMustBeEmittedMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("ThrowRequiredMemberMustBeEmitted", Globals.ScanAllMembers);
Debug.Assert(s_throwRequiredMemberMustBeEmittedMethod != null);
}
return s_throwRequiredMemberMustBeEmittedMethod;
}
}
private static MethodInfo s_getHasValueMethod;
internal static MethodInfo GetHasValueMethod
{
get
{
if (s_getHasValueMethod == null)
{
s_getHasValueMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("GetHasValue", Globals.ScanAllMembers);
Debug.Assert(s_getHasValueMethod != null);
}
return s_getHasValueMethod;
}
}
private static MethodInfo s_writeISerializableMethod;
internal static MethodInfo WriteISerializableMethod
{
get
{
if (s_writeISerializableMethod == null)
s_writeISerializableMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteISerializable", Globals.ScanAllMembers);
return s_writeISerializableMethod;
}
}
private static MethodInfo s_isMemberTypeSameAsMemberValue;
internal static MethodInfo IsMemberTypeSameAsMemberValue
{
get
{
if (s_isMemberTypeSameAsMemberValue == null)
{
s_isMemberTypeSameAsMemberValue = typeof(XmlObjectSerializerWriteContext).GetMethod("IsMemberTypeSameAsMemberValue", Globals.ScanAllMembers, new Type[] { typeof(object), typeof(Type) });
Debug.Assert(s_isMemberTypeSameAsMemberValue != null);
}
return s_isMemberTypeSameAsMemberValue;
}
}
private static MethodInfo s_writeExtensionDataMethod;
internal static MethodInfo WriteExtensionDataMethod => s_writeExtensionDataMethod ??
(s_writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers));
private static MethodInfo s_writeXmlValueMethod;
internal static MethodInfo WriteXmlValueMethod
{
get
{
if (s_writeXmlValueMethod == null)
{
s_writeXmlValueMethod = typeof(DataContract).GetMethod("WriteXmlValue", Globals.ScanAllMembers);
Debug.Assert(s_writeXmlValueMethod != null);
}
return s_writeXmlValueMethod;
}
}
private static MethodInfo s_readXmlValueMethod;
internal static MethodInfo ReadXmlValueMethod
{
get
{
if (s_readXmlValueMethod == null)
{
s_readXmlValueMethod = typeof(DataContract).GetMethod("ReadXmlValue", Globals.ScanAllMembers);
Debug.Assert(s_readXmlValueMethod != null);
}
return s_readXmlValueMethod;
}
}
private static PropertyInfo s_namespaceProperty;
internal static PropertyInfo NamespaceProperty
{
get
{
if (s_namespaceProperty == null)
{
s_namespaceProperty = typeof(DataContract).GetProperty("Namespace", Globals.ScanAllMembers);
Debug.Assert(s_namespaceProperty != null);
}
return s_namespaceProperty;
}
}
private static FieldInfo s_contractNamespacesField;
internal static FieldInfo ContractNamespacesField
{
get
{
if (s_contractNamespacesField == null)
{
s_contractNamespacesField = typeof(ClassDataContract).GetField("ContractNamespaces", Globals.ScanAllMembers);
Debug.Assert(s_contractNamespacesField != null);
}
return s_contractNamespacesField;
}
}
private static FieldInfo s_memberNamesField;
internal static FieldInfo MemberNamesField
{
get
{
if (s_memberNamesField == null)
{
s_memberNamesField = typeof(ClassDataContract).GetField("MemberNames", Globals.ScanAllMembers);
Debug.Assert(s_memberNamesField != null);
}
return s_memberNamesField;
}
}
private static MethodInfo s_extensionDataSetExplicitMethodInfo;
internal static MethodInfo ExtensionDataSetExplicitMethodInfo => s_extensionDataSetExplicitMethodInfo ??
(s_extensionDataSetExplicitMethodInfo = typeof(IExtensibleDataObject).GetMethod(Globals.ExtensionDataSetMethod));
private static PropertyInfo s_childElementNamespacesProperty;
internal static PropertyInfo ChildElementNamespacesProperty
{
get
{
if (s_childElementNamespacesProperty == null)
{
s_childElementNamespacesProperty = typeof(ClassDataContract).GetProperty("ChildElementNamespaces", Globals.ScanAllMembers);
Debug.Assert(s_childElementNamespacesProperty != null);
}
return s_childElementNamespacesProperty;
}
}
private static PropertyInfo s_collectionItemNameProperty;
internal static PropertyInfo CollectionItemNameProperty
{
get
{
if (s_collectionItemNameProperty == null)
{
s_collectionItemNameProperty = typeof(CollectionDataContract).GetProperty("CollectionItemName", Globals.ScanAllMembers);
Debug.Assert(s_collectionItemNameProperty != null);
}
return s_collectionItemNameProperty;
}
}
private static PropertyInfo s_childElementNamespaceProperty;
internal static PropertyInfo ChildElementNamespaceProperty
{
get
{
if (s_childElementNamespaceProperty == null)
{
s_childElementNamespaceProperty = typeof(CollectionDataContract).GetProperty("ChildElementNamespace", Globals.ScanAllMembers);
Debug.Assert(s_childElementNamespaceProperty != null);
}
return s_childElementNamespaceProperty;
}
}
private static MethodInfo s_getDateTimeOffsetMethod;
internal static MethodInfo GetDateTimeOffsetMethod
{
get
{
if (s_getDateTimeOffsetMethod == null)
{
s_getDateTimeOffsetMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffset", Globals.ScanAllMembers);
Debug.Assert(s_getDateTimeOffsetMethod != null);
}
return s_getDateTimeOffsetMethod;
}
}
private static MethodInfo s_getDateTimeOffsetAdapterMethod;
internal static MethodInfo GetDateTimeOffsetAdapterMethod
{
get
{
if (s_getDateTimeOffsetAdapterMethod == null)
{
s_getDateTimeOffsetAdapterMethod = typeof(DateTimeOffsetAdapter).GetMethod("GetDateTimeOffsetAdapter", Globals.ScanAllMembers);
Debug.Assert(s_getDateTimeOffsetAdapterMethod != null);
}
return s_getDateTimeOffsetAdapterMethod;
}
}
#if !uapaot
private static MethodInfo s_getTypeHandleMethod;
internal static MethodInfo GetTypeHandleMethod
{
get
{
if (s_getTypeHandleMethod == null)
{
s_getTypeHandleMethod = typeof(Type).GetMethod("get_TypeHandle");
Debug.Assert(s_getTypeHandleMethod != null);
}
return s_getTypeHandleMethod;
}
}
private static MethodInfo s_getTypeMethod;
internal static MethodInfo GetTypeMethod
{
get
{
if (s_getTypeMethod == null)
{
s_getTypeMethod = typeof(object).GetMethod("GetType");
Debug.Assert(s_getTypeMethod != null);
}
return s_getTypeMethod;
}
}
private static MethodInfo s_throwInvalidDataContractExceptionMethod;
internal static MethodInfo ThrowInvalidDataContractExceptionMethod
{
get
{
if (s_throwInvalidDataContractExceptionMethod == null)
{
s_throwInvalidDataContractExceptionMethod = typeof(DataContract).GetMethod("ThrowInvalidDataContractException", Globals.ScanAllMembers, new Type[] { typeof(string), typeof(Type) });
Debug.Assert(s_throwInvalidDataContractExceptionMethod != null);
}
return s_throwInvalidDataContractExceptionMethod;
}
}
private static PropertyInfo s_serializeReadOnlyTypesProperty;
internal static PropertyInfo SerializeReadOnlyTypesProperty
{
get
{
if (s_serializeReadOnlyTypesProperty == null)
{
s_serializeReadOnlyTypesProperty = typeof(XmlObjectSerializerWriteContext).GetProperty("SerializeReadOnlyTypes", Globals.ScanAllMembers);
Debug.Assert(s_serializeReadOnlyTypesProperty != null);
}
return s_serializeReadOnlyTypesProperty;
}
}
private static PropertyInfo s_classSerializationExceptionMessageProperty;
internal static PropertyInfo ClassSerializationExceptionMessageProperty
{
get
{
if (s_classSerializationExceptionMessageProperty == null)
{
s_classSerializationExceptionMessageProperty = typeof(ClassDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers);
Debug.Assert(s_classSerializationExceptionMessageProperty != null);
}
return s_classSerializationExceptionMessageProperty;
}
}
private static PropertyInfo s_collectionSerializationExceptionMessageProperty;
internal static PropertyInfo CollectionSerializationExceptionMessageProperty
{
get
{
if (s_collectionSerializationExceptionMessageProperty == null)
{
s_collectionSerializationExceptionMessageProperty = typeof(CollectionDataContract).GetProperty("SerializationExceptionMessage", Globals.ScanAllMembers);
Debug.Assert(s_collectionSerializationExceptionMessageProperty != null);
}
return s_collectionSerializationExceptionMessageProperty;
}
}
#endif
}
}
| |
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;
namespace EdiEngine.Standards.X12_004010.Maps
{
public class M_218 : MapLoop
{
public M_218() : base(null)
{
Content.AddRange(new MapBaseEntity[] {
new TF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new G62() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_TS(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_SCL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_SCL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_SCL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
//0100
public class L_N1 : MapLoop
{
public L_N1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new G61() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new N9() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2000
public class L_TS : MapLoop
{
public L_TS(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new TS() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new G62() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
new CL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new WGP() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TFR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new TFM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2100
public class L_SCL : MapLoop
{
public L_SCL(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SCL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new TFM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new RTS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2200
public class L_SCL_1 : MapLoop
{
public L_SCL_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SCL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new TFM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_CL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 25 },
});
}
}
//2210
public class L_CL : MapLoop
{
public L_CL(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new RTS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2300
public class L_LX : MapLoop
{
public L_LX(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new GY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LX_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2310
public class L_LX_1 : MapLoop
{
public L_LX_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new GY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new SCL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TFR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new TFM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new RTS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_SCL_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2320
public class L_SCL_2 : MapLoop
{
public L_SCL_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SCL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new RTS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2400
public class L_LX_2 : MapLoop
{
public L_LX_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new GY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LX_3(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2410
public class L_LX_3 : MapLoop
{
public L_LX_3(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new GY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new L_SCL_3(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9999 },
});
}
}
//2420
public class L_SCL_3 : MapLoop
{
public L_SCL_3(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SCL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new TFR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new TFM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
new L_CL_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999 },
});
}
}
//2430
public class L_CL_1 : MapLoop
{
public L_CL_1(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new RTS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2500
public class L_LX_4 : MapLoop
{
public L_LX_4(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new GY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new SCL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2600
public class L_LX_5 : MapLoop
{
public L_LX_5(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new GY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_LX_6(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2610
public class L_LX_6 : MapLoop
{
public L_LX_6(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new GY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new TFA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TFD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2700
public class L_SCL_4 : MapLoop
{
public L_SCL_4(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new SCL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new LS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new L_CL_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 9999 },
new LE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
});
}
}
//2710
public class L_CL_2 : MapLoop
{
public L_CL_2(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new CL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new TFA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
new TFD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
});
}
}
//2800
public class L_LX_7 : MapLoop
{
public L_LX_7(MapLoop parentLoop) : base(parentLoop)
{
Content.AddRange(new MapBaseEntity[] {
new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
new MCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
new GY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 99 },
});
}
}
}
}
| |
using System;
using System.Text;
using VisualHint.SmartPropertyGrid;
using System.Windows.Forms;
using System.Globalization;
using System.ComponentModel;
using System.Drawing;
using System.Resources;
using System.Reflection;
using System.Collections.Generic;
using System.Xml;
#region Module XML Notes
/// <summary>
//<Module>
//<ModuleInformation>
// <ExecutableName>DataSource</ExecutableName>
//</ModuleInformation>
//<Inputs></Inputs>
//<Outputs></Outputs>
//<Parameters>
// <Parameter>
// <Name>SampleRate</Name>
// <Type>Double</Type>
// <Default>0</Default>
// <Minimum>1</Minimum>
// <Maximum>1000000</Maximum>
// <Units>Hz</Units>
// <Description>Sample rate, in Hertz</Description>
// </Parameter>
//</Module>
// public RunfileModuleDescriptor this[string ModuleName]
//{
// get
// {
// //Search for the Matching moduleName
// foreach (RunfileModuleDescriptor currentModule in theRunfileModuleDescriptors)
// {
// if (currentModule.ModuleInformation.ExecutableName == ModuleName)
// return currentModule;
// }
// throw new IndexOutOfRangeException("The requested module executable \"" + ModuleName + "\" was not found in the Runfile");
// }
//}
// (I-O-P)
// public EarlabParameter this[string ModuleName, string ParamName]
// or
// public EarlabInput this[string InputName]
// public EarlabOutput this[string OutputName]
// maybe data structure has all modules?
/// </summary>
///
#endregion
namespace RunfileEditor
{
//parses module xml into something useful
public class ModuleXML
{
#region Data Members
//1.) (!) Meta info
public ModuleXmlInformation theModuleXmlInformation;
//2.) (?) Inputs
public List<ModuleXmlInput> theModuleXmlInputs;
//3.) (?) Outputs
public List<ModuleXmlOutput> theModuleXmlOutputs;
//4.) (!) Parameters
public List<ModuleXmlParameter> theModuleXmlParameters = new List<ModuleXmlParameter>();
#endregion
//which one is more useful? index on directory at large
//or index at each bit.
//Indexed by Parameter Type, Parameter Name
/// <summary>
///
/// </summary>
/// <param name="ParameterName"></param>
/// <param name="ParameterType"></param>
/// <returns></returns>
#region Data Properties
public ModuleXmlParameter this[string ParameterName, string ParameterType]
{
get
{
foreach (ModuleXmlParameter MXLParameter in theModuleXmlParameters)
{
//Check to see if the name matches
if ( MXLParameter.ParameterName.ToLower() == ParameterName.ToLower() )
{
//if the name matches, check to see if type matches
if (MXLParameter.ParameterType.ToLower() == ParameterType.ToLower())
{
//if ParameterName && ParameterType == true return it.
return MXLParameter;
}
}
}
//Info!!! Bug here
// The requested parameter "intarrayparam, integer[]" was not found in the Module XML
throw new IndexOutOfRangeException("The requested parameter \"" + ParameterName + " , " + ParameterType + "\" was not found in the Module XML");
}
}
#endregion
#region Constructors
//blank constructor
public ModuleXML()
{
//
// TODO: Add constructor logic here
//
}
//Ok this comes in from the EFI --
//EFI says here's the document you want.
public ModuleXML(XmlDocument ModuleXML)
{
//1.) Handle Meta info
//(xml statement)
//theModuleXmlInformation = new ModuleXmlInformation(ModuleXML["ModuleInformation"]);
XmlNodeList XList = ModuleXML.GetElementsByTagName("ModuleInformation");
theModuleXmlInformation = new ModuleXmlInformation(XList[0]);
//2.) Handle I
//(xml statement)
XmlNodeList InList = ModuleXML.GetElementsByTagName("Input");
foreach(XmlNode Input in InList)
{
theModuleXmlInputs.Add(new ModuleXmlInput(Input));
}
//2.) Handle O
//(xml statement)
XmlNodeList OutList = ModuleXML.GetElementsByTagName("Output");
foreach (XmlNode Output in OutList)
{
theModuleXmlOutputs.Add(new ModuleXmlOutput(Output));
}
//2.) Handle P
//(xml statement) //weird error! on second iteration???
XmlNodeList PList = ModuleXML.GetElementsByTagName("Parameter");
foreach (XmlNode Parameter in PList)
{
theModuleXmlParameters.Add(new ModuleXmlParameter(Parameter));
}
}
#endregion
}
//(!) Works just like ModuleInformation.
// end duplicaton or?
public class ModuleXmlInformation
{
/*
<ModuleInformation>
<ExecutableName>DataSource</ExecutableName>
</ModuleInformation
*/
//works just like RunfileInformation
#region Data Members
//public Data
public string ModuleXMLExecutablename;
#endregion
#region Data Properties
public ModuleXmlInformation(XmlNode ModuleInfo)
{
//(xml statement)
ModuleXMLExecutablename = ModuleInfo["ExecutableName"].InnerText;
}
#endregion
}
//(?) needs info
public class ModuleXmlInput
{
//public data
public ModuleXmlInput(XmlNode ModuleInput)
{
}
}
//(?) needs info
public class ModuleXmlOutput
{
//public data
//!!!
public ModuleXmlOutput(XmlNode ModuleOutput)
{
}
}
//(!)works!
public class ModuleXmlParameter
{
#region ModuleXMLParameter Notes
//NEW NOTE!!!
//Store the value Node
//And say if it is an array or not!
/*
<Parameter>
<Name>SampleRate</Name>
<Type>Double</Type>
<Default>0</Default>
<Minimum>1</Minimum>
<Maximum>1000000</Maximum>
<Units>Hz</Units>
<Description>Sample rate, in Hertz</Description>
</Parameter>
*/
/*
integer int from Runfile
<Parameter>
<Name>ChannelNumber</Name>
<Type>Integer</Type>
<Value>0</Value>
</Parameter>
*/
#endregion
#region Data Members
//Public data
public string ParameterName;
public string ParameterType;
public string ParameterUnits;
public string ParameterDescription;
public bool isArray;
//Public Xml Node Data
public XmlNode ParameterDefaultValue;
public XmlNode ParameterMinimumValue;
public XmlNode ParameterMaximumValue;
#endregion
#region Constructors
//--------------------------------->
public ModuleXmlParameter()
{
}
public ModuleXmlParameter(XmlNode ModuleParameterXml)
{
//xml node to vars
//string Values;
//(xml statement)
ParameterUnits = ModuleParameterXml["Units"].InnerText;
ParameterName = ModuleParameterXml["Name"].InnerText;
ParameterType = ModuleParameterXml["Type"].InnerText;
ParameterDescription = ModuleParameterXml["Description"].InnerText;
//basically we need a quick function to strip out all the white space
ParameterType = ParameterType.Replace(" ", "");
ParameterName = ParameterName.Replace(" ", "");
//Do we need to standardize how the ParameterType ends up stored? as the real or Temp?
//I like the idea of standardizing the thing. (?)
//Also, since we are storing this stuff as a string this is an
//Might want to write a static class to help with
//1.) Array types etc, takes a string in, returns a bool value?
if( ParameterType.ToLower() == "integer[]" || ParameterType.ToLower() == "double[]" || ParameterType.ToLower() == "string[]")
{ isArray = true;
XmlNodeList TempValues = ModuleParameterXml["Minimum"].GetElementsByTagName("Value");
ParameterMinimumValue = TempValues[0];
TempValues = ModuleParameterXml["Maximum"].GetElementsByTagName("Value");
ParameterMaximumValue = TempValues[0];
TempValues = ModuleParameterXml["Default"].GetElementsByTagName("Value");
ParameterDefaultValue = TempValues[0];
}
else
{isArray = false;
ParameterMinimumValue = ModuleParameterXml["Minimum"];
ParameterMaximumValue = ModuleParameterXml["Maximum"];
ParameterDefaultValue = ModuleParameterXml["Default"];
}
//add parameter value
//(xml statement)
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public class Directory_Exists : FileSystemTest
{
#region Utilities
public bool Exists(string path)
{
return Directory.Exists(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullAsPath_ReturnsFalse()
{
Assert.False(Exists(null));
}
[Fact]
public void EmptyAsPath_ReturnsFalse()
{
Assert.False(Exists(string.Empty));
}
[Theory,
MemberData(nameof(ValidPathComponentNames))]
public void NonExistentValidPath_ReturnsFalse(string path)
{
Assert.False(Exists(path), path);
}
[Theory,
MemberData(nameof(ValidPathComponentNames))]
public void ValidPathExists_ReturnsTrue(string component)
{
string path = Path.Combine(TestDirectory, component);
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(path));
}
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
public void PathWithInvalidCharactersAsPath_ReturnsFalse(string invalidPath)
{
// Checks that errors aren't thrown when calling Exists() on paths with impossible to create characters
char[] trimmed = { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20, (char)0x85, (char)0xA0 };
Assert.False(Exists(invalidPath));
if (!trimmed.Contains(invalidPath.ToCharArray()[0]))
Assert.False(Exists(TestDirectory + Path.DirectorySeparatorChar + invalidPath));
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Assert.False(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void PathAlreadyExistsAsDirectory()
{
string path = GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void DotAsPath_ReturnsTrue()
{
Assert.True(Exists(Path.Combine(TestDirectory, ".")));
}
[Fact]
public void DirectoryGetCurrentDirectoryAsPath_ReturnsTrue()
{
Assert.True(Exists(Directory.GetCurrentDirectory()));
}
[Fact]
public void DotDotAsPath_ReturnsTrue()
{
Assert.True(Exists(Path.Combine(TestDirectory, GetTestFileName(), "..")));
}
[Fact]
public void DirectoryLongerThanMaxLongPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath())), (path) =>
{
Assert.False(Exists(path), path);
});
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
public void SymLinksMayExistIndependentlyOfTarget()
{
var path = GetTestFilePath();
var linkPath = GetTestFilePath();
Directory.CreateDirectory(path);
Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true));
// Both the symlink and the target exist
Assert.True(Directory.Exists(path), "path should exist");
Assert.True(Directory.Exists(linkPath), "linkPath should exist");
Assert.False(File.Exists(linkPath));
// Delete the target. The symlink should still exist. On Unix, the symlink will now be
// considered a file (since it's broken and we don't know what it'll eventually point to).
Directory.Delete(path);
Assert.False(Directory.Exists(path), "path should now not exist");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.True(Directory.Exists(linkPath), "linkPath should still exist as a directory");
Assert.False(File.Exists(linkPath), "linkPath should not be a file");
}
else
{
Assert.False(Directory.Exists(linkPath), "linkPath should no longer be a directory");
Assert.True(File.Exists(linkPath), "linkPath should now be a file");
}
// Now delete the symlink.
// On Unix, deleting the symlink should fail, because it's not a directory, it's a file.
// On Windows, it should succeed.
try
{
Directory.Delete(linkPath);
Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "Should only succeed on Windows");
}
catch (IOException)
{
Assert.False(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "Should only fail on Unix");
File.Delete(linkPath);
}
Assert.False(Directory.Exists(linkPath), "linkPath should no longer exist as a directory");
Assert.False(File.Exists(linkPath), "linkPath should no longer exist as a file");
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
public void SymlinkToNewDirectory()
{
string path = GetTestFilePath();
Directory.CreateDirectory(path);
string linkPath = GetTestFilePath();
Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true));
Assert.True(Directory.Exists(path));
Assert.True(Directory.Exists(linkPath));
}
#endregion
#region PlatformSpecific
[ConditionalTheory(nameof(UsingNewNormalization)),
MemberData(nameof(ValidPathComponentNames))]
[PlatformSpecific(TestPlatforms.Windows)] // Extended path exists
public void ValidExtendedPathExists_ReturnsTrue(string component)
{
string path = IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, "extended", component);
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(path));
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // Extended path already exists as file
public void ExtendedPathAlreadyExistsAsFile()
{
string path = IOInputs.ExtendedPrefix + GetTestFilePath();
File.Create(path).Dispose();
Assert.False(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // Extended path already exists as directory
public void ExtendedPathAlreadyExistsAsDirectory()
{
string path = IOInputs.ExtendedPrefix + GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[PlatformSpecific(TestPlatforms.Windows)] // Long directory path doesn't throw on Exists
public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath())), (path) =>
{
Assert.False(Exists(path));
});
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Unix equivalent tested already in CreateDirectory
public void WindowsWhiteSpaceAsPath_ReturnsFalse(string component)
{
// Checks that errors aren't thrown when calling Exists() on impossible paths
Assert.False(Exists(component));
}
[Fact]
[PlatformSpecific(CaseInsensitivePlatforms)]
public void DoesCaseInsensitiveInvariantComparisons()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.True(Exists(testDir.FullName));
Assert.True(Exists(testDir.FullName.ToUpperInvariant()));
Assert.True(Exists(testDir.FullName.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(CaseSensitivePlatforms)]
public void DoesCaseSensitiveComparisons()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.True(Exists(testDir.FullName));
Assert.False(Exists(testDir.FullName.ToUpperInvariant()));
Assert.False(Exists(testDir.FullName.ToLowerInvariant()));
}
[ConditionalTheory(nameof(UsingNewNormalization)),
MemberData(nameof(SimpleWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // In Windows, trailing whitespace in a path is trimmed appropriately
public void TrailingWhitespaceExistence_SimpleWhiteSpace(string component)
{
// This test relies on \\?\ support
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = GetTestFilePath(memberName: "Extended") + component;
testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + path);
Assert.False(Exists(path), path);
Assert.True(Exists(testDir.FullName));
}
[Theory,
MemberData(nameof(NonControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)]
public void NonControlWhiteSpaceExists(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath() + component);
string path = testDir.FullName;
Assert.True(Exists(path), "directory with non control whitespace should exist");
}
[Theory,
MemberData(nameof(SimpleWhiteSpace))] // *Just spaces*
[PlatformSpecific(TestPlatforms.Windows)]
public void TrailingSpaceExists(string component)
{
// Windows trims spaces
string path = GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path + component);
Assert.True(Exists(path), "can find without space");
Assert.True(Exists(path + component), "can find with space");
}
[Theory,
MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // alternate data stream
public void PathWithAlternateDataStreams_ReturnsFalse(string component)
{
Assert.False(Exists(component));
}
[Theory,
MemberData(nameof(PathsWithReservedDeviceNames))]
[OuterLoop]
[PlatformSpecific(TestPlatforms.Windows)] // device names
public void PathWithReservedDeviceNameAsPath_ReturnsFalse(string component)
{
Assert.False(Exists(component));
}
[Theory,
MemberData(nameof(UncPathsWithoutShareName))]
public void UncPathWithoutShareNameAsPath_ReturnsFalse(string component)
{
Assert.False(Exists(component));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // max directory length not fixed on Unix
public void DirectoryEqualToMaxDirectory_ReturnsTrue()
{
// Creates directories up to the maximum directory length all at once
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory);
Directory.CreateDirectory(path);
Assert.True(Exists(path));
}
[Theory,
MemberData(nameof(PathsWithComponentLongerThanMaxComponent))]
[PlatformSpecific(TestPlatforms.Windows)] // max directory length not fixed on Unix
public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse(string component)
{
Assert.False(Exists(component));
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(TestPlatforms.Windows)] // drive labels
public void NotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Exists(drive);
Assert.False(result);
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(TestPlatforms.Windows)] // drive labels
public void SubdirectoryOnNotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Exists(Path.Combine(drive, "Subdirectory"));
Assert.False(result);
}
// Not all drives may be accessible (locked, no rights, etc.), and as such would return false.
// eg. Create a new volume, bitlocker it, and lock it. This new volume is no longer accessible
// and any attempt to access this drive will return false.
// We just care that we can access an accessible drive directly, we don't care which one.
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInAppContainer))] // Can't read root in appcontainer
[PlatformSpecific(TestPlatforms.Windows)] // drive labels
public void DriveAsPath()
{
Assert.False(Exists(IOServices.GetNonExistentDrive()));
Assert.Contains(IOServices.GetReadyDrives(), drive => Exists(drive));
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // drive labels
public void ExtendedDriveAsPath()
{
Assert.False(Exists(IOInputs.ExtendedPrefix + IOServices.GetNonExistentDrive()));
if (PlatformDetection.IsNotInAppContainer)
Assert.Contains(IOServices.GetReadyDrives(), drive => Exists(IOInputs.ExtendedPrefix + drive));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // drive labels
public void SubdirectoryOnNonExistentDriveAsPath_ReturnsFalse()
{
Assert.False(Exists(Path.Combine(IOServices.GetNonExistentDrive(), "nonexistentsubdir")));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Makes call to native code (libc)
public void FalseForNonRegularFile()
{
string fileName = GetTestFilePath();
Assert.Equal(0, mkfifo(fileName, 0));
Assert.False(Directory.Exists(fileName));
}
#endregion
}
}
| |
/*
* Copyright 2004 - $Date: 2008-11-15 23:58:07 +0100 (za, 15 nov 2008) $ by PeopleWare n.v..
*
* 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.
*/
#region Using
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using log4net;
using Microsoft.SharePoint.Client;
using PPWCode.Util.SharePoint.I.Helpers;
using File = Microsoft.SharePoint.Client.File;
#endregion
namespace PPWCode.Util.SharePoint.I
{
/// <summary>
/// Actual implementation of <see cref="ISharePointClient"/>.
/// </summary>
public class SharePointClient
: ISharePointClient
{
#region fields
private static readonly ILog s_Logger = LogManager.GetLogger(typeof(SharePointClient));
#endregion
#region Private helpers
/// <summary>
/// Gets a client context on which the rootweb is already loaded.
/// User is responsible for disposing the context.
/// </summary>
private ClientContext GetSharePointClientContext()
{
ClientContext ctx = new ClientContext(SharePointSiteUrl);
if (Credentials != null)
{
s_Logger.Debug("GetSharePointClientContext: Credentials ok");
ctx.Credentials = Credentials;
}
else
{
s_Logger.Debug("GetSharePointClientContext: Credentials not ok");
}
ctx.Load(ctx.Site.RootWeb);
ctx.ExecuteQuery();
s_Logger.Debug(string.Format("Connect to SharePoint using user {0}", ctx.Web.CurrentUser));
return ctx;
}
private static void CreateFolderForEnsure(ClientContext spClientContext, string relativeUrl)
{
string workUrl = relativeUrl.StartsWith("/")
? relativeUrl.Substring(1)
: relativeUrl;
string[] foldernames = workUrl.Split('/');
spClientContext.Load(spClientContext.Site.RootWeb.RootFolder);
spClientContext.ExecuteQuery();
Folder parentfolder = spClientContext.Site.RootWeb.RootFolder;
string workname = String.Empty;
string parentfoldername = String.Empty;
foreach (string folderName in foldernames)
{
try
{
workname = String.Format("{0}/{1}", workname, folderName);
Folder workfolder = spClientContext.Site.RootWeb.GetFolderByServerRelativeUrl(workname);
spClientContext.Load(workfolder);
spClientContext.ExecuteQuery();
parentfolder = workfolder;
}
catch (ServerException se)
{
if (se.ServerErrorTypeName == typeof(FileNotFoundException).FullName)
{
if (parentfolder == null)
{
parentfolder = spClientContext.Site.RootWeb.GetFolderByServerRelativeUrl(parentfoldername);
spClientContext.Load(parentfolder);
}
parentfolder.Folders.Add(folderName);
spClientContext.ExecuteQuery();
parentfolder = null;
}
}
parentfoldername = workname;
}
}
#endregion
#region ISharePointClient interface
public string SharePointSiteUrl { get; set; }
public ICredentials Credentials { get; set; }
/// <inheritdoc cref="ISharePointClient.EnsureFolder" />
public void EnsureFolder(string relativeUrl)
{
try
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
Web rootWeb = spClientContext.Site.RootWeb;
//Check if the url exists
try
{
rootWeb.GetFolderByServerRelativeUrl(relativeUrl);
spClientContext.ExecuteQuery();
}
catch (ServerException se)
{
// If not, create it.
if (se.ServerErrorTypeName == typeof(FileNotFoundException).FullName)
{
CreateFolderForEnsure(spClientContext, relativeUrl);
}
}
}
}
catch (Exception e)
{
s_Logger.Error(string.Format("EnsureFolder({0}) failed using ClientContext {1}.", relativeUrl, SharePointSiteUrl), e);
throw;
}
}
public SharePointDocument DownloadDocument(string relativeUrl)
{
try
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
Web currentWeb = spClientContext.Web;
spClientContext.Load(currentWeb);
spClientContext.ExecuteQuery();
var fi = File.OpenBinaryDirect(spClientContext, relativeUrl);
if (fi == null)
{
throw new ApplicationException(@"fi == null");
}
if (fi.Stream == null)
{
throw new ApplicationException(@"fi.Stream == null");
}
return new SharePointDocument(fi.Stream.ConvertToByteArray());
}
}
catch (Exception e)
{
s_Logger.Error(string.Format("DownloadDocument({0}) failed using ClientContext {1}.", relativeUrl, SharePointSiteUrl), e);
throw;
}
}
public void UploadDocument(string relativeUrl, SharePointDocument doc)
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
//Check if the url exists
int index = relativeUrl.LastIndexOf("/");
string parentFolder = relativeUrl.Substring(0, index);
//Create intermediate folders if not exist
EnsureFolder(parentFolder);
spClientContext.ExecuteQuery();
try
{
string targetUrl = string.Format("{0}{1}", SharePointSiteUrl, relativeUrl);
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetUrl);
//Set credentials of the current security context
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "PUT";
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (MemoryStream ms = new MemoryStream(doc.Content))
{
ms.Position = 0;
// Get the start point
int startBuffer = ms.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = ms.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
if (response != null)
{
//Close response
response.Close();
}
}
catch (Exception e)
{
s_Logger.Error(string.Format("UploadDocument({0}) failed using ClientContext {1}.", relativeUrl, SharePointSiteUrl), e);
throw;
}
}
}
public bool ValidateUri(Uri sharePointUri)
{
if (sharePointUri != null)
{
string baseUrl = sharePointUri.GetLeftPart(UriPartial.Authority);
if (!string.IsNullOrEmpty(baseUrl))
{
using (ClientContext clientContext = new ClientContext(baseUrl))
{
if (Credentials != null)
{
clientContext.Credentials = Credentials;
}
//get the site collection
Web site = clientContext.Web;
string localPath = sharePointUri.LocalPath;
if (!string.IsNullOrEmpty(localPath))
{
//get the document library folder
site.GetFolderByServerRelativeUrl(localPath);
try
{
clientContext.ExecuteQuery();
return true;
}
catch (ServerException)
{
return false;
}
catch (Exception)
{
return false;
}
}
}
}
}
return false;
}
public void OpenUri(Uri uri)
{
string url = uri.OriginalString;
if (!string.IsNullOrEmpty(url))
{
Process.Start(new ProcessStartInfo
{
UseShellExecute = true,
FileName = url,
Verb = "Open",
LoadUserProfile = true
});
}
}
public List<SharePointSearchResult> SearchFiles(string url)
{
try
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
Web rootWeb = spClientContext.Site.RootWeb;
Folder spFolder = rootWeb.GetFolderByServerRelativeUrl(url); // "/Shared%20Documents/MEERTENS%20MATHIEU%20-%2051062002701/Construo/Actua/");
spClientContext.Load(spFolder.Files);
spClientContext.ExecuteQuery();
List<SharePointSearchResult> result = new List<SharePointSearchResult>();
foreach (File spFile in spFolder.Files)
{
var fileInformation = new SharePointSearchResult();
fileInformation.Properties.Add("FileName", spFile.Name);
fileInformation.Properties.Add("Description", spFile.CheckInComment);
fileInformation.Properties.Add("MajorVersion", spFile.MajorVersion);
fileInformation.Properties.Add("MinorVersion", spFile.MinorVersion);
fileInformation.Properties.Add("ModifiedBy", spFile.ModifiedBy);
fileInformation.Properties.Add("DateModified", spFile.TimeLastModified);
fileInformation.Properties.Add("CreatedBy", spFile.Author);
fileInformation.Properties.Add("DateCreated", spFile.TimeCreated);
fileInformation.Properties.Add("ServerRelativeUrl", spFile.ServerRelativeUrl);
result.Add(fileInformation);
}
return result;
}
}
catch (Exception e)
{
s_Logger.Error(string.Format("SearchFiles({0}) failed using ClientContext {1}.", url, SharePointSiteUrl), e);
throw;
}
}
// renameFolder(string baseRelativeUrl, string oldFolderName, string newFolderName)
// ex. renameFolder("/PensioB", "NAME, FIRSTNAME@123409876@12", "NAME, FIRSTNAME@123409876@9876")
// ex. renameFolder("/PensioB/NAME, FIRSTNAME@123409876@12/Payments/Beneficiaries", "NAME, FIRSTNAME@123409876@12", "NAME, FIRSTNAME@123409876@9876")
// list /PensioB
// --> listitem NAME, FIRSTNAME@123409876@12
// --> list
// --> listitem Payments
// ....
// ("PensioB", "AAA-Test/test1/test2", "AAA-Test1/test3/test9")
public void RenameFolder(string urlContainingFolder, string oldFolderName, string newFolderName)
{
try
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
Web web = spClientContext.Site.RootWeb;
// get document library
List list = web.Lists.GetByTitle(ExtractListName(urlContainingFolder));
// find all items with given name inside the baseRelativeUrl
CamlQuery query = CreateCamlQueryFindExactFolderPath(
urlContainingFolder,
string.Format("{0}/{1}", urlContainingFolder, oldFolderName));
ListItemCollection listItemCollection = list.GetItems(query);
// To load all fields, take the following
// spClientContext.Load(listItemCollection);
// only load required fields
spClientContext.Load(
listItemCollection,
fs => fs.Include(
fi => fi["Title"],
fi => fi["FileLeafRef"],
fi => fi["FileRef"]));
spClientContext.ExecuteQuery();
// for all found folders, rename them
if (listItemCollection.Count != 0)
{
ListItem listitem = listItemCollection[0];
s_Logger.DebugFormat("Title: {0}", listitem["Title"]);
s_Logger.DebugFormat("FileLeafRef: {0}", listitem["FileLeafRef"]);
s_Logger.DebugFormat("FileRef: {0}", listitem["FileRef"]);
listitem["Title"] = newFolderName;
listitem["FileLeafRef"] = newFolderName;
listitem.Update();
spClientContext.ExecuteQuery();
}
}
}
catch (Exception e)
{
s_Logger.ErrorFormat(
"Error renaming in [{0}] from old name [{1}] to new name [{2}]. Exception({3}).",
urlContainingFolder,
oldFolderName,
newFolderName,
e);
throw;
}
}
#region private helper methods
private static string ExtractListName(string relativeUrl)
{
string listBase = relativeUrl;
if (listBase.StartsWith("/"))
{
listBase = listBase.Remove(0, 1);
}
listBase = listBase.Split('/')[0];
return listBase;
}
#endregion
#region Caml queries
// ReSharper disable MemberCanBeMadeStatic.Local
private CamlQuery CreateCamlQueryFindExactFolderPath(string baseRelativeUrl, string oldFolderName)
// ReSharper restore MemberCanBeMadeStatic.Local
{
CamlQuery query = new CamlQuery();
query.ViewXml = "<View Scope=\"RecursiveAll\"> " +
"<Query>" +
"<Where>" +
"<And>" +
"<Eq>" +
"<FieldRef Name=\"FSObjType\" />" +
"<Value Type=\"Integer\">1</Value>" +
"</Eq>" +
"<Eq>" +
"<FieldRef Name=\"FileRef\"/>" +
"<Value Type=\"Text\">" + oldFolderName + "</Value>" +
"</Eq>" +
"</And>" +
"</Where>" +
"</Query>" +
"</View>";
query.FolderServerRelativeUrl = baseRelativeUrl;
return query;
}
// ReSharper disable MemberCanBeMadeStatic.Local
private CamlQuery CreateCamlQueryFindAllOccurencesOfFolder(string baseRelativeUrl, string oldFolderName)
// ReSharper restore MemberCanBeMadeStatic.Local
{
CamlQuery query = new CamlQuery();
query.ViewXml = "<View Scope=\"RecursiveAll\"> " +
"<Query>" +
"<Where>" +
"<And>" +
"<Eq>" +
"<FieldRef Name=\"FSObjType\" />" +
"<Value Type=\"Integer\">1</Value>" +
"</Eq>" +
"<Eq>" +
"<FieldRef Name=\"FileLeafRef\"/>" +
"<Value Type=\"Text\">" + oldFolderName + "</Value>" +
"</Eq>" +
"</And>" +
"</Where>" +
"</Query>" +
"</View>";
query.FolderServerRelativeUrl = baseRelativeUrl;
return query;
}
#endregion
// renameFolder(string baseRelativeUrl, string oldFolderName, string newFolderName)
// ex. renameAllOccurencesOfFolder("/PensioB", "NAME, FIRSTNAME@123409876@12", "NAME, FIRSTNAME@123409876@9876")
// ex. renameAllOccurencesOfFolder("/PensioB/NAME, FIRSTNAME@123409876@12/Payments/Beneficiaries", "NAME, FIRSTNAME@123409876@12", "NAME, FIRSTNAME@123409876@9876")
// list /PensioB
// --> listitem NAME, FIRSTNAME@123409876@12
// --> list
// --> listitem Payments
// ....
// ("PensioB", "AAA-Test/test1/test2", "AAA-Test1/test3/test9")
public void RenameAllOccurrencesOfFolder(string baseRelativeUrl, string oldFolderName, string newFolderName)
{
List<string> renamedListItemCollection = new List<string>();
try
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
Web web = spClientContext.Site.RootWeb;
// get document library
List list = web.Lists.GetByTitle(ExtractListName(baseRelativeUrl));
// find all items with given name inside the baseRelativeUrl
CamlQuery query = CreateCamlQueryFindAllOccurencesOfFolder(baseRelativeUrl, oldFolderName);
ListItemCollection listItemCollection = list.GetItems(query);
// To load all fields, take the following
// spClientContext.Load(listItemCollection);
// only load required fields
spClientContext.Load(
listItemCollection,
fs => fs.Include(
fi => fi["Title"],
fi => fi["FileLeafRef"],
fi => fi["FileRef"]));
spClientContext.ExecuteQuery();
// for all found folders, rename them
if (listItemCollection.Count != 0)
{
for (var counter = 0; counter < listItemCollection.Count; counter++)
{
s_Logger.DebugFormat("Title: {0}", listItemCollection[counter]["Title"]);
s_Logger.DebugFormat("FileLeafRef: {0}", listItemCollection[counter]["FileLeafRef"]);
s_Logger.DebugFormat("FileRef: {0}", listItemCollection[counter]["FileRef"]);
listItemCollection[counter]["Title"] = newFolderName;
listItemCollection[counter]["FileLeafRef"] = newFolderName;
listItemCollection[counter].Update();
spClientContext.ExecuteQuery();
string newFileRef = listItemCollection[counter]["FileRef"].ToString();
renamedListItemCollection.Add(newFileRef);
}
}
}
}
catch (Exception e)
{
renamedListItemCollection.Reverse();
foreach (string item in renamedListItemCollection)
{
string relativeUrl = ExtractRelativeUrlFromBaseRelativeUrl(item);
try
{
RenameFolder(relativeUrl, newFolderName, oldFolderName);
}
catch (Exception exception)
{
s_Logger.ErrorFormat(
"Error during cleanup (folder={0}, old={1}, new={2}) of failed rename. Exception({3}).",
relativeUrl,
newFolderName,
oldFolderName,
exception);
}
}
s_Logger.ErrorFormat(
"Error renaming in [{0}] from old name [{1}] to new name [{2}]. Exception({3}).",
baseRelativeUrl,
oldFolderName,
newFolderName,
e);
throw;
}
}
#endregion
//parameter baseRelativeUrl is path where folder will be created in
//if baseRelativeUrl does not exist, exception will be thrown;
//parameter newFolderName is new path or new foldername
//if newFolderName does exist, exception will be thrown
public void CreateFolder(string baseRelativeUrl, string newFolderName)
{
try
{
using (ClientContext spClientContext = GetSharePointClientContext())
{
string[] foldernames = newFolderName.Split('/');
Web web = spClientContext.Web;
//get document library
List list = web.Lists.GetByTitle(ExtractListName(baseRelativeUrl));
if (newFolderName != string.Empty)
{
string url = string.Empty;
for (int teller = 0; teller < foldernames.Length; teller++)
{
ListItemCreationInformation newItem = new ListItemCreationInformation();
newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
if (teller > 0)
{
url += "/" + foldernames[teller - 1];
newItem.FolderUrl = baseRelativeUrl + url;
}
else
{
newItem.FolderUrl = baseRelativeUrl;
}
newItem.LeafName = foldernames[teller];
ListItem item = list.AddItem(newItem);
item["Title"] = foldernames[teller];
item.Update();
}
}
spClientContext.ExecuteQuery();
}
}
catch (Exception ex)
{
s_Logger.ErrorFormat(
"Error creating folder [{0}] in [{1}]. Exception({2}).",
newFolderName,
baseRelativeUrl,
ex);
throw;
}
}
public void DeleteFolder(string baseRelativeUrl)
{
try
{
using (ClientContext spClientcontext = GetSharePointClientContext())
{
// make sure url starts with "/"
if (!baseRelativeUrl.StartsWith("/"))
{
baseRelativeUrl = '/' + baseRelativeUrl;
}
string relativeUrl = ExtractRelativeUrlFromBaseRelativeUrl(baseRelativeUrl);
Web web = spClientcontext.Web;
List list = web.Lists.GetByTitle(ExtractListName(baseRelativeUrl));
CamlQuery query = CreateCamlQueryFindExactFolderPath(relativeUrl, baseRelativeUrl);
ListItemCollection listItemCollection = list.GetItems(query);
spClientcontext.Load(list);
spClientcontext.Load(listItemCollection);
spClientcontext.ExecuteQuery();
if (listItemCollection.Count != 0)
{
foreach (var listitem in listItemCollection)
{
listitem.DeleteObject();
}
spClientcontext.ExecuteQuery();
}
}
}
catch (Exception ex)
{
s_Logger.ErrorFormat(
"Error deleting folder [{0}]. Exception({1}).",
baseRelativeUrl,
ex);
throw;
}
}
//checks if folder exists in list
//Parameter baseRelativeUrl has to start with List ex.PensioB/test1
public bool CheckExcistenceAllOccurencesFolderInList(string baseRelativeUrl)
{
using (ClientContext spClientcontext = GetSharePointClientContext())
{
if (!string.IsNullOrEmpty(baseRelativeUrl))
{
// make sure url starts with "/"
if (!baseRelativeUrl.StartsWith("/"))
{
baseRelativeUrl = '/' + baseRelativeUrl;
}
string[] foldernames = baseRelativeUrl.Split('/');
//get foldername
string folderName = foldernames[foldernames.Length - 1];
//make relativeUrl
string relativeUrl = '/' + foldernames[1];
if (foldernames.Length > 2)
{
for (int teller = 2; teller < foldernames.Length - 1; teller++)
{
relativeUrl += '/' + foldernames[teller];
}
}
try
{
Web web = spClientcontext.Web;
//get document library
List list = web.Lists.GetByTitle(ExtractListName(baseRelativeUrl));
CamlQuery query = CreateCamlQueryFindAllOccurencesOfFolder(relativeUrl, folderName);
ListItemCollection listItemCollection = list.GetItems(query);
spClientcontext.Load(list);
spClientcontext.Load(listItemCollection);
spClientcontext.ExecuteQuery();
return listItemCollection.Count != 0;
}
catch (Exception ex)
{
s_Logger.ErrorFormat(
"Error searching folder [{0}]. Exception({1}).",
baseRelativeUrl,
ex);
throw;
}
}
}
return false;
}
//checks if folder exists in certain path in list
//parameter baseRelativeUrl has to start with list ex.PensioB/test1
public bool CheckExistenceFolderWithExactPathInList(string baseRelativeUrl)
{
using (ClientContext spClientcontext = GetSharePointClientContext())
{
if (!string.IsNullOrEmpty(baseRelativeUrl))
{
// make sure url starts with "/"
if (!baseRelativeUrl.StartsWith("/"))
{
baseRelativeUrl = '/' + baseRelativeUrl;
}
string relativeUrl = ExtractRelativeUrlFromBaseRelativeUrl(baseRelativeUrl);
try
{
//get document library
Web web = spClientcontext.Web;
List list = web.Lists.GetByTitle(ExtractListName(baseRelativeUrl));
CamlQuery query = CreateCamlQueryFindExactFolderPath(relativeUrl, baseRelativeUrl);
ListItemCollection listItemCollection = list.GetItems(query);
spClientcontext.Load(list);
spClientcontext.Load(listItemCollection);
spClientcontext.ExecuteQuery();
return listItemCollection.Count != 0;
}
catch (Exception ex)
{
s_Logger.ErrorFormat(
"Error searching folder [{0}]. Exception({1}).",
baseRelativeUrl,
ex);
throw;
}
}
}
return false;
}
private string ExtractRelativeUrlFromBaseRelativeUrl(string baseRelativeUrl)
{
// make sure url starts with "/"
if (!baseRelativeUrl.StartsWith("/"))
{
baseRelativeUrl = '/' + baseRelativeUrl;
}
string[] foldernames = baseRelativeUrl.Split('/');
string relativeUrl = '/' + foldernames[1];
if (foldernames.Length > 2)
{
for (int teller = 2; teller < foldernames.Length - 1; teller++)
{
relativeUrl += '/' + foldernames[teller];
}
}
return relativeUrl;
}
}
}
| |
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 MVP.Service.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//---------------------------------------------------------------------
// Authors: jachymko
//
// Description: Class for managing NTFS reparse points.
//
// Creation Date: Dec 15, 2006
//---------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
using Pscx.Interop;
namespace Pscx.IO.Ntfs
{
public static class ReparsePointHelper
{
public static string MakeParsedPath(string unparsed)
{
PscxArgumentException.ThrowIfIsNullOrEmpty(unparsed);
if (unparsed[unparsed.Length - 1] == '\\')
{
unparsed = unparsed.Substring(0, unparsed.Length - 1);
}
if (unparsed.StartsWith(UnparsedPathPrefix) && unparsed.Contains(":"))
{
return unparsed.Substring(UnparsedPathPrefix.Length);
}
return unparsed;
}
public static string MakeUnparsedPath(string parsed)
{
parsed = EnsurePathSlash(parsed);
if (parsed.StartsWith(UnparsedPathPrefix))
{
return parsed;
}
return UnparsedPathPrefix + parsed;
}
public static string EnsurePathSlash(string path)
{
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException();
if (path[path.Length - 1] != '\\')
{
path += '\\';
}
return path;
}
public static unsafe byte[] GetReparsePointData(string path)
{
if (Directory.Exists(path))
{
path = EnsurePathSlash(path);
}
using (SafeHandle hReparsePoint = OpenReparsePoint(path, false))
{
if (hReparsePoint.IsInvalid)
{
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
byte[] bytes = new byte[MAX_REPARSE_SIZE];
uint bytesReturned = 0;
fixed (void* buffer = bytes)
{
if (!UnsafeNativeMethods.DeviceIoControl(
hReparsePoint,
UnsafeNativeMethods.FSCTL_GET_REPARSE_POINT,
null, 0,
buffer, MAX_REPARSE_SIZE,
out bytesReturned,
null))
{
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
}
byte[] trimmed = new byte[bytesReturned];
Buffer.BlockCopy(bytes, 0, trimmed, 0, (int)(bytesReturned));
return trimmed;
}
}
public static unsafe ReparsePointInfo GetReparsePoint(string path)
{
byte[] bytes = GetReparsePointData(path);
if (bytes == null)
{
return null;
}
fixed (byte* buffer = bytes)
{
REPARSE_GUID_DATA_BUFFER* reparseInfo = (REPARSE_GUID_DATA_BUFFER*)buffer;
if (IsMicrosoftReparseTag(reparseInfo->ReparseTag))
{
switch (reparseInfo->ReparseTag)
{
case ReparsePointType.MountPoint:
{
MOUNTPOINT_REPARSE_DATA_BUFFER* mp = (MOUNTPOINT_REPARSE_DATA_BUFFER*)buffer;
byte* mpdata = buffer + MOUNTPOINT_REPARSE_DATA_BUFFER_HEADER_SIZE;
string printName = GetStringFromBuffer(new IntPtr(mpdata + mp->PrintNameOffset), mp->PrintNameLength);
string substituteName = GetStringFromBuffer(new IntPtr(mpdata + mp->SubstituteNameOffset), mp->SubstituteNameLength);
return new LinkReparsePointInfo(ReparsePointType.MountPoint, path, substituteName);
}
case ReparsePointType.SymbolicLink:
{
SYMLINK_REPARSE_DATA_BUFFER* symlink = (SYMLINK_REPARSE_DATA_BUFFER*)buffer;
IntPtr ptr = new IntPtr(buffer + symlink->PrintNameOffset + SYMLINK_REPARSE_DATA_BUFFER_HEADER_SIZE);
string printName = GetStringFromBuffer(ptr, symlink->PrintNameLength);
ptr = new IntPtr(buffer + symlink->SubstituteNameOffset + SYMLINK_REPARSE_DATA_BUFFER_HEADER_SIZE);
string substituteName = GetStringFromBuffer(ptr, symlink->SubstituteNameLength);
return new LinkReparsePointInfo(ReparsePointType.SymbolicLink, path, substituteName);
}
}
}
return new ReparsePointInfo(path, reparseInfo->ReparseTag);
}
}
public static bool IsReparsePoint(string path)
{
FileSystemInfo info = new FileInfo(path);
if(!info.Exists)
{
info = new DirectoryInfo(path);
}
if (info.Exists)
{
return (info.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
}
return false;
}
public static unsafe bool CreateJunction(string junction, string target)
{
byte[] bytes = new byte[MAX_REPARSE_SIZE];
uint bytesReturned;
target = MakeUnparsedPath(target);
int targetLength = Encoding.Unicode.GetBytes(
target, 0, target.Length,
bytes, MOUNTPOINT_REPARSE_DATA_BUFFER_HEADER_SIZE);
using (SafeHandle hReparsePoint = OpenReparsePoint(junction, true))
{
if (hReparsePoint.IsInvalid)
{
throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
}
fixed (void* buffer = bytes)
{
SET_MOUNTPOINT_REPARSE_DATA_BUFFER* mp = (SET_MOUNTPOINT_REPARSE_DATA_BUFFER*)buffer;
mp->ReparseTag = (uint)ReparsePointType.MountPoint;
mp->ReparseTargetLength = (ushort)(targetLength);
mp->ReparseTargetMaximumLength = (ushort)(targetLength + WCHAR_SIZE);
mp->ReparseDataLength = (ushort)(targetLength + 12); // dont ask
return UnsafeNativeMethods.DeviceIoControl(
hReparsePoint,
UnsafeNativeMethods.FSCTL_SET_REPARSE_POINT,
buffer, (uint)(mp->ReparseDataLength + 8), // dont ask either
null, 0,
out bytesReturned,
null);
}
}
}
private static SafeFileHandle OpenReparsePoint(string path, bool writable)
{
AdjustToken();
NativeMethods.FileAccess access = NativeMethods.FileAccess.GenericRead;
if (writable)
{
access |= NativeMethods.FileAccess.GenericWrite;
}
return NativeMethods.CreateFile(
path,
access,
NativeMethods.FileShare.None,
IntPtr.Zero,
NativeMethods.CreationDisposition.OpenExisting,
NativeMethods.FileAttributes.BackupSemantics |
NativeMethods.FileAttributes.OpenReparsePoint,
IntPtr.Zero);
}
private static void AdjustToken()
{
using (Process process = Process.GetCurrentProcess())
{
SafeTokenHandle hToken = SafeTokenHandle.InvalidHandle;
try
{
if (!NativeMethods.OpenProcessToken(process.Handle, TokenAccessLevels.AdjustPrivileges, ref hToken))
{
throw PscxException.LastWin32Exception();
}
TokenPrivilegeCollection privileges = new TokenPrivilegeCollection();
privileges.Enable(TokenPrivilege.Backup);
privileges.Enable(TokenPrivilege.Restore);
Utils.AdjustTokenPrivileges(hToken, privileges);
}
finally
{
hToken.Dispose();
}
}
}
private static unsafe string GetStringFromBuffer(IntPtr ptr, int length)
{
char[] chars = new char[length];
Marshal.Copy(ptr, chars, 0, length);
for (int i = 0; i < length; i++)
{
if (chars[i] == '\0')
{
length = i;
break;
}
}
return new string(chars, 0, length);
}
private static bool IsMicrosoftReparseTag(ReparsePointType tag)
{
return ((uint)(tag) & 0x80000000) != 0;
}
private const string UnparsedPathPrefix = "\\??\\";
private const int MOUNTPOINT_REPARSE_DATA_BUFFER_HEADER_SIZE = 16;
private const int SYMLINK_REPARSE_DATA_BUFFER_HEADER_SIZE = 20;
private const int MAX_REPARSE_SIZE = 0x4000;
private const int WCHAR_SIZE = 2;
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Agens.StickersEditor.UnityEditor.iOS.Xcode
{
internal class DeviceTypeRequirement
{
public static readonly string Key = "idiom";
public static readonly string Any = "universal";
public static readonly string iPhone = "iphone";
public static readonly string iPad = "ipad";
public static readonly string Mac = "mac";
public static readonly string iWatch = "watch";
}
internal class MemoryRequirement
{
public static readonly string Key = "memory";
public static readonly string Any = "";
public static readonly string Mem1GB = "1GB";
public static readonly string Mem2GB = "2GB";
}
internal class GraphicsRequirement
{
public static readonly string Key = "graphics-feature-set";
public static readonly string Any = "";
public static readonly string Metal1v2 = "metal1v2";
public static readonly string Metal2v2 = "metal2v2";
}
// only used for image sets
internal class SizeClassRequirement
{
public static readonly string HeightKey = "height-class";
public static readonly string WidthKey = "width-class";
public static readonly string Any = "";
public static readonly string Compact = "compact";
public static readonly string Regular = "regular";
}
// only used for image sets
internal class ScaleRequirement
{
public static readonly string Key = "scale";
public static readonly string Any = ""; // vector image
public static readonly string X1 = "1x";
public static readonly string X2 = "2x";
public static readonly string X3 = "3x";
}
internal class DeviceRequirement
{
internal Dictionary<string, string> values = new Dictionary<string, string>();
public DeviceRequirement AddDevice(string device)
{
AddCustom(DeviceTypeRequirement.Key, device);
return this;
}
public DeviceRequirement AddMemory(string memory)
{
AddCustom(MemoryRequirement.Key, memory);
return this;
}
public DeviceRequirement AddGraphics(string graphics)
{
AddCustom(GraphicsRequirement.Key, graphics);
return this;
}
public DeviceRequirement AddWidthClass(string sizeClass)
{
AddCustom(SizeClassRequirement.WidthKey, sizeClass);
return this;
}
public DeviceRequirement AddHeightClass(string sizeClass)
{
AddCustom(SizeClassRequirement.HeightKey, sizeClass);
return this;
}
public DeviceRequirement AddScale(string scale)
{
AddCustom(ScaleRequirement.Key, scale);
return this;
}
public DeviceRequirement AddCustom(string key, string value)
{
if (values.ContainsKey(key))
values.Remove(key);
values.Add(key, value);
return this;
}
public DeviceRequirement()
{
values.Add("idiom", DeviceTypeRequirement.Any);
}
}
internal class AssetCatalog
{
AssetFolder m_Root;
public string path { get { return m_Root.path; } }
public AssetFolder root { get { return m_Root; } }
public AssetCatalog(string path, string authorId)
{
if (Path.GetExtension(path) != ".xcassets")
throw new Exception("Asset catalogs must have xcassets extension");
m_Root = new AssetFolder(path, null, authorId);
}
AssetFolder OpenFolderForResource(string relativePath)
{
var pathItems = PBX.Utils.SplitPath(relativePath).ToList();
// remove path filename
pathItems.RemoveAt(pathItems.Count - 1);
AssetFolder folder = root;
foreach (var pathItem in pathItems)
folder = folder.OpenFolder(pathItem);
return folder;
}
// Checks if a dataset at the given path exists and returns it if it does.
// Otherwise, creates a new dataset. Parent folders are created if needed.
// Note: the path is filesystem path, not logical asset name formed
// only from names of the folders that have "provides namespace" attribute.
// If you want to put certain resources in folders with namespace, first
// manually create the folders and then set the providesNamespace attribute.
// OpenNamespacedFolder may help to do this.
public AssetDataSet OpenDataSet(string relativePath)
{
var folder = OpenFolderForResource(relativePath);
return folder.OpenDataSet(Path.GetFileName(relativePath));
}
public AssetImageSet OpenImageSet(string relativePath)
{
var folder = OpenFolderForResource(relativePath);
return folder.OpenImageSet(Path.GetFileName(relativePath));
}
public AssetImageStack OpenImageStack(string relativePath)
{
var folder = OpenFolderForResource(relativePath);
return folder.OpenImageStack(Path.GetFileName(relativePath));
}
// Checks if a folder with given path exists and returns it if it does.
// Otherwise, creates a new folder. Parent folders are created if needed.
public AssetFolder OpenFolder(string relativePath)
{
if (relativePath == null)
return root;
var pathItems = PBX.Utils.SplitPath(relativePath);
if (pathItems.Length == 0)
return root;
AssetFolder folder = root;
foreach (var pathItem in pathItems)
folder = folder.OpenFolder(pathItem);
return folder;
}
// Creates a directory structure with "provides namespace" attribute.
// First, retrieves or creates the directory at relativeBasePath, creating parent
// directories if needed. Effectively calls OpenFolder(relativeBasePath).
// Then, relative to this directory, creates namespacePath directories with "provides
// namespace" attribute set. Fails if the attribute can't be set.
public AssetFolder OpenNamespacedFolder(string relativeBasePath, string namespacePath)
{
var folder = OpenFolder(relativeBasePath);
var pathItems = PBX.Utils.SplitPath(namespacePath);
foreach (var pathItem in pathItems)
{
folder = folder.OpenFolder(pathItem);
folder.providesNamespace = true;
}
return folder;
}
public void Write()
{
m_Root.Write();
}
}
internal abstract class AssetCatalogItem
{
public readonly string name;
public readonly string authorId;
public string path { get { return m_Path; } }
protected Dictionary<string, string> m_Properties = new Dictionary<string, string>();
protected string m_Path;
public AssetCatalogItem(string name, string authorId)
{
if (name != null && name.Contains("/"))
throw new Exception("Asset catalog item must not have slashes in name");
this.name = name;
this.authorId = authorId;
}
protected JsonElementDict WriteInfoToJson(JsonDocument doc)
{
var info = doc.root.CreateDict("info");
info.SetInteger("version", 1);
info.SetString("author", authorId);
return info;
}
public abstract void Write();
}
internal class AssetFolder : AssetCatalogItem
{
List<AssetCatalogItem> m_Items = new List<AssetCatalogItem>();
bool m_ProvidesNamespace = false;
public bool providesNamespace
{
get { return m_ProvidesNamespace; }
set {
if (m_Items.Count > 0 && value != m_ProvidesNamespace)
throw new Exception("Asset folder namespace providing status can't be "+
"changed after items have been added");
m_ProvidesNamespace = value;
}
}
internal AssetFolder(string parentPath, string name, string authorId) : base(name, authorId)
{
if (name != null)
m_Path = Path.Combine(parentPath, name);
else
m_Path = parentPath;
}
// Checks if a folder with given name exists and returns it if it does.
// Otherwise, creates a new folder.
public AssetFolder OpenFolder(string name)
{
var item = GetChild(name);
if (item != null)
{
if (item is AssetFolder)
return item as AssetFolder;
throw new Exception("The given path is already occupied with an asset");
}
var folder = new AssetFolder(m_Path, name, authorId);
m_Items.Add(folder);
return folder;
}
T GetExistingItemWithType<T>(string name) where T : class
{
var item = GetChild(name);
if (item != null)
{
if (item is T)
return item as T;
throw new Exception("The given path is already occupied with an asset");
}
return null;
}
// Checks if a dataset with given name exists and returns it if it does.
// Otherwise, creates a new data set.
public AssetDataSet OpenDataSet(string name)
{
var item = GetExistingItemWithType<AssetDataSet>(name);
if (item != null)
return item;
var dataset = new AssetDataSet(m_Path, name, authorId);
m_Items.Add(dataset);
return dataset;
}
// Checks if an imageset with given name exists and returns it if it does.
// Otherwise, creates a new image set.
public AssetImageSet OpenImageSet(string name)
{
var item = GetExistingItemWithType<AssetImageSet>(name);
if (item != null)
return item;
var imageset = new AssetImageSet(m_Path, name, authorId);
m_Items.Add(imageset);
return imageset;
}
// Checks if a image stack with given name exists and returns it if it does.
// Otherwise, creates a new image stack.
public AssetImageStack OpenImageStack(string name)
{
var item = GetExistingItemWithType<AssetImageStack>(name);
if (item != null)
return item;
var imageStack = new AssetImageStack(m_Path, name, authorId);
m_Items.Add(imageStack);
return imageStack;
}
// Returns the requested item or null if not found
public AssetCatalogItem GetChild(string name)
{
foreach (var item in m_Items)
{
if (item.name == name)
return item;
}
return null;
}
void WriteJson()
{
if (!providesNamespace)
return; // json is optional when namespace is not provided
var doc = new JsonDocument();
WriteInfoToJson(doc);
var props = doc.root.CreateDict("properties");
props.SetBoolean("provides-namespace", providesNamespace);
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
public override void Write()
{
if (Directory.Exists(m_Path))
Directory.Delete(m_Path, true); // ensure we start from clean state
Directory.CreateDirectory(m_Path);
WriteJson();
foreach (var item in m_Items)
item.Write();
}
}
abstract class AssetCatalogItemWithVariants : AssetCatalogItem
{
protected List<VariantData> m_Variants = new List<VariantData>();
protected List<string> m_ODRTags = new List<string>();
protected AssetCatalogItemWithVariants(string name, string authorId) :
base(name, authorId)
{
}
protected class VariantData
{
public DeviceRequirement requirement;
public string path;
public VariantData(DeviceRequirement requirement, string path)
{
this.requirement = requirement;
this.path = path;
}
}
public bool HasVariant(DeviceRequirement requirement)
{
foreach (var item in m_Variants)
{
if (item.requirement.values == requirement.values)
return true;
}
return false;
}
public void AddOnDemandResourceTag(string tag)
{
if (!m_ODRTags.Contains(tag))
m_ODRTags.Add(tag);
}
protected void AddVariant(VariantData newItem)
{
foreach (var item in m_Variants)
{
if (item.requirement.values == newItem.requirement.values)
throw new Exception("The given requirement has been already added");
if (Path.GetFileName(item.path) == Path.GetFileName(path))
throw new Exception("Two items within the same set must not have the same file name");
}
if (Path.GetFileName(newItem.path) == "Contents.json")
throw new Exception("The file name must not be equal to Contents.json");
m_Variants.Add(newItem);
}
protected void WriteODRTagsToJson(JsonElementDict info)
{
if (m_ODRTags.Count > 0)
{
var tags = info.CreateArray("on-demand-resource-tags");
foreach (var tag in m_ODRTags)
tags.AddString(tag);
}
}
protected void WriteRequirementsToJson(JsonElementDict item, DeviceRequirement req)
{
foreach (var kv in req.values)
{
if (kv.Value != null && kv.Value != "")
item.SetString(kv.Key, kv.Value);
}
}
}
internal class AssetDataSet : AssetCatalogItemWithVariants
{
class DataSetVariant : VariantData
{
public string id;
public DataSetVariant(DeviceRequirement requirement, string path, string id) : base(requirement, path)
{
this.id = id;
}
}
internal AssetDataSet(string parentPath, string name, string authorId) : base(name, authorId)
{
m_Path = Path.Combine(parentPath, name + ".dataset");
}
// an exception is thrown is two equivalent requirements are added.
// The same asset dataset must not have paths with equivalent filenames.
// The identifier allows to identify which data variant is actually loaded (use
// the typeIdentifer property of the NSDataAsset that was created from the data set)
public void AddVariant(DeviceRequirement requirement, string path, string typeIdentifier)
{
foreach (DataSetVariant item in m_Variants)
{
if (item.id != null && typeIdentifier != null && item.id == typeIdentifier)
throw new Exception("Two items within the same dataset must not have the same id");
}
AddVariant(new DataSetVariant(requirement, path, typeIdentifier));
}
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDocument();
var info = WriteInfoToJson(doc);
WriteODRTagsToJson(info);
var data = doc.root.CreateArray("data");
foreach (DataSetVariant item in m_Variants)
{
var filename = Path.GetFileName(item.path);
File.Copy(item.path, Path.Combine(m_Path, filename));
var docItem = data.AddDict();
docItem.SetString("filename", filename);
WriteRequirementsToJson(docItem, item.requirement);
if (item.id != null)
docItem.SetString("universal-type-identifier", item.id);
}
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
}
internal class ImageAlignment
{
public int left = 0, right = 0, top = 0, bottom = 0;
}
internal class ImageResizing
{
public enum SlicingType
{
Horizontal,
Vertical,
HorizontalAndVertical
}
public enum ResizeMode
{
Stretch,
Tile
}
public SlicingType type = SlicingType.HorizontalAndVertical;
public int left = 0; // only valid for horizontal slicing
public int right = 0; // only valid for horizontal slicing
public int top = 0; // only valid for vertical slicing
public int bottom = 0; // only valid for vertical slicing
public ResizeMode centerResizeMode = ResizeMode.Stretch;
public int centerWidth = 0; // only valid for vertical slicing
public int centerHeight = 0; // only valid for horizontal slicing
}
// TODO: rendering intent property
internal class AssetImageSet : AssetCatalogItemWithVariants
{
internal AssetImageSet(string assetCatalogPath, string name, string authorId) : base(name, authorId)
{
m_Path = Path.Combine(assetCatalogPath, name + ".imageset");
}
class ImageSetVariant : VariantData
{
public ImageAlignment alignment = null;
public ImageResizing resizing = null;
public ImageSetVariant(DeviceRequirement requirement, string path) : base(requirement, path)
{
}
}
public void AddVariant(DeviceRequirement requirement, string path)
{
AddVariant(new ImageSetVariant(requirement, path));
}
public void AddVariant(DeviceRequirement requirement, string path, ImageAlignment alignment, ImageResizing resizing)
{
var imageset = new ImageSetVariant(requirement, path);
imageset.alignment = alignment;
imageset.resizing = resizing;
AddVariant(imageset);
}
void WriteAlignmentToJson(JsonElementDict item, ImageAlignment alignment)
{
var docAlignment = item.CreateDict("alignment-insets");
docAlignment.SetInteger("top", alignment.top);
docAlignment.SetInteger("bottom", alignment.bottom);
docAlignment.SetInteger("left", alignment.left);
docAlignment.SetInteger("right", alignment.right);
}
static string GetSlicingMode(ImageResizing.SlicingType mode)
{
switch (mode)
{
case ImageResizing.SlicingType.Horizontal: return "3-part-horizontal";
case ImageResizing.SlicingType.Vertical: return "3-part-vertical";
case ImageResizing.SlicingType.HorizontalAndVertical: return "9-part";
}
return "";
}
static string GetCenterResizeMode(ImageResizing.ResizeMode mode)
{
switch (mode)
{
case ImageResizing.ResizeMode.Stretch: return "stretch";
case ImageResizing.ResizeMode.Tile: return "tile";
}
return "";
}
void WriteResizingToJson(JsonElementDict item, ImageResizing resizing)
{
var docResizing = item.CreateDict("resizing");
docResizing.SetString("mode", GetSlicingMode(resizing.type));
var docCenter = docResizing.CreateDict("center");
docCenter.SetString("mode", GetCenterResizeMode(resizing.centerResizeMode));
docCenter.SetInteger("width", resizing.centerWidth);
docCenter.SetInteger("height", resizing.centerHeight);
var docInsets = docResizing.CreateDict("cap-insets");
docInsets.SetInteger("top", resizing.top);
docInsets.SetInteger("bottom", resizing.bottom);
docInsets.SetInteger("left", resizing.left);
docInsets.SetInteger("right", resizing.right);
}
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDocument();
var info = WriteInfoToJson(doc);
WriteODRTagsToJson(info);
var images = doc.root.CreateArray("images");
foreach (ImageSetVariant item in m_Variants)
{
var filename = Path.GetFileName(item.path);
File.Copy(item.path, Path.Combine(m_Path, filename));
var docItem = images.AddDict();
docItem.SetString("filename", filename);
WriteRequirementsToJson(docItem, item.requirement);
if (item.alignment != null)
WriteAlignmentToJson(docItem, item.alignment);
if (item.resizing != null)
WriteResizingToJson(docItem, item.resizing);
}
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
}
/* A stack layer may either contain an image set or reference another imageset
*/
class AssetImageStackLayer : AssetCatalogItem
{
internal AssetImageStackLayer(string assetCatalogPath, string name, string authorId) : base(name, authorId)
{
m_Path = Path.Combine(assetCatalogPath, name + ".imagestacklayer");
m_Imageset = new AssetImageSet(m_Path, "Content", authorId);
}
AssetImageSet m_Imageset = null;
string m_ReferencedName = null;
public void SetReference(string name)
{
m_Imageset = null;
m_ReferencedName = name;
}
public string ReferencedName()
{
return m_ReferencedName;
}
public AssetImageSet GetImageSet()
{
return m_Imageset;
}
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDocument();
WriteInfoToJson(doc);
if (m_ReferencedName != null)
{
var props = doc.root.CreateDict("properties");
var reference = props.CreateDict("content-reference");
reference.SetString("type", "image-set");
reference.SetString("name", m_ReferencedName);
reference.SetString("matching-style", "fully-qualified-name");
}
if (m_Imageset != null)
m_Imageset.Write();
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
}
class AssetImageStack : AssetCatalogItem
{
List<AssetImageStackLayer> m_Layers = new List<AssetImageStackLayer>();
internal AssetImageStack(string assetCatalogPath, string name, string authorId) : base(name, authorId)
{
m_Path = Path.Combine(assetCatalogPath, name + ".imagestack");
}
public AssetImageStackLayer AddLayer(string name)
{
foreach (var layer in m_Layers)
{
if (layer.name == name)
throw new Exception("A layer with given name already exists");
}
var newLayer = new AssetImageStackLayer(m_Path, name, authorId);
m_Layers.Add(newLayer);
return newLayer;
}
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDocument();
WriteInfoToJson(doc);
var docLayers = doc.root.CreateArray("layers");
foreach (var layer in m_Layers)
{
layer.Write();
var docLayer = docLayers.AddDict();
docLayer.SetString("filename", Path.GetFileName(layer.path));
}
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
}
} // namespace UnityEditor.iOS.Xcode
| |
// 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="AccountLinkServiceClient"/> instances.</summary>
public sealed partial class AccountLinkServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AccountLinkServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AccountLinkServiceSettings"/>.</returns>
public static AccountLinkServiceSettings GetDefault() => new AccountLinkServiceSettings();
/// <summary>Constructs a new <see cref="AccountLinkServiceSettings"/> object with default settings.</summary>
public AccountLinkServiceSettings()
{
}
private AccountLinkServiceSettings(AccountLinkServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetAccountLinkSettings = existing.GetAccountLinkSettings;
CreateAccountLinkSettings = existing.CreateAccountLinkSettings;
MutateAccountLinkSettings = existing.MutateAccountLinkSettings;
OnCopy(existing);
}
partial void OnCopy(AccountLinkServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AccountLinkServiceClient.GetAccountLink</c> and <c>AccountLinkServiceClient.GetAccountLinkAsync</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 GetAccountLinkSettings { 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>AccountLinkServiceClient.CreateAccountLink</c> and <c>AccountLinkServiceClient.CreateAccountLinkAsync</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 CreateAccountLinkSettings { 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>AccountLinkServiceClient.MutateAccountLink</c> and <c>AccountLinkServiceClient.MutateAccountLinkAsync</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 MutateAccountLinkSettings { 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="AccountLinkServiceSettings"/> object.</returns>
public AccountLinkServiceSettings Clone() => new AccountLinkServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AccountLinkServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AccountLinkServiceClientBuilder : gaxgrpc::ClientBuilderBase<AccountLinkServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AccountLinkServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AccountLinkServiceClientBuilder()
{
UseJwtAccessWithScopes = AccountLinkServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AccountLinkServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AccountLinkServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AccountLinkServiceClient Build()
{
AccountLinkServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AccountLinkServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AccountLinkServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AccountLinkServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AccountLinkServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AccountLinkServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AccountLinkServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AccountLinkServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AccountLinkServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AccountLinkServiceClient.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>AccountLinkService client wrapper, for convenient use.</summary>
/// <remarks>
/// This service allows management of links between Google Ads accounts and other
/// accounts.
/// </remarks>
public abstract partial class AccountLinkServiceClient
{
/// <summary>
/// The default endpoint for the AccountLinkService 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 AccountLinkService scopes.</summary>
/// <remarks>
/// The default AccountLinkService 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="AccountLinkServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AccountLinkServiceClientBuilder"/>
/// .
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AccountLinkServiceClient"/>.</returns>
public static stt::Task<AccountLinkServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AccountLinkServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AccountLinkServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="AccountLinkServiceClientBuilder"/>
/// .
/// </summary>
/// <returns>The created <see cref="AccountLinkServiceClient"/>.</returns>
public static AccountLinkServiceClient Create() => new AccountLinkServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AccountLinkServiceClient"/> 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="AccountLinkServiceSettings"/>.</param>
/// <returns>The created <see cref="AccountLinkServiceClient"/>.</returns>
internal static AccountLinkServiceClient Create(grpccore::CallInvoker callInvoker, AccountLinkServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AccountLinkService.AccountLinkServiceClient grpcClient = new AccountLinkService.AccountLinkServiceClient(callInvoker);
return new AccountLinkServiceClientImpl(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 AccountLinkService client</summary>
public virtual AccountLinkService.AccountLinkServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the account link 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::AccountLink GetAccountLink(GetAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the account link 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::AccountLink> GetAccountLinkAsync(GetAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the account link 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::AccountLink> GetAccountLinkAsync(GetAccountLinkRequest request, st::CancellationToken cancellationToken) =>
GetAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the account link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the account link.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AccountLink GetAccountLink(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAccountLink(new GetAccountLinkRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the account link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the account link.
/// </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::AccountLink> GetAccountLinkAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAccountLinkAsync(new GetAccountLinkRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the account link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the account link.
/// </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::AccountLink> GetAccountLinkAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetAccountLinkAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the account link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the account link.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::AccountLink GetAccountLink(gagvr::AccountLinkName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAccountLink(new GetAccountLinkRequest
{
ResourceNameAsAccountLinkName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the account link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the account link.
/// </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::AccountLink> GetAccountLinkAsync(gagvr::AccountLinkName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetAccountLinkAsync(new GetAccountLinkRequest
{
ResourceNameAsAccountLinkName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the account link in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the account link.
/// </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::AccountLink> GetAccountLinkAsync(gagvr::AccountLinkName resourceName, st::CancellationToken cancellationToken) =>
GetAccountLinkAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates an account link.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// [ThirdPartyAppAnalyticsLinkError]()
/// </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 CreateAccountLinkResponse CreateAccountLink(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an account link.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// [ThirdPartyAppAnalyticsLinkError]()
/// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates an account link.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// [ThirdPartyAppAnalyticsLinkError]()
/// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(CreateAccountLinkRequest request, st::CancellationToken cancellationToken) =>
CreateAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates an account link.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// [ThirdPartyAppAnalyticsLinkError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer for which the account link is created.
/// </param>
/// <param name="accountLink">
/// Required. The account link to be created.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual CreateAccountLinkResponse CreateAccountLink(string customerId, gagvr::AccountLink accountLink, gaxgrpc::CallSettings callSettings = null) =>
CreateAccountLink(new CreateAccountLinkRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
AccountLink = gax::GaxPreconditions.CheckNotNull(accountLink, nameof(accountLink)),
}, callSettings);
/// <summary>
/// Creates an account link.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// [ThirdPartyAppAnalyticsLinkError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer for which the account link is created.
/// </param>
/// <param name="accountLink">
/// Required. The account link to be created.
/// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(string customerId, gagvr::AccountLink accountLink, gaxgrpc::CallSettings callSettings = null) =>
CreateAccountLinkAsync(new CreateAccountLinkRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
AccountLink = gax::GaxPreconditions.CheckNotNull(accountLink, nameof(accountLink)),
}, callSettings);
/// <summary>
/// Creates an account link.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// [ThirdPartyAppAnalyticsLinkError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer for which the account link is created.
/// </param>
/// <param name="accountLink">
/// Required. The account link to be created.
/// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(string customerId, gagvr::AccountLink accountLink, st::CancellationToken cancellationToken) =>
CreateAccountLinkAsync(customerId, accountLink, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or removes an account link.
/// From V5, create is not supported through
/// AccountLinkService.MutateAccountLink. Please use
/// AccountLinkService.CreateAccountLink instead.
///
/// List of thrown errors:
/// [AccountLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [FieldMaskError]()
/// [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 MutateAccountLinkResponse MutateAccountLink(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or removes an account link.
/// From V5, create is not supported through
/// AccountLinkService.MutateAccountLink. Please use
/// AccountLinkService.CreateAccountLink instead.
///
/// List of thrown errors:
/// [AccountLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [FieldMaskError]()
/// [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<MutateAccountLinkResponse> MutateAccountLinkAsync(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or removes an account link.
/// From V5, create is not supported through
/// AccountLinkService.MutateAccountLink. Please use
/// AccountLinkService.CreateAccountLink instead.
///
/// List of thrown errors:
/// [AccountLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [FieldMaskError]()
/// [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<MutateAccountLinkResponse> MutateAccountLinkAsync(MutateAccountLinkRequest request, st::CancellationToken cancellationToken) =>
MutateAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or removes an account link.
/// From V5, create is not supported through
/// AccountLinkService.MutateAccountLink. Please use
/// AccountLinkService.CreateAccountLink instead.
///
/// List of thrown errors:
/// [AccountLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the link.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAccountLinkResponse MutateAccountLink(string customerId, AccountLinkOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateAccountLink(new MutateAccountLinkRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Creates or removes an account link.
/// From V5, create is not supported through
/// AccountLinkService.MutateAccountLink. Please use
/// AccountLinkService.CreateAccountLink instead.
///
/// List of thrown errors:
/// [AccountLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the link.
/// </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<MutateAccountLinkResponse> MutateAccountLinkAsync(string customerId, AccountLinkOperation operation, gaxgrpc::CallSettings callSettings = null) =>
MutateAccountLinkAsync(new MutateAccountLinkRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)),
}, callSettings);
/// <summary>
/// Creates or removes an account link.
/// From V5, create is not supported through
/// AccountLinkService.MutateAccountLink. Please use
/// AccountLinkService.CreateAccountLink instead.
///
/// List of thrown errors:
/// [AccountLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer being modified.
/// </param>
/// <param name="operation">
/// Required. The operation to perform on the link.
/// </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<MutateAccountLinkResponse> MutateAccountLinkAsync(string customerId, AccountLinkOperation operation, st::CancellationToken cancellationToken) =>
MutateAccountLinkAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AccountLinkService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// This service allows management of links between Google Ads accounts and other
/// accounts.
/// </remarks>
public sealed partial class AccountLinkServiceClientImpl : AccountLinkServiceClient
{
private readonly gaxgrpc::ApiCall<GetAccountLinkRequest, gagvr::AccountLink> _callGetAccountLink;
private readonly gaxgrpc::ApiCall<CreateAccountLinkRequest, CreateAccountLinkResponse> _callCreateAccountLink;
private readonly gaxgrpc::ApiCall<MutateAccountLinkRequest, MutateAccountLinkResponse> _callMutateAccountLink;
/// <summary>
/// Constructs a client wrapper for the AccountLinkService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="AccountLinkServiceSettings"/> used within this client.</param>
public AccountLinkServiceClientImpl(AccountLinkService.AccountLinkServiceClient grpcClient, AccountLinkServiceSettings settings)
{
GrpcClient = grpcClient;
AccountLinkServiceSettings effectiveSettings = settings ?? AccountLinkServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetAccountLink = clientHelper.BuildApiCall<GetAccountLinkRequest, gagvr::AccountLink>(grpcClient.GetAccountLinkAsync, grpcClient.GetAccountLink, effectiveSettings.GetAccountLinkSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetAccountLink);
Modify_GetAccountLinkApiCall(ref _callGetAccountLink);
_callCreateAccountLink = clientHelper.BuildApiCall<CreateAccountLinkRequest, CreateAccountLinkResponse>(grpcClient.CreateAccountLinkAsync, grpcClient.CreateAccountLink, effectiveSettings.CreateAccountLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callCreateAccountLink);
Modify_CreateAccountLinkApiCall(ref _callCreateAccountLink);
_callMutateAccountLink = clientHelper.BuildApiCall<MutateAccountLinkRequest, MutateAccountLinkResponse>(grpcClient.MutateAccountLinkAsync, grpcClient.MutateAccountLink, effectiveSettings.MutateAccountLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAccountLink);
Modify_MutateAccountLinkApiCall(ref _callMutateAccountLink);
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_GetAccountLinkApiCall(ref gaxgrpc::ApiCall<GetAccountLinkRequest, gagvr::AccountLink> call);
partial void Modify_CreateAccountLinkApiCall(ref gaxgrpc::ApiCall<CreateAccountLinkRequest, CreateAccountLinkResponse> call);
partial void Modify_MutateAccountLinkApiCall(ref gaxgrpc::ApiCall<MutateAccountLinkRequest, MutateAccountLinkResponse> call);
partial void OnConstruction(AccountLinkService.AccountLinkServiceClient grpcClient, AccountLinkServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AccountLinkService client</summary>
public override AccountLinkService.AccountLinkServiceClient GrpcClient { get; }
partial void Modify_GetAccountLinkRequest(ref GetAccountLinkRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_CreateAccountLinkRequest(ref CreateAccountLinkRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateAccountLinkRequest(ref MutateAccountLinkRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the account link 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::AccountLink GetAccountLink(GetAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAccountLinkRequest(ref request, ref callSettings);
return _callGetAccountLink.Sync(request, callSettings);
}
/// <summary>
/// Returns the account link 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::AccountLink> GetAccountLinkAsync(GetAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetAccountLinkRequest(ref request, ref callSettings);
return _callGetAccountLink.Async(request, callSettings);
}
/// <summary>
/// Creates an account link.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// [ThirdPartyAppAnalyticsLinkError]()
/// </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 CreateAccountLinkResponse CreateAccountLink(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateAccountLinkRequest(ref request, ref callSettings);
return _callCreateAccountLink.Sync(request, callSettings);
}
/// <summary>
/// Creates an account link.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// [ThirdPartyAppAnalyticsLinkError]()
/// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateAccountLinkRequest(ref request, ref callSettings);
return _callCreateAccountLink.Async(request, callSettings);
}
/// <summary>
/// Creates or removes an account link.
/// From V5, create is not supported through
/// AccountLinkService.MutateAccountLink. Please use
/// AccountLinkService.CreateAccountLink instead.
///
/// List of thrown errors:
/// [AccountLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [FieldMaskError]()
/// [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 MutateAccountLinkResponse MutateAccountLink(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAccountLinkRequest(ref request, ref callSettings);
return _callMutateAccountLink.Sync(request, callSettings);
}
/// <summary>
/// Creates or removes an account link.
/// From V5, create is not supported through
/// AccountLinkService.MutateAccountLink. Please use
/// AccountLinkService.CreateAccountLink instead.
///
/// List of thrown errors:
/// [AccountLinkError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [FieldMaskError]()
/// [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<MutateAccountLinkResponse> MutateAccountLinkAsync(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAccountLinkRequest(ref request, ref callSettings);
return _callMutateAccountLink.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using static Android.Text.TextUtils;
using Xamstrap;
using Xamstrap.AttachedProperties;
[assembly: ExportRenderer(typeof(Xamarin.Forms.Button), typeof(Xamstrap.Droid.ResponsiveButtonRenderer))]
namespace Xamstrap.Droid
{
public class ResponsiveButtonRenderer : ButtonRenderer
{
Android.Widget.Button thisButton;
private Color originalBackgroundColor;
private Color pressedBackgroundColor;
private Color pressedTextColor;
private Color originalTextColor;
private bool isToggleButton;
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
{
base.OnElementChanged(e);
thisButton = Control as Android.Widget.Button;
if (thisButton != null)
{
thisButton.SetMaxLines(1);
thisButton.Ellipsize = TruncateAt.End;
}
List<string> classes = Element.GetValue(ResponsiveProperty.ClassProperty)?.ToString().Split(" ".ToCharArray()).ToList();
if (classes != null)
{
ProcessButtonTheme(classes);
ProcessButtonSize(classes);
}
//Handle Button Pading
var padding = (Thickness)Element.GetValue(ButtonProperty.PaddingProperty);
if (padding.Left != -100 && padding.Top != -100 && padding.Right != -100 && padding.Bottom != -100)
{
int top = int.Parse(padding.Top.ToString());
int left = int.Parse(padding.Left.ToString());
int bottom = int.Parse(padding.Bottom.ToString());
int right = int.Parse(padding.Right.ToString());
thisButton.SetPadding(left, top, right, bottom);
Element.HeightRequest = Element.FontSize + padding.VerticalThickness + 10;
}
// Handle PressedBackgroundColor
pressedBackgroundColor = (Xamarin.Forms.Color)Element.GetValue(ButtonProperty.PressedBackgroundColorProperty);
if (!pressedBackgroundColor.Equals(Color.Default))
{
originalBackgroundColor = Element.BackgroundColor;
//Handle TextColor
pressedTextColor = (Xamarin.Forms.Color)Element.GetValue(ButtonProperty.PressedTextColorProperty);
if (!pressedTextColor.Equals(Color.Default))
originalTextColor = Element.TextColor;
thisButton.Touch += ButtonTouched;
thisButton.SetSingleLine(true);
isToggleButton = Convert.ToBoolean(Element.GetValue(ButtonProperty.IsToggleButtonProperty));
}
// Handle Horizontal Content Alignment
var horizontalContentAlignment = (ButtonProperty.HorizontalContentAlignmentType)Element.GetValue(ButtonProperty.HorizontalContentAlignmentProperty);
if (horizontalContentAlignment != ButtonProperty.HorizontalContentAlignmentType.PlatformDefault)
{
switch (horizontalContentAlignment)
{
case ButtonProperty.HorizontalContentAlignmentType.Fill:
thisButton.Gravity = thisButton.Gravity | GravityFlags.FillHorizontal;
break;
case ButtonProperty.HorizontalContentAlignmentType.Left:
thisButton.Gravity = thisButton.Gravity | GravityFlags.Left;
break;
case ButtonProperty.HorizontalContentAlignmentType.Right:
thisButton.Gravity = thisButton.Gravity | GravityFlags.Right;
break;
case ButtonProperty.HorizontalContentAlignmentType.Centre:
thisButton.Gravity = thisButton.Gravity | GravityFlags.CenterHorizontal;
break;
}
}
// Handle Vertical Content Alignment
var verticalContentAlignment = (ButtonProperty.VerticalContentAlignmentType)Element.GetValue(ButtonProperty.VerticalContentAlignmentProperty);
if (verticalContentAlignment != ButtonProperty.VerticalContentAlignmentType.PlatformDefault)
{
switch (verticalContentAlignment)
{
case ButtonProperty.VerticalContentAlignmentType.Fill:
thisButton.Gravity = thisButton.Gravity | GravityFlags.FillVertical;
break;
case ButtonProperty.VerticalContentAlignmentType.Top:
thisButton.Gravity = thisButton.Gravity | GravityFlags.Top;
break;
case ButtonProperty.VerticalContentAlignmentType.Bottom:
thisButton.Gravity = thisButton.Gravity | GravityFlags.Bottom;
break;
case ButtonProperty.VerticalContentAlignmentType.Centre:
thisButton.Gravity = thisButton.Gravity | GravityFlags.CenterVertical;
break;
}
}
}
private void ProcessButtonTheme(List<string> classes)
{
if (classes.Any(o => o.Equals(Constant.BtnDefault)))
{
object backgroundColor = null;
object textColor = null;
object borderColor = null;
object borderWidth = null;
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnDefaultBackgroundColor, out backgroundColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnDefaultTextColor, out textColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnDefaultBorderColor, out borderColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnDefaultBorderWidth, out borderWidth);
if (backgroundColor != null)
{
Element.BackgroundColor = (Color)backgroundColor;
}
else
Element.BackgroundColor = Color.FromHex("#fff");
if (textColor != null)
Element.TextColor = (Color)textColor;
else
Element.TextColor = Color.FromHex("#333");
if (borderColor != null)
Element.BorderColor = (Color)borderColor;
else
Element.BorderColor = Color.FromHex("#ccc");
if (borderWidth != null)
Element.BorderWidth = Convert.ToInt16(borderWidth);
else
Element.BorderWidth = 1;
}
else if (classes.Any(o => o.Equals(Constant.BtnPrimary)))
{
object backgroundColor = null;
object textColor = null;
object borderColor = null;
object borderWidth = null;
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnPrimaryBackgroundColor, out backgroundColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnPrimaryTextColor, out textColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnPrimaryBorderColor, out borderColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnPrimaryBorderWidth, out borderWidth);
if (backgroundColor != null)
Element.BackgroundColor = (Color)backgroundColor;
else
Element.BackgroundColor = Color.FromHex("#337ab7");
if (textColor != null)
Element.TextColor = (Color)textColor;
else
Element.TextColor = Color.FromHex("#fff");
if (borderColor != null)
Element.BorderColor = (Color)borderColor;
else
Element.BorderColor = Color.FromHex("#2e6da4");
if (borderWidth != null)
Element.BorderWidth = Convert.ToInt16(borderWidth);
else
Element.BorderWidth = 1;
}
else if (classes.Any(o => o.Equals(Constant.BtnSuccess)))
{
object backgroundColor = null;
object textColor = null;
object borderColor = null;
object borderWidth = null;
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnSuccessBackgroundColor, out backgroundColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnSuccessTextColor, out textColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnSuccessBorderColor, out borderColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnSuccessBorderWidth, out borderWidth);
if (backgroundColor != null)
Element.BackgroundColor = (Color)backgroundColor;
else
Element.BackgroundColor = Color.FromHex("#5cb85c");
if (textColor != null)
Element.TextColor = (Color)textColor;
else
Element.TextColor = Color.FromHex("#fff");
if (borderColor != null)
Element.BorderColor = (Color)borderColor;
else
Element.BorderColor = Color.FromHex("#4cae4c");
if (borderWidth != null)
Element.BorderWidth = Convert.ToInt16(borderWidth);
else
Element.BorderWidth = 1;
}
else if (classes.Any(o => o.Equals(Constant.BtnInfo)))
{
object backgroundColor = null;
object textColor = null;
object borderColor = null;
object borderWidth = null;
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnInfoBackgroundColor, out backgroundColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnInfoTextColor, out textColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnInfoBorderColor, out borderColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnInfoBorderWidth, out borderWidth);
if (backgroundColor != null)
Element.BackgroundColor = (Color)backgroundColor;
else
Element.BackgroundColor = Color.FromHex("#5bc0de");
if (textColor != null)
Element.TextColor = (Color)textColor;
else
Element.TextColor = Color.FromHex("#fff");
if (borderColor != null)
Element.BorderColor = (Color)borderColor;
else
Element.BorderColor = Color.FromHex("#46b8da");
if (borderWidth != null)
Element.BorderWidth = Convert.ToInt16(borderWidth);
else
Element.BorderWidth = 1;
}
else if (classes.Any(o => o.Equals(Constant.BtnWarning)))
{
object backgroundColor = null;
object textColor = null;
object borderColor = null;
object borderWidth = null;
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnWarningBackgroundColor, out backgroundColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnWarningTextColor, out textColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnWarningBorderColor, out borderColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnWarningBorderWidth, out borderWidth);
if (backgroundColor != null)
Element.BackgroundColor = (Color)backgroundColor;
else
Element.BackgroundColor = Color.FromHex("#f0ad4e");
if (textColor != null)
Element.TextColor = (Color)textColor;
else
Element.TextColor = Color.FromHex("#fff");
if (borderColor != null)
Element.BorderColor = (Color)borderColor;
else
Element.BorderColor = Color.FromHex("#eea236");
if (borderWidth != null)
Element.BorderWidth = Convert.ToInt16(borderWidth);
else
Element.BorderWidth = 1;
}
else if (classes.Any(o => o.Equals(Constant.BtnDanger)))
{
object backgroundColor = null;
object textColor = null;
object borderColor = null;
object borderWidth = null;
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnDangerBackgroundColor, out backgroundColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnDangerTextColor, out textColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnDangerBorderColor, out borderColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnDangerBorderWidth, out borderWidth);
if (backgroundColor != null)
Element.BackgroundColor = (Color)backgroundColor;
else
Element.BackgroundColor = Color.FromHex("#d9534f");
if (textColor != null)
Element.TextColor = (Color)textColor;
else
Element.TextColor = Color.FromHex("#fff");
if (borderColor != null)
Element.BorderColor = (Color)borderColor;
else
Element.BorderColor = Color.FromHex("#d43f3a");
if (borderWidth != null)
Element.BorderWidth = Convert.ToInt16(borderWidth);
else
Element.BorderWidth = 1;
}
else if (classes.Any(o => o.Equals(Constant.BtnLink)))
{
object backgroundColor = null;
object textColor = null;
object borderColor = null;
object borderWidth = null;
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnLinkBackgroundColor, out backgroundColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnLinkTextColor, out textColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnLinkBorderColor, out borderColor);
Xamarin.Forms.Application.Current.Resources?.TryGetValue(Constant.BtnLinkBorderWidth, out borderWidth);
if (backgroundColor != null)
Element.BackgroundColor = (Color)backgroundColor;
else
Element.BackgroundColor = Color.Transparent;
if (textColor != null)
Element.TextColor = (Color)textColor;
else
Element.TextColor = Color.FromHex("#337ab7");
if (borderColor != null)
Element.BorderColor = (Color)borderColor;
if (borderWidth != null)
Element.BorderWidth = Convert.ToInt16(borderWidth);
}
}
private void ProcessButtonSize(List<string> classes)
{
if (classes.Any(o => o.Equals(Constant.BtnXS)))
{
Element.FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Xamarin.Forms.Button));
thisButton.SetPadding(8, 7, 8, 7);
Element.HeightRequest = Element.FontSize + 14 + 10;
}
else if (classes.Any(o => o.Equals(Constant.BtnSM)))
{
Element.FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Xamarin.Forms.Button));
}
else if (classes.Any(o => o.Equals(Constant.BtnMD)))
{
Element.FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Xamarin.Forms.Button));
thisButton.SetPadding(18, 15, 18, 15);
Element.HeightRequest = Element.FontSize + 30 + 10;
}
else if (classes.Any(o => o.Equals(Constant.BtnLG)))
{
Element.FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Xamarin.Forms.Button));
thisButton.SetPadding(21, 17, 21, 17);
Element.HeightRequest = Element.FontSize + 34 + 10;
}
}
private void ButtonTouched(object sender, TouchEventArgs e)
{
if (e.Event.Action == MotionEventActions.Down)
{
Element.BackgroundColor = pressedBackgroundColor;
Element.TextColor = pressedTextColor;
}
else if (e.Event.Action == MotionEventActions.Up && !isToggleButton)
{
Element.BackgroundColor = originalBackgroundColor;
Element.TextColor = originalTextColor;
}
e.Handled = false;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
thisButton.Touch -= ButtonTouched;
}
base.Dispose(disposing);
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Media;
using Windows.Media.Capture;
using Windows.Media.FaceAnalysis;
using Windows.Media.MediaProperties;
using Windows.System.Threading;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;
namespace SDKTemplate
{
/// <summary>
/// Page for demonstrating FaceTracking.
/// </summary>
public sealed partial class TrackFacesInWebcam : Page
{
/// <summary>
/// Brush for drawing the bounding box around each identified face.
/// </summary>
private readonly SolidColorBrush lineBrush = new SolidColorBrush(Windows.UI.Colors.Yellow);
/// <summary>
/// Thickness of the face bounding box lines.
/// </summary>
private readonly double lineThickness = 2.0;
/// <summary>
/// Transparent fill for the bounding box.
/// </summary>
private readonly SolidColorBrush fillBrush = new SolidColorBrush(Windows.UI.Colors.Transparent);
/// <summary>
/// Reference back to the "root" page of the app.
/// </summary>
private MainPage rootPage;
/// <summary>
/// Holds the current scenario state value.
/// </summary>
private ScenarioState currentState;
/// <summary>
/// References a MediaCapture instance; is null when not in Streaming state.
/// </summary>
private MediaCapture mediaCapture;
/// <summary>
/// Cache of properties from the current MediaCapture device which is used for capturing the preview frame.
/// </summary>
private VideoEncodingProperties videoProperties;
/// <summary>
/// References a FaceTracker instance.
/// </summary>
private FaceTracker faceTracker;
/// <summary>
/// A periodic timer to execute FaceTracker on preview frames
/// </summary>
private ThreadPoolTimer frameProcessingTimer;
/// <summary>
/// Semaphore to ensure FaceTracking logic only executes one at a time
/// </summary>
private SemaphoreSlim frameProcessingSemaphore = new SemaphoreSlim(1);
/// <summary>
/// Initializes a new instance of the <see cref="TrackFacesInWebcam"/> class.
/// </summary>
public TrackFacesInWebcam()
{
this.InitializeComponent();
this.currentState = ScenarioState.Idle;
App.Current.Suspending += this.OnSuspending;
}
/// <summary>
/// Values for identifying and controlling scenario states.
/// </summary>
private enum ScenarioState
{
/// <summary>
/// Display is blank - default state.
/// </summary>
Idle,
/// <summary>
/// Webcam is actively engaged and a live video stream is displayed.
/// </summary>
Streaming
}
/// <summary>
/// Responds when we navigate to this page.
/// </summary>
/// <param name="e">Event data</param>
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
this.rootPage = MainPage.Current;
// The 'await' operation can only be used from within an async method but class constructors
// cannot be labeled as async, and so we'll initialize FaceTracker here.
if (this.faceTracker == null)
{
this.faceTracker = await FaceTracker.CreateAsync();
}
}
/// <summary>
/// Responds to App Suspend event to stop/release MediaCapture object if it's running and return to Idle state.
/// </summary>
/// <param name="sender">The source of the Suspending event</param>
/// <param name="e">Event data</param>
private void OnSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
if (this.currentState == ScenarioState.Streaming)
{
var deferral = e.SuspendingOperation.GetDeferral();
try
{
this.ChangeScenarioState(ScenarioState.Idle);
}
finally
{
deferral.Complete();
}
}
}
/// <summary>
/// Initializes a new MediaCapture instance and starts the Preview streaming to the CamPreview UI element.
/// </summary>
/// <returns>Async Task object returning true if initialization and streaming were successful and false if an exception occurred.</returns>
private async Task<bool> StartWebcamStreaming()
{
bool successful = true;
try
{
this.mediaCapture = new MediaCapture();
// For this scenario, we only need Video (not microphone) so specify this in the initializer.
// NOTE: the appxmanifest only declares "webcam" under capabilities and if this is changed to include
// microphone (default constructor) you must add "microphone" to the manifest or initialization will fail.
MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Video;
await this.mediaCapture.InitializeAsync(settings);
this.mediaCapture.Failed += this.MediaCapture_CameraStreamFailed;
// Cache the media properties as we'll need them later.
var deviceController = this.mediaCapture.VideoDeviceController;
this.videoProperties = deviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;
// Immediately start streaming to our CaptureElement UI.
// NOTE: CaptureElement's Source must be set before streaming is started.
this.CamPreview.Source = this.mediaCapture;
await this.mediaCapture.StartPreviewAsync();
// Use a 66 millisecond interval for our timer, i.e. 15 frames per second
TimeSpan timerInterval = TimeSpan.FromMilliseconds(66);
this.frameProcessingTimer = Windows.System.Threading.ThreadPoolTimer.CreatePeriodicTimer(new Windows.System.Threading.TimerElapsedHandler(ProcessCurrentVideoFrame), timerInterval);
}
catch (System.UnauthorizedAccessException)
{
// If the user has disabled their webcam this exception is thrown; provide a descriptive message to inform the user of this fact.
this.rootPage.NotifyUser("Webcam is disabled or access to the webcam is disabled for this app.\nEnsure Privacy Settings allow webcam usage.", NotifyType.ErrorMessage);
successful = false;
}
catch (Exception ex)
{
this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
successful = false;
}
return successful;
}
/// <summary>
/// Safely stops webcam streaming (if running) and releases MediaCapture object.
/// </summary>
private async void ShutdownWebCam()
{
if(this.frameProcessingTimer != null)
{
this.frameProcessingTimer.Cancel();
}
if (this.mediaCapture != null)
{
if (this.mediaCapture.CameraStreamState == Windows.Media.Devices.CameraStreamState.Streaming)
{
try
{
await this.mediaCapture.StopPreviewAsync();
}
catch(Exception)
{
; // Since we're going to destroy the MediaCapture object there's nothing to do here
}
}
this.mediaCapture.Dispose();
}
this.frameProcessingTimer = null;
this.CamPreview.Source = null;
this.mediaCapture = null;
this.CameraStreamingButton.IsEnabled = true;
}
/// <summary>
/// This method is invoked by a ThreadPoolTimer to execute the FaceTracker and Visualization logic at approximately 15 frames per second.
/// </summary>
/// <remarks>
/// Keep in mind this method is called from a Timer and not synchronized with the camera stream. Also, the processing time of FaceTracker
/// will vary depending on the size of each frame and the number of faces being tracked. That is, a large image with several tracked faces may
/// take longer to process.
/// </remarks>
/// <param name="timer">Timer object invoking this call</param>
private async void ProcessCurrentVideoFrame(ThreadPoolTimer timer)
{
if (this.currentState != ScenarioState.Streaming)
{
return;
}
// If a lock is being held it means we're still waiting for processing work on the previous frame to complete.
// In this situation, don't wait on the semaphore but exit immediately.
if (!frameProcessingSemaphore.Wait(0))
{
return;
}
try
{
IList<DetectedFace> faces = null;
// Create a VideoFrame object specifying the pixel format we want our capture image to be (NV12 bitmap in this case).
// GetPreviewFrame will convert the native webcam frame into this format.
const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Nv12;
using (VideoFrame previewFrame = new VideoFrame(InputPixelFormat, (int)this.videoProperties.Width, (int)this.videoProperties.Height))
{
await this.mediaCapture.GetPreviewFrameAsync(previewFrame);
// The returned VideoFrame should be in the supported NV12 format but we need to verify this.
if (FaceDetector.IsBitmapPixelFormatSupported(previewFrame.SoftwareBitmap.BitmapPixelFormat))
{
faces = await this.faceTracker.ProcessNextFrameAsync(previewFrame);
}
else
{
throw new System.NotSupportedException("PixelFormat '" + InputPixelFormat.ToString() + "' is not supported by FaceDetector");
}
// Create our visualization using the frame dimensions and face results but run it on the UI thread.
var previewFrameSize = new Windows.Foundation.Size(previewFrame.SoftwareBitmap.PixelWidth, previewFrame.SoftwareBitmap.PixelHeight);
var ignored = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
this.SetupVisualization(previewFrameSize, faces);
});
}
}
catch (Exception ex)
{
var ignored = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
this.rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
});
}
finally
{
frameProcessingSemaphore.Release();
}
}
/// <summary>
/// Takes the webcam image and FaceTracker results and assembles the visualization onto the Canvas.
/// </summary>
/// <param name="framePizelSize">Width and height (in pixels) of the video capture frame</param>
/// <param name="foundFaces">List of detected faces; output from FaceTracker</param>
private void SetupVisualization(Windows.Foundation.Size framePizelSize, IList<DetectedFace> foundFaces)
{
this.VisualizationCanvas.Children.Clear();
double actualWidth = this.VisualizationCanvas.ActualWidth;
double actualHeight = this.VisualizationCanvas.ActualHeight;
if (this.currentState == ScenarioState.Streaming && foundFaces != null && actualWidth != 0 && actualHeight != 0)
{
double widthScale = framePizelSize.Width / actualWidth;
double heightScale = framePizelSize.Height / actualHeight;
foreach (DetectedFace face in foundFaces)
{
// Create a rectangle element for displaying the face box but since we're using a Canvas
// we must scale the rectangles according to the frames's actual size.
Rectangle box = new Rectangle();
box.Width = (uint)(face.FaceBox.Width / widthScale);
box.Height = (uint)(face.FaceBox.Height / heightScale);
box.Fill = this.fillBrush;
box.Stroke = this.lineBrush;
box.StrokeThickness = this.lineThickness;
box.Margin = new Thickness((uint)(face.FaceBox.X / widthScale), (uint)(face.FaceBox.Y / heightScale), 0, 0);
this.VisualizationCanvas.Children.Add(box);
}
}
}
/// <summary>
/// Manages the scenario's internal state. Invokes the internal methods and updates the UI according to the
/// passed in state value. Handles failures and resets the state if necessary.
/// </summary>
/// <param name="newState">State to switch to</param>
private async void ChangeScenarioState(ScenarioState newState)
{
// Disable UI while state change is in progress
this.CameraStreamingButton.IsEnabled = false;
switch (newState)
{
case ScenarioState.Idle:
this.ShutdownWebCam();
this.VisualizationCanvas.Children.Clear();
this.CameraStreamingButton.Content = "Start Streaming";
this.currentState = newState;
break;
case ScenarioState.Streaming:
if (!await this.StartWebcamStreaming())
{
this.ChangeScenarioState(ScenarioState.Idle);
break;
}
this.VisualizationCanvas.Children.Clear();
this.CameraStreamingButton.Content = "Stop Streaming";
this.currentState = newState;
this.CameraStreamingButton.IsEnabled = true;
break;
}
}
/// <summary>
/// Handles MediaCapture stream failures by shutting down streaming and returning to Idle state.
/// </summary>
/// <param name="sender">The source of the event, i.e. our MediaCapture object</param>
/// <param name="args">Event data</param>
private void MediaCapture_CameraStreamFailed(MediaCapture sender, object args)
{
// MediaCapture is not Agile and so we cannot invoke its methods on this caller's thread
// and instead need to schedule the state change on the UI thread.
var ignored = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
ChangeScenarioState(ScenarioState.Idle);
});
}
/// <summary>
/// Handles "streaming" button clicks to start/stop webcam streaming.
/// </summary>
/// <param name="sender">Button user clicked</param>
/// <param name="e">Event data</param>
private void CameraStreamingButton_Click(object sender, RoutedEventArgs e)
{
if (this.currentState == ScenarioState.Streaming)
{
this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
this.ChangeScenarioState(ScenarioState.Idle);
}
else
{
this.rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
this.ChangeScenarioState(ScenarioState.Streaming);
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2016 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.Collections.Generic;
using System.Threading;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Execution
{
public class WorkItemTests
{
private WorkItem _workItem;
private TestExecutionContext _context;
[SetUp]
public void CreateWorkItems()
{
IMethodInfo method = new MethodWrapper(typeof(DummyFixture), "DummyTest");
ITest test = new TestMethod(method);
_workItem = WorkItemBuilder.CreateWorkItem(test, TestFilter.Empty);
_context = new TestExecutionContext();
_workItem.InitializeContext(_context);
}
[Test]
public void ConstructWorkItem()
{
Assert.That(_workItem, Is.TypeOf<SimpleWorkItem>());
Assert.That(_workItem.Test.Name, Is.EqualTo("DummyTest"));
Assert.That(_workItem.State, Is.EqualTo(WorkItemState.Ready));
}
[Test]
public void ExecuteWorkItem()
{
_workItem.Execute();
Assert.That(_workItem.State, Is.EqualTo(WorkItemState.Complete));
Assert.That(_context.CurrentResult.ResultState, Is.EqualTo(ResultState.Success));
Assert.That(_context.ExecutionStatus, Is.EqualTo(TestExecutionStatus.Running));
}
[Test]
public void CanStopRun()
{
_context.ExecutionStatus = TestExecutionStatus.StopRequested;
_workItem.Execute();
Assert.That(_workItem.State, Is.EqualTo(WorkItemState.Complete));
Assert.That(_context.CurrentResult.ResultState, Is.EqualTo(ResultState.Success));
Assert.That(_context.ExecutionStatus, Is.EqualTo(TestExecutionStatus.StopRequested));
}
Thread _thread;
private void StartExecution()
{
_thread = new Thread(ThreadProc);
_thread.Start();
}
private void ThreadProc()
{
_workItem.Execute();
}
// Use static for simplicity
static class DummyFixture
{
public static int Delay = 0;
public static void DummyTest()
{
if (Delay > 0)
Thread.Sleep(Delay);
}
}
#if APARTMENT_STATE
[TestCaseSource(nameof(GetTargetApartmentTestData))]
public void GetsTargetApartmentFromParentTests(Test test, ApartmentState expected)
{
var work = new FakeWorkItem(test, TestFilter.Empty);
Assert.That(work.TargetApartment, Is.EqualTo(expected));
}
[TestCaseSource(nameof(GetTargetApartmentTestData))]
public void GetsTargetApartmentFromParentTestsInWrappedTests(Test test, ApartmentState expected)
{
var work = new FakeWorkItem(test, TestFilter.Empty);
var wrapped = new FakeWorkItem(work);
Assert.That(wrapped.TargetApartment, Is.EqualTo(expected));
}
public static IEnumerable<TestCaseData> GetTargetApartmentTestData()
{
yield return new TestCaseData(CreateFakeTests(ApartmentState.Unknown, ApartmentState.Unknown, ApartmentState.Unknown), ApartmentState.Unknown);
yield return new TestCaseData(CreateFakeTests(ApartmentState.Unknown, ApartmentState.Unknown, ApartmentState.STA), ApartmentState.STA);
yield return new TestCaseData(CreateFakeTests(ApartmentState.Unknown, ApartmentState.STA, ApartmentState.Unknown), ApartmentState.STA);
yield return new TestCaseData(CreateFakeTests(ApartmentState.STA, ApartmentState.Unknown, ApartmentState.Unknown), ApartmentState.STA);
yield return new TestCaseData(CreateFakeTests(ApartmentState.Unknown, ApartmentState.Unknown, ApartmentState.MTA), ApartmentState.MTA);
yield return new TestCaseData(CreateFakeTests(ApartmentState.Unknown, ApartmentState.MTA, ApartmentState.Unknown), ApartmentState.MTA);
yield return new TestCaseData(CreateFakeTests(ApartmentState.MTA, ApartmentState.Unknown, ApartmentState.Unknown), ApartmentState.MTA);
yield return new TestCaseData(CreateFakeTests(ApartmentState.STA, ApartmentState.MTA, ApartmentState.Unknown), ApartmentState.MTA);
yield return new TestCaseData(CreateFakeTests(ApartmentState.MTA, ApartmentState.STA, ApartmentState.Unknown), ApartmentState.STA);
}
static ITest CreateFakeTests(ApartmentState assemblyApartment, ApartmentState fixtureApartment, ApartmentState methodApartment) =>
new FakeTest("Method", methodApartment)
{
Parent = new FakeTest("Fixture", fixtureApartment)
{
Parent = new FakeTest("Assembly", assemblyApartment)
}
};
class FakeTest : Test
{
public FakeTest(string name, ApartmentState apartmentState) : base(name)
{
if (apartmentState != ApartmentState.Unknown)
Properties.Add(PropertyNames.ApartmentState, apartmentState);
}
public override object[] Arguments
{
get { throw new System.NotImplementedException(); }
}
public override string XmlElementName => "MockTest";
public override bool HasChildren => Tests.Count > 0;
public override IList<ITest> Tests => new List<ITest>();
public override TNode AddToXml(TNode parentNode, bool recursive)
{
throw new System.NotImplementedException();
}
public override TestResult MakeTestResult() => new FakeTestResult(this);
}
class FakeTestResult : TestResult
{
public FakeTestResult(ITest test) : base(test)
{
}
public override int FailCount => 0;
public override int WarningCount => 0;
public override int PassCount => 1;
public override int SkipCount => 0;
public override int InconclusiveCount => 0;
public override bool HasChildren => false;
public override IEnumerable<ITestResult> Children => null;
}
class FakeWorkItem : WorkItem
{
public FakeWorkItem(WorkItem wrappedItem) : base(wrappedItem)
{
}
public FakeWorkItem(Test test, ITestFilter filter) : base(test, filter)
{
}
protected override void PerformWork()
{
throw new System.NotImplementedException();
}
}
#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.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Hyak.Common;
using Microsoft.Azure.Insights;
using Microsoft.Azure.Insights.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Insights
{
/// <summary>
/// Operations for metric values.
/// </summary>
public partial class MetricOperations : IServiceOperations<InsightsClient>, IMetricOperations
{
/// <summary>
/// Initializes a new instance of the MetricOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal MetricOperations(InsightsClient client)
{
this._client = client;
}
private InsightsClient _client;
/// <summary>
/// Gets a reference to the Microsoft.Azure.Insights.InsightsClient.
/// </summary>
public InsightsClient Client
{
get { return this._client; }
}
/// <summary>
/// The List Metric operation lists the metric value sets for the
/// resource metrics.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource identifier of the target resource to get
/// metrics for.
/// </param>
/// <param name='filterString'>
/// Optional. An OData $filter expression that supports querying by the
/// name, startTime, endTime and timeGrain of the metric value sets.
/// For example, "(name.value eq 'Percentage CPU') and startTime eq
/// 2014-07-02T01:00Z and endTime eq 2014-08-21T01:00:00Z and
/// timeGrain eq duration'PT1H'". In the expression, startTime,
/// endTime and timeGrain are required. Name is optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Metric values operation response.
/// </returns>
public async Task<MetricListResponse> GetMetricsInternalAsync(string resourceUri, string filterString, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("filterString", filterString);
TracingAdapter.Enter(invocationId, this, "GetMetricsAsync", tracingParameters);
}
// Construct URL
string url = "/" + Uri.EscapeDataString(resourceUri) + "/metrics?";
url = url + "api-version=2014-04-01";
if (filterString != null)
{
url = url + "&$filter=" + Uri.EscapeDataString(filterString);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
MetricListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new MetricListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
MetricCollection metricCollectionInstance = new MetricCollection();
result.MetricCollection = metricCollectionInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Metric metricInstance = new Metric();
metricCollectionInstance.Value.Add(metricInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
LocalizableString nameInstance = new LocalizableString();
metricInstance.Name = nameInstance;
JToken valueValue2 = nameValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
nameInstance.Value = valueInstance;
}
JToken localizedValueValue = nameValue["localizedValue"];
if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
{
string localizedValueInstance = ((string)localizedValueValue);
nameInstance.LocalizedValue = localizedValueInstance;
}
}
JToken unitValue = valueValue["unit"];
if (unitValue != null && unitValue.Type != JTokenType.Null)
{
Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true));
metricInstance.Unit = unitInstance;
}
JToken timeGrainValue = valueValue["timeGrain"];
if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
{
TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue));
metricInstance.TimeGrain = timeGrainInstance;
}
JToken startTimeValue = valueValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
metricInstance.StartTime = startTimeInstance;
}
JToken endTimeValue = valueValue["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTime endTimeInstance = ((DateTime)endTimeValue);
metricInstance.EndTime = endTimeInstance;
}
JToken metricValuesArray = valueValue["metricValues"];
if (metricValuesArray != null && metricValuesArray.Type != JTokenType.Null)
{
foreach (JToken metricValuesValue in ((JArray)metricValuesArray))
{
MetricValue metricValueInstance = new MetricValue();
metricInstance.MetricValues.Add(metricValueInstance);
JToken timestampValue = metricValuesValue["timestamp"];
if (timestampValue != null && timestampValue.Type != JTokenType.Null)
{
DateTime timestampInstance = ((DateTime)timestampValue);
metricValueInstance.Timestamp = timestampInstance;
}
JToken averageValue = metricValuesValue["average"];
if (averageValue != null && averageValue.Type != JTokenType.Null)
{
double averageInstance = ((double)averageValue);
metricValueInstance.Average = averageInstance;
}
JToken minimumValue = metricValuesValue["minimum"];
if (minimumValue != null && minimumValue.Type != JTokenType.Null)
{
double minimumInstance = ((double)minimumValue);
metricValueInstance.Minimum = minimumInstance;
}
JToken maximumValue = metricValuesValue["maximum"];
if (maximumValue != null && maximumValue.Type != JTokenType.Null)
{
double maximumInstance = ((double)maximumValue);
metricValueInstance.Maximum = maximumInstance;
}
JToken totalValue = metricValuesValue["total"];
if (totalValue != null && totalValue.Type != JTokenType.Null)
{
double totalInstance = ((double)totalValue);
metricValueInstance.Total = totalInstance;
}
JToken countValue = metricValuesValue["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
metricValueInstance.Count = countInstance;
}
JToken lastValue = metricValuesValue["last"];
if (lastValue != null && lastValue.Type != JTokenType.Null)
{
double lastInstance = ((double)lastValue);
metricValueInstance.Last = lastInstance;
}
JToken propertiesSequenceElement = ((JToken)metricValuesValue["properties"]);
if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in propertiesSequenceElement)
{
string propertiesKey = ((string)property.Name);
string propertiesValue = ((string)property.Value);
metricValueInstance.Properties.Add(propertiesKey, propertiesValue);
}
}
}
}
JToken resourceIdValue = valueValue["resourceId"];
if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
{
string resourceIdInstance = ((string)resourceIdValue);
metricInstance.ResourceId = resourceIdInstance;
}
JToken propertiesSequenceElement2 = ((JToken)valueValue["properties"]);
if (propertiesSequenceElement2 != null && propertiesSequenceElement2.Type != JTokenType.Null)
{
foreach (JProperty property2 in propertiesSequenceElement2)
{
string propertiesKey2 = ((string)property2.Name);
string propertiesValue2 = ((string)property2.Value);
metricInstance.Properties.Add(propertiesKey2, propertiesValue2);
}
}
JToken dimensionNameValue = valueValue["dimensionName"];
if (dimensionNameValue != null && dimensionNameValue.Type != JTokenType.Null)
{
LocalizableString dimensionNameInstance = new LocalizableString();
metricInstance.DimensionName = dimensionNameInstance;
JToken valueValue3 = dimensionNameValue["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue3);
dimensionNameInstance.Value = valueInstance2;
}
JToken localizedValueValue2 = dimensionNameValue["localizedValue"];
if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null)
{
string localizedValueInstance2 = ((string)localizedValueValue2);
dimensionNameInstance.LocalizedValue = localizedValueInstance2;
}
}
JToken dimensionValueValue = valueValue["dimensionValue"];
if (dimensionValueValue != null && dimensionValueValue.Type != JTokenType.Null)
{
LocalizableString dimensionValueInstance = new LocalizableString();
metricInstance.DimensionValue = dimensionValueInstance;
JToken valueValue4 = dimensionValueValue["value"];
if (valueValue4 != null && valueValue4.Type != JTokenType.Null)
{
string valueInstance3 = ((string)valueValue4);
dimensionValueInstance.Value = valueInstance3;
}
JToken localizedValueValue3 = dimensionValueValue["localizedValue"];
if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null)
{
string localizedValueInstance3 = ((string)localizedValueValue3);
dimensionValueInstance.LocalizedValue = localizedValueInstance3;
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// 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.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reactive.Disposables;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Its.Recipes;
using Its.Validation;
using Its.Validation.Configuration;
using Moq;
using NUnit.Framework;
using Sample.Domain.Ordering;
using Sample.Domain.Ordering.Commands;
using Microsoft.Its.Domain.Testing;
namespace Microsoft.Its.Domain.Tests
{
[TestFixture]
public class CommandTests
{
private CompositeDisposable disposables;
[SetUp]
public void SetUp()
{
// disable authorization
Command<FakeAggregateWithEnactCommandConvention>.AuthorizeDefault = (o, c) => true;
Command<FakeAggregateWithNestedCommandConvention>.AuthorizeDefault = (o, c) => true;
Command<Order>.AuthorizeDefault = (o, c) => true;
disposables = new CompositeDisposable
{
ConfigurationContext.Establish(new Configuration()
.IgnoreScheduledCommands())
};
}
[TearDown]
public void TearDown()
{
disposables.Dispose();
}
[Test]
public void Default_CommandValidator_uses_DataAnnotations()
{
var command = new CommandWithDataAnnotations();
var aggregate = new FakeAggregateWithEnactCommandConvention();
var report = aggregate.Validate(command);
report
.Failures
.Should()
.Contain(f => f.MemberPath == "Name");
}
[Test]
public void Default_CommandValidator_for_ConstructorCommand_uses_DataAnnotations()
{
var command = new ConstructorCommandWithDataAnnotations();
var aggregate = new FakeAggregateWithEnactCommandConvention();
var report = aggregate.Validate(command);
report
.Failures
.Should()
.Contain(f => f.MemberPath == "Name");
}
[Test]
public void When_command_state_is_invalid_then_calling_ApplyTo_throws()
{
var command = new CommandWithAggregateValidator();
command.Invoking(c => c.ApplyTo(new FakeAggregateWithEnactCommandConvention()))
.ShouldThrow<CommandValidationException>()
.And
.Message.Should().Contain("Validation error while applying CommandWithAggregateValidator to a FakeAggregateWithEnactCommandConvention")
.And
.Contain("The Name field is required");
}
[Test]
public void When_aggregate_state_is_invalid_then_calling_ApplyTo_throws()
{
var command = new CommandWithAggregateValidator
{
Name = "foo"
};
command.Invoking(c => c.ApplyTo(new FakeAggregateWithEnactCommandConvention()))
.ShouldThrow<CommandValidationException>()
.And
.Message.Should().Contain("Ain't valid!");
}
[Test]
public void An_aggregate_can_record_an_event_for_a_command_that_fails_during_validation_using_HandleCommandValidationFailure()
{
var order = new Order(new CreateOrder(Any.FullName()))
.Apply(new AddItem
{
Price = 10m,
ProductName = Any.CompanyName()
})
.Apply(new Ship())
.Apply(new ChargeCreditCard
{
Amount = 10m,
CallPaymentService = _ => { throw new ArgumentException("Insufficient funds!"); }
});
order.PendingEvents
.Last()
.Should()
.BeOfType<Order.CreditCardChargeRejected>();
}
[Test]
public void A_command_can_call_a_domain_service_and_cache_the_value_and_set_its_ETag_on_success()
{
var chargeCreditCard = new ChargeCreditCard
{
Amount = 10m
};
var order = new Order(new CreateOrder(Any.FullName()))
.Apply(new AddItem
{
Price = 10m,
ProductName = Any.CompanyName()
})
.Apply(new Ship())
.Apply(chargeCreditCard);
var charged = order.PendingEvents
.Last()
.As<Order.CreditCardCharged>();
charged.ETag.Should().Be(chargeCreditCard.ETag);
charged.Amount.Should().Be(chargeCreditCard.Amount);
}
[Test]
public void An_aggregate_can_choose_whether_to_throw_for_a_failed_command_using_HandleCommandValidationFailure()
{
Action charge = () => new Order(new CreateOrder(Any.FullName()))
.Apply(new ChargeCreditCard());
charge.ShouldThrow<CommandValidationException>()
.And
.Message
.Should()
.Contain("The field Amount must be between 0.01 and 1.79769313486232E+308.");
}
[Test]
public void When_command_validator_is_not_of_the_correct_generic_type_then_an_informative_exception_is_thrown()
{
var command = new CommandWithBadCommandValidator();
command.Invoking(c => c.ApplyTo(new FakeAggregateWithEnactCommandConvention()))
.ShouldThrow<InvalidOperationException>()
.And
.Message.Should().Contain("Property CommandValidator returned a validator of the wrong type.");
}
[Test]
public void When_command_validator_is_IValidationrule_of_the_correct_generic_type_then_no_exception_is_thrown()
{
var command = new CommandWithCommandValidator(Validate.That<CommandWithCommandValidator>(s => true));
command.Invoking(c => c.ApplyTo(new FakeAggregateWithEnactCommandConvention()))
.ShouldNotThrow();
}
[Test]
public void Authorization_can_be_specified_in_the_command_class()
{
var command = new CommandWithCustomAuthorization
{
Authorized = () => false
};
command.Invoking(c => c.ApplyTo(new FakeAggregateWithEnactCommandConvention()))
.ShouldThrow<CommandAuthorizationException>();
command.Authorized = () => true;
command.Invoking(c => c.ApplyTo(new FakeAggregateWithEnactCommandConvention()))
.ShouldNotThrow();
}
[Test]
public void When_AppliesToVersion_is_specified_on_command_and_does_not_match_aggregate_Version_then_Apply_throws()
{
var order = new Order();
order.Apply(new AddItem { Price = 10, ProductName = "Widget" })
.Apply(new Ship())
.Apply(new ProvideCreditCardInfo
{
CreditCardCvv2 = "123",
CreditCardExpirationMonth = "09",
CreditCardExpirationYear = "2071",
CreditCardNumber = "2344123412341234",
CreditCardName = Any.FullName()
})
.Apply(new ChargeCreditCard
{
Amount = 10,
})
.Apply(new Deliver())
.ConfirmSave();
var actualVersion = order.Version();
var requiredVersion = actualVersion - 1;
var command = new Cancel
{
AppliesToVersion = requiredVersion
};
Action applyCancel = () => order.Apply(command);
applyCancel.ShouldThrow<ConcurrencyException>()
.WithMessage(string.Format("The command's AppliesToVersion value ({0}) does not match the aggregate's version ({1})", requiredVersion, actualVersion));
}
[Test]
public void When_AppliesToVersion_is_specified_on_command_and_does_indeed_match_aggregate_Version_then_Apply_does_not_throw()
{
var order = new Order();
order.ConfirmSave();
var actualVersion = order.Version();
var requiredVersion = actualVersion;
var command = new Cancel
{
AppliesToVersion = requiredVersion
};
Action applyCancel = () => order.Apply(command);
applyCancel.ShouldNotThrow("Because the AppliesToVersion value ({0}) matches the aggregate's version ({1})", requiredVersion, actualVersion);
}
[Test]
public void Command_T_KnownTypes_returns_nested_types()
{
Command<FakeAggregateWithNestedCommandConvention>.KnownTypes
.Should()
.Contain(t => t == typeof (FakeAggregateWithNestedCommandConvention.CommandWithAggregateValidator));
}
[Test]
public void Named_returns_nested_types()
{
Command<FakeAggregateWithNestedCommandConvention>.Named("CommandWithAggregateValidator")
.Should()
.Be(typeof (FakeAggregateWithNestedCommandConvention.CommandWithAggregateValidator));
}
[Test]
public void CommandValidator_rules_based_on_data_annotations_attributes_are_cached()
{
var command1 = new CommandWithDataAnnotations();
var command2 = new CommandWithDataAnnotations();
command1.CommandValidator.Should().BeSameAs(command2.CommandValidator);
}
[Test]
public void Custom_CommandValidator_rules_are_not_cached()
{
var command1 = new CommandWithCommandValidator(Validate.That<CommandWithCommandValidator>(t => true));
var command2 = new CommandWithCommandValidator(Validate.That<CommandWithCommandValidator>(t => true));
command1.CommandValidator.Should().NotBeSameAs(command2.CommandValidator);
}
[Test]
public void Commands_can_be_made_idempotent_by_setting_an_ETag()
{
var newName = Any.FullName();
var etag = Any.Word();
var order = new Order(new CreateOrder(Any.FullName()));
order.Apply(new ChangeCustomerInfo
{
CustomerName = newName,
ETag = etag
});
order.ConfirmSave();
order.Apply(new ChangeCustomerInfo
{
CustomerName = Any.FullName(),
ETag = etag
});
order.CustomerName.Should().Be(newName);
}
[Test]
public void ICommandHandler_implementations_have_dependencies_injected()
{
Configuration.Current.UseDependency<IPaymentService>(_ => new CreditCardPaymentGateway());
var order = new Order(new CreateOrder(Any.FullName()))
.Apply(new AddItem
{
Price = 5m,
ProductName = Any.Word()
})
.Apply(new Ship())
.Apply(new ChargeAccount
{
AccountNumber = Any.PositiveInt().ToString()
});
order.Events()
.Last()
.Should()
.BeOfType<Order.PaymentConfirmed>();
}
[Test]
public void A_command_handler_can_record_an_event_for_a_failed_domain_service_call()
{
var paymentService = new Mock<IPaymentService>();
paymentService.Setup(m => m.Charge(It.IsAny<decimal>()))
.Throws(new InvalidOperationException("Account does not exist"));
Configuration.Current.UseDependency(_ => paymentService.Object);
var order = new Order(new CreateOrder(Any.FullName()))
.Apply(new AddItem
{
Price = 5m,
ProductName = Any.Word()
})
.Apply(new Ship())
.Apply(new ChargeAccount
{
AccountNumber = Any.PositiveInt().ToString()
});
order.PendingEvents
.Last()
.Should()
.BeOfType<Order.ChargeAccountChargeRejected>();
}
[Test]
public async Task A_command_can_be_applied_asynchronously()
{
Configuration.Current.UseDependency<IPaymentService>(_ => new CreditCardPaymentGateway());
var order = new Order(new CreateOrder(Any.FullName()));
order.Apply(new AddItem
{
Price = 5m,
ProductName = Any.Word()
});
await order.ApplyAsync(new Ship());
order.Events()
.Last()
.Should()
.BeOfType<Order.Shipped>();
}
public class FakeAggregateWithEnactCommandConvention : EventSourcedAggregate<FakeAggregateWithEnactCommandConvention>
{
public FakeAggregateWithEnactCommandConvention(ConstructorCommand<FakeAggregateWithEnactCommandConvention> createCommand) : base(createCommand)
{
}
public bool IsValid = true;
public FakeAggregateWithEnactCommandConvention(Guid? id = null) : base(id)
{
}
public FakeAggregateWithEnactCommandConvention(Guid id, IEnumerable<IEvent> eventHistory) : base(id, eventHistory)
{
}
public void EnactCommand(CommandWithAggregateValidator command)
{
}
public void EnactCommand(CommandWithCommandValidator command)
{
}
public void EnactCommand(CommandWithCustomAuthorization command)
{
}
}
public class FakeAggregateWithNestedCommandConvention : IEventSourced
{
public FakeAggregateWithNestedCommandConvention()
{
}
public FakeAggregateWithNestedCommandConvention(Guid id, IEnumerable<IEvent> history)
{
Id = id;
PendingEvents = history;
}
public Guid Id { get; private set; }
public long Version
{
get
{
return PendingEvents.Max(e => e.SequenceNumber);
}
}
public IEnumerable<IEvent> PendingEvents { get; private set; }
public void ConfirmSave()
{
throw new NotImplementedException();
}
public bool IsValid = true;
public class CommandWithAggregateValidator : Command<FakeAggregateWithNestedCommandConvention>
{
[Required]
public string Name { get; set; }
public override IValidationRule<FakeAggregateWithNestedCommandConvention> Validator
{
get
{
return Validate
.That<FakeAggregateWithNestedCommandConvention>(o => IsValid)
.WithErrorMessage("Ain't valid!");
}
}
public bool IsValid { get; set; }
}
}
public class CommandWithCommandValidator : Command<FakeAggregateWithEnactCommandConvention>
{
private readonly IValidationRule commandValidator;
public CommandWithCommandValidator(IValidationRule commandValidator)
{
this.commandValidator = commandValidator;
}
public override IValidationRule<FakeAggregateWithEnactCommandConvention> Validator
{
get
{
return Validate.That<FakeAggregateWithEnactCommandConvention>(o => o.IsValid);
}
}
public override IValidationRule CommandValidator
{
get
{
return commandValidator;
}
}
}
public class CommandWithBadCommandValidator : Command<FakeAggregateWithEnactCommandConvention>
{
public override IValidationRule CommandValidator
{
get
{
return Validate.That<string>(t => true);
}
}
}
public class CommandWithCustomAuthorization : Command<FakeAggregateWithEnactCommandConvention>
{
public override IValidationRule<FakeAggregateWithEnactCommandConvention> Validator
{
get
{
return Validate.That<FakeAggregateWithEnactCommandConvention>(a => true);
}
}
public override bool Authorize(FakeAggregateWithEnactCommandConvention aggregate)
{
return Authorized();
}
public Func<bool> Authorized = () => false;
}
public class CommandWithAggregateValidator : Command<FakeAggregateWithEnactCommandConvention>
{
[Required]
public string Name { get; set; }
public override IValidationRule<FakeAggregateWithEnactCommandConvention> Validator
{
get
{
return Validate
.That<FakeAggregateWithEnactCommandConvention>(o => IsValid)
.WithErrorMessage("Ain't valid!");
}
}
public bool IsValid { get; set; }
}
public class CommandWithDataAnnotations : Command<FakeAggregateWithEnactCommandConvention>
{
[Required]
public string Name { get; set; }
}
public class ConstructorCommandWithDataAnnotations : ConstructorCommand<FakeAggregateWithEnactCommandConvention>
{
[Required]
public string Name { get; set; }
public override IValidationRule CommandValidator
{
get
{
var baseValidations = (IValidationRule<ConstructorCommandWithDataAnnotations>) base.CommandValidator;
return new ValidationPlan<ConstructorCommandWithDataAnnotations>
{
baseValidations
};
}
}
}
public class NonEventSourcedCommand : Command<object>
{
public override bool Authorize(object aggregate)
{
return true;
}
}
}
}
| |
//
// https://github.com/mythz/ServiceStack.Redis
// ServiceStack.Redis: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Demis Bellot ([email protected])
//
// Copyright 2013 ServiceStack.
//
// Licensed under the same terms of Redis and ServiceStack: new BSD license.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NServiceKit.Common.Extensions;
using NServiceKit.Common.Utils;
using NServiceKit.DesignPatterns.Model;
using NServiceKit.Redis.Pipeline;
using NServiceKit.Text;
namespace NServiceKit.Redis.Generic
{
/// <summary>
/// Allows you to get Redis value operations to operate against POCO types.
/// </summary>
/// <typeparam name="T"></typeparam>
public partial class RedisTypedClient<T>
: IRedisTypedClient<T>
{
readonly ITypeSerializer<T> serializer = new JsonSerializer<T>();
private readonly RedisClient client;
public IRedisClient RedisClient
{
get { return client; }
}
public IRedisNativeClient NativeClient
{
get { return client; }
}
/// <summary>
/// Use this to share the same redis connection with another
/// </summary>
/// <param name="client">The client.</param>
public RedisTypedClient(RedisClient client)
{
this.client = client;
this.Lists = new RedisClientLists(this);
this.Sets = new RedisClientSets(this);
this.SortedSets = new RedisClientSortedSets(this);
this.SequenceKey = client.GetTypeSequenceKey<T>();
this.TypeIdsSetKey = client.GetTypeIdsSetKey<T>();
this.TypeLockKey = string.Concat(client.NamespacePrefix, "lock:", typeof(T).Name);
this.RecentSortedSetKey = string.Concat(client.NamespacePrefix, "recent:", typeof(T).Name);
}
private readonly string RecentSortedSetKey;
public string TypeIdsSetKey { get; set; }
public string TypeLockKey { get; set; }
public IRedisTypedTransaction<T> CreateTransaction()
{
return new RedisTypedTransaction<T>(this);
}
public IRedisTypedPipeline<T> CreatePipeline()
{
return new RedisTypedPipeline<T>(this);
}
public IDisposable AcquireLock()
{
return client.AcquireLock(this.TypeLockKey);
}
public IDisposable AcquireLock(TimeSpan timeOut)
{
return client.AcquireLock(this.TypeLockKey, timeOut);
}
public IRedisTransactionBase Transaction
{
get
{
return client.Transaction;
}
set
{
client.Transaction = value;
}
}
public IRedisPipelineShared Pipeline
{
get
{
return client.Pipeline;
}
set
{
client.Pipeline = value;
}
}
public void Watch(params string[] keys)
{
client.Watch(keys);
}
public void UnWatch()
{
client.UnWatch();
}
public void Multi()
{
this.client.Multi();
}
public void Discard()
{
this.client.Discard();
}
public void Exec()
{
client.Exec();
}
internal void AddTypeIdsRegisteredDuringPipeline()
{
client.AddTypeIdsRegisteredDuringPipeline();
}
internal void ClearTypeIdsRegisteredDuringPipeline()
{
client.ClearTypeIdsRegisteredDuringPipeline();
}
public List<string> GetAllKeys()
{
return client.GetAllKeys();
}
public IRedisSet TypeIdsSet
{
get
{
return new RedisClientSet(client, client.GetTypeIdsSetKey<T>());
}
}
public T this[string key]
{
get { return GetValue(key); }
set { SetEntry(key, value); }
}
public byte[] SerializeValue(T value)
{
var strValue = serializer.SerializeToString(value);
return Encoding.UTF8.GetBytes(strValue);
}
public T DeserializeValue(byte[] value)
{
var strValue = value != null ? Encoding.UTF8.GetString(value) : null;
return serializer.DeserializeFromString(strValue);
}
public void SetEntry(string key, T value)
{
if (key == null)
throw new ArgumentNullException("key");
client.Set(key, SerializeValue(value));
client.RegisterTypeId(value);
}
public void SetEntry(string key, T value, TimeSpan expireIn)
{
if (key == null)
throw new ArgumentNullException("key");
client.Set(key, SerializeValue(value), expireIn);
client.RegisterTypeId(value);
}
public bool SetEntryIfNotExists(string key, T value)
{
var success = client.SetNX(key, SerializeValue(value)) == RedisNativeClient.Success;
if (success) client.RegisterTypeId(value);
return success;
}
public T GetValue(string key)
{
return DeserializeValue(client.Get(key));
}
public T GetAndSetValue(string key, T value)
{
return DeserializeValue(client.GetSet(key, SerializeValue(value)));
}
public bool ContainsKey(string key)
{
return client.Exists(key) == RedisNativeClient.Success;
}
public bool RemoveEntry(string key)
{
return client.Del(key) == RedisNativeClient.Success;
}
public bool RemoveEntry(params string[] keys)
{
return client.Del(keys) == RedisNativeClient.Success;
}
public bool RemoveEntry(params IHasStringId[] entities)
{
var ids = entities.ConvertAll(x => x.Id);
var success = client.Del(ids.ToArray()) == RedisNativeClient.Success;
if (success) client.RemoveTypeIds(ids.ToArray());
return success;
}
public long IncrementValue(string key)
{
return client.Incr(key);
}
public long IncrementValueBy(string key, int count)
{
return client.IncrBy(key, count);
}
public long DecrementValue(string key)
{
return client.Decr(key);
}
public long DecrementValueBy(string key, int count)
{
return client.DecrBy(key, count);
}
public string SequenceKey { get; set; }
public void SetSequence(int value)
{
client.GetSet(SequenceKey, Encoding.UTF8.GetBytes(value.ToString()));
}
public long GetNextSequence()
{
return IncrementValue(SequenceKey);
}
public long GetNextSequence(int incrBy)
{
return IncrementValueBy(SequenceKey, incrBy);
}
public RedisKeyType GetEntryType(string key)
{
return client.GetEntryType(key);
}
public string GetRandomKey()
{
return client.RandomKey();
}
public bool ExpireEntryIn(string key, TimeSpan expireIn)
{
return client.Expire(key, (int)expireIn.TotalSeconds);
}
public bool ExpireEntryAt(string key, DateTime expireAt)
{
return client.ExpireAt(key, expireAt.ToUnixTime());
}
public bool ExpireIn(object id, TimeSpan expireIn)
{
var key = client.UrnKey<T>(id);
return client.Expire(key, (int)expireIn.TotalSeconds);
}
public bool ExpireAt(object id, DateTime expireAt)
{
var key = client.UrnKey<T>(id);
return client.ExpireAt(key, expireAt.ToUnixTime());
}
public TimeSpan GetTimeToLive(string key)
{
return TimeSpan.FromSeconds(client.Ttl(key));
}
public void Save()
{
client.Save();
}
public void SaveAsync()
{
client.SaveAsync();
}
public void FlushDb()
{
client.FlushDb();
}
public void FlushAll()
{
client.FlushAll();
}
public T[] SearchKeys(string pattern)
{
var strKeys = client.SearchKeys(pattern);
var keysCount = strKeys.Count;
var keys = new T[keysCount];
for (var i=0; i < keysCount; i++)
{
keys[i] = serializer.DeserializeFromString(strKeys[i]);
}
return keys;
}
public List<T> GetValues(List<string> keys)
{
if (keys.IsNullOrEmpty()) return new List<T>();
var resultBytesArray = client.MGet(keys.ToArray());
var results = new List<T>();
foreach (var resultBytes in resultBytesArray)
{
if (resultBytes == null) continue;
var result = DeserializeValue(resultBytes);
results.Add(result);
}
return results;
}
public void StoreAsHash(T entity)
{
client.StoreAsHash(entity);
}
public T GetFromHash(object id)
{
return client.GetFromHash<T>(id);
}
#region Implementation of IBasicPersistenceProvider<T>
public T GetById(object id)
{
var key = client.UrnKey<T>(id);
return this.GetValue(key);
}
public IList<T> GetByIds(IEnumerable ids)
{
if (ids != null)
{
var urnKeys = ids.ConvertAll(x => client.UrnKey<T>(x));
if (urnKeys.Count != 0)
return GetValues(urnKeys);
}
return new List<T>();
}
public IList<T> GetAll()
{
var allKeys = client.GetAllItemsFromSet(this.TypeIdsSetKey);
return this.GetByIds(allKeys.ToArray());
}
public T Store(T entity)
{
var urnKey = client.UrnKey(entity);
this.SetEntry(urnKey, entity);
return entity;
}
public void StoreAll(IEnumerable<T> entities)
{
if (entities == null) return;
var entitiesList = entities.ToList();
var len = entitiesList.Count;
var keys = new byte[len][];
var values = new byte[len][];
for (var i = 0; i < len; i++)
{
keys[i] = client.UrnKey(entitiesList[i]).ToUtf8Bytes();
values[i] = Redis.RedisClient.SerializeToUtf8Bytes(entitiesList[i]);
}
client.MSet(keys, values);
client.RegisterTypeIds(entitiesList);
}
public void Delete(T entity)
{
var urnKey = client.UrnKey(entity);
this.RemoveEntry(urnKey);
client.RemoveTypeIds(entity);
}
public void DeleteById(object id)
{
var urnKey = client.UrnKey<T>(id);
this.RemoveEntry(urnKey);
client.RemoveTypeIds<T>(id.ToString());
}
public void DeleteByIds(IEnumerable ids)
{
if (ids == null) return;
var urnKeys = ids.ConvertAll(t => client.UrnKey<T>(t));
if (urnKeys.Count > 0)
{
this.RemoveEntry(urnKeys.ToArray());
client.RemoveTypeIds<T>(ids.ConvertAll(x => x.ToString()).ToArray());
}
}
public void DeleteAll()
{
var ids = client.GetAllItemsFromSet(this.TypeIdsSetKey);
var urnKeys = ids.ConvertAll(t => client.UrnKey<T>(t));
if (urnKeys.Count > 0)
{
this.RemoveEntry(urnKeys.ToArray());
this.RemoveEntry(this.TypeIdsSetKey);
}
}
#endregion
internal void ExpectQueued()
{
client.ExpectQueued();
}
internal void ExpectOk()
{
client.ExpectOk();
}
internal int ReadMultiDataResultCount()
{
return client.ReadMultiDataResultCount();
}
public void FlushSendBuffer()
{
client.FlushSendBuffer();
}
public void ResetSendBuffer()
{
client.ResetSendBuffer();
}
[Obsolete("Does nothing currently, RedisTypedClient will not be IDisposable in a future version")]
public void Dispose() {}
}
}
| |
#region License
/*
* EndPointManager.cs
*
* This code is derived from EndPointManager.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2016 sta.blockhead
*
* 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
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <[email protected]>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <[email protected]>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
namespace WebSocketSharp.Net
{
internal sealed class EndPointManager
{
#region Private Fields
private static readonly Dictionary<IPEndPoint, EndPointListener> _endpoints;
#endregion
#region Static Constructor
static EndPointManager ()
{
_endpoints = new Dictionary<IPEndPoint, EndPointListener> ();
}
#endregion
#region Private Constructors
private EndPointManager ()
{
}
#endregion
#region Private Methods
private static void addPrefix (string uriPrefix, HttpListener listener)
{
var pref = new HttpListenerPrefix (uriPrefix);
var addr = convertToIPAddress (pref.Host);
if (!addr.IsLocal ())
throw new HttpListenerException (87, "Includes an invalid host.");
int port;
if (!Int32.TryParse (pref.Port, out port))
throw new HttpListenerException (87, "Includes an invalid port.");
if (!port.IsPortNumber ())
throw new HttpListenerException (87, "Includes an invalid port.");
var path = pref.Path;
if (path.IndexOf ('%') != -1)
throw new HttpListenerException (87, "Includes an invalid path.");
if (path.IndexOf ("//", StringComparison.Ordinal) != -1)
throw new HttpListenerException (87, "Includes an invalid path.");
var endpoint = new IPEndPoint (addr, port);
EndPointListener lsnr;
if (_endpoints.TryGetValue (endpoint, out lsnr)) {
if (lsnr.IsSecure ^ pref.IsSecure)
throw new HttpListenerException (87, "Includes an invalid scheme.");
}
else {
lsnr =
new EndPointListener (
endpoint,
pref.IsSecure,
listener.CertificateFolderPath,
listener.SslConfiguration,
listener.ReuseAddress
);
_endpoints.Add (endpoint, lsnr);
}
lsnr.AddPrefix (pref, listener);
}
private static IPAddress convertToIPAddress (string hostname)
{
return hostname == "*" || hostname == "+" ? IPAddress.Any : hostname.ToIPAddress ();
}
private static void removePrefix (string uriPrefix, HttpListener listener)
{
var pref = new HttpListenerPrefix (uriPrefix);
var addr = convertToIPAddress (pref.Host);
if (!addr.IsLocal ())
return;
int port;
if (!Int32.TryParse (pref.Port, out port))
return;
if (!port.IsPortNumber ())
return;
var path = pref.Path;
if (path.IndexOf ('%') != -1)
return;
if (path.IndexOf ("//", StringComparison.Ordinal) != -1)
return;
var endpoint = new IPEndPoint (addr, port);
EndPointListener lsnr;
if (!_endpoints.TryGetValue (endpoint, out lsnr))
return;
if (lsnr.IsSecure ^ pref.IsSecure)
return;
lsnr.RemovePrefix (pref, listener);
}
#endregion
#region Internal Methods
internal static bool RemoveEndPoint (IPEndPoint endpoint)
{
lock (((ICollection) _endpoints).SyncRoot) {
EndPointListener lsnr;
if (!_endpoints.TryGetValue (endpoint, out lsnr))
return false;
_endpoints.Remove (endpoint);
lsnr.Close ();
return true;
}
}
#endregion
#region Public Methods
public static void AddListener (HttpListener listener)
{
var added = new List<string> ();
lock (((ICollection) _endpoints).SyncRoot) {
try {
foreach (var pref in listener.Prefixes) {
addPrefix (pref, listener);
added.Add (pref);
}
}
catch {
foreach (var pref in added)
removePrefix (pref, listener);
throw;
}
}
}
public static void AddPrefix (string uriPrefix, HttpListener listener)
{
lock (((ICollection) _endpoints).SyncRoot)
addPrefix (uriPrefix, listener);
}
public static void RemoveListener (HttpListener listener)
{
lock (((ICollection) _endpoints).SyncRoot) {
foreach (var pref in listener.Prefixes)
removePrefix (pref, listener);
}
}
public static void RemovePrefix (string uriPrefix, HttpListener listener)
{
lock (((ICollection) _endpoints).SyncRoot)
removePrefix (uriPrefix, listener);
}
#endregion
}
}
| |
using System;
/*
* 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 org.apache.commons.math3.exception;
using org.apache.commons.math3.analysis.util;
using FastMath = System.Math;
namespace org.apache.commons.math3.analysis.solvers
{
/// <summary>
/// This class implements a modification of the <a
/// href="http://mathworld.wolfram.com/BrentsMethod.html"> Brent algorithm</a>.
/// <para>
/// The changes with respect to the original Brent algorithm are:
/// <ul>
/// <li>the returned value is chosen in the current interval according
/// to user specified <seealso cref="AllowedSolution"/>,</li>
/// <li>the maximal order for the invert polynomial root search is
/// user-specified instead of being invert quadratic only</li>
/// </ul>
/// </para>
/// The given interval must bracket the root.
///
/// @version $Id: BracketingNthOrderBrentSolver.java 1379560 2012-08-31 19:40:30Z erans $
/// </summary>
public class BracketingNthOrderBrentSolver : AbstractUnivariateSolver, BracketedUnivariateSolver<UnivariateFunction>
{
/// <summary>
/// Default absolute accuracy. </summary>
private const double DEFAULT_ABSOLUTE_ACCURACY = 1e-6;
/// <summary>
/// Default maximal order. </summary>
private const int DEFAULT_MAXIMAL_ORDER = 5;
/// <summary>
/// Maximal aging triggering an attempt to balance the bracketing interval. </summary>
private const int MAXIMAL_AGING = 2;
/// <summary>
/// Reduction factor for attempts to balance the bracketing interval. </summary>
private const double REDUCTION_FACTOR = 1.0 / 16.0;
/// <summary>
/// Maximal order. </summary>
private readonly int maximalOrder;
/// <summary>
/// The kinds of solutions that the algorithm may accept. </summary>
private AllowedSolution allowed;
/// <summary>
/// Construct a solver with default accuracy and maximal order (1e-6 and 5 respectively)
/// </summary>
public BracketingNthOrderBrentSolver()
: this(DEFAULT_ABSOLUTE_ACCURACY, DEFAULT_MAXIMAL_ORDER)
{
}
/// <summary>
/// Construct a solver.
/// </summary>
/// <param name="absoluteAccuracy"> Absolute accuracy. </param>
/// <param name="maximalOrder"> maximal order. </param>
/// <exception cref="NumberIsTooSmallException"> if maximal order is lower than 2 </exception>
public BracketingNthOrderBrentSolver(double absoluteAccuracy, int maximalOrder)
: base(absoluteAccuracy)
{
if (maximalOrder < 2)
{
throw new NumberIsTooSmallException(maximalOrder, 2, true);
}
this.maximalOrder = maximalOrder;
this.allowed = AllowedSolution.ANY_SIDE;
}
/// <summary>
/// Construct a solver.
/// </summary>
/// <param name="relativeAccuracy"> Relative accuracy. </param>
/// <param name="absoluteAccuracy"> Absolute accuracy. </param>
/// <param name="maximalOrder"> maximal order. </param>
/// <exception cref="NumberIsTooSmallException"> if maximal order is lower than 2 </exception>
public BracketingNthOrderBrentSolver(double relativeAccuracy, double absoluteAccuracy, int maximalOrder)
: base(relativeAccuracy, absoluteAccuracy)
{
if (maximalOrder < 2)
{
throw new NumberIsTooSmallException(maximalOrder, 2, true);
}
this.maximalOrder = maximalOrder;
this.allowed = AllowedSolution.ANY_SIDE;
}
/// <summary>
/// Construct a solver.
/// </summary>
/// <param name="relativeAccuracy"> Relative accuracy. </param>
/// <param name="absoluteAccuracy"> Absolute accuracy. </param>
/// <param name="functionValueAccuracy"> Function value accuracy. </param>
/// <param name="maximalOrder"> maximal order. </param>
/// <exception cref="NumberIsTooSmallException"> if maximal order is lower than 2 </exception>
public BracketingNthOrderBrentSolver(double relativeAccuracy, double absoluteAccuracy, double functionValueAccuracy, int maximalOrder)
: base(relativeAccuracy, absoluteAccuracy, functionValueAccuracy)
{
if (maximalOrder < 2)
{
throw new NumberIsTooSmallException(maximalOrder, 2, true);
}
this.maximalOrder = maximalOrder;
this.allowed = AllowedSolution.ANY_SIDE;
}
/// <summary>
/// Get the maximal order. </summary>
/// <returns> maximal order </returns>
public virtual int MaximalOrder
{
get { return this.maximalOrder; }
}
/// <summary>
/// {@inheritDoc}
/// </summary>
protected internal override double DoSolve()
{
// prepare arrays with the first points
double[] x = new double[this.maximalOrder + 1];
double[] y = new double[this.maximalOrder + 1];
x[0] = this.Min;
x[1] = this.StartValue;
x[2] = this.Max;
this.VerifySequence(x[0], x[1], x[2]);
// evaluate initial guess
y[1] = this.ComputeObjectiveValue(x[1]);
if (MyUtils.Equals(y[1], 0.0, 1))
{
// return the initial guess if it is a perfect root.
return x[1];
}
// evaluate first endpoint
y[0] = this.ComputeObjectiveValue(x[0]);
if (MyUtils.Equals(y[0], 0.0, 1))
{
// return the first endpoint if it is a perfect root.
return x[0];
}
int nbPoints;
int signChangeIndex;
if (y[0] * y[1] < 0)
{
// reduce interval if it brackets the root
nbPoints = 2;
signChangeIndex = 1;
}
else
{
// evaluate second endpoint
y[2] = this.ComputeObjectiveValue(x[2]);
if (MyUtils.Equals(y[2], 0.0, 1))
{
// return the second endpoint if it is a perfect root.
return x[2];
}
if (y[1] * y[2] < 0)
{
// use all computed point as a start sampling array for solving
nbPoints = 3;
signChangeIndex = 2;
}
else
{
throw new NoBracketingException(x[0], x[2], y[0], y[2]);
}
}
// prepare a work array for inverse polynomial interpolation
double[] tmpX = new double[x.Length];
// current tightest bracketing of the root
double xA = x[signChangeIndex - 1];
double yA = y[signChangeIndex - 1];
double absYA = FastMath.Abs(yA);
int agingA = 0;
double xB = x[signChangeIndex];
double yB = y[signChangeIndex];
double absYB = FastMath.Abs(yB);
int agingB = 0;
// search loop
while (true)
{
// check convergence of bracketing interval
double xTol = this.AbsoluteAccuracy + this.RelativeAccuracy * FastMath.Max(FastMath.Abs(xA), FastMath.Abs(xB));
if (((xB - xA) <= xTol) || (FastMath.Max(absYA, absYB) < this.FunctionValueAccuracy))
{
switch (this.allowed)
{
case AllowedSolution.ANY_SIDE:
return absYA < absYB ? xA : xB;
case AllowedSolution.LEFT_SIDE:
return xA;
case AllowedSolution.RIGHT_SIDE:
return xB;
case AllowedSolution.BELOW_SIDE:
return (yA <= 0) ? xA : xB;
case AllowedSolution.ABOVE_SIDE:
return (yA < 0) ? xB : xA;
default:
// this should never happen
throw new MathInternalError();
}
}
// target for the next evaluation point
double targetY;
if (agingA >= MAXIMAL_AGING)
{
// we keep updating the high bracket, try to compensate this
int p = agingA - MAXIMAL_AGING;
double weightA = (1 << p) - 1;
double weightB = p + 1;
targetY = (weightA * yA - weightB * REDUCTION_FACTOR * yB) / (weightA + weightB);
}
else if (agingB >= MAXIMAL_AGING)
{
// we keep updating the low bracket, try to compensate this
int p = agingB - MAXIMAL_AGING;
double weightA = p + 1;
double weightB = (1 << p) - 1;
targetY = (weightB * yB - weightA * REDUCTION_FACTOR * yA) / (weightA + weightB);
}
else
{
// bracketing is balanced, try to find the root itself
targetY = 0;
}
// make a few attempts to guess a root,
double nextX;
int start = 0;
int end = nbPoints;
do
{
// guess a value for current target, using inverse polynomial interpolation
Array.Copy(x, start, tmpX, start, end - start);
nextX = this.GuessX(targetY, tmpX, y, start, end);
if (!((nextX > xA) && (nextX < xB)))
{
// the guessed root is not strictly inside of the tightest bracketing interval
// the guessed root is either not strictly inside the interval or it
// is a NaN (which occurs when some sampling points share the same y)
// we try again with a lower interpolation order
if (signChangeIndex - start >= end - signChangeIndex)
{
// we have more points before the sign change, drop the lowest point
++start;
}
else
{
// we have more points after sign change, drop the highest point
--end;
}
// we need to do one more attempt
nextX = double.NaN;
}
} while (double.IsNaN(nextX) && (end - start > 1));
if (double.IsNaN(nextX))
{
// fall back to bisection
nextX = xA + 0.5 * (xB - xA);
start = signChangeIndex - 1;
end = signChangeIndex;
}
// evaluate the function at the guessed root
double nextY = this.ComputeObjectiveValue(nextX);
if (MyUtils.Equals(nextY, 0.0, 1))
{
// we have found an exact root, since it is not an approximation
// we don't need to bother about the allowed solutions setting
return nextX;
}
if ((nbPoints > 2) && (end - start != nbPoints))
{
// we have been forced to ignore some points to keep bracketing,
// they are probably too far from the root, drop them from now on
nbPoints = end - start;
Array.Copy(x, start, x, 0, nbPoints);
Array.Copy(y, start, y, 0, nbPoints);
signChangeIndex -= start;
}
else if (nbPoints == x.Length)
{
// we have to drop one point in order to insert the new one
nbPoints--;
// keep the tightest bracketing interval as centered as possible
if (signChangeIndex >= (x.Length + 1) / 2)
{
// we drop the lowest point, we have to shift the arrays and the index
Array.Copy(x, 1, x, 0, nbPoints);
Array.Copy(y, 1, y, 0, nbPoints);
--signChangeIndex;
}
}
// insert the last computed point
//(by construction, we know it lies inside the tightest bracketing interval)
Array.Copy(x, signChangeIndex, x, signChangeIndex + 1, nbPoints - signChangeIndex);
x[signChangeIndex] = nextX;
Array.Copy(y, signChangeIndex, y, signChangeIndex + 1, nbPoints - signChangeIndex);
y[signChangeIndex] = nextY;
++nbPoints;
// update the bracketing interval
if (nextY * yA <= 0)
{
// the sign change occurs before the inserted point
xB = nextX;
yB = nextY;
absYB = FastMath.Abs(yB);
++agingA;
agingB = 0;
}
else
{
// the sign change occurs after the inserted point
xA = nextX;
yA = nextY;
absYA = FastMath.Abs(yA);
agingA = 0;
++agingB;
// update the sign change index
signChangeIndex++;
}
}
}
/// <summary>
/// Guess an x value by n<sup>th</sup> order inverse polynomial interpolation.
/// <para>
/// The x value is guessed by evaluating polynomial Q(y) at y = targetY, where Q
/// is built such that for all considered points (x<sub>i</sub>, y<sub>i</sub>),
/// Q(y<sub>i</sub>) = x<sub>i</sub>.
/// </para> </summary>
/// <param name="targetY"> target value for y </param>
/// <param name="x"> reference points abscissas for interpolation,
/// note that this array <em>is</em> modified during computation </param>
/// <param name="y"> reference points ordinates for interpolation </param>
/// <param name="start"> start index of the points to consider (inclusive) </param>
/// <param name="end"> end index of the points to consider (exclusive) </param>
/// <returns> guessed root (will be a NaN if two points share the same y) </returns>
private double GuessX(double targetY, double[] x, double[] y, int start, int end)
{
// compute Q Newton coefficients by divided differences
for (int i = start; i < end - 1; ++i)
{
int delta = i + 1 - start;
for (int j = end - 1; j > i; --j)
{
x[j] = (x[j] - x[j - 1]) / (y[j] - y[j - delta]);
}
}
// evaluate Q(targetY)
double x0 = 0;
for (int j = end - 1; j >= start; --j)
{
x0 = x[j] + x0 * (targetY - y[j]);
}
return x0;
}
/// <summary>
/// {@inheritDoc} </summary>
public virtual double Solve(int maxEval, UnivariateFunction f, double min, double max, AllowedSolution allowedSolution)
{
this.allowed = allowedSolution;
return base.Solve(maxEval, f, min, max);
}
/// <summary>
/// {@inheritDoc} </summary>
public virtual double Solve(int maxEval, UnivariateFunction f, double min, double max, double startValue, AllowedSolution allowedSolution)
{
this.allowed = allowedSolution;
return base.Solve(maxEval, f, min, max, startValue);
}
}
}
| |
// 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 UnpackLowInt16()
{
var test = new SimpleBinaryOpTest__UnpackLowInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__UnpackLowInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__UnpackLowInt16 testClass)
{
var result = Sse2.UnpackLow(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__UnpackLowInt16 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__UnpackLowInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public SimpleBinaryOpTest__UnpackLowInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.UnpackLow(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.UnpackLow(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.UnpackLow(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int16>* pClsVar2 = &_clsVar2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Int16*)(pClsVar1)),
Sse2.LoadVector128((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.UnpackLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.UnpackLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.UnpackLow(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__UnpackLowInt16();
var result = Sse2.UnpackLow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__UnpackLowInt16();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int16>* pFld2 = &test._fld2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.UnpackLow(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.UnpackLow(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.UnpackLow(
Sse2.LoadVector128((Int16*)(&test._fld1)),
Sse2.LoadVector128((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != left[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i % 2 == 0) ? result[i] != left[i/2] : result[i] != right[(i - 1)/2])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.UnpackLow)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Text;
using System.Transactions;
public class ChannelDispatcher : ChannelDispatcherBase
{
ThreadSafeMessageFilterTable<EndpointAddress> addressTable;
string bindingName;
SynchronizedCollection<IChannelInitializer> channelInitializers;
CommunicationObjectManager<IChannel> channels;
EndpointDispatcherCollection endpointDispatchers;
Collection<IErrorHandler> errorHandlers;
EndpointDispatcherTable filterTable;
ServiceHostBase host;
bool isTransactedReceive;
bool asynchronousTransactedAcceptEnabled;
bool receiveContextEnabled;
readonly IChannelListener listener;
ListenerHandler listenerHandler;
int maxTransactedBatchSize;
MessageVersion messageVersion;
SynchronizedChannelCollection<IChannel> pendingChannels; // app has not yet seen these.
bool receiveSynchronously;
bool sendAsynchronously;
int maxPendingReceives;
bool includeExceptionDetailInFaults;
ServiceThrottle serviceThrottle;
bool session;
SharedRuntimeState shared;
IDefaultCommunicationTimeouts timeouts;
IsolationLevel transactionIsolationLevel = ServiceBehaviorAttribute.DefaultIsolationLevel;
bool transactionIsolationLevelSet;
TimeSpan transactionTimeout;
bool performDefaultCloseInput;
EventTraceActivity eventTraceActivity;
ErrorBehavior errorBehavior;
internal ChannelDispatcher(SharedRuntimeState shared)
{
this.Initialize(shared);
}
public ChannelDispatcher(IChannelListener listener)
: this(listener, null, null)
{
}
public ChannelDispatcher(IChannelListener listener, string bindingName)
: this(listener, bindingName, null)
{
}
public ChannelDispatcher(IChannelListener listener, string bindingName, IDefaultCommunicationTimeouts timeouts)
{
if (listener == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("listener");
}
this.listener = listener;
this.bindingName = bindingName;
this.timeouts = new ImmutableCommunicationTimeouts(timeouts);
this.session = ((listener is IChannelListener<IInputSessionChannel>) ||
(listener is IChannelListener<IReplySessionChannel>) ||
(listener is IChannelListener<IDuplexSessionChannel>));
this.Initialize(new SharedRuntimeState(true));
}
void Initialize(SharedRuntimeState shared)
{
this.shared = shared;
this.endpointDispatchers = new EndpointDispatcherCollection(this);
this.channelInitializers = this.NewBehaviorCollection<IChannelInitializer>();
this.channels = new CommunicationObjectManager<IChannel>(this.ThisLock);
this.pendingChannels = new SynchronizedChannelCollection<IChannel>(this.ThisLock);
this.errorHandlers = new Collection<IErrorHandler>();
this.isTransactedReceive = false;
this.asynchronousTransactedAcceptEnabled = false;
this.receiveSynchronously = false;
this.serviceThrottle = null;
this.transactionTimeout = TimeSpan.Zero;
this.maxPendingReceives = MultipleReceiveBinder.MultipleReceiveDefaults.MaxPendingReceives;
if (this.listener != null)
{
this.listener.Faulted += new EventHandler(OnListenerFaulted);
}
}
public string BindingName
{
get { return this.bindingName; }
}
public SynchronizedCollection<IChannelInitializer> ChannelInitializers
{
get { return this.channelInitializers; }
}
protected override TimeSpan DefaultCloseTimeout
{
get
{
if (this.timeouts != null)
{
return this.timeouts.CloseTimeout;
}
else
{
return ServiceDefaults.CloseTimeout;
}
}
}
protected override TimeSpan DefaultOpenTimeout
{
get
{
if (this.timeouts != null)
{
return this.timeouts.OpenTimeout;
}
else
{
return ServiceDefaults.OpenTimeout;
}
}
}
internal EndpointDispatcherTable EndpointDispatcherTable
{
get { return this.filterTable; }
}
internal CommunicationObjectManager<IChannel> Channels
{
get { return this.channels; }
}
public SynchronizedCollection<EndpointDispatcher> Endpoints
{
get { return this.endpointDispatchers; }
}
public Collection<IErrorHandler> ErrorHandlers
{
get { return this.errorHandlers; }
}
public MessageVersion MessageVersion
{
get { return this.messageVersion; }
set
{
this.messageVersion = value;
this.ThrowIfDisposedOrImmutable();
}
}
internal bool Session
{
get { return this.session; }
}
public override ServiceHostBase Host
{
get { return this.host; }
}
internal bool EnableFaults
{
get { return this.shared.EnableFaults; }
set
{
this.ThrowIfDisposedOrImmutable();
this.shared.EnableFaults = value;
}
}
internal bool IsOnServer
{
get { return this.shared.IsOnServer; }
}
public bool IsTransactedAccept
{
get { return this.isTransactedReceive && this.session; }
}
public bool IsTransactedReceive
{
get
{
return this.isTransactedReceive;
}
set
{
this.ThrowIfDisposedOrImmutable();
this.isTransactedReceive = value;
}
}
public bool AsynchronousTransactedAcceptEnabled
{
get
{
return this.asynchronousTransactedAcceptEnabled;
}
set
{
this.ThrowIfDisposedOrImmutable();
this.asynchronousTransactedAcceptEnabled = value;
}
}
public bool ReceiveContextEnabled
{
get
{
return this.receiveContextEnabled;
}
set
{
this.ThrowIfDisposedOrImmutable();
this.receiveContextEnabled = value;
}
}
internal bool BufferedReceiveEnabled
{
get;
set;
}
public override IChannelListener Listener
{
get { return this.listener; }
}
public int MaxTransactedBatchSize
{
get
{
return this.maxTransactedBatchSize;
}
set
{
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeNonNegative)));
}
this.ThrowIfDisposedOrImmutable();
this.maxTransactedBatchSize = value;
}
}
public ServiceThrottle ServiceThrottle
{
get
{
return this.serviceThrottle;
}
set
{
this.ThrowIfDisposedOrImmutable();
this.serviceThrottle = value;
}
}
public bool ManualAddressing
{
get { return this.shared.ManualAddressing; }
set
{
this.ThrowIfDisposedOrImmutable();
this.shared.ManualAddressing = value;
}
}
internal SynchronizedChannelCollection<IChannel> PendingChannels
{
get { return this.pendingChannels; }
}
public bool ReceiveSynchronously
{
get
{
return this.receiveSynchronously;
}
set
{
this.ThrowIfDisposedOrImmutable();
this.receiveSynchronously = value;
}
}
public bool SendAsynchronously
{
get
{
return this.sendAsynchronously;
}
set
{
this.ThrowIfDisposedOrImmutable();
this.sendAsynchronously = value;
}
}
public int MaxPendingReceives
{
get
{
return this.maxPendingReceives;
}
set
{
this.ThrowIfDisposedOrImmutable();
this.maxPendingReceives = value;
}
}
public bool IncludeExceptionDetailInFaults
{
get { return this.includeExceptionDetailInFaults; }
set
{
lock (this.ThisLock)
{
this.ThrowIfDisposedOrImmutable();
this.includeExceptionDetailInFaults = value;
}
}
}
internal IDefaultCommunicationTimeouts DefaultCommunicationTimeouts
{
get { return this.timeouts; }
}
public IsolationLevel TransactionIsolationLevel
{
get { return this.transactionIsolationLevel; }
set
{
switch (value)
{
case IsolationLevel.Serializable:
case IsolationLevel.RepeatableRead:
case IsolationLevel.ReadCommitted:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.Snapshot:
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
this.ThrowIfDisposedOrImmutable();
this.transactionIsolationLevel = value;
this.transactionIsolationLevelSet = true;
}
}
internal bool TransactionIsolationLevelSet
{
get { return this.transactionIsolationLevelSet; }
}
public TimeSpan TransactionTimeout
{
get
{
return this.transactionTimeout;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.ThrowIfDisposedOrImmutable();
this.transactionTimeout = value;
}
}
void AbortPendingChannels()
{
lock (this.ThisLock)
{
for (int i = this.pendingChannels.Count - 1; i >= 0; i--)
{
this.pendingChannels[i].Abort();
}
}
}
internal override void CloseInput(TimeSpan timeout)
{
// we have to perform some slightly convoluted logic here due to
// backwards compat. We probably need an IAsyncChannelDispatcher
// interface that has timeouts and async
this.CloseInput();
if (this.performDefaultCloseInput)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
lock (this.ThisLock)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
for (int i = 0; i < this.endpointDispatchers.Count; i++)
{
EndpointDispatcher endpointDispatcher = this.endpointDispatchers[i];
this.TraceEndpointLifetime(endpointDispatcher, TraceCode.EndpointListenerClose, SR.GetString(SR.TraceCodeEndpointListenerClose));
}
}
ListenerHandler handler = this.listenerHandler;
if (handler != null)
{
handler.CloseInput(timeoutHelper.RemainingTime());
}
}
if (!this.session)
{
ListenerHandler handler = this.listenerHandler;
if (handler != null)
{
handler.Close(timeoutHelper.RemainingTime());
}
}
}
}
internal void ReleasePerformanceCounters()
{
if (PerformanceCounters.PerformanceCountersEnabled)
{
for (int i = 0; i < this.endpointDispatchers.Count; i++)
{
if (null != this.endpointDispatchers[i])
{
this.endpointDispatchers[i].ReleasePerformanceCounters();
}
}
}
}
public override void CloseInput()
{
this.performDefaultCloseInput = true;
}
void OnListenerFaulted(object sender, EventArgs e)
{
this.Fault();
}
internal bool HandleError(Exception error)
{
ErrorHandlerFaultInfo dummy = new ErrorHandlerFaultInfo();
return this.HandleError(error, ref dummy);
}
internal bool HandleError(Exception error, ref ErrorHandlerFaultInfo faultInfo)
{
ErrorBehavior behavior;
lock (this.ThisLock)
{
if (this.errorBehavior != null)
{
behavior = this.errorBehavior;
}
else
{
behavior = new ErrorBehavior(this);
}
}
if (behavior != null)
{
return behavior.HandleError(error, ref faultInfo);
}
else
{
return false;
}
}
internal void InitializeChannel(IClientChannel channel)
{
this.ThrowIfDisposedOrNotOpen();
try
{
for (int i = 0; i < this.channelInitializers.Count; ++i)
{
this.channelInitializers[i].Initialize(channel);
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
internal EndpointDispatcher Match(Message message, out bool addressMatched)
{
lock (this.ThisLock)
{
return this.filterTable.Lookup(message, out addressMatched);
}
}
internal SynchronizedCollection<T> NewBehaviorCollection<T>()
{
return new ChannelDispatcherBehaviorCollection<T>(this);
}
internal bool HasApplicationEndpoints()
{
foreach (EndpointDispatcher endpointDispatcher in this.Endpoints)
{
if (!endpointDispatcher.IsSystemEndpoint)
{
return true;
}
}
return false;
}
void OnAddEndpoint(EndpointDispatcher endpoint)
{
lock (this.ThisLock)
{
endpoint.Attach(this);
if (this.State == CommunicationState.Opened)
{
if (this.addressTable != null)
{
this.addressTable.Add(endpoint.AddressFilter, endpoint.EndpointAddress, endpoint.FilterPriority);
}
this.filterTable.AddEndpoint(endpoint);
}
}
}
void OnRemoveEndpoint(EndpointDispatcher endpoint)
{
lock (this.ThisLock)
{
if (this.State == CommunicationState.Opened)
{
this.filterTable.RemoveEndpoint(endpoint);
if (this.addressTable != null)
{
this.addressTable.Remove(endpoint.AddressFilter);
}
}
endpoint.Detach(this);
}
}
protected override void OnAbort()
{
if (this.listener != null)
{
this.listener.Abort();
}
ListenerHandler handler = this.listenerHandler;
if (handler != null)
{
handler.Abort();
}
this.AbortPendingChannels();
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
if (this.listener != null)
{
this.listener.Close(timeoutHelper.RemainingTime());
}
ListenerHandler handler = this.listenerHandler;
if (handler != null)
{
handler.Close(timeoutHelper.RemainingTime());
}
this.AbortPendingChannels();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
List<ICommunicationObject> list = new List<ICommunicationObject>();
if (this.listener != null)
{
list.Add(this.listener);
}
ListenerHandler handler = this.listenerHandler;
if (handler != null)
{
list.Add(handler);
}
return new CloseCollectionAsyncResult(timeout, callback, state, list);
}
protected override void OnEndClose(IAsyncResult result)
{
try
{
CloseCollectionAsyncResult.End(result);
}
finally
{
this.AbortPendingChannels();
}
}
protected override void OnClosed()
{
base.OnClosed();
if (DiagnosticUtility.ShouldTraceInformation)
{
for (int i = 0; i < this.endpointDispatchers.Count; i++)
{
EndpointDispatcher endpointDispatcher = this.endpointDispatchers[i];
this.TraceEndpointLifetime(endpointDispatcher, TraceCode.EndpointListenerClose, SR.GetString(SR.TraceCodeEndpointListenerClose));
}
}
}
protected override void OnOpen(TimeSpan timeout)
{
ThrowIfNotAttachedToHost();
ThrowIfNoMessageVersion();
if (this.listener != null)
{
try
{
this.listener.Open(timeout);
}
catch (InvalidOperationException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateOuterExceptionWithEndpointsInformation(e));
}
}
}
InvalidOperationException CreateOuterExceptionWithEndpointsInformation(InvalidOperationException e)
{
string endpointContractNames = CreateContractListString();
if (String.IsNullOrEmpty(endpointContractNames))
{
return new InvalidOperationException(SR.GetString(SR.SFxChannelDispatcherUnableToOpen1, this.listener.Uri), e);
}
else
{
return new InvalidOperationException(SR.GetString(SR.SFxChannelDispatcherUnableToOpen2, this.listener.Uri, endpointContractNames), e);
}
}
internal string CreateContractListString()
{
const string OpenQuote = "\"";
const string CloseQuote = "\"";
const string Space = " ";
Collection<string> namesSeen = new Collection<string>();
StringBuilder endpointContractNames = new StringBuilder();
lock (this.ThisLock)
{
foreach (EndpointDispatcher ed in this.Endpoints)
{
if (!namesSeen.Contains(ed.ContractName))
{
if (endpointContractNames.Length > 0)
{
endpointContractNames.Append(CultureInfo.CurrentCulture.TextInfo.ListSeparator);
endpointContractNames.Append(Space);
}
endpointContractNames.Append(OpenQuote);
endpointContractNames.Append(ed.ContractName);
endpointContractNames.Append(CloseQuote);
namesSeen.Add(ed.ContractName);
}
}
}
return endpointContractNames.ToString();
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
ThrowIfNotAttachedToHost();
ThrowIfNoMessageVersion();
if (this.listener != null)
{
try
{
return this.listener.BeginOpen(timeout, callback, state);
}
catch (InvalidOperationException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateOuterExceptionWithEndpointsInformation(e));
}
}
else
{
return new CompletedAsyncResult(callback, state);
}
}
protected override void OnEndOpen(IAsyncResult result)
{
if (this.listener != null)
{
try
{
this.listener.EndOpen(result);
}
catch (InvalidOperationException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateOuterExceptionWithEndpointsInformation(e));
}
}
else
{
CompletedAsyncResult.End(result);
}
}
protected override void OnOpening()
{
ThrowIfNotAttachedToHost();
if (TD.ListenerOpenStartIsEnabled())
{
this.eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate();
TD.ListenerOpenStart(this.eventTraceActivity,
(this.Listener != null) ? this.Listener.Uri.ToString() : string.Empty,
(this.host != null && host.EventTraceActivity != null) ? this.host.EventTraceActivity.ActivityId : Guid.Empty);
}
base.OnOpening();
}
protected override void OnOpened()
{
ThrowIfNotAttachedToHost();
base.OnOpened();
if (TD.ListenerOpenStopIsEnabled())
{
TD.ListenerOpenStop(this.eventTraceActivity);
this.eventTraceActivity = null; // clear this since we don't need this anymore.
}
this.errorBehavior = new ErrorBehavior(this);
this.filterTable = new EndpointDispatcherTable(this.ThisLock);
for (int i = 0; i < this.endpointDispatchers.Count; i++)
{
EndpointDispatcher endpoint = this.endpointDispatchers[i];
// Force a build of the runtime to catch any unexpected errors before we are done opening.
endpoint.DispatchRuntime.GetRuntime();
// Lock down the DispatchRuntime.
endpoint.DispatchRuntime.LockDownProperties();
this.filterTable.AddEndpoint(endpoint);
if ((this.addressTable != null) && (endpoint.OriginalAddress != null))
{
this.addressTable.Add(endpoint.AddressFilter, endpoint.OriginalAddress, endpoint.FilterPriority);
}
if (DiagnosticUtility.ShouldTraceInformation)
{
this.TraceEndpointLifetime(endpoint, TraceCode.EndpointListenerOpen, SR.GetString(SR.TraceCodeEndpointListenerOpen));
}
}
ServiceThrottle throttle = this.serviceThrottle;
if (throttle == null)
{
throttle = this.host.ServiceThrottle;
}
IListenerBinder binder = ListenerBinder.GetBinder(this.listener, this.messageVersion);
this.listenerHandler = new ListenerHandler(binder, this, this.host, throttle, this.timeouts);
this.listenerHandler.Open(); // This never throws, which is why it's ok for it to happen in OnOpened
}
internal void ProvideFault(Exception e, FaultConverter faultConverter, ref ErrorHandlerFaultInfo faultInfo)
{
ErrorBehavior behavior;
lock (this.ThisLock)
{
if (this.errorBehavior != null)
{
behavior = this.errorBehavior;
}
else
{
behavior = new ErrorBehavior(this);
}
}
behavior.ProvideFault(e, faultConverter, ref faultInfo);
}
internal void SetEndpointAddressTable(ThreadSafeMessageFilterTable<EndpointAddress> table)
{
if (table == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("table");
}
this.ThrowIfDisposedOrImmutable();
this.addressTable = table;
}
internal new void ThrowIfDisposedOrImmutable()
{
base.ThrowIfDisposedOrImmutable();
this.shared.ThrowIfImmutable();
}
void ThrowIfNotAttachedToHost()
{
// if we are on the server, we need a host
// if we are on the client, we never call Open(), so this method is not invoked
if (this.host == null)
{
Exception error = new InvalidOperationException(SR.GetString(SR.SFxChannelDispatcherNoHost0));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
void ThrowIfNoMessageVersion()
{
if (this.messageVersion == null)
{
Exception error = new InvalidOperationException(SR.GetString(SR.SFxChannelDispatcherNoMessageVersion));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
void TraceEndpointLifetime(EndpointDispatcher endpoint, int traceCode, string traceDescription)
{
if (DiagnosticUtility.ShouldTraceInformation)
{
Dictionary<string, object> values = new Dictionary<string, object>(3)
{
{ "ContractNamespace", endpoint.ContractNamespace },
{ "ContractName", endpoint.ContractName },
{ "Endpoint", endpoint.ListenUri }
};
TraceUtility.TraceEvent(TraceEventType.Information, traceCode,
traceDescription, new DictionaryTraceRecord(values), endpoint, null);
}
}
protected override void Attach(ServiceHostBase host)
{
if (host == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("host");
}
ServiceHostBase serviceHost = host;
this.ThrowIfDisposedOrImmutable();
if (this.host != null)
{
Exception error = new InvalidOperationException(SR.GetString(SR.SFxChannelDispatcherMultipleHost0));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
this.host = serviceHost;
}
protected override void Detach(ServiceHostBase host)
{
if (host == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("host");
}
if (this.host != host)
{
Exception error = new InvalidOperationException(SR.GetString(SR.SFxChannelDispatcherDifferentHost0));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
this.ThrowIfDisposedOrImmutable();
this.host = null;
}
class EndpointDispatcherCollection : SynchronizedCollection<EndpointDispatcher>
{
ChannelDispatcher owner;
internal EndpointDispatcherCollection(ChannelDispatcher owner)
: base(owner.ThisLock)
{
this.owner = owner;
}
protected override void ClearItems()
{
foreach (EndpointDispatcher item in this.Items)
{
this.owner.OnRemoveEndpoint(item);
}
base.ClearItems();
}
protected override void InsertItem(int index, EndpointDispatcher item)
{
if (item == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
this.owner.OnAddEndpoint(item);
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
EndpointDispatcher item = this.Items[index];
base.RemoveItem(index);
this.owner.OnRemoveEndpoint(item);
}
protected override void SetItem(int index, EndpointDispatcher item)
{
Exception error = new InvalidOperationException(SR.GetString(SR.SFxCollectionDoesNotSupportSet0));
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(error);
}
}
class ChannelDispatcherBehaviorCollection<T> : SynchronizedCollection<T>
{
ChannelDispatcher outer;
internal ChannelDispatcherBehaviorCollection(ChannelDispatcher outer)
: base(outer.ThisLock)
{
this.outer = outer;
}
protected override void ClearItems()
{
this.outer.ThrowIfDisposedOrImmutable();
base.ClearItems();
}
protected override void InsertItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
}
this.outer.ThrowIfDisposedOrImmutable();
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
this.outer.ThrowIfDisposedOrImmutable();
base.RemoveItem(index);
}
protected override void SetItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
}
this.outer.ThrowIfDisposedOrImmutable();
base.SetItem(index, item);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Configuration;
using AutoMapper.Execution;
namespace AutoMapper
{
using AutoMapper.Features;
using Internal;
using static Expression;
/// <summary>
/// Main configuration object holding all mapping configuration for a source and destination type
/// </summary>
[DebuggerDisplay("{SourceType.Name} -> {DestinationType.Name}")]
public class TypeMap
{
private readonly HashSet<LambdaExpression> _afterMapActions = new HashSet<LambdaExpression>();
private readonly HashSet<LambdaExpression> _beforeMapActions = new HashSet<LambdaExpression>();
private readonly HashSet<TypePair> _includedDerivedTypes = new HashSet<TypePair>();
private readonly HashSet<TypePair> _includedBaseTypes = new HashSet<TypePair>();
private readonly Dictionary<string, PropertyMap> _propertyMaps = new Dictionary<string, PropertyMap>();
private readonly Dictionary<MemberPath, PathMap> _pathMaps = new Dictionary<MemberPath, PathMap>();
private readonly Dictionary<MemberInfo, SourceMemberConfig> _sourceMemberConfigs = new Dictionary<MemberInfo, SourceMemberConfig>();
private PropertyMap[] _orderedPropertyMaps;
private bool _sealed;
private readonly HashSet<TypeMap> _inheritedTypeMaps = new HashSet<TypeMap>();
private readonly List<IncludedMember> _includedMembersTypeMaps = new List<IncludedMember>();
private readonly List<ValueTransformerConfiguration> _valueTransformerConfigs = new List<ValueTransformerConfiguration>();
public TypeMap(TypeDetails sourceType, TypeDetails destinationType, ProfileMap profile)
{
SourceTypeDetails = sourceType;
DestinationTypeDetails = destinationType;
Types = new TypePair(sourceType.Type, destinationType.Type);
Profile = profile;
}
private IEnumerable<SourceMemberConfig> SourceMemberConfigs => _sourceMemberConfigs.Values;
public PathMap FindOrCreatePathMapFor(LambdaExpression destinationExpression, MemberPath path, TypeMap typeMap)
{
var pathMap = _pathMaps.GetOrDefault(path);
if(pathMap == null)
{
pathMap = new PathMap(destinationExpression, path, typeMap);
AddPathMap(pathMap);
}
return pathMap;
}
private void AddPathMap(PathMap pathMap) => _pathMaps.Add(pathMap.MemberPath, pathMap);
public Features<IRuntimeFeature> Features { get; } = new Features<IRuntimeFeature>();
public PathMap FindPathMapByDestinationPath(string destinationFullPath) =>
PathMaps.SingleOrDefault(item => string.Join(".", item.MemberPath.Members.Select(m => m.Name)) == destinationFullPath);
public LambdaExpression MapExpression { get; private set; }
public TypePair Types { get; }
public ConstructorMap ConstructorMap { get; set; }
public TypeDetails SourceTypeDetails { get; }
public TypeDetails DestinationTypeDetails { get; }
public Type SourceType => SourceTypeDetails.Type;
public Type DestinationType => DestinationTypeDetails.Type;
public ProfileMap Profile { get; }
public LambdaExpression CustomMapFunction { get; set; }
public LambdaExpression CustomMapExpression { get; set; }
public LambdaExpression CustomCtorFunction { get; set; }
public LambdaExpression CustomCtorExpression { get; set; }
public Type DestinationTypeOverride { get; set; }
public Type DestinationTypeToUse => DestinationTypeOverride ?? DestinationType;
public bool ConstructDestinationUsingServiceLocator { get; set; }
public bool IncludeAllDerivedTypes { get; set; }
public MemberList ConfiguredMemberList { get; set; }
public IEnumerable<TypePair> IncludedDerivedTypes => _includedDerivedTypes;
public IEnumerable<TypePair> IncludedBaseTypes => _includedBaseTypes;
public IEnumerable<LambdaExpression> BeforeMapActions => _beforeMapActions;
public IEnumerable<LambdaExpression> AfterMapActions => _afterMapActions;
public IEnumerable<ValueTransformerConfiguration> ValueTransformers => _valueTransformerConfigs;
public bool PreserveReferences { get; set; }
public LambdaExpression Condition { get; set; }
public int MaxDepth { get; set; }
public Type TypeConverterType { get; set; }
public bool DisableConstructorValidation { get; set; }
public IEnumerable<PropertyMap> PropertyMaps => _orderedPropertyMaps ?? (IEnumerable<PropertyMap>)_propertyMaps.Values;
public IEnumerable<PathMap> PathMaps => _pathMaps.Values;
public IEnumerable<IMemberMap> MemberMaps => PropertyMaps.Cast<IMemberMap>().Concat(PathMaps).Concat(GetConstructorMemberMaps());
public bool? IsValid { get; set; }
internal bool WasInlineChecked { get; set; }
public bool PassesCtorValidation =>
DisableConstructorValidation
|| CustomCtorExpression != null
|| CustomCtorFunction != null
|| ConstructDestinationUsingServiceLocator
|| ConstructorMap?.CanResolve == true
|| DestinationTypeToUse.IsInterface
|| DestinationTypeToUse.IsAbstract
|| DestinationTypeToUse.IsGenericTypeDefinition
|| DestinationTypeToUse.IsValueType
|| DestinationTypeDetails.Constructors.FirstOrDefault(c => c.GetParameters().All(p => p.IsOptional)) != null;
public bool IsConstructorMapping =>
CustomCtorExpression == null
&& CustomCtorFunction == null
&& !ConstructDestinationUsingServiceLocator
&& (ConstructorMap?.CanResolve ?? false);
public bool ShouldCheckForValid =>
CustomMapFunction == null
&& CustomMapExpression == null
&& TypeConverterType == null
&& DestinationTypeOverride == null
&& ConfiguredMemberList != MemberList.None
&& !(IsValid ?? false);
public bool IsClosedGeneric { get; internal set; }
public LambdaExpression[] IncludedMembers { get; internal set; } = Array.Empty<LambdaExpression>();
public string[] IncludedMembersNames { get; internal set; } = Array.Empty<string>();
public Type MakeGenericType(Type type) => type.IsGenericTypeDefinition ?
type.MakeGenericType(SourceType.GenericTypeArguments.Concat(DestinationType.GenericTypeArguments).Take(type.GetGenericParameters().Length).ToArray()) :
type;
public LambdaExpression[] GetUntypedIncludedMembers() =>
SourceType.IsGenericTypeDefinition ?
Array.Empty<LambdaExpression>() :
IncludedMembersNames.Select(name => ExpressionFactory.MemberAccessLambda(SourceType, name)).ToArray();
public bool ConstructorParameterMatches(string destinationPropertyName) =>
ConstructorMap?.CtorParams.Any(c => !c.HasDefaultValue && string.Equals(c.Parameter.Name, destinationPropertyName, StringComparison.OrdinalIgnoreCase)) == true;
public void AddPropertyMap(MemberInfo destProperty, IEnumerable<MemberInfo> resolvers)
{
var propertyMap = new PropertyMap(destProperty, this);
propertyMap.ChainMembers(resolvers);
AddPropertyMap(propertyMap);
}
private void AddPropertyMap(PropertyMap propertyMap) => _propertyMaps.Add(propertyMap.DestinationName, propertyMap);
public string[] GetUnmappedPropertyNames()
{
var autoMappedProperties = GetPropertyNames(PropertyMaps);
IEnumerable<string> properties;
if(ConfiguredMemberList == MemberList.Destination)
{
properties = DestinationTypeDetails.PublicWriteAccessors
.Select(p => p.Name)
.Except(autoMappedProperties)
.Except(PathMaps.Select(p => p.MemberPath.First.Name));
}
else
{
var redirectedSourceMembers = MemberMaps
.Where(pm => pm.IsMapped && pm.SourceMember != null && pm.SourceMember.Name != pm.DestinationName)
.Select(pm => pm.SourceMember.Name);
var ignoredSourceMembers = SourceMemberConfigs
.Where(smc => smc.IsIgnored())
.Select(pm => pm.SourceMember.Name);
properties = SourceTypeDetails.PublicReadAccessors
.Select(p => p.Name)
.Except(autoMappedProperties)
.Except(redirectedSourceMembers)
.Except(ignoredSourceMembers);
}
return properties.Where(memberName => !Profile.GlobalIgnores.Any(memberName.StartsWith)).ToArray();
string GetPropertyName(PropertyMap pm) => ConfiguredMemberList == MemberList.Destination
? pm.DestinationName
: pm.SourceMembers.Count > 1
? pm.SourceMembers.First().Name
: pm.SourceMember?.Name ?? pm.DestinationName;
string[] GetPropertyNames(IEnumerable<PropertyMap> propertyMaps) => propertyMaps.Where(pm => pm.IsMapped).Select(GetPropertyName).ToArray();
}
public PropertyMap FindOrCreatePropertyMapFor(MemberInfo destinationProperty)
{
var propertyMap = GetPropertyMap(destinationProperty.Name);
if (propertyMap != null) return propertyMap;
propertyMap = new PropertyMap(destinationProperty, this);
AddPropertyMap(propertyMap);
return propertyMap;
}
public void IncludeDerivedTypes(Type derivedSourceType, Type derivedDestinationType)
{
var derivedTypes = new TypePair(derivedSourceType, derivedDestinationType);
if (derivedTypes.Equals(Types))
{
throw new InvalidOperationException("You cannot include a type map into itself.");
}
_includedDerivedTypes.Add(derivedTypes);
}
public void IncludeBaseTypes(Type baseSourceType, Type baseDestinationType)
{
var baseTypes = new TypePair(baseSourceType, baseDestinationType);
if (baseTypes.Equals(Types))
{
throw new InvalidOperationException("You cannot include a type map into itself.");
}
_includedBaseTypes.Add(baseTypes);
}
internal void IgnorePaths(MemberInfo destinationMember)
{
foreach(var pathMap in PathMaps.Where(pm => pm.MemberPath.First == destinationMember))
{
pathMap.Ignored = true;
}
}
public Type GetDerivedTypeFor(Type derivedSourceType)
{
if (DestinationTypeOverride != null)
{
return DestinationTypeOverride;
}
// This might need to be fixed for multiple derived source types to different dest types
var match = _includedDerivedTypes.FirstOrDefault(tp => tp.SourceType == derivedSourceType);
return match.DestinationType ?? DestinationType;
}
public bool HasDerivedTypesToInclude() => _includedDerivedTypes.Any() || DestinationTypeOverride != null;
public void AddBeforeMapAction(LambdaExpression beforeMap) => _beforeMapActions.Add(beforeMap);
public void AddAfterMapAction(LambdaExpression afterMap) => _afterMapActions.Add(afterMap);
public void AddValueTransformation(ValueTransformerConfiguration valueTransformerConfiguration)
{
_valueTransformerConfigs.Add(valueTransformerConfiguration);
}
public void Seal(IConfigurationProvider configurationProvider)
{
if(_sealed)
{
return;
}
_sealed = true;
foreach (var includedMemberTypeMap in _includedMembersTypeMaps)
{
includedMemberTypeMap.TypeMap.Seal(configurationProvider);
ApplyIncludedMemberTypeMap(includedMemberTypeMap);
}
foreach (var inheritedTypeMap in _inheritedTypeMaps)
{
ApplyInheritedTypeMap(inheritedTypeMap);
}
_orderedPropertyMaps = PropertyMaps.OrderBy(map => map.MappingOrder).ToArray();
_propertyMaps.Clear();
MapExpression = CreateMapperLambda(configurationProvider, null);
Features.Seal(configurationProvider);
}
internal LambdaExpression CreateMapperLambda(IConfigurationProvider configurationProvider, HashSet<TypeMap> typeMapsPath) =>
Types.IsGenericTypeDefinition ? null : new TypeMapPlanBuilder(configurationProvider, this).CreateMapperLambda(typeMapsPath);
private PropertyMap GetPropertyMap(string name) => _propertyMaps.GetOrDefault(name);
private PropertyMap GetPropertyMap(PropertyMap propertyMap) => GetPropertyMap(propertyMap.DestinationName);
public void AddMemberMap(IncludedMember includedMember) => _includedMembersTypeMaps.Add(includedMember);
public SourceMemberConfig FindOrCreateSourceMemberConfigFor(MemberInfo sourceMember)
{
var config = _sourceMemberConfigs.GetOrDefault(sourceMember);
if(config != null) return config;
config = new SourceMemberConfig(sourceMember);
AddSourceMemberConfig(config);
return config;
}
private void AddSourceMemberConfig(SourceMemberConfig config) => _sourceMemberConfigs.Add(config.SourceMember, config);
public bool AddInheritedMap(TypeMap inheritedTypeMap) => _inheritedTypeMaps.Add(inheritedTypeMap);
private void ApplyIncludedMemberTypeMap(IncludedMember includedMember)
{
var typeMap = includedMember.TypeMap;
var expression = includedMember.MemberExpression;
var memberMaps = typeMap.PropertyMaps.
Where(m => m.CanResolveValue && GetPropertyMap(m)==null)
.Select(p => new PropertyMap(p, this, expression))
.ToList();
var notOverridenPathMaps = NotOverridenPathMaps(typeMap);
if(memberMaps.Count == 0 && notOverridenPathMaps.Count == 0)
{
return;
}
memberMaps.ForEach(p=>
{
AddPropertyMap(p);
foreach(var transformer in typeMap.ValueTransformers)
{
p.AddValueTransformation(transformer);
}
});
_beforeMapActions.UnionWith(typeMap._beforeMapActions.Select(CheckCustomSource));
_afterMapActions.UnionWith(typeMap._afterMapActions.Select(CheckCustomSource));
notOverridenPathMaps.ForEach(p=>AddPathMap(new PathMap(p, this, expression) { CustomMapExpression = CheckCustomSource(p.CustomMapExpression) }));
return;
LambdaExpression CheckCustomSource(LambdaExpression lambda) => PropertyMap.CheckCustomSource(lambda, expression);
}
private void ApplyInheritedTypeMap(TypeMap inheritedTypeMap)
{
foreach(var inheritedMappedProperty in inheritedTypeMap.PropertyMaps.Where(m => m.IsMapped))
{
var conventionPropertyMap = GetPropertyMap(inheritedMappedProperty);
if(conventionPropertyMap != null)
{
conventionPropertyMap.ApplyInheritedPropertyMap(inheritedMappedProperty);
}
else
{
AddPropertyMap(new PropertyMap(inheritedMappedProperty, this));
}
}
_beforeMapActions.UnionWith(inheritedTypeMap._beforeMapActions);
_afterMapActions.UnionWith(inheritedTypeMap._afterMapActions);
var notOverridenSourceConfigs =
inheritedTypeMap.SourceMemberConfigs.Where(
baseConfig => SourceMemberConfigs.All(derivedConfig => derivedConfig.SourceMember != baseConfig.SourceMember)).ToList();
notOverridenSourceConfigs.ForEach(AddSourceMemberConfig);
var notOverridenPathMaps = NotOverridenPathMaps(inheritedTypeMap);
notOverridenPathMaps.ForEach(AddPathMap);
_valueTransformerConfigs.InsertRange(0, inheritedTypeMap._valueTransformerConfigs);
}
private List<PathMap> NotOverridenPathMaps(TypeMap inheritedTypeMap) =>
inheritedTypeMap.PathMaps.Where(
baseConfig => PathMaps.All(derivedConfig => derivedConfig.MemberPath != baseConfig.MemberPath)).ToList();
internal void CopyInheritedMapsTo(TypeMap typeMap) => typeMap._inheritedTypeMaps.UnionWith(_inheritedTypeMaps);
private IEnumerable<IMemberMap> GetConstructorMemberMaps()
=> CustomCtorExpression != null
|| CustomCtorFunction != null
|| ConstructDestinationUsingServiceLocator
|| ConstructorMap?.CanResolve != true
? Enumerable.Empty<IMemberMap>()
: ConstructorMap?.CtorParams ?? Enumerable.Empty<IMemberMap>();
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Aspose.OCR.Live.Demos.UI.Services;
using Aspose.OCR.Live.Demos.UI.Models;
namespace Aspose.OCR.Live.Demos.UI.Config
{
public class BasePage : BaseRootPage
{
private string _product;
/// <summary>
/// Product name (e.g. words, cells)
/// </summary>
public string Product
{
get
{
if (string.IsNullOrEmpty(_product))
{
if (Page.RouteData.Values["Product"] != null)
{
_product = Page.RouteData.Values["Product"].ToString().ToLower();
}
}
return _product;
}
set => _product = value;
}
private string _feature;
/// <summary>
/// Product name (e.g. words, cells)
/// </summary>
public string Feature
{
get
{
if (_feature == null)
if (Page.RouteData.Values.ContainsKey("Feature"))
_feature = Page.RouteData.Values["Feature"].ToString().ToLower();
else
_feature = "";
return _feature;
}
set => _feature = value;
}
public string _pageProductTitle;
/// <summary>
/// Product title (e.g. Aspose.Words)
/// </summary>
public string PageProductTitle
{
get
{
if (_pageProductTitle == null)
_pageProductTitle = Resources["Aspose" + TitleCase(Product)];
return _pageProductTitle;
}
}
private string _productH1 = "";
public string ProductH1
{
get
{
return _productH1;
}
}
private string _productH4 = "";
public string ProductH4
{
get
{
return _productH4;
}
}
private string _extension1 = "";
public string Extension1
{
get
{
return _extension1;
}
}
private int _appURLID = 0;
public int AppURLID
{
get
{
return _appURLID;
}
}
private string _extension1Description = "";
public string Extension1Description
{
get
{
return _extension1Description;
}
}
protected override void OnLoad(EventArgs e)
{
if (Resources != null)
{
Page.Title = Resources["ApplicationTitle"];
}
base.OnLoad(e);
}
/// <summary>
/// Set validation for RegularExpressionValidators, InputFile and ViewStates using Resources[Product + "ValidationExpression"]
/// </summary>
private void SetAccept(string validationExpression, params HtmlInputFile[] inpufiles)
{
var accept = validationExpression.ToLower().Replace("|", ",");
foreach (var inpufile in inpufiles)
inpufile.Attributes.Add("accept", accept.ToLower().Replace("|", ","));
}
/// <summary>
/// Set validation for RegularExpressionValidators and ViewStates using Resources[Product + "ValidationExpression"].
/// If the 'ControlToValidate' option is HtmlInputFile, it sets accept an attribute to that control
/// </summary>
/// <param name="validators"></param>
protected void SetValidation(params RegularExpressionValidator[] validators)
{
var validationExpression = "";
var validFileExtensions = "";
// Check for format like .Doc
if (Page.RouteData.Values["Format"] != null)
{
validFileExtensions = Page.RouteData.Values["Format"].ToString().ToUpper();
validationExpression = "." + validFileExtensions.ToLower();
}
else
{
validationExpression = Resources[Product + "ValidationExpression"];
validFileExtensions = GetValidFileExtensions(validationExpression);
}
SetValidation(validationExpression, validators);
ViewState["product"] = Product;
ViewState["validFileExtensions"] = validFileExtensions;
}
protected void SetValidationExpression(string validationExpression, params RegularExpressionValidator[] validators)
{
var validFileExtensions = GetValidFileExtensions(validationExpression);
SetValidation(validationExpression, validators);
ViewState["product"] = Product;
ViewState["validFileExtensions"] = validFileExtensions;
}
/// <summary>
/// Set validation for RegularExpressionValidators, InputFile and ViewStates using validationExpression
/// </summary>
protected string SetValidation(string validationExpression, params RegularExpressionValidator[] validators)
{
// Check for format if format is available then valid expression will be only format for auto generated URLs
if (Page.RouteData.Values["Format"] != null)
{
validationExpression = "." + Page.RouteData.Values["Format"].ToString().ToLower();
}
var validFileExtensions = GetValidFileExtensions(validationExpression);
foreach (var v in validators)
{
v.ValidationExpression = @"(.*?)(" + validationExpression.ToLower() + "|" + validationExpression.ToUpper() + ")$";
v.ErrorMessage = Resources["InvalidFileExtension"] + " " + validFileExtensions;
if (!string.IsNullOrEmpty(v.ControlToValidate))
{
var control = v.FindControl(v.ControlToValidate);
if (control is HtmlInputFile inpufile)
SetAccept(validationExpression, inpufile);
}
}
return validFileExtensions;
}
/// <summary>
/// Get the text of valid file extensions
/// e.g. DOC, DOCX, DOT, DOTX, RTF or ODT
/// </summary>
/// <param name="validationExpression"></param>
/// <returns></returns>
protected string GetValidFileExtensions(string validationExpression)
{
var validFileExtensions = validationExpression.Replace(".", "").Replace("|", ", ").ToUpper();
var index = validFileExtensions.LastIndexOf(",");
if (index != -1)
{
var substr = validFileExtensions.Substring(index);
var str = substr.Replace(",", " or");
validFileExtensions = validFileExtensions.Replace(substr, str);
}
return validFileExtensions;
}
/// <summary>
/// Check for null and ContentLength of the PostedFile
/// </summary>
/// <param name="fileInputs"></param>
/// <returns></returns>
protected bool CheckFileInputs(params HtmlInputFile[] fileInputs)
{
return fileInputs.All(x => x != null && x.PostedFile.ContentLength > 0);
}
/// <summary>
/// Save uploaded file to the directory
/// </summary>
/// <returns>SaveLocation with filename</returns>
private string SaveUploadedFile(string directory, HtmlInputFile fileInput)
{
var fn = Path.GetFileName(fileInput.PostedFile.FileName); // Edge browser sents a full path for a filename
var saveLocation = Path.Combine(directory, fn);
fileInput.PostedFile.SaveAs(saveLocation);
return saveLocation;
}
/// <summary>
/// Check response for null and StatusCode. Call action if everything is fine or show error message if not
/// </summary>
/// <param name="response"></param>
/// <param name="controlErrorMessage"></param>
/// <param name="action"></param>
protected void PerformResponse(Response response, HtmlGenericControl controlErrorMessage, Action<Response> action)
{
if (response == null)
throw new Exception(Resources["ResponseTime"]);
if (response.StatusCode == 200 && response.FileProcessingErrorCode == 0)
action(response);
else
ShowErrorMessage(controlErrorMessage, response);
}
/// <summary>
/// Check FileProcessingErrorCode of the response and show the error message
/// </summary>
/// <param name="control"></param>
/// <param name="response"></param>
protected void ShowErrorMessage(HtmlGenericControl control, Response response)
{
string txt;
switch (response.FileProcessingErrorCode)
{
case FileProcessingErrorCode.NoImagesFound:
txt = Resources["NoImagesFoundMessage"];
break;
case FileProcessingErrorCode.NoSearchResults:
txt = Resources["NoSearchResultsMessage"];
break;
case FileProcessingErrorCode.WrongRegExp:
txt = Resources["WrongRegExpMessage"];
break;
default:
txt = response.Status;
break;
}
ShowErrorMessage(control, txt);
}
protected void SetFormatInformations(string format, HtmlControl dvAppProductSection, HtmlControl dvHowToSection, HtmlControl dvExtensionDescription )
{
if (Page.RouteData.Values[format] != null)
{
// Populate contents from database based on URL
string _url = HttpContext.Current.Request.Url.AbsolutePath.ToLower();
if (dvAppProductSection != null)
{
dvAppProductSection.Visible = false;
}
//Page.Title = hMainTitle.InnerText; // Resources["PerformOCR"];
}
}
protected void ShowErrorMessage(HtmlGenericControl control, string message)
{
if(message.ToLower().Contains("password"))
{
if ("pdf words cells slides note".Contains(Product.ToLower()) && !AppRelativeVirtualPath.ToLower().Contains("unlock"))
{
string asposeUrl = "/" + Product + "/unlock";
message = "Your file seems to be encrypted. Please use our <a style=\"color:yellow\" href=\"" + asposeUrl + "\">" + PageProductTitle + " Unlock</a> app to remove the password.";
}
}
control.Visible = true;
control.InnerHtml = message;
control.Attributes.Add("class", "alert alert-danger");
}
protected void ShowSuccessMessage(HtmlGenericControl control, string message)
{
control.Visible = true;
control.InnerHtml = message;
control.Attributes.Add("class", "alert alert-success");
}
protected void CheckReturnFromViewer(Action<Response> action)
{
if (Request.QueryString["folderName"] != null && Request.QueryString["fileName"] != null)
{
var response = new Response()
{
FileName = Request.QueryString["fileName"],
FolderName = Request.QueryString["folderName"]
};
action(response);
}
}
protected string TitleCase(string value)
{
return new CultureInfo("en-US", false).TextInfo.ToTitleCase(value);
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.Forms.dll
// Description: The Windows Forms user interface layer for the DotSpatial.Symbology library.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 5/22/2009 11:25:31 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// A Color lever is a control that shows a color on a plate, and has a knob on a lever on the side of the plate for
/// controlling the opacity, where the up position is opaque and the bottom position is transparent.
/// </summary>
[DefaultEvent("ColorChanging"),
ToolboxBitmap(typeof(ColorLever), "GradientControls.ColorLever.ico")]
public class ColorLever : Control
{
#region events
/// <summary>
/// Occurs whenever either the color or the opacity for this control is adjusted
/// </summary>
public event EventHandler ColorChanged;
/// <summary>
/// Occurs as the opacity is being adjusted by the slider, but while the slider is
/// still being dragged.
/// </summary>
public event EventHandler OpacityChanging;
/// <summary>
/// Because the color is changed any time the opacity is changed, while the lever is being
/// adjusted, the color is being updated as well as the opacity. Therefore, this is fired
/// both when the color is changed directly or when the slider is being adjusted.
/// </summary>
public event EventHandler ColorChanging;
#endregion
#region Private Variables
private readonly ToolTip _ttHelp;
private double _angle;
private int _barLength;
private int _barWidth;
private int _borderWidth;
private Color _color;
private bool _flip;
private bool _isDragging;
private Color _knobColor;
private int _knobRadius;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of ColorLever
/// </summary>
public ColorLever()
{
_color = SymbologyGlobal.RandomLightColor(1F);
_borderWidth = 5;
_knobRadius = 7;
_barLength = 5;
_barWidth = 5;
_knobColor = Color.SteelBlue;
_ttHelp = new ToolTip();
_ttHelp.SetToolTip(this, "Click to change the color, or rotate the lever to control opacity.");
}
#endregion
#region Methods
#endregion
#region Properties
/// <summary>
/// Gets or sets the double valued angle for this control.
/// </summary>
[Editor(typeof(AngleEditor), typeof(UITypeEditor))]
public double Angle
{
get { return _angle; }
set { _angle = value; }
}
/// <summary>
/// Gets or sets the bar length
/// </summary>
public int BarLength
{
get { return _barLength; }
set { _barLength = value; }
}
/// <summary>
/// Gets or sets the width of the bar connecting the knob
/// </summary>
public int BarWidth
{
get { return _barWidth; }
set { _barWidth = value; }
}
/// <summary>
/// Gets or sets the border width
/// </summary>
public int BorderWidth
{
get { return _borderWidth; }
set { _borderWidth = value; }
}
/// <summary>
/// Gets or sets the color being displayed on the color plate.
/// </summary>
public Color Color
{
get { return _color; }
set { _color = value; }
}
/// <summary>
/// Gets or sets the radius to use for the knob on the opacity lever.
/// </summary>
public int KnobRadius
{
get { return _knobRadius; }
set { _knobRadius = value; }
}
/// <summary>
/// Gets or sets the knob color.
/// </summary>
public Color KnobColor
{
get { return _knobColor; }
set { _knobColor = value; }
}
/// <summary>
/// Gets or sets a boolean that can be used to reverse the lever, rather than simply rotating it.
/// </summary>
public bool Flip
{
get { return _flip; }
set { _flip = value; }
}
/// <summary>
/// Gets or sets the opacity for the color lever. This will also
/// adjust the knob position.
/// </summary>
[Editor(typeof(OpacityEditor), typeof(UITypeEditor))]
public float Opacity
{
get { return _color.GetOpacity(); }
set
{
_color = _color.ToTransparent(value);
Invalidate();
}
}
#endregion
#region Protected Methods
/// <summary>
/// Prevent flicker
/// </summary>
/// <param name="pevent"></param>
protected override void OnPaintBackground(PaintEventArgs pevent)
{
//base.OnPaintBackground(pevent);
}
/// <summary>
/// Draw the clipped portion
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
Rectangle clip = e.ClipRectangle;
if (clip.IsEmpty) clip = ClientRectangle;
Bitmap bmp = new Bitmap(clip.Width, clip.Height);
Graphics g = Graphics.FromImage(bmp);
g.TranslateTransform(-clip.X, -clip.Y);
g.Clip = new Region(clip);
g.Clear(BackColor);
g.SmoothingMode = SmoothingMode.AntiAlias;
OnDraw(g, clip);
g.Dispose();
e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel);
}
/// <summary>
/// Controls the actual drawing for this gradient slider control.
/// </summary>
/// <param name="g"></param>
/// <param name="clipRectangle"></param>
protected virtual void OnDraw(Graphics g, Rectangle clipRectangle)
{
Matrix old = g.Transform;
Matrix flipRot = g.Transform;
Transform(flipRot);
g.Transform = flipRot;
DrawColorSemicircle(g);
DrawKnob(g);
DrawLever(g, clipRectangle);
DrawHand(g);
g.Transform = old;
}
private void Transform(Matrix flipRot)
{
flipRot.Translate(Width / 2F, Height / 2F);
if (_flip)
{
flipRot.Scale(-1F, 1F);
}
flipRot.Rotate(-(float)_angle);
double ang = _angle * Math.PI / 180;
float scale = (float)(1 / (1 + (Math.Sqrt(2) - 1) * Math.Abs(Math.Sin(ang))));
flipRot.Scale(scale, scale); // A rotated square would go outside the bounds of the control, so resize.
flipRot.Translate(-Width / 2F, -Height / 2F);
}
private void DrawHand(Graphics g)
{
if (_isDragging == false) return;
Rectangle r = GetKnobBounds();
Icon ico = SymbologyFormsImages.Pan;
if (ico != null) g.DrawIcon(ico, r.X + r.Width / 2 - ico.Width / 2, r.Y + r.Height / 2 - ico.Height / 2);
}
private void DrawColorSemicircle(Graphics g)
{
Rectangle bounds = GetSemicircleBounds();
if (bounds.Width <= 0 || bounds.Height <= 0) return;
GraphicsPath gp = new GraphicsPath();
gp.AddPie(new Rectangle(-bounds.Width, bounds.Y, bounds.Width * 2, bounds.Height), -90, 180);
Rectangle roundBounds = new Rectangle(bounds.X, bounds.Y, bounds.Width, bounds.Height);
LinearGradientBrush lgb = new LinearGradientBrush(roundBounds, BackColor.Lighter(.5F), BackColor.Darker(.5F), LinearGradientMode.ForwardDiagonal);
g.FillPath(lgb, gp);
lgb.Dispose();
gp.Dispose();
gp = new GraphicsPath();
Rectangle innerRound = GetInnerSemicircleBounds();
if (innerRound.Width <= 0 || innerRound.Height <= 0) return;
gp.AddPie(new Rectangle(innerRound.X - innerRound.Width, innerRound.Y, innerRound.Width * 2, innerRound.Height), -90, 180);
PointF center = new PointF(innerRound.X + innerRound.Width / 2, innerRound.Y + innerRound.Height / 2);
float x = center.X - innerRound.Width;
float y = center.Y - innerRound.Height;
float w = innerRound.Width * 2;
float h = innerRound.Height * 2;
RectangleF circum = new RectangleF(x, y, w, h);
GraphicsPath coloring = new GraphicsPath();
coloring.AddEllipse(circum);
PathGradientBrush pgb = new PathGradientBrush(coloring);
pgb.CenterColor = _color.Lighter(.2F);
pgb.SurroundColors = new[] { _color.Darker(.2F) };
pgb.CenterPoint = new PointF(innerRound.X + 3, innerRound.Y + innerRound.Height / 3);
g.FillPath(pgb, gp);
lgb.Dispose();
gp.Dispose();
}
// calculate so that the bar can rotate freely all the way around the rotation axis.
private Rectangle GetSemicircleBounds()
{
int l = _barLength + _knobRadius * 2;
Rectangle result = new Rectangle(0, l, Width - l, Height - 2 * l);
return result;
}
private Rectangle GetInnerSemicircleBounds()
{
Rectangle result = GetSemicircleBounds();
result.X += _borderWidth;
result.Width -= _borderWidth * 2;
result.Y += _borderWidth;
result.Height -= _borderWidth * 2;
return result;
}
private Rectangle GetKnobBounds()
{
Rectangle result = new Rectangle();
result.Width = _knobRadius * 2;
result.Height = _knobRadius * 2;
double scale = Height - _knobRadius * 2 - 1;
result.Y = Convert.ToInt32((1 - _color.GetOpacity()) * scale);
double angle = GetKnobAngle();
scale = Width - _knobRadius * 2 - 1;
result.X = Convert.ToInt32(scale * Math.Sin(angle));
return result;
}
private double GetKnobAngle()
{
return Math.Acos((double)_color.GetOpacity() * 2 - 1);
}
private void DrawKnob(Graphics g)
{
Rectangle bounds = GetKnobBounds();
LinearGradientBrush lgb = new LinearGradientBrush(bounds, _knobColor.Lighter(.3F), _knobColor.Darker(.3F), LinearGradientMode.ForwardDiagonal);
g.FillEllipse(lgb, bounds);
lgb.Dispose();
}
private void DrawLever(Graphics g, Rectangle clipRectangle)
{
Point start = new Point(_knobRadius, Height / 2);
Rectangle knob = GetKnobBounds();
PointF center = new PointF(knob.X + _knobRadius, knob.Y + _knobRadius);
double dx = center.X - start.X;
double dy = center.Y - start.Y;
double len = Math.Sqrt(dx * dx + dy * dy);
double sx = dx / len;
double sy = dy / len;
PointF kJoint = new PointF((float)(center.X - sx * _knobRadius), (float)(center.Y - sy * _knobRadius));
PointF sJoint = new PointF((float)(center.X - sx * (_knobRadius + _barLength)), (float)(center.Y - sy * (_barLength + _knobRadius)));
Pen back = new Pen(BackColor.Darker(.2F), _barWidth);
back.EndCap = LineCap.Round;
back.StartCap = LineCap.Round;
Pen front = new Pen(BackColor, (float)_barWidth / 2);
front.EndCap = LineCap.Round;
front.StartCap = LineCap.Round;
g.DrawLine(back, sJoint, kJoint);
g.DrawLine(front, sJoint, kJoint);
back.Dispose();
front.Dispose();
}
/// <summary>
/// Uses the current transform matrix to calculate the coordinates in terms of the unrotated, unflipped image
/// </summary>
/// <param name="location"></param>
protected Point ClientToStandard(Point location)
{
Point result = location;
Matrix flipRot = new Matrix();
Transform(flipRot);
flipRot.Invert();
Point[] transformed = new[] { result };
flipRot.TransformPoints(transformed);
return transformed[0];
}
/// <summary>
/// Transforms a point from the standard orientation of the control into client coordinates.
/// </summary>
/// <param name="location"></param>
/// <returns></returns>
protected Point StandardToClient(Point location)
{
Point result = location;
Matrix flipRot = new Matrix();
Transform(flipRot);
Point[] transformed = new[] { result };
flipRot.TransformPoints(transformed);
return transformed[0];
}
/// <summary>
/// Handles the mouse down position for dragging the lever.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// turn the mouse coordinates into a standardized orientation where the control looks like the letter D
Point loc = ClientToStandard(e.Location);
Rectangle knob = GetKnobBounds();
if (knob.Contains(loc))
{
_isDragging = true;
Cursor.Hide();
}
}
base.OnMouseDown(e);
}
/// <summary>
/// Handles the mouse move event to handle when the lever is dragged.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseMove(MouseEventArgs e)
{
if (_isDragging)
{
// turn the mouse coordinates into a standardized orientation where the control looks like the letter D
Point loc = ClientToStandard(e.Location);
Point center = new Point(_knobRadius, Height / 2);
double dx = loc.X - center.X;
double dy = (loc.Y - center.Y);
if (dx == 0 && dy == 0) return;
double h;
if (dx > 0)
{
h = (1 - (dy / Math.Sqrt((dx * dx + dy * dy)))) / 2;
}
else
{
if (dy > 0)
{
h = 0;
}
else
{
h = 1;
}
}
Opacity = (float)h;
Rectangle knob = GetKnobBounds();
if (knob.Contains(loc) == false)
{
// nudge the hidden mouse so that it at least stays in the balpark of the knob.
center = new Point(knob.X + knob.Width / 2, knob.Y + knob.Height / 2);
dx = loc.X - center.X;
dy = loc.Y - center.Y;
double len = Math.Sqrt(dx * dx + dy * dy);
double rx = dx / len;
double ry = dy / len;
Point c = new Point(Convert.ToInt32(center.X + rx), Convert.ToInt32(center.Y + ry));
Point client = StandardToClient(c);
Point screen = PointToScreen(client);
Cursor.Position = screen;
}
OnOpacityChanging();
OnColorChanging();
Invalidate();
}
base.OnMouseMove(e);
}
/// <summary>
/// Controls the mouse up for ending the drag movement, or possibly launching the color dialog to change the base color.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (_isDragging)
{
_isDragging = false;
Rectangle knob = GetKnobBounds();
Point center = new Point(knob.X + knob.Width / 2, knob.Y + knob.Height / 2);
Point client = StandardToClient(center);
Point screen = PointToScreen(client);
Cursor.Position = screen;
Cursor.Show();
OnColorChanging();
OnColorChanged();
}
else
{
ColorDialog cdlg = new ColorDialog();
if (cdlg.ShowDialog() == DialogResult.OK)
{
_color = cdlg.Color;
OnColorChanging();
OnColorChanged();
}
}
Invalidate();
}
base.OnMouseUp(e);
}
/// <summary>
/// Fires a ColorChanged event whenver the opacity or color have been altered.
/// </summary>
protected virtual void OnColorChanged()
{
if (ColorChanged != null) ColorChanged(this, EventArgs.Empty);
}
/// <summary>
/// Fires the ColorChanging evetn whenever the color is changing either directly, or by the use of the opacity lever.
/// </summary>
protected virtual void OnColorChanging()
{
if (ColorChanging != null) ColorChanging(this, EventArgs.Empty);
}
/// <summary>
/// Fires the OpacityChanging event when the opacity is being changed
/// </summary>
protected virtual void OnOpacityChanging()
{
if (OpacityChanging != null) OpacityChanging(this, EventArgs.Empty);
}
#endregion
}
}
| |
// 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="MobileAppCategoryConstantServiceClient"/> instances.</summary>
public sealed partial class MobileAppCategoryConstantServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="MobileAppCategoryConstantServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="MobileAppCategoryConstantServiceSettings"/>.</returns>
public static MobileAppCategoryConstantServiceSettings GetDefault() => new MobileAppCategoryConstantServiceSettings();
/// <summary>
/// Constructs a new <see cref="MobileAppCategoryConstantServiceSettings"/> object with default settings.
/// </summary>
public MobileAppCategoryConstantServiceSettings()
{
}
private MobileAppCategoryConstantServiceSettings(MobileAppCategoryConstantServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetMobileAppCategoryConstantSettings = existing.GetMobileAppCategoryConstantSettings;
OnCopy(existing);
}
partial void OnCopy(MobileAppCategoryConstantServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>MobileAppCategoryConstantServiceClient.GetMobileAppCategoryConstant</c> and
/// <c>MobileAppCategoryConstantServiceClient.GetMobileAppCategoryConstantAsync</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 GetMobileAppCategoryConstantSettings { 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="MobileAppCategoryConstantServiceSettings"/> object.</returns>
public MobileAppCategoryConstantServiceSettings Clone() => new MobileAppCategoryConstantServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="MobileAppCategoryConstantServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class MobileAppCategoryConstantServiceClientBuilder : gaxgrpc::ClientBuilderBase<MobileAppCategoryConstantServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public MobileAppCategoryConstantServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public MobileAppCategoryConstantServiceClientBuilder()
{
UseJwtAccessWithScopes = MobileAppCategoryConstantServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref MobileAppCategoryConstantServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<MobileAppCategoryConstantServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override MobileAppCategoryConstantServiceClient Build()
{
MobileAppCategoryConstantServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<MobileAppCategoryConstantServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<MobileAppCategoryConstantServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private MobileAppCategoryConstantServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return MobileAppCategoryConstantServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<MobileAppCategoryConstantServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return MobileAppCategoryConstantServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => MobileAppCategoryConstantServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
MobileAppCategoryConstantServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => MobileAppCategoryConstantServiceClient.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>MobileAppCategoryConstantService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to fetch mobile app category constants.
/// </remarks>
public abstract partial class MobileAppCategoryConstantServiceClient
{
/// <summary>
/// The default endpoint for the MobileAppCategoryConstantService 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 MobileAppCategoryConstantService scopes.</summary>
/// <remarks>
/// The default MobileAppCategoryConstantService 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="MobileAppCategoryConstantServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="MobileAppCategoryConstantServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="MobileAppCategoryConstantServiceClient"/>.</returns>
public static stt::Task<MobileAppCategoryConstantServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new MobileAppCategoryConstantServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="MobileAppCategoryConstantServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="MobileAppCategoryConstantServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="MobileAppCategoryConstantServiceClient"/>.</returns>
public static MobileAppCategoryConstantServiceClient Create() =>
new MobileAppCategoryConstantServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="MobileAppCategoryConstantServiceClient"/> 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="MobileAppCategoryConstantServiceSettings"/>.</param>
/// <returns>The created <see cref="MobileAppCategoryConstantServiceClient"/>.</returns>
internal static MobileAppCategoryConstantServiceClient Create(grpccore::CallInvoker callInvoker, MobileAppCategoryConstantServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient grpcClient = new MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient(callInvoker);
return new MobileAppCategoryConstantServiceClientImpl(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 MobileAppCategoryConstantService client</summary>
public virtual MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested mobile app category constant.
///
/// 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::MobileAppCategoryConstant GetMobileAppCategoryConstant(GetMobileAppCategoryConstantRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested mobile app category constant.
///
/// 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::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(GetMobileAppCategoryConstantRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested mobile app category constant.
///
/// 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::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(GetMobileAppCategoryConstantRequest request, st::CancellationToken cancellationToken) =>
GetMobileAppCategoryConstantAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::MobileAppCategoryConstant GetMobileAppCategoryConstant(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetMobileAppCategoryConstant(new GetMobileAppCategoryConstantRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant 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::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetMobileAppCategoryConstantAsync(new GetMobileAppCategoryConstantRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant 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::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetMobileAppCategoryConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::MobileAppCategoryConstant GetMobileAppCategoryConstant(gagvr::MobileAppCategoryConstantName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetMobileAppCategoryConstant(new GetMobileAppCategoryConstantRequest
{
ResourceNameAsMobileAppCategoryConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant 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::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(gagvr::MobileAppCategoryConstantName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetMobileAppCategoryConstantAsync(new GetMobileAppCategoryConstantRequest
{
ResourceNameAsMobileAppCategoryConstantName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. Resource name of the mobile app category constant 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::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(gagvr::MobileAppCategoryConstantName resourceName, st::CancellationToken cancellationToken) =>
GetMobileAppCategoryConstantAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>MobileAppCategoryConstantService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to fetch mobile app category constants.
/// </remarks>
public sealed partial class MobileAppCategoryConstantServiceClientImpl : MobileAppCategoryConstantServiceClient
{
private readonly gaxgrpc::ApiCall<GetMobileAppCategoryConstantRequest, gagvr::MobileAppCategoryConstant> _callGetMobileAppCategoryConstant;
/// <summary>
/// Constructs a client wrapper for the MobileAppCategoryConstantService service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="MobileAppCategoryConstantServiceSettings"/> used within this client.
/// </param>
public MobileAppCategoryConstantServiceClientImpl(MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient grpcClient, MobileAppCategoryConstantServiceSettings settings)
{
GrpcClient = grpcClient;
MobileAppCategoryConstantServiceSettings effectiveSettings = settings ?? MobileAppCategoryConstantServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetMobileAppCategoryConstant = clientHelper.BuildApiCall<GetMobileAppCategoryConstantRequest, gagvr::MobileAppCategoryConstant>(grpcClient.GetMobileAppCategoryConstantAsync, grpcClient.GetMobileAppCategoryConstant, effectiveSettings.GetMobileAppCategoryConstantSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetMobileAppCategoryConstant);
Modify_GetMobileAppCategoryConstantApiCall(ref _callGetMobileAppCategoryConstant);
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_GetMobileAppCategoryConstantApiCall(ref gaxgrpc::ApiCall<GetMobileAppCategoryConstantRequest, gagvr::MobileAppCategoryConstant> call);
partial void OnConstruction(MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient grpcClient, MobileAppCategoryConstantServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC MobileAppCategoryConstantService client</summary>
public override MobileAppCategoryConstantService.MobileAppCategoryConstantServiceClient GrpcClient { get; }
partial void Modify_GetMobileAppCategoryConstantRequest(ref GetMobileAppCategoryConstantRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested mobile app category constant.
///
/// 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::MobileAppCategoryConstant GetMobileAppCategoryConstant(GetMobileAppCategoryConstantRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetMobileAppCategoryConstantRequest(ref request, ref callSettings);
return _callGetMobileAppCategoryConstant.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested mobile app category constant.
///
/// 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::MobileAppCategoryConstant> GetMobileAppCategoryConstantAsync(GetMobileAppCategoryConstantRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetMobileAppCategoryConstantRequest(ref request, ref callSettings);
return _callGetMobileAppCategoryConstant.Async(request, callSettings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DG.Tweening;
using MoreMountains.NiceVibrations;
using Proyecto26;
using Cysharp.Threading.Tasks;
using E7.Native;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UI;
public class EventSelectionScreen : Screen
{
public Image coverImage;
public Image logoImage;
public TransitionElement infoBanner;
public Text durationText;
public InteractableMonoBehavior viewDetailsButton;
public InteractableMonoBehavior viewObjectivesButton;
public InteractableMonoBehavior enterButton;
public InteractableMonoBehavior helpButton;
public InteractableMonoBehavior previousButton;
public InteractableMonoBehavior nextButton;
public BadgeNotification viewDetailsNotification;
public BadgeNotification viewObjectivesNotification;
public override void OnScreenInitialized()
{
base.OnScreenInitialized();
coverImage.sprite = null;
logoImage.sprite = null;
helpButton.onPointerClick.SetListener(_ => Dialog.PromptAlert("EVENT_TUTORIAL".Get()));
}
public override void OnScreenBecameActive()
{
coverImage.color = Color.black;
logoImage.color = Color.white.WithAlpha(0);
base.OnScreenBecameActive();
}
protected override async void LoadPayload(ScreenLoadPromise promise)
{
SpinnerOverlay.Show();
await Context.LevelManager.LoadLevelsOfType(LevelType.User);
RestClient.GetArray<EventMeta>(new RequestHelper
{
Uri = $"{Context.ApiUrl}/events",
Headers = Context.OnlinePlayer.GetRequestHeaders(),
EnableDebug = true
}).Then(data =>
{
if (data.Length == 0)
{
Dialog.PromptGoBack("DIALOG_EVENTS_NOT_AVAILABLE".Get());
promise.Reject();
return;
}
IntentPayload.Events = data.ToList();
promise.Resolve(IntentPayload);
})
.CatchRequestError(error =>
{
Debug.LogError(error);
Dialog.PromptGoBack("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
promise.Reject();
})
.Finally(() => SpinnerOverlay.Hide());
}
protected override void Render()
{
previousButton.onPointerClick.RemoveAllListeners();
nextButton.onPointerClick.RemoveAllListeners();
if (LoadedPayload.Events.Count == 1)
{
previousButton.scaleOnClick = false;
nextButton.scaleOnClick = false;
previousButton.GetComponentInChildren<Image>().SetAlpha(0.3f);
nextButton.GetComponentInChildren<Image>().SetAlpha(0.3f);
}
else
{
previousButton.scaleOnClick = true;
nextButton.scaleOnClick = true;
previousButton.GetComponentInChildren<Image>().SetAlpha(1f);
nextButton.GetComponentInChildren<Image>().SetAlpha(1f);
previousButton.onPointerClick.AddListener(_ => PreviousEvent());
nextButton.onPointerClick.AddListener(_ => NextEvent());
}
base.Render();
}
protected override void OnRendered()
{
base.OnRendered();
if (LoadedPayload.SelectedIndex < 0 || LoadedPayload.SelectedIndex >= LoadedPayload.Events.Count) LoadedPayload.SelectedIndex = 0;
LoadEvent(LoadedPayload.Events[LoadedPayload.SelectedIndex]);
}
public void LoadEvent(EventMeta meta)
{
async UniTask LoadCover(CancellationToken token)
{
Assert.IsNotNull(meta.cover);
var tasks = new List<UniTask>();
if (coverImage.sprite != null)
{
coverImage.DOKill();
coverImage.DOColor(Color.black, 0.4f);
tasks.Add(UniTask.Delay(TimeSpan.FromSeconds(0.4f), cancellationToken: token));
}
Sprite sprite = null;
tasks.Add(Context.AssetMemory.LoadAsset<Sprite>(meta.cover.OriginalUrl, AssetTag.EventCover, cancellationToken: token).ContinueWith(result => sprite = result));
try
{
await tasks;
}
catch (OperationCanceledException)
{
return;
}
coverImage.sprite = sprite;
coverImage.FitSpriteAspectRatio();
coverImage.DOColor(Color.white, 2f).SetDelay(0.8f);
}
async UniTask LoadLogo(CancellationToken token)
{
Assert.IsNotNull(meta.logo);
var tasks = new List<UniTask>();
if (logoImage.sprite != null)
{
logoImage.DOKill();
logoImage.DOFade(0, 0.4f);
tasks.Add(UniTask.Delay(TimeSpan.FromSeconds(0.4f), cancellationToken: token));
}
Sprite sprite = null;
tasks.Add(Context.AssetMemory.LoadAsset<Sprite>(meta.logo.OriginalUrl, AssetTag.EventLogo, cancellationToken: token).ContinueWith(result => sprite = result));
try
{
await tasks;
}
catch (OperationCanceledException)
{
return;
}
logoImage.sprite = sprite;
logoImage.DOFade(1, 0.8f).SetDelay(0.4f);
}
AddTask(LoadCover);
AddTask(LoadLogo);
Context.Player.Settings.SeenEvents.Add(meta.uid);
Context.Player.SaveSettings();
infoBanner.Leave(onComplete: () =>
{
if (!Context.Player.Settings.ReadEventDetails.Contains(meta.uid))
{
viewDetailsNotification.Show();
}
if (!Context.Player.Settings.ReadEventObjectives.Contains(meta.uid))
{
viewObjectivesNotification.Show();
}
viewDetailsButton.onPointerClick.SetListener(_ =>
{
Context.Player.Settings.ReadEventDetails.Add(meta.uid);
Context.Player.SaveSettings();
viewDetailsNotification.Hide();
if (meta.url.IsNullOrEmptyTrimmed())
{
Application.OpenURL($"{Context.WebsiteUrl}/posts/{meta.uid}");
}
else
{
WebViewOverlay.Show(meta.url,
onFullyShown: () =>
{
LoopAudioPlayer.Instance.FadeOutLoopPlayer();
},
onFullyHidden: async () =>
{
AudioSettings.Reset(AudioSettings.GetConfiguration());
Context.AudioManager.Dispose();
Context.AudioManager.Initialize();
await UniTask.DelayFrame(5);
LoopAudioPlayer.Instance.Apply(it =>
{
it.FadeInLoopPlayer();
it.PlayAudio(it.PlayingAudio, forceReplay: true);
});
});
}
});
const string dateFormat = "yyyy/MM/dd HH:mm";
durationText.text = (meta.startDate.HasValue ? meta.startDate.Value.LocalDateTime.ToString(dateFormat) : "")
+ "~"
+ (meta.endDate.HasValue ? meta.endDate.Value.LocalDateTime.ToString(dateFormat) : "");
viewObjectivesButton.onPointerClick.SetListener(_ =>
{
Context.Player.Settings.ReadEventObjectives.Add(meta.uid);
Context.Player.SaveSettings();
viewObjectivesNotification.Hide();
SpinnerOverlay.Show();
RestClient.Get<AdventureState>(new RequestHelper
{
Uri = $"{Context.ApiUrl}/epics/adventures/{meta.epicId}",
Headers = Context.OnlinePlayer.GetRequestHeaders(),
EnableDebug = true
})
.Then(QuestOverlay.Show)
.Catch(err =>
{
Debug.LogError(err);
Dialog.PromptAlert("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
})
.Finally(() => SpinnerOverlay.Hide());
});
enterButton.onPointerClick.SetListener(_ =>
{
if (meta.locked)
{
Context.Haptic(HapticTypes.Failure, true);
// TODO
return;
}
Context.Haptic(HapticTypes.SoftImpact, true);
if (meta.levelId != null)
{
SpinnerOverlay.Show();
RestClient.Get<OnlineLevel>(new RequestHelper
{
Uri = $"{Context.ApiUrl}/levels/{meta.levelId}"
}).Then(level =>
{
Context.ScreenManager.ChangeScreen(
GamePreparationScreen.Id, ScreenTransition.In, 0.4f,
transitionFocus: GetComponent<RectTransform>().GetScreenSpaceCenter(),
payload: new GamePreparationScreen.Payload {Level = level.ToLevel(LevelType.User)}
);
}).CatchRequestError(error =>
{
Debug.LogError(error);
Dialog.PromptAlert("DIALOG_COULD_NOT_CONNECT_TO_SERVER".Get());
}).Finally(() => SpinnerOverlay.Hide());
}
else if (meta.collectionId != null)
{
Context.ScreenManager.ChangeScreen(
CollectionDetailsScreen.Id, ScreenTransition.In, 0.4f,
transitionFocus: GetComponent<RectTransform>().GetScreenSpaceCenter(),
payload: new CollectionDetailsScreen.Payload
{CollectionId = meta.collectionId, Type = LevelType.User}
);
}
});
infoBanner.transform.RebuildLayout();
infoBanner.Enter();
});
}
private void NextEvent()
{
LoadedPayload.SelectedIndex = (LoadedPayload.SelectedIndex + 1).Mod(LoadedPayload.Events.Count);
LoadEvent(LoadedPayload.Events[LoadedPayload.SelectedIndex]);
}
private void PreviousEvent()
{
LoadedPayload.SelectedIndex = (LoadedPayload.SelectedIndex - 1).Mod(LoadedPayload.Events.Count);
LoadEvent(LoadedPayload.Events[LoadedPayload.SelectedIndex]);
}
public override void OnScreenChangeFinished(Screen from, Screen to)
{
base.OnScreenChangeFinished(from, to);
if (from == this)
{
coverImage.DOKill();
coverImage.sprite = null;
logoImage.DOKill();
logoImage.sprite = null;
if (to is MainMenuScreen)
{
Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.EventCover);
Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.EventLogo);
Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.RemoteLevelCoverThumbnail);
LoadedPayload = null;
}
}
}
public class Payload : ScreenPayload
{
public List<EventMeta> Events;
public int SelectedIndex;
}
public new Payload IntentPayload => (Payload) base.IntentPayload;
public new Payload LoadedPayload
{
get => (Payload) base.LoadedPayload;
set => base.LoadedPayload = value;
}
public override ScreenPayload GetDefaultPayload() => new Payload();
public const string Id = "EventSelection";
public override string GetId() => Id;
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Datastream.V1Alpha1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedDatastreamClientTest
{
[xunit::FactAttribute]
public void GetConnectionProfileRequestObject()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
OracleProfile = new OracleProfile(),
GcsProfile = new GcsProfile(),
MysqlProfile = new MysqlProfile(),
NoConnectivity = new NoConnectivitySettings(),
StaticServiceIpConnectivity = new StaticServiceIpConnectivity(),
ForwardSshConnectivity = new ForwardSshTunnelConnectivity(),
PrivateConnectivity = new PrivateConnectivity(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
ConnectionProfile response = client.GetConnectionProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionProfileRequestObjectAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
OracleProfile = new OracleProfile(),
GcsProfile = new GcsProfile(),
MysqlProfile = new MysqlProfile(),
NoConnectivity = new NoConnectivitySettings(),
StaticServiceIpConnectivity = new StaticServiceIpConnectivity(),
ForwardSshConnectivity = new ForwardSshTunnelConnectivity(),
PrivateConnectivity = new PrivateConnectivity(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConnectionProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
ConnectionProfile responseCallSettings = await client.GetConnectionProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConnectionProfile responseCancellationToken = await client.GetConnectionProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnectionProfile()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
OracleProfile = new OracleProfile(),
GcsProfile = new GcsProfile(),
MysqlProfile = new MysqlProfile(),
NoConnectivity = new NoConnectivitySettings(),
StaticServiceIpConnectivity = new StaticServiceIpConnectivity(),
ForwardSshConnectivity = new ForwardSshTunnelConnectivity(),
PrivateConnectivity = new PrivateConnectivity(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
ConnectionProfile response = client.GetConnectionProfile(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionProfileAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
OracleProfile = new OracleProfile(),
GcsProfile = new GcsProfile(),
MysqlProfile = new MysqlProfile(),
NoConnectivity = new NoConnectivitySettings(),
StaticServiceIpConnectivity = new StaticServiceIpConnectivity(),
ForwardSshConnectivity = new ForwardSshTunnelConnectivity(),
PrivateConnectivity = new PrivateConnectivity(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConnectionProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
ConnectionProfile responseCallSettings = await client.GetConnectionProfileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConnectionProfile responseCancellationToken = await client.GetConnectionProfileAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetConnectionProfileResourceNames()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
OracleProfile = new OracleProfile(),
GcsProfile = new GcsProfile(),
MysqlProfile = new MysqlProfile(),
NoConnectivity = new NoConnectivitySettings(),
StaticServiceIpConnectivity = new StaticServiceIpConnectivity(),
ForwardSshConnectivity = new ForwardSshTunnelConnectivity(),
PrivateConnectivity = new PrivateConnectivity(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
ConnectionProfile response = client.GetConnectionProfile(request.ConnectionProfileName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetConnectionProfileResourceNamesAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetConnectionProfileRequest request = new GetConnectionProfileRequest
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
};
ConnectionProfile expectedResponse = new ConnectionProfile
{
ConnectionProfileName = ConnectionProfileName.FromProjectLocationConnectionProfile("[PROJECT]", "[LOCATION]", "[CONNECTION_PROFILE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
OracleProfile = new OracleProfile(),
GcsProfile = new GcsProfile(),
MysqlProfile = new MysqlProfile(),
NoConnectivity = new NoConnectivitySettings(),
StaticServiceIpConnectivity = new StaticServiceIpConnectivity(),
ForwardSshConnectivity = new ForwardSshTunnelConnectivity(),
PrivateConnectivity = new PrivateConnectivity(),
};
mockGrpcClient.Setup(x => x.GetConnectionProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ConnectionProfile>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
ConnectionProfile responseCallSettings = await client.GetConnectionProfileAsync(request.ConnectionProfileName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ConnectionProfile responseCancellationToken = await client.GetConnectionProfileAsync(request.ConnectionProfileName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DiscoverConnectionProfileRequestObject()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DiscoverConnectionProfileRequest request = new DiscoverConnectionProfileRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Recursive = true,
RecursionDepth = -1975322556,
OracleRdbms = new OracleRdbms(),
MysqlRdbms = new MysqlRdbms(),
ConnectionProfile = new ConnectionProfile(),
ConnectionProfileName = "connection_profile_name6b70b941",
};
DiscoverConnectionProfileResponse expectedResponse = new DiscoverConnectionProfileResponse
{
OracleRdbms = new OracleRdbms(),
MysqlRdbms = new MysqlRdbms(),
};
mockGrpcClient.Setup(x => x.DiscoverConnectionProfile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
DiscoverConnectionProfileResponse response = client.DiscoverConnectionProfile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DiscoverConnectionProfileRequestObjectAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DiscoverConnectionProfileRequest request = new DiscoverConnectionProfileRequest
{
ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Recursive = true,
RecursionDepth = -1975322556,
OracleRdbms = new OracleRdbms(),
MysqlRdbms = new MysqlRdbms(),
ConnectionProfile = new ConnectionProfile(),
ConnectionProfileName = "connection_profile_name6b70b941",
};
DiscoverConnectionProfileResponse expectedResponse = new DiscoverConnectionProfileResponse
{
OracleRdbms = new OracleRdbms(),
MysqlRdbms = new MysqlRdbms(),
};
mockGrpcClient.Setup(x => x.DiscoverConnectionProfileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<DiscoverConnectionProfileResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
DiscoverConnectionProfileResponse responseCallSettings = await client.DiscoverConnectionProfileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
DiscoverConnectionProfileResponse responseCancellationToken = await client.DiscoverConnectionProfileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetStreamRequestObject()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetStreamRequest request = new GetStreamRequest
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
};
Stream expectedResponse = new Stream
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
SourceConfig = new SourceConfig(),
DestinationConfig = new DestinationConfig(),
State = Stream.Types.State.Paused,
Errors = { new Error(), },
BackfillAll = new Stream.Types.BackfillAllStrategy(),
BackfillNone = new Stream.Types.BackfillNoneStrategy(),
};
mockGrpcClient.Setup(x => x.GetStream(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Stream response = client.GetStream(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetStreamRequestObjectAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetStreamRequest request = new GetStreamRequest
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
};
Stream expectedResponse = new Stream
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
SourceConfig = new SourceConfig(),
DestinationConfig = new DestinationConfig(),
State = Stream.Types.State.Paused,
Errors = { new Error(), },
BackfillAll = new Stream.Types.BackfillAllStrategy(),
BackfillNone = new Stream.Types.BackfillNoneStrategy(),
};
mockGrpcClient.Setup(x => x.GetStreamAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Stream>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Stream responseCallSettings = await client.GetStreamAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Stream responseCancellationToken = await client.GetStreamAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetStream()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetStreamRequest request = new GetStreamRequest
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
};
Stream expectedResponse = new Stream
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
SourceConfig = new SourceConfig(),
DestinationConfig = new DestinationConfig(),
State = Stream.Types.State.Paused,
Errors = { new Error(), },
BackfillAll = new Stream.Types.BackfillAllStrategy(),
BackfillNone = new Stream.Types.BackfillNoneStrategy(),
};
mockGrpcClient.Setup(x => x.GetStream(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Stream response = client.GetStream(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetStreamAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetStreamRequest request = new GetStreamRequest
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
};
Stream expectedResponse = new Stream
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
SourceConfig = new SourceConfig(),
DestinationConfig = new DestinationConfig(),
State = Stream.Types.State.Paused,
Errors = { new Error(), },
BackfillAll = new Stream.Types.BackfillAllStrategy(),
BackfillNone = new Stream.Types.BackfillNoneStrategy(),
};
mockGrpcClient.Setup(x => x.GetStreamAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Stream>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Stream responseCallSettings = await client.GetStreamAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Stream responseCancellationToken = await client.GetStreamAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetStreamResourceNames()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetStreamRequest request = new GetStreamRequest
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
};
Stream expectedResponse = new Stream
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
SourceConfig = new SourceConfig(),
DestinationConfig = new DestinationConfig(),
State = Stream.Types.State.Paused,
Errors = { new Error(), },
BackfillAll = new Stream.Types.BackfillAllStrategy(),
BackfillNone = new Stream.Types.BackfillNoneStrategy(),
};
mockGrpcClient.Setup(x => x.GetStream(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Stream response = client.GetStream(request.StreamName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetStreamResourceNamesAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetStreamRequest request = new GetStreamRequest
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
};
Stream expectedResponse = new Stream
{
StreamName = StreamName.FromProjectLocationStream("[PROJECT]", "[LOCATION]", "[STREAM]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
SourceConfig = new SourceConfig(),
DestinationConfig = new DestinationConfig(),
State = Stream.Types.State.Paused,
Errors = { new Error(), },
BackfillAll = new Stream.Types.BackfillAllStrategy(),
BackfillNone = new Stream.Types.BackfillNoneStrategy(),
};
mockGrpcClient.Setup(x => x.GetStreamAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Stream>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Stream responseCallSettings = await client.GetStreamAsync(request.StreamName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Stream responseCancellationToken = await client.GetStreamAsync(request.StreamName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPrivateConnectionRequestObject()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPrivateConnectionRequest request = new GetPrivateConnectionRequest
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
};
PrivateConnection expectedResponse = new PrivateConnection
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = PrivateConnection.Types.State.Created,
Error = new Error(),
VpcPeeringConfig = new VpcPeeringConfig(),
};
mockGrpcClient.Setup(x => x.GetPrivateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
PrivateConnection response = client.GetPrivateConnection(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPrivateConnectionRequestObjectAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPrivateConnectionRequest request = new GetPrivateConnectionRequest
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
};
PrivateConnection expectedResponse = new PrivateConnection
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = PrivateConnection.Types.State.Created,
Error = new Error(),
VpcPeeringConfig = new VpcPeeringConfig(),
};
mockGrpcClient.Setup(x => x.GetPrivateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PrivateConnection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
PrivateConnection responseCallSettings = await client.GetPrivateConnectionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PrivateConnection responseCancellationToken = await client.GetPrivateConnectionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPrivateConnection()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPrivateConnectionRequest request = new GetPrivateConnectionRequest
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
};
PrivateConnection expectedResponse = new PrivateConnection
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = PrivateConnection.Types.State.Created,
Error = new Error(),
VpcPeeringConfig = new VpcPeeringConfig(),
};
mockGrpcClient.Setup(x => x.GetPrivateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
PrivateConnection response = client.GetPrivateConnection(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPrivateConnectionAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPrivateConnectionRequest request = new GetPrivateConnectionRequest
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
};
PrivateConnection expectedResponse = new PrivateConnection
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = PrivateConnection.Types.State.Created,
Error = new Error(),
VpcPeeringConfig = new VpcPeeringConfig(),
};
mockGrpcClient.Setup(x => x.GetPrivateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PrivateConnection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
PrivateConnection responseCallSettings = await client.GetPrivateConnectionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PrivateConnection responseCancellationToken = await client.GetPrivateConnectionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPrivateConnectionResourceNames()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPrivateConnectionRequest request = new GetPrivateConnectionRequest
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
};
PrivateConnection expectedResponse = new PrivateConnection
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = PrivateConnection.Types.State.Created,
Error = new Error(),
VpcPeeringConfig = new VpcPeeringConfig(),
};
mockGrpcClient.Setup(x => x.GetPrivateConnection(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
PrivateConnection response = client.GetPrivateConnection(request.PrivateConnectionName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPrivateConnectionResourceNamesAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPrivateConnectionRequest request = new GetPrivateConnectionRequest
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
};
PrivateConnection expectedResponse = new PrivateConnection
{
PrivateConnectionName = PrivateConnectionName.FromProjectLocationPrivateConnection("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
State = PrivateConnection.Types.State.Created,
Error = new Error(),
VpcPeeringConfig = new VpcPeeringConfig(),
};
mockGrpcClient.Setup(x => x.GetPrivateConnectionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PrivateConnection>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
PrivateConnection responseCallSettings = await client.GetPrivateConnectionAsync(request.PrivateConnectionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PrivateConnection responseCancellationToken = await client.GetPrivateConnectionAsync(request.PrivateConnectionName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRouteRequestObject()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouteRequest request = new GetRouteRequest
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
};
Route expectedResponse = new Route
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
DestinationAddress = "destination_addressdf5ed78b",
DestinationPort = -91432045,
};
mockGrpcClient.Setup(x => x.GetRoute(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Route response = client.GetRoute(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRouteRequestObjectAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouteRequest request = new GetRouteRequest
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
};
Route expectedResponse = new Route
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
DestinationAddress = "destination_addressdf5ed78b",
DestinationPort = -91432045,
};
mockGrpcClient.Setup(x => x.GetRouteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Route>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Route responseCallSettings = await client.GetRouteAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Route responseCancellationToken = await client.GetRouteAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRoute()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouteRequest request = new GetRouteRequest
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
};
Route expectedResponse = new Route
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
DestinationAddress = "destination_addressdf5ed78b",
DestinationPort = -91432045,
};
mockGrpcClient.Setup(x => x.GetRoute(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Route response = client.GetRoute(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRouteAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouteRequest request = new GetRouteRequest
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
};
Route expectedResponse = new Route
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
DestinationAddress = "destination_addressdf5ed78b",
DestinationPort = -91432045,
};
mockGrpcClient.Setup(x => x.GetRouteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Route>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Route responseCallSettings = await client.GetRouteAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Route responseCancellationToken = await client.GetRouteAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRouteResourceNames()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouteRequest request = new GetRouteRequest
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
};
Route expectedResponse = new Route
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
DestinationAddress = "destination_addressdf5ed78b",
DestinationPort = -91432045,
};
mockGrpcClient.Setup(x => x.GetRoute(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Route response = client.GetRoute(request.RouteName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRouteResourceNamesAsync()
{
moq::Mock<Datastream.DatastreamClient> mockGrpcClient = new moq::Mock<Datastream.DatastreamClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRouteRequest request = new GetRouteRequest
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
};
Route expectedResponse = new Route
{
RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
DisplayName = "display_name137f65c2",
DestinationAddress = "destination_addressdf5ed78b",
DestinationPort = -91432045,
};
mockGrpcClient.Setup(x => x.GetRouteAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Route>(stt::Task.FromResult(expectedResponse), null, null, null, null));
DatastreamClient client = new DatastreamClientImpl(mockGrpcClient.Object, null);
Route responseCallSettings = await client.GetRouteAsync(request.RouteName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Route responseCancellationToken = await client.GetRouteAsync(request.RouteName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
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 Votter.Services.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace UnitTests {
// Why the heck does .NET provide SendKeys but not mouse simulation???
// Another interesting tid-bit. Reading the cursor position doesn't work over
// terminal server!
public class Mouse {
static int Timeout = 100;
private Mouse() { }
public static void MouseDown(Point pt, MouseButtons buttons) {
MouseInput input = new MouseInput();
input.type = (int)InputType.INPUT_MOUSE;
input.dx = pt.X;
input.dy = pt.Y;
input.dwFlags = (int)GetMouseDownFlags(buttons);
input.dwFlags |= (int)MouseFlags.MOUSEEVENTF_ABSOLUTE;
SendInput(input);
}
private static MouseFlags GetMouseDownFlags(MouseButtons buttons) {
MouseFlags flags = 0;
if ((buttons & MouseButtons.Left) != 0) {
flags |= MouseFlags.MOUSEEVENTF_LEFTDOWN;
}
if ((buttons & MouseButtons.Right) != 0) {
flags |= MouseFlags.MOUSEEVENTF_RIGHTDOWN;
}
if ((buttons & MouseButtons.Middle) != 0) {
flags |= MouseFlags.MOUSEEVENTF_MIDDLEDOWN;
}
if ((buttons & MouseButtons.XButton1) != 0) {
flags |= MouseFlags.MOUSEEVENTF_XDOWN;
}
return flags;
}
public static void MouseUp(Point pt, MouseButtons buttons) {
MouseInput input = new MouseInput();
input.type = (int)InputType.INPUT_MOUSE;
input.dx = pt.X;
input.dy = pt.Y;
MouseFlags flags = MouseFlags.MOUSEEVENTF_ABSOLUTE;
if ((buttons & MouseButtons.Left) != 0) {
flags |= MouseFlags.MOUSEEVENTF_LEFTUP;
}
if ((buttons & MouseButtons.Right) != 0) {
flags |= MouseFlags.MOUSEEVENTF_RIGHTUP;
}
if ((buttons & MouseButtons.Middle) != 0) {
flags |= MouseFlags.MOUSEEVENTF_MIDDLEUP;
}
if ((buttons & MouseButtons.XButton1) != 0) {
flags |= MouseFlags.MOUSEEVENTF_XUP;
}
input.dwFlags = (int)flags;
SendInput(input);
}
public static void MouseClick(Point pt, MouseButtons buttons) {
MouseDown(pt, buttons);
MouseUp(pt, buttons);
}
public static void MouseDoubleClick(Point pt, MouseButtons buttons) {
MouseClick(pt, buttons);
MouseClick(pt, buttons);
}
public static void MouseMoveBy(int dx, int dy, MouseButtons buttons) {
MouseInput input = new MouseInput();
input.type = (int)(InputType.INPUT_MOUSE);
input.dx = dx;
input.dy = dy;
input.dwFlags = (int)MouseFlags.MOUSEEVENTF_MOVE;
SendInput(input);
Application.DoEvents();
}
public static void MouseDragDrop(Point start, Point end, int step, MouseButtons buttons) {
int s = Timeout;
Timeout = 10;
MouseDown(start, buttons);
Application.DoEvents();
Thread.Sleep(200);
MouseDragTo(start, end, step, buttons);
Thread.Sleep(200);
MouseUp(end, buttons);
Application.DoEvents();
Thread.Sleep(200);
Timeout = s;
}
public static void MouseMoveTo(Point start, Point end, int step) {
MouseDragTo(start, end, step, MouseButtons.None);
}
public static void MouseDragTo(Point start, Point end, int step, MouseButtons buttons) {
// Interpolate and move mouse smoothly over to given location.
int dx = end.X - start.X;
int dy = end.Y - start.Y;
int length = (int)Math.Sqrt((dx * dx) + (dy * dy));
step = Math.Abs(step);
int s = Timeout;
Timeout = 10;
Application.DoEvents();
int lastx = start.X;
int lasty = start.Y;
Point pos;
for (int i = 0; i < length; i += step) {
int tx = start.X + (dx * i) / length;
int ty = start.Y + (dy * i) / length;
int mx = tx - lastx;
int my = ty - lasty;
if (mx != 0 || my != 0) {
MouseMoveBy(mx, my, buttons);
}
// Now calibrate movement based on current mouse position.
Application.DoEvents();
pos = Control.MousePosition;
lastx = pos.X;
lasty = pos.Y;
}
pos = Control.MousePosition;
dx = pos.X - end.X;
dy = pos.Y - end.Y;
MouseMoveBy(dx, dy, buttons);
Application.DoEvents();
Timeout = s;
}
public static void MouseWheel(int clicks) {
MouseInput input = new MouseInput();
input.type = (int)InputType.INPUT_MOUSE;
input.mouseData = clicks;
MouseFlags flags = MouseFlags.MOUSEEVENTF_WHEEL;
input.dwFlags = (int)flags;
Point c = Cursor.Position;
input.dx = c.X;
input.dy = c.Y;
SendInput(input);
}
static void SendInput(MouseInput input) {
//Trace.WriteLine("SendInput:" + input.dx + "," + input.dy + " cursor is at " + Cursor.Position.X + "," + Cursor.Position.Y);
if ((input.dwFlags & (int)MouseFlags.MOUSEEVENTF_ABSOLUTE) != 0) {
Cursor.Position = new Point(input.dx, input.dy);
}
input.time = Environment.TickCount;
int cb = Marshal.SizeOf(input);
Debug.Assert(cb == 28); // must match what C++ returns for the INPUT union.
IntPtr ptr = Marshal.AllocCoTaskMem(cb);
try {
Marshal.StructureToPtr(input, ptr, false);
uint rc = SendInput(1, ptr, cb);
if (rc != 1) {
int hr = GetLastError();
throw new ApplicationException("SendInput error " + hr);
}
} finally {
Marshal.FreeCoTaskMem(ptr);
}
}
[DllImport("Kernel32.dll")]
static extern int GetLastError();
// Simluate MouseEvents
enum InputType { INPUT_MOUSE = 0, INPUT_KEYBOARD = 1, INPUT_HARDWARE = 2 };
enum MouseFlags {
MOUSEEVENTF_MOVE = 0x0001, /* mouse move */
MOUSEEVENTF_LEFTDOWN = 0x0002, /* left button down */
MOUSEEVENTF_LEFTUP = 0x0004, /* left button up */
MOUSEEVENTF_RIGHTDOWN = 0x0008, /* right button down */
MOUSEEVENTF_RIGHTUP = 0x0010, /* right button up */
MOUSEEVENTF_MIDDLEDOWN = 0x0020, /* middle button down */
MOUSEEVENTF_MIDDLEUP = 0x0040, /* middle button up */
MOUSEEVENTF_XDOWN = 0x0080, /* x button down */
MOUSEEVENTF_XUP = 0x0100, /* x button down */
MOUSEEVENTF_WHEEL = 0x0800, /* wheel button rolled */
MOUSEEVENTF_VIRTUALDESK = 0x4000, /* map to entire virtual desktop */
MOUSEEVENTF_ABSOLUTE = 0x8000, /* absolute move */
}
[StructLayout(LayoutKind.Sequential)]
struct MouseInput {
public int type;
public int dx;
public int dy;
public int mouseData;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
};
[StructLayout(LayoutKind.Sequential)]
struct MouseMovePoint {
public int x;
public int y;
public int time;
public IntPtr dwExtraInfo;
};
[DllImport("User32", EntryPoint = "SendInput")]
static extern uint SendInput(uint nInputs, IntPtr pInputs, int cbSize);
}
}
| |
using System;
using System.Xml;
using System.Xml.XPath;
using System.Collections.Generic;
using System.IO;
using Umbraco.Core;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
namespace umbraco.cms.businesslogic.packager
{
public class data
{
private static XmlDocument _source;
public static XmlDocument Source
{
get
{
return _source;
}
}
public static void Reload(string dataSource)
{
//do some error checking and create the folders/files if they don't exist
if (!File.Exists(dataSource))
{
if (!Directory.Exists(IOHelper.MapPath(Settings.PackagerRoot)))
{
Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagerRoot));
}
if (!Directory.Exists(IOHelper.MapPath(Settings.PackagesStorage)))
{
Directory.CreateDirectory(IOHelper.MapPath(Settings.PackagesStorage));
}
if (!Directory.Exists(IOHelper.MapPath(Settings.InstalledPackagesStorage)))
{
Directory.CreateDirectory(IOHelper.MapPath(Settings.InstalledPackagesStorage));
}
StreamWriter sw = File.CreateText(dataSource);
sw.Write(umbraco.cms.businesslogic.Packager.FileResources.PackageFiles.Packages);
sw.Flush();
sw.Close();
}
if (_source == null)
{
_source = new XmlDocument();
}
//error checking here
if (File.Exists(dataSource))
{
var isEmpty = false;
using (var sr = new StreamReader(dataSource))
{
if (sr.ReadToEnd().IsNullOrWhiteSpace())
{
isEmpty = true;
}
}
if (isEmpty)
{
File.WriteAllText(dataSource, @"<?xml version=""1.0"" encoding=""utf-8""?><packages></packages>");
}
}
_source.Load(dataSource);
}
public static XmlNode GetFromId(int Id, string dataSource, bool reload)
{
if(reload)
Reload(dataSource);
return Source.SelectSingleNode("/packages/package [@id = '" + Id.ToString().ToUpper() + "']");
}
public static XmlNode GetFromGuid(string guid, string dataSource, bool reload) {
if (reload)
Reload(dataSource);
return Source.SelectSingleNode("/packages/package [@packageGuid = '" + guid + "']");
}
public static PackageInstance MakeNew(string Name, string dataSource)
{
PackageInstance retVal = new PackageInstance();
try
{
Reload(dataSource);
int _maxId = 1;
// Find max id
foreach (XmlNode n in Source.SelectNodes("packages/package"))
{
if (int.Parse(n.Attributes.GetNamedItem("id").Value) >= _maxId)
_maxId = int.Parse(n.Attributes.GetNamedItem("id").Value) + 1;
}
XmlElement instance = Source.CreateElement("package");
instance.Attributes.Append(xmlHelper.addAttribute(Source, "id", _maxId.ToString()));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "version", ""));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "url", ""));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "name", Name));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "folder", System.Guid.NewGuid().ToString()));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "packagepath", ""));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "repositoryGuid", ""));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "packageGuid", System.Guid.NewGuid().ToString()));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "hasUpdate", "false"));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "enableSkins", "false"));
instance.Attributes.Append(xmlHelper.addAttribute(Source, "skinRepoGuid", ""));
XmlElement license = Source.CreateElement("license");
license.InnerText = "MIT License";
license.Attributes.Append(xmlHelper.addAttribute(Source, "url", "http://opensource.org/licenses/MIT"));
instance.AppendChild(license);
XmlElement author = Source.CreateElement("author");
author.InnerText = "";
author.Attributes.Append(xmlHelper.addAttribute(Source, "url", ""));
instance.AppendChild(author);
instance.AppendChild(xmlHelper.addTextNode(Source, "readme", ""));
instance.AppendChild(xmlHelper.addTextNode(Source, "actions", ""));
instance.AppendChild(xmlHelper.addTextNode(Source, "datatypes", ""));
XmlElement content = Source.CreateElement("content");
content.InnerText = "";
content.Attributes.Append(xmlHelper.addAttribute(Source, "nodeId", ""));
content.Attributes.Append(xmlHelper.addAttribute(Source, "loadChildNodes", "false"));
instance.AppendChild(content);
instance.AppendChild(xmlHelper.addTextNode(Source, "templates", ""));
instance.AppendChild(xmlHelper.addTextNode(Source, "stylesheets", ""));
instance.AppendChild(xmlHelper.addTextNode(Source, "documenttypes", ""));
instance.AppendChild(xmlHelper.addTextNode(Source, "macros", ""));
instance.AppendChild(xmlHelper.addTextNode(Source, "files", ""));
instance.AppendChild(xmlHelper.addTextNode(Source, "languages", ""));
instance.AppendChild(xmlHelper.addTextNode(Source, "dictionaryitems", ""));
instance.AppendChild(xmlHelper.addTextNode(Source, "loadcontrol", ""));
Source.SelectSingleNode("packages").AppendChild(instance);
Source.Save(dataSource);
retVal = data.Package(_maxId, dataSource);
}
catch (Exception ex)
{
LogHelper.Error<data>("An error occurred", ex);
}
return retVal;
}
public static PackageInstance Package(int id, string datasource) {
return ConvertXmlToPackage( GetFromId(id, datasource, true) );
}
public static PackageInstance Package(string guid, string datasource) {
try
{
XmlNode node = GetFromGuid(guid, datasource, true);
if (node != null)
return ConvertXmlToPackage(node);
else
return new PackageInstance();
}
catch (Exception ex)
{
LogHelper.Error<data>("An error occurred", ex);
return new PackageInstance();
}
}
public static List<PackageInstance> GetAllPackages(string dataSource) {
Reload(dataSource);
XmlNodeList nList = data.Source.SelectNodes("packages/package");
List<PackageInstance> retVal = new List<PackageInstance>();
for (int i = 0; i < nList.Count; i++)
{
try
{
retVal.Add(ConvertXmlToPackage(nList[i]));
}
catch (Exception ex)
{
LogHelper.Error<data>("An error occurred in GetAllPackages", ex);
}
}
return retVal;
}
private static PackageInstance ConvertXmlToPackage(XmlNode n) {
PackageInstance retVal = new PackageInstance();
if (n != null) {
retVal.Id = int.Parse(safeAttribute("id",n));
retVal.Name = safeAttribute("name",n);
retVal.Folder = safeAttribute("folder", n);
retVal.PackagePath = safeAttribute("packagepath", n);
retVal.Version = safeAttribute("version", n);
retVal.Url = safeAttribute("url", n);
retVal.RepositoryGuid = safeAttribute("repositoryGuid", n);
retVal.PackageGuid = safeAttribute("packageGuid", n);
retVal.HasUpdate = bool.Parse(safeAttribute("hasUpdate",n));
bool _enableSkins = false;
bool.TryParse(safeAttribute("enableSkins", n), out _enableSkins);
retVal.EnableSkins = _enableSkins;
retVal.SkinRepoGuid = string.IsNullOrEmpty(safeAttribute("skinRepoGuid", n)) ? Guid.Empty : new Guid(safeAttribute("skinRepoGuid", n));
retVal.License = safeNodeValue(n.SelectSingleNode("license"));
retVal.LicenseUrl = n.SelectSingleNode("license").Attributes.GetNamedItem("url").Value;
retVal.Author = safeNodeValue(n.SelectSingleNode("author"));
retVal.AuthorUrl = safeAttribute("url", n.SelectSingleNode("author"));
retVal.Readme = safeNodeValue(n.SelectSingleNode("readme"));
retVal.Actions = safeNodeInnerXml(n.SelectSingleNode("actions"));
retVal.ContentNodeId = safeAttribute("nodeId", n.SelectSingleNode("content"));
retVal.ContentLoadChildNodes = bool.Parse(safeAttribute("loadChildNodes",n.SelectSingleNode("content")));
retVal.Macros = new List<string>(safeNodeValue(n.SelectSingleNode("macros")).Trim(',').Split(','));
retVal.Macros = new List<string>(safeNodeValue(n.SelectSingleNode("macros")).Trim(',').Split(','));
retVal.Templates = new List<string>(safeNodeValue(n.SelectSingleNode("templates")).Trim(',').Split(','));
retVal.Stylesheets = new List<string>(safeNodeValue(n.SelectSingleNode("stylesheets")).Trim(',').Split(','));
retVal.Documenttypes = new List<string>(safeNodeValue(n.SelectSingleNode("documenttypes")).Trim(',').Split(','));
retVal.Languages = new List<string>(safeNodeValue(n.SelectSingleNode("languages")).Trim(',').Split(','));
retVal.DictionaryItems = new List<string>(safeNodeValue(n.SelectSingleNode("dictionaryitems")).Trim(',').Split(','));
retVal.DataTypes = new List<string>(safeNodeValue(n.SelectSingleNode("datatypes")).Trim(',').Split(','));
XmlNodeList xmlFiles = n.SelectNodes("files/file");
retVal.Files = new List<string>();
for (int i = 0; i < xmlFiles.Count; i++)
retVal.Files.Add(xmlFiles[i].InnerText);
retVal.LoadControl = safeNodeValue(n.SelectSingleNode("loadcontrol"));
}
return retVal;
}
public static void Delete(int Id, string dataSource)
{
Reload(dataSource);
// Remove physical xml file if any
//PackageInstance p = new PackageInstance(Id);
//TODO DELETE PACKAGE FOLDER...
//p.Folder
XmlNode n = data.GetFromId(Id, dataSource, true);
data.Source.SelectSingleNode("/packages").RemoveChild(n);
data.Source.Save(dataSource);
}
public static void UpdateValue(XmlNode n, string Value)
{
if (n.FirstChild != null)
n.FirstChild.Value = Value;
else
{
n.AppendChild(Source.CreateTextNode(Value));
}
//Save();
}
public static void Save(PackageInstance package, string dataSource)
{
try
{
Reload(dataSource);
XmlNode _xmlDef = GetFromId(package.Id, dataSource, false);
_xmlDef.Attributes.GetNamedItem("name").Value = package.Name;
_xmlDef.Attributes.GetNamedItem("version").Value = package.Version;
_xmlDef.Attributes.GetNamedItem("url").Value = package.Url;
_xmlDef.Attributes.GetNamedItem("packagepath").Value = package.PackagePath;
_xmlDef.Attributes.GetNamedItem("repositoryGuid").Value = package.RepositoryGuid;
_xmlDef.Attributes.GetNamedItem("packageGuid").Value = package.PackageGuid;
_xmlDef.Attributes.GetNamedItem("hasUpdate").Value = package.HasUpdate.ToString();
_xmlDef.Attributes.GetNamedItem("enableSkins").Value = package.EnableSkins.ToString();
_xmlDef.Attributes.GetNamedItem("skinRepoGuid").Value = package.SkinRepoGuid.ToString();
_xmlDef.SelectSingleNode("license").FirstChild.Value = package.License;
_xmlDef.SelectSingleNode("license").Attributes.GetNamedItem("url").Value = package.LicenseUrl;
_xmlDef.SelectSingleNode("author").InnerText = package.Author;
_xmlDef.SelectSingleNode("author").Attributes.GetNamedItem("url").Value = package.AuthorUrl;
_xmlDef.SelectSingleNode("readme").InnerXml = "<![CDATA[" + package.Readme + "]]>";
if(_xmlDef.SelectSingleNode("actions") == null)
_xmlDef.AppendChild(xmlHelper.addTextNode(Source, "actions", ""));
_xmlDef.SelectSingleNode("actions").InnerXml = package.Actions;
_xmlDef.SelectSingleNode("content").Attributes.GetNamedItem("nodeId").Value = package.ContentNodeId.ToString();
_xmlDef.SelectSingleNode("content").Attributes.GetNamedItem("loadChildNodes").Value = package.ContentLoadChildNodes.ToString();
_xmlDef.SelectSingleNode("macros").InnerText = joinList(package.Macros, ',');
_xmlDef.SelectSingleNode("templates").InnerText = joinList(package.Templates, ',');
_xmlDef.SelectSingleNode("stylesheets").InnerText = joinList(package.Stylesheets, ',');
_xmlDef.SelectSingleNode("documenttypes").InnerText = joinList(package.Documenttypes, ',');
_xmlDef.SelectSingleNode("languages").InnerText = joinList(package.Languages, ',');
_xmlDef.SelectSingleNode("dictionaryitems").InnerText = joinList(package.DictionaryItems, ',');
_xmlDef.SelectSingleNode("datatypes").InnerText = joinList(package.DataTypes, ',');
_xmlDef.SelectSingleNode("files").InnerXml = "";
foreach (string fileStr in package.Files) {
if(!string.IsNullOrEmpty(fileStr.Trim()))
_xmlDef.SelectSingleNode("files").AppendChild(xmlHelper.addTextNode(data.Source, "file", fileStr));
}
_xmlDef.SelectSingleNode("loadcontrol").InnerText = package.LoadControl;
Source.Save(dataSource);
}
catch(Exception F)
{
LogHelper.Error<data>("An error occurred", F);
}
}
private static string safeAttribute(string name, XmlNode n) {
try {
return n.Attributes.GetNamedItem(name).Value;
} catch {
return "";
}
}
private static string safeNodeValue(XmlNode n) {
try {
return xmlHelper.GetNodeValue(n);
} catch {
return "";
}
}
private static string safeNodeInnerXml(XmlNode n) {
try {
return n.InnerXml;
} catch {
return "";
}
}
private static string joinList(List<string> list, char seperator) {
string retVal = "";
foreach (string str in list) {
retVal += str + seperator.ToString();
}
return retVal.Trim(seperator);
}
public data()
{
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using EnvDTE;
using VSLangProj;
namespace Microsoft.VisualStudioTools.Project.Automation
{
/// <summary>
/// Represents an automation friendly version of a language-specific project.
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProject : VSProject
{
#region fields
private ProjectNode project;
private OAVSProjectEvents events;
#endregion
#region ctors
internal OAVSProject(ProjectNode project)
{
this.project = project;
}
#endregion
#region VSProject Members
public virtual ProjectItem AddWebReference(string bstrUrl)
{
throw new NotImplementedException();
}
public virtual BuildManager BuildManager
{
get
{
throw new NotImplementedException();
//return new OABuildManager(this.project);
}
}
public virtual void CopyProject(string bstrDestFolder, string bstrDestUNCPath, prjCopyProjectOption copyProjectOption, string bstrUsername, string bstrPassword)
{
throw new NotImplementedException();
}
public virtual ProjectItem CreateWebReferencesFolder()
{
throw new NotImplementedException();
}
public virtual DTE DTE
{
get
{
return (EnvDTE.DTE)this.project.Site.GetService(typeof(EnvDTE.DTE));
}
}
public virtual VSProjectEvents Events
{
get
{
if (events == null)
events = new OAVSProjectEvents(this);
return events;
}
}
public virtual void Exec(prjExecCommand command, int bSuppressUI, object varIn, out object pVarOut)
{
throw new NotImplementedException(); ;
}
public virtual void GenerateKeyPairFiles(string strPublicPrivateFile, string strPublicOnlyFile)
{
throw new NotImplementedException(); ;
}
public virtual string GetUniqueFilename(object pDispatch, string bstrRoot, string bstrDesiredExt)
{
throw new NotImplementedException(); ;
}
public virtual Imports Imports
{
get
{
throw new NotImplementedException();
}
}
public virtual EnvDTE.Project Project
{
get
{
return this.project.GetAutomationObject() as EnvDTE.Project;
}
}
public virtual References References
{
get
{
ReferenceContainerNode references = project.GetReferenceContainer() as ReferenceContainerNode;
if (null == references)
{
return new OAReferences(null, project);
}
return references.Object as References;
}
}
public virtual void Refresh()
{
}
public virtual string TemplatePath
{
get
{
throw new NotImplementedException();
}
}
public virtual ProjectItem WebReferencesFolder
{
get
{
throw new NotImplementedException();
}
}
public virtual bool WorkOffline
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
/// <summary>
/// Provides access to language-specific project events
/// </summary>
[ComVisible(true), CLSCompliant(false)]
public class OAVSProjectEvents : VSProjectEvents
{
#region fields
private OAVSProject vsProject;
#endregion
#region ctors
public OAVSProjectEvents(OAVSProject vsProject)
{
this.vsProject = vsProject;
}
#endregion
#region VSProjectEvents Members
public virtual BuildManagerEvents BuildManagerEvents
{
get
{
return vsProject.BuildManager as BuildManagerEvents;
}
}
public virtual ImportsEvents ImportsEvents
{
get
{
throw new NotImplementedException();
}
}
public virtual ReferencesEvents ReferencesEvents
{
get
{
return vsProject.References as ReferencesEvents;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.class01.class01
{
using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.class01.class01;
// <Area> dynamic in unsafe code </Area>
// <Title> unsafe type </Title>
// <Description>
// class
// </Description>
//<Expects Status=success></Expects>
// <Code>
public unsafe class C
{
public static int* p;
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new C();
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.codeblock01.codeblock01
{
using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.codeblock01.codeblock01;
public unsafe class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
unsafe
{
dynamic d = 1;
d = new Test();
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach01.freach01
{
using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach01.freach01;
// <Area> dynamic in unsafe code </Area>
// <Title> unsafe context </Title>
// <Description>
// foreach
// </Description>
//<Expects Status=success></Expects>
// <Code>
public unsafe class C
{
public static int* p;
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
C[] arrayC = new C[]
{
new C(), new C(), new C()}
;
foreach (dynamic d in arrayC) // C is an unsafe type
{
if (d.GetType() != typeof(C))
{
return 1;
}
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach02.freach02
{
using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach02.freach02;
// <Area> dynamic in unsafe code </Area>
// <Title> unsafe context </Title>
// <Description>
// foreach
// </Description>
//<Expects Status=success></Expects>
// <Code>
public unsafe class C
{
public static int* p;
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic arrayC = new C[]
{
new C(), new C(), new C()}
;
foreach (C c in arrayC) // C is an unsafe type
{
if (c.GetType() != typeof(C))
{
return 1;
}
}
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach03.freach03
{
using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach03.freach03;
// <Area> dynamic in unsafe code </Area>
// <Title> unsafe context </Title>
// <Description>
// foreach
// </Description>
//<Expects Status=success></Expects>
// <Code>
// pointer arrays are not supported
//public unsafe class C
//{
//public static int* p;
//}
//[TestClass]public class Test
//{
//[Test][Priority(Priority.Priority2)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod(null));} public unsafe static int MainMethod(string[] args)
//{
//int a = 1, b = 2, c = 3;
//dynamic arrayp = new int*[] { &a, &b, &c };
//try
//{
//foreach (dynamic d in arrayp)
//{
//}
//}
//catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
//{
//if (ErrorVerifier.Verify(ErrorMessageId.UnsafeNeeded, e.Message))
//return 0;
//}
//return 1;
//}
//}
//// </Code>
}
namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.strct01.strct01
{
using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.strct01.strct01;
// <Area> dynamic in unsafe code </Area>
// <Title> unsafe type</Title>
// <Description>
// struct
// </Description>
//<Expects Status=success></Expects>
// <Code>
public unsafe struct S
{
public static int* p;
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new S();
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.while01.while01
{
using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.while01.while01;
// <Area> dynamic in unsafe code </Area>
// <Title> unsafe context </Title>
// <Description>
// foreach
// </Description>
//<Expects Status=success></Expects>
// <Code>
public unsafe class C
{
public static int* p;
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
unsafe
{
int index = 5;
do
{
dynamic d = new C();
int* p = &index;
*p = *p - 1;
}
while (index > 0);
}
return 0;
}
}
// </Code>
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using RVA = System.UInt32;
namespace Mono.Cecil {
public sealed class MethodDefinition : MethodReference, IMemberDefinition, ISecurityDeclarationProvider {
ushort attributes;
ushort impl_attributes;
internal volatile bool sem_attrs_ready;
internal MethodSemanticsAttributes sem_attrs;
Collection<CustomAttribute> custom_attributes;
Collection<SecurityDeclaration> security_declarations;
internal RVA rva;
internal PInvokeInfo pinvoke;
Collection<MethodReference> overrides;
internal MethodBody body;
public MethodAttributes Attributes {
get { return (MethodAttributes) attributes; }
set { attributes = (ushort) value; }
}
public MethodImplAttributes ImplAttributes {
get { return (MethodImplAttributes) impl_attributes; }
set { impl_attributes = (ushort) value; }
}
public MethodSemanticsAttributes SemanticsAttributes {
get {
if (sem_attrs_ready)
return sem_attrs;
if (HasImage) {
ReadSemantics ();
return sem_attrs;
}
sem_attrs = MethodSemanticsAttributes.None;
sem_attrs_ready = true;
return sem_attrs;
}
set { sem_attrs = value; }
}
internal void ReadSemantics ()
{
if (sem_attrs_ready)
return;
var module = this.Module;
if (module == null)
return;
if (!module.HasImage)
return;
module.Read (this, (method, reader) => reader.ReadAllSemantics (method));
}
public bool HasSecurityDeclarations {
get {
if (security_declarations != null)
return security_declarations.Count > 0;
return this.GetHasSecurityDeclarations (Module);
}
}
public Collection<SecurityDeclaration> SecurityDeclarations {
get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); }
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (Module);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); }
}
public int RVA {
get { return (int) rva; }
}
public bool HasBody {
get {
return (attributes & (ushort) MethodAttributes.Abstract) == 0 &&
(attributes & (ushort) MethodAttributes.PInvokeImpl) == 0 &&
(impl_attributes & (ushort) MethodImplAttributes.InternalCall) == 0 &&
(impl_attributes & (ushort) MethodImplAttributes.Native) == 0 &&
(impl_attributes & (ushort) MethodImplAttributes.Unmanaged) == 0 &&
(impl_attributes & (ushort) MethodImplAttributes.Runtime) == 0;
}
}
public MethodBody Body {
get {
MethodBody localBody = this.body;
if (localBody != null)
return localBody;
if (!HasBody)
return null;
if (HasImage && rva != 0)
return Module.Read (ref body, this, (method, reader) => reader.ReadMethodBody (method));
return body = new MethodBody (this);
}
set {
var module = this.Module;
if (module == null) {
body = value;
return;
}
// we reset Body to null in ILSpy to save memory; so we need that operation to be thread-safe
lock (module.SyncRoot) {
body = value;
}
}
}
public bool HasPInvokeInfo {
get {
if (pinvoke != null)
return true;
return IsPInvokeImpl;
}
}
public PInvokeInfo PInvokeInfo {
get {
if (pinvoke != null)
return pinvoke;
if (HasImage && IsPInvokeImpl)
return Module.Read (ref pinvoke, this, (method, reader) => reader.ReadPInvokeInfo (method));
return null;
}
set {
IsPInvokeImpl = true;
pinvoke = value;
}
}
public bool HasOverrides {
get {
if (overrides != null)
return overrides.Count > 0;
return HasImage && Module.Read (this, (method, reader) => reader.HasOverrides (method));
}
}
public Collection<MethodReference> Overrides {
get {
if (overrides != null)
return overrides;
if (HasImage)
return Module.Read (ref overrides, this, (method, reader) => reader.ReadOverrides (method));
return overrides = new Collection<MethodReference> ();
}
}
public override bool HasGenericParameters {
get {
if (generic_parameters != null)
return generic_parameters.Count > 0;
return this.GetHasGenericParameters (Module);
}
}
public override Collection<GenericParameter> GenericParameters {
get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, Module)); }
}
#region MethodAttributes
public bool IsCompilerControlled {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled, value); }
}
public bool IsPrivate {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private, value); }
}
public bool IsFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem, value); }
}
public bool IsAssembly {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly, value); }
}
public bool IsFamily {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family, value); }
}
public bool IsFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public, value); }
}
public bool IsStatic {
get { return attributes.GetAttributes ((ushort) MethodAttributes.Static); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Static, value); }
}
public bool IsFinal {
get { return attributes.GetAttributes ((ushort) MethodAttributes.Final); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Final, value); }
}
public bool IsVirtual {
get { return attributes.GetAttributes ((ushort) MethodAttributes.Virtual); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Virtual, value); }
}
public bool IsHideBySig {
get { return attributes.GetAttributes ((ushort) MethodAttributes.HideBySig); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HideBySig, value); }
}
public bool IsReuseSlot {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot, value); }
}
public bool IsNewSlot {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot, value); }
}
public bool IsCheckAccessOnOverride {
get { return attributes.GetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride, value); }
}
public bool IsAbstract {
get { return attributes.GetAttributes ((ushort) MethodAttributes.Abstract); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Abstract, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((ushort) MethodAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.SpecialName, value); }
}
public bool IsPInvokeImpl {
get { return attributes.GetAttributes ((ushort) MethodAttributes.PInvokeImpl); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.PInvokeImpl, value); }
}
public bool IsUnmanagedExport {
get { return attributes.GetAttributes ((ushort) MethodAttributes.UnmanagedExport); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.UnmanagedExport, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((ushort) MethodAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.RTSpecialName, value); }
}
public bool HasSecurity {
get { return attributes.GetAttributes ((ushort) MethodAttributes.HasSecurity); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HasSecurity, value); }
}
#endregion
#region MethodImplAttributes
public bool IsIL {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL, value); }
}
public bool IsNative {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native, value); }
}
public bool IsRuntime {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime, value); }
}
public bool IsUnmanaged {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged, value); }
}
public bool IsManaged {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed, value); }
}
public bool IsForwardRef {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.ForwardRef); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.ForwardRef, value); }
}
public bool IsPreserveSig {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.PreserveSig); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.PreserveSig, value); }
}
public bool IsInternalCall {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.InternalCall); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.InternalCall, value); }
}
public bool IsSynchronized {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.Synchronized); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.Synchronized, value); }
}
public bool NoInlining {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoInlining); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoInlining, value); }
}
public bool NoOptimization {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoOptimization); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoOptimization, value); }
}
#endregion
#region MethodSemanticsAttributes
public bool IsSetter {
get { return this.GetSemantics (MethodSemanticsAttributes.Setter); }
set { this.SetSemantics (MethodSemanticsAttributes.Setter, value); }
}
public bool IsGetter {
get { return this.GetSemantics (MethodSemanticsAttributes.Getter); }
set { this.SetSemantics (MethodSemanticsAttributes.Getter, value); }
}
public bool IsOther {
get { return this.GetSemantics (MethodSemanticsAttributes.Other); }
set { this.SetSemantics (MethodSemanticsAttributes.Other, value); }
}
public bool IsAddOn {
get { return this.GetSemantics (MethodSemanticsAttributes.AddOn); }
set { this.SetSemantics (MethodSemanticsAttributes.AddOn, value); }
}
public bool IsRemoveOn {
get { return this.GetSemantics (MethodSemanticsAttributes.RemoveOn); }
set { this.SetSemantics (MethodSemanticsAttributes.RemoveOn, value); }
}
public bool IsFire {
get { return this.GetSemantics (MethodSemanticsAttributes.Fire); }
set { this.SetSemantics (MethodSemanticsAttributes.Fire, value); }
}
#endregion
public new TypeDefinition DeclaringType {
get { return (TypeDefinition) base.DeclaringType; }
set { base.DeclaringType = value; }
}
public bool IsConstructor {
get {
return this.IsRuntimeSpecialName
&& this.IsSpecialName
&& (this.Name == ".cctor" || this.Name == ".ctor");
}
}
public override bool IsDefinition {
get { return true; }
}
internal MethodDefinition ()
{
this.token = new MetadataToken (TokenType.Method);
}
public MethodDefinition (string name, MethodAttributes attributes, TypeReference returnType)
: base (name, returnType)
{
this.attributes = (ushort) attributes;
this.HasThis = !this.IsStatic;
this.token = new MetadataToken (TokenType.Method);
}
public override MethodDefinition Resolve ()
{
return this;
}
}
static partial class Mixin {
public static ParameterDefinition GetParameter (this MethodBody self, int index)
{
var method = self.method;
if (method.HasThis) {
if (index == 0)
return self.ThisParameter;
index--;
}
var parameters = method.Parameters;
if (index < 0 || index >= parameters.size)
return null;
return parameters [index];
}
public static VariableDefinition GetVariable (this MethodBody self, int index)
{
var variables = self.Variables;
if (index < 0 || index >= variables.size)
return null;
return variables [index];
}
public static bool GetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics)
{
return (self.SemanticsAttributes & semantics) != 0;
}
public static void SetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics, bool value)
{
if (value)
self.SemanticsAttributes |= semantics;
else
self.SemanticsAttributes &= ~semantics;
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
[StructLayout(LayoutKind.Sequential, Pack = 8, Size = 8)]
struct MyVector64<T> where T : struct { }
[StructLayout(LayoutKind.Sequential, Pack = 16, Size = 16)]
struct MyVector128<T> where T : struct { }
[StructLayout(LayoutKind.Sequential, Pack = 32, Size = 32)]
struct MyVector256<T> where T : struct { }
interface ITestStructure
{
int Size { get; }
int OffsetOfByte { get; }
int OffsetOfValue { get; }
}
struct DefaultLayoutDefaultPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<DefaultLayoutDefaultPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Sequential)]
struct SequentialLayoutDefaultPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<SequentialLayoutDefaultPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct SequentialLayoutMinPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<SequentialLayoutMinPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Sequential, Pack = 128)]
struct SequentialLayoutMaxPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<SequentialLayoutMaxPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Auto)]
struct AutoLayoutDefaultPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<AutoLayoutDefaultPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Auto, Pack = 1)]
struct AutoLayoutMinPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<AutoLayoutMinPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
[StructLayout(LayoutKind.Auto, Pack = 128)]
struct AutoLayoutMaxPacking<T> : ITestStructure
{
public byte _byte;
public T _value;
public int Size => Unsafe.SizeOf<AutoLayoutMaxPacking<T>>();
public int OffsetOfByte => Program.OffsetOf(ref this, ref _byte);
public int OffsetOfValue => Program.OffsetOf(ref this, ref _value);
}
unsafe class Program
{
const int Pass = 100;
const int Fail = 0;
static int Main(string[] args)
{
bool succeeded = true;
// Test fundamental data types
succeeded &= TestBoolean();
succeeded &= TestByte();
succeeded &= TestChar();
succeeded &= TestDouble();
succeeded &= TestInt16();
succeeded &= TestInt32();
succeeded &= TestInt64();
succeeded &= TestIntPtr();
succeeded &= TestSByte();
succeeded &= TestSingle();
succeeded &= TestUInt16();
succeeded &= TestUInt32();
succeeded &= TestUInt64();
succeeded &= TestUIntPtr();
succeeded &= TestVector64();
succeeded &= TestVector128();
succeeded &= TestVector256();
// Test custom data types with explicit size/packing
succeeded &= TestMyVector64();
succeeded &= TestMyVector128();
succeeded &= TestMyVector256();
return succeeded ? Pass : Fail;
}
static bool TestBoolean()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutDefaultPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMinPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMaxPacking<bool>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
return succeeded;
}
static bool TestByte()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutDefaultPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMinPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMaxPacking<byte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
return succeeded;
}
static bool TestChar()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutDefaultPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutMinPacking<char>>(
expectedSize: 3,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<AutoLayoutDefaultPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<char>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestDouble()
{
bool succeeded = true;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (RuntimeInformation.OSArchitecture != Architecture.X86))
{
succeeded &= Test<DefaultLayoutDefaultPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<double>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
}
else
{
// The System V ABI for i386 defines this type as having 4-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<double>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestInt16()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutDefaultPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutMinPacking<short>>(
expectedSize: 3,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<AutoLayoutDefaultPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<short>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestInt32()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<int>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<int>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestInt64()
{
bool succeeded = true;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (RuntimeInformation.OSArchitecture != Architecture.X86))
{
succeeded &= Test<DefaultLayoutDefaultPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<long>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<long>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
}
else
{
// The System V ABI for i386 defines this type as having 4-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<long>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<long>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestIntPtr()
{
bool succeeded = true;
if (Environment.Is64BitProcess)
{
succeeded &= Test<DefaultLayoutDefaultPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<IntPtr>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutDefaultPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<IntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<DefaultLayoutDefaultPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<IntPtr>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<IntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
}
return succeeded;
}
static bool TestSByte()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutDefaultPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMinPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<AutoLayoutMaxPacking<sbyte>>(
expectedSize: 2,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
return succeeded;
}
static bool TestSingle()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<float>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<float>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestUInt16()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutDefaultPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<SequentialLayoutMinPacking<ushort>>(
expectedSize: 3,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 0,
expectedOffsetValue: 2
);
succeeded &= Test<AutoLayoutDefaultPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<ushort>>(
expectedSize: 4,
expectedOffsetByte: 2,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestUInt32()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<uint>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<uint>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
return succeeded;
}
static bool TestUInt64()
{
bool succeeded = true;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (RuntimeInformation.OSArchitecture != Architecture.X86))
{
succeeded &= Test<DefaultLayoutDefaultPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<double>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<double>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
}
else
{
// The System V ABI for i386 defines this type as having 4-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<double>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<double>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestUIntPtr()
{
bool succeeded = true;
if (Environment.Is64BitProcess)
{
succeeded &= Test<DefaultLayoutDefaultPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<UIntPtr>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutDefaultPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<UIntPtr>>(
expectedSize: 16,
expectedOffsetByte: 8,
expectedOffsetValue: 0
);
}
else
{
succeeded &= Test<DefaultLayoutDefaultPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutDefaultPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<SequentialLayoutMinPacking<UIntPtr>>(
expectedSize: 5,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutDefaultPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMinPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
succeeded &= Test<AutoLayoutMaxPacking<UIntPtr>>(
expectedSize: 8,
expectedOffsetByte: 4,
expectedOffsetValue: 0
);
}
return succeeded;
}
static bool TestVector64()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMinPacking<Vector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<Vector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<Vector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<Vector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestVector128()
{
bool succeeded = true;
if (RuntimeInformation.OSArchitecture == Architecture.Arm)
{
// The Procedure Call Standard for ARM defines this type as having 8-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<DefaultLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 32,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 32,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector128<byte>>>(
expectedSize: 32,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
}
succeeded &= Test<SequentialLayoutMinPacking<Vector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<Vector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<Vector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<Vector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestVector256()
{
bool succeeded = true;
if (RuntimeInformation.OSArchitecture == Architecture.Arm)
{
// The Procedure Call Standard for ARM defines this type as having 8-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else if (RuntimeInformation.OSArchitecture == Architecture.Arm64)
{
// The Procedure Call Standard for ARM64 defines this type as having 16-byte alignment
succeeded &= Test<DefaultLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 48,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 48,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 48,
expectedOffsetByte: 0,
expectedOffsetValue: 16
);
}
else
{
succeeded &= Test<DefaultLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 64,
expectedOffsetByte: 0,
expectedOffsetValue: 32
);
succeeded &= Test<SequentialLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 64,
expectedOffsetByte: 0,
expectedOffsetValue: 32
);
succeeded &= Test<SequentialLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 64,
expectedOffsetByte: 0,
expectedOffsetValue: 32
);
}
succeeded &= Test<SequentialLayoutMinPacking<Vector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<Vector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<Vector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<Vector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestMyVector64()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<MyVector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<MyVector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<MyVector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<MyVector64<byte>>>(
expectedSize: 9,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<MyVector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector64<byte>>>(
expectedSize: 16,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<MyVector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector64<byte>>>(
expectedSize: 12,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestMyVector128()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<MyVector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<MyVector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<MyVector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<MyVector128<byte>>>(
expectedSize: 17,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<MyVector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector128<byte>>>(
expectedSize: 24,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<MyVector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector128<byte>>>(
expectedSize: 20,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool TestMyVector256()
{
bool succeeded = true;
succeeded &= Test<DefaultLayoutDefaultPacking<MyVector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutDefaultPacking<MyVector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMinPacking<MyVector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
succeeded &= Test<SequentialLayoutMaxPacking<MyVector256<byte>>>(
expectedSize: 33,
expectedOffsetByte: 0,
expectedOffsetValue: 1
);
if (Environment.Is64BitProcess)
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMinPacking<MyVector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector256<byte>>>(
expectedSize: 40,
expectedOffsetByte: 0,
expectedOffsetValue: 8
);
}
else
{
succeeded &= Test<AutoLayoutDefaultPacking<MyVector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMinPacking<MyVector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
succeeded &= Test<AutoLayoutMaxPacking<MyVector256<byte>>>(
expectedSize: 36,
expectedOffsetByte: 0,
expectedOffsetValue: 4
);
}
return succeeded;
}
static bool Test<T>(int expectedSize, int expectedOffsetByte, int expectedOffsetValue) where T : ITestStructure
{
bool succeeded = true;
var testStructure = default(T);
int size = testStructure.Size;
if (size != expectedSize)
{
Console.WriteLine($"Unexpected Size for {testStructure.GetType()}.");
Console.WriteLine($" Expected: {expectedSize}; Actual: {size}");
succeeded = false;
}
int offsetByte = testStructure.OffsetOfByte;
if (offsetByte != expectedOffsetByte)
{
Console.WriteLine($"Unexpected Offset for {testStructure.GetType()}.Byte.");
Console.WriteLine($" Expected: {expectedOffsetByte}; Actual: {offsetByte}");
succeeded = false;
}
int offsetValue = testStructure.OffsetOfValue;
if (offsetValue != expectedOffsetValue)
{
Console.WriteLine($"Unexpected Offset for {testStructure.GetType()}.Value.");
Console.WriteLine($" Expected: {expectedOffsetValue}; Actual: {offsetValue}");
succeeded = false;
}
if (!succeeded)
{
Console.WriteLine();
}
return succeeded;
}
internal static int OffsetOf<T, U>(ref T origin, ref U target)
{
return Unsafe.ByteOffset(ref origin, ref Unsafe.As<U, T>(ref target)).ToInt32();
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
namespace Adxstudio.Xrm.Search.Store.Encryption
{
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Text;
/// <summary>
/// The fs buffered reader writer.
/// </summary>
public class FsBufferedReaderWriter : BufferedPageReaderWriter
{
/// <summary>
/// File header marker for file validation and in case of futher file structure changes
/// </summary>
private readonly byte[] headerMarker = Encoding.ASCII.GetBytes("ADX");
/// <summary>
/// The file.
/// </summary>
protected readonly FileInfo File;
/// <summary>
/// The file stream.
/// </summary>
private readonly Stream fileStream;
/// <summary>
/// Is read only mode for file
/// </summary>
private readonly bool readOnly;
/// <summary>
/// Key header size
/// </summary>
private long lengthOffset;
/// <summary>
/// Data offset
/// </summary>
private long dataOffset;
/// <summary>
/// The commited file size.
/// </summary>
private long commitedFileSize;
/// <summary>
/// The certificate
/// </summary>
private X509Certificate2 certificate;
/// <summary>
/// Cloned instance indicator
/// </summary>
internal bool IsClone;
/// <summary>
/// Initializes a new instance of the <see cref="FsBufferedReaderWriter"/> class.
/// </summary>
/// <param name="file">
/// The file.
/// </param>
/// <param name="certificate">
/// The certificate.
/// </param>
/// <param name="readOnly">
/// Ts read only
/// </param>
public FsBufferedReaderWriter(FileInfo file, X509Certificate2 certificate, bool readOnly)
{
this.File = file;
this.fileStream = this.File.Open(this.readOnly ? FileMode.Open : FileMode.OpenOrCreate, this.readOnly ? FileAccess.Read : FileAccess.ReadWrite, FileShare.ReadWrite);
this.certificate = certificate;
this.readOnly = readOnly;
if (this.fileStream.Length <= this.dataOffset && !this.readOnly)
{
this.WriteHeader();
}
else
{
this.ReadHeader();
}
this.Initialize();
}
/// <summary>
/// Gets the length.
/// </summary>
public override long Length
{
get
{
return this.ReadLength();
}
}
/// <summary>
/// Gets or sets the page size.
/// </summary>
public override int PageSize
{
get
{
return EncryptedDirectory.PageSize;
}
}
/// <summary>
/// The dispose.
/// </summary>
public override void Dispose()
{
base.Dispose();
if (!this.IsClone && this.fileStream != null)
{
this.fileStream.Dispose();
}
}
/// <summary>
/// Clones instance
/// </summary>
/// <returns>copy of instance</returns>
public override object Clone()
{
// Lucene does input reader clone. So we need to handle it properly
var copy = (FsBufferedReaderWriter)MemberwiseClone();
copy.IsClone = true;
copy.pageBuffer = new byte[this.PageSize];
Array.Copy(this.pageBuffer, copy.pageBuffer, this.PageSize);
return copy;
}
/// <summary>
/// The read page.
/// </summary>
/// <param name="pageNumber">
/// The page number.
/// </param>
/// <param name="destination">
/// The destination.
/// </param>
public override void ReadPage(long pageNumber, byte[] destination)
{
this.fileStream.Seek(this.dataOffset + (pageNumber * (this.PageSize + 500)), SeekOrigin.Begin);
var readInt = this.ReadInt();
var encrypted = new byte[readInt];
this.fileStream.Read(encrypted, 0, readInt);
this.DecryptData(encrypted, destination);
}
/// <summary>
/// The write page.
/// </summary>
/// <param name="pageNumber">
/// The page number.
/// </param>
/// <param name="source">
/// The source.
/// </param>
public override void WritePage(long pageNumber, byte[] source)
{
var encrypted = this.EncryptData(source);
this.fileStream.Seek(this.dataOffset + (pageNumber * (this.PageSize + 500)), SeekOrigin.Begin);
this.WriteInt(encrypted.Length);
this.fileStream.Write(encrypted, 0, encrypted.Length);
// We need to track actual data size as our file has some overheap and also data could be padded to block size
if (this.fileSize > this.Length)
{
this.WriteLength(this.fileSize);
}
}
/// <summary>
/// The decript data.
/// </summary>
/// <param name="source">
/// The source.
/// </param>
/// <param name="destination">
/// The destination.
/// </param>
protected void DecryptData(byte[] source, byte[] destination)
{
var envelopedCms = new EnvelopedCms();
envelopedCms.Decode(source);
envelopedCms.Decrypt(new X509Certificate2Collection(this.certificate));
Buffer.BlockCopy(envelopedCms.ContentInfo.Content, 0, destination, 0, envelopedCms.ContentInfo.Content.Length);
}
/// <summary>
/// Encrypts the data.
/// </summary>
/// <param name="source">The source.</param>
/// <returns>encrypted data</returns>
protected byte[] EncryptData(byte[] source)
{
var contentInfo = new ContentInfo(source);
var envelopedCms = new EnvelopedCms(contentInfo);
envelopedCms.Encrypt(new CmsRecipient(this.certificate));
return envelopedCms.Encode();
}
/// <summary>
/// Writes encryption token to file
/// </summary>
protected void WriteHeader()
{
var fs = this.fileStream;
// Write header marker
fs.Seek(0, SeekOrigin.Begin);
fs.Write(this.headerMarker, 0, this.headerMarker.Length);
// Write version
fs.WriteByte(1);
this.lengthOffset = fs.Position;
this.dataOffset = this.lengthOffset + sizeof(long);
}
/// <summary>
/// Reads encryption tokens from file
/// </summary>
protected void ReadHeader()
{
try
{
var fs = this.fileStream;
// Check header
byte[] fileMarker = new byte[this.headerMarker.Length];
fs.Seek(0, SeekOrigin.Begin);
fs.Read(fileMarker, 0, fileMarker.Length);
if (!fileMarker.SequenceEqual(this.headerMarker))
{
throw new InvalidOperationException(
string.Format("File {0} does not looks like search index",
this.File.FullName));
}
// Read version
var version = fs.ReadByte(); // Not in use right now. Just in case for required next changes
this.lengthOffset = fs.Position;
this.dataOffset = this.lengthOffset + sizeof(long);
}
catch (Exception e)
{
throw new InvalidOperationException("Not able to read keys from file", e);
}
}
/// <summary>
/// The read length.
/// </summary>
/// <returns>
/// The <see cref="long"/>.
/// </returns>
protected long ReadLength()
{
if (this.commitedFileSize > 0)
{
return this.commitedFileSize;
}
try
{
var raw = new byte[sizeof(long)];
this.fileStream.Seek(this.lengthOffset, SeekOrigin.Begin);
this.fileStream.Read(raw, 0, raw.Length);
var value = BitConverter.ToInt64(raw, 0);
return value;
}
catch (IOException)
{
return 0;
}
}
/// <summary>
/// The write length.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
protected void WriteLength(long value)
{
var raw = BitConverter.GetBytes(this.fileSize);
this.fileStream.Seek(this.lengthOffset, SeekOrigin.Begin);
this.fileStream.Write(raw, 0, raw.Length);
this.commitedFileSize = this.fileSize;
}
/// <summary>
/// Writes integer value to stream
/// </summary>
/// <param name="value">int value</param>
protected void WriteInt(int value)
{
var raw = BitConverter.GetBytes(value);
this.fileStream.Write(raw, 0, raw.Length);
}
/// <summary>
/// Reads integer value from stream
/// </summary>
/// <returns>int value</returns>
protected int ReadInt()
{
var raw = new byte[sizeof(int)];
this.fileStream.Read(raw, 0, raw.Length);
var value = BitConverter.ToInt32(raw, 0);
return value;
}
}
}
| |
using System;
using Android.Animation;
using Android.Content;
using Android.Content.Res;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Views.Animations;
using Android.Widget;
using Java.Interop;
namespace RecordGuard.ListSample.Android.Extensions.CustomViews
{
[Register("com.recordguard.PlayPauseView")]
public class PlayPauseView : FrameLayout {
private static readonly long PlayPauseAnimationDuration = 200;
private PlayPauseDrawable mDrawable;
private Paint mPaint = new Paint();
private int mPauseBackgroundColor;
private int mPlayBackgroundColor;
private AnimatorSet mAnimatorSet;
private int mBackgroundColor;
private int mWidth;
private int mHeight;
protected PlayPauseView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public PlayPauseView(Context context) : base(context) {
mPlayBackgroundColor = Color.Blue;
mPauseBackgroundColor = Color.Cyan;
Color fillColor = Color.White;
mDrawable = new PlayPauseDrawable(fillColor);
init(context);
}
public PlayPauseView(Context context, IAttributeSet attrs) : base(context, attrs) {
TypedArray a = context.Theme.ObtainStyledAttributes(
attrs,
Resource.Styleable.PlayPauseView,
0, 0);
int fillColor;
try {
mPlayBackgroundColor = a.GetColor(Resource.Styleable.PlayPauseView_play_bg, Color.Blue);
mPauseBackgroundColor = a.GetColor(Resource.Styleable.PlayPauseView_pause_bg, Color.Cyan);
fillColor = a.GetColor(Resource.Styleable.PlayPauseView_fill_color, Color.White);
} finally {
a.Recycle();
}
mDrawable = new PlayPauseDrawable(new Color(fillColor));
init(context);
}
private void init(Context context) {
SetWillNotDraw(false);
mPaint.AntiAlias = true;
mPaint.SetStyle(Paint.Style.Fill);
mDrawable.SetCallback(this);
mBackgroundColor = mPlayBackgroundColor;
}
protected override IParcelable OnSaveInstanceState() {
var superState = base.OnSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.IsPlay = mDrawable.IsPlay();
return ss;
}
protected override void OnRestoreInstanceState(IParcelable state) {
SavedState ss = (SavedState) state;
base.OnRestoreInstanceState(ss.SuperState);
InitStatus(ss.IsPlay);
Invalidate();
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = View.MeasureSpec.GetSize(widthMeasureSpec);
int height = View.MeasureSpec.GetSize(heightMeasureSpec);
int size = Math.Min(width, height);
SetMeasuredDimension(
View.MeasureSpec.MakeMeasureSpec(size, MeasureSpecMode.Exactly),
View.MeasureSpec.MakeMeasureSpec(size, MeasureSpecMode.Exactly)
);
}
protected override void OnSizeChanged(int w, int h, int oldw, int oldh) {
base.OnSizeChanged(w, h, oldw, oldh);
mDrawable.SetBounds(0, 0, w, h);
mWidth = w;
mHeight = h;
if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
OutlineProvider = new ActionOutlineProvider((v, outline) =>
{
outline.SetOval(0, 0, v.Width, v.Height);
});
ClipToOutline = (true);
}
}
[Export("setColor")]
public void SetColor(int color) {
mBackgroundColor = color;
Invalidate();
}
[Export("getColor")]
public int GetColor() {
return mBackgroundColor;
}
protected override bool VerifyDrawable(Drawable who) {
return who == mDrawable || base.VerifyDrawable(who);
}
protected override void OnDraw(Canvas canvas) {
base.OnDraw(canvas);
mPaint.Color = new Color(mBackgroundColor);
mPaint.AntiAlias = true;
float radius = Math.Min(mWidth, mHeight) / 2f;
canvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
canvas.DrawCircle(mWidth / 2f, mHeight / 2f, radius, mPaint);
mDrawable.Draw(canvas);
}
/**
* Toogle the play/pause status
*/
public void Toggle() {
Toggle(true);
}
/**
* Change status to play or pause
*
* @param isPlay for playing, false else
*/
public void Change(bool isPlay) {
Change(isPlay, true);
}
/**
* Change status to play or pause
*
* @param isPlay for playing, false else
* @param withAnim false to change status without animation
*/
public void Change(bool isPlay, bool withAnim) {
if (mDrawable.IsPlay() == isPlay)
return;
Toggle(withAnim);
}
/**
* Toogle the play/pause status
*
* @param withAnim false to change status without animation
*/
public void Toggle(bool withAnim) {
if (withAnim) {
if (mAnimatorSet != null) {
mAnimatorSet.Cancel();
}
mAnimatorSet = new AnimatorSet();
bool isPlay = mDrawable.IsPlay();
ObjectAnimator colorAnim = ObjectAnimator.OfInt(this, "color", isPlay ? mPauseBackgroundColor : mPlayBackgroundColor);
colorAnim.SetEvaluator(new ArgbEvaluator());
Animator pausePlayAnim = mDrawable.GetPausePlayAnimator();
mAnimatorSet.SetInterpolator(new DecelerateInterpolator());
mAnimatorSet.SetDuration(PlayPauseAnimationDuration);
mAnimatorSet.PlayTogether(colorAnim, pausePlayAnim);
mAnimatorSet.Start();
} else {
bool isPlay = mDrawable.IsPlay();
InitStatus(!isPlay);
Invalidate();
}
}
private void InitStatus(bool isPlay) {
if (isPlay) {
mDrawable.SetPlay();
SetColor(mPlayBackgroundColor);
} else {
mDrawable.SetPause();
SetColor(mPauseBackgroundColor);
}
}
public bool IsPlay() {
return mDrawable.IsPlay();
}
public bool IsPlaying
{
get => mDrawable.IsPlay();
set
{
if (!IsPlaying != value)
Toggle();
}
}
private class SavedState : BaseSavedState {
public bool IsPlay { get; set; }
public SavedState(IParcelable superState) : base(superState) {
}
public SavedState(Parcel @in) : base(@in) {
IsPlay = @in.ReadByte() > 0;
}
public override void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
{
base.WriteToParcel(dest, flags);
dest.WriteByte(IsPlay ? (sbyte) 1 : (sbyte) 0);
}
}
private class ActionOutlineProvider : ViewOutlineProvider
{
private readonly Action<View, Outline> _outlineProviderAction;
public ActionOutlineProvider(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public ActionOutlineProvider(Action<View, Outline> outlineProviderAction)
{
_outlineProviderAction = outlineProviderAction;
}
public override void GetOutline(View view, Outline outline)
{
_outlineProviderAction(view, outline);
}
}
}
}
| |
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 MusicStore.Services.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
namespace System.Net.Http.Headers
{
public class ContentDispositionHeaderValue : ICloneable
{
#region Fields
private const string fileName = "filename";
private const string name = "name";
private const string fileNameStar = "filename*";
private const string creationDate = "creation-date";
private const string modificationDate = "modification-date";
private const string readDate = "read-date";
private const string size = "size";
// Use ObjectCollection<T> since we may have multiple parameters with the same name.
private ObjectCollection<NameValueHeaderValue> _parameters;
private string _dispositionType;
#endregion Fields
#region Properties
public string DispositionType
{
get { return _dispositionType; }
set
{
CheckDispositionTypeFormat(value, nameof(value));
_dispositionType = value;
}
}
public ICollection<NameValueHeaderValue> Parameters
{
get
{
if (_parameters == null)
{
_parameters = new ObjectCollection<NameValueHeaderValue>();
}
return _parameters;
}
}
public string Name
{
get { return GetName(name); }
set { SetName(name, value); }
}
public string FileName
{
get { return GetName(fileName); }
set { SetName(fileName, value); }
}
public string FileNameStar
{
get { return GetName(fileNameStar); }
set { SetName(fileNameStar, value); }
}
public DateTimeOffset? CreationDate
{
get { return GetDate(creationDate); }
set { SetDate(creationDate, value); }
}
public DateTimeOffset? ModificationDate
{
get { return GetDate(modificationDate); }
set { SetDate(modificationDate, value); }
}
public DateTimeOffset? ReadDate
{
get { return GetDate(readDate); }
set { SetDate(readDate, value); }
}
public long? Size
{
get
{
NameValueHeaderValue sizeParameter = NameValueHeaderValue.Find(_parameters, size);
ulong value;
if (sizeParameter != null)
{
string sizeString = sizeParameter.Value;
if (ulong.TryParse(sizeString, NumberStyles.Integer, CultureInfo.InvariantCulture, out value))
{
return (long)value;
}
}
return null;
}
set
{
NameValueHeaderValue sizeParameter = NameValueHeaderValue.Find(_parameters, size);
if (value == null)
{
// Remove parameter.
if (sizeParameter != null)
{
_parameters.Remove(sizeParameter);
}
}
else if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
else if (sizeParameter != null)
{
sizeParameter.Value = value.Value.ToString(CultureInfo.InvariantCulture);
}
else
{
string sizeString = value.Value.ToString(CultureInfo.InvariantCulture);
Parameters.Add(new NameValueHeaderValue(size, sizeString));
}
}
}
#endregion Properties
#region Constructors
internal ContentDispositionHeaderValue()
{
// Used by the parser to create a new instance of this type.
}
protected ContentDispositionHeaderValue(ContentDispositionHeaderValue source)
{
Debug.Assert(source != null);
_dispositionType = source._dispositionType;
if (source._parameters != null)
{
foreach (var parameter in source._parameters)
{
this.Parameters.Add((NameValueHeaderValue)((ICloneable)parameter).Clone());
}
}
}
public ContentDispositionHeaderValue(string dispositionType)
{
CheckDispositionTypeFormat(dispositionType, nameof(dispositionType));
_dispositionType = dispositionType;
}
#endregion Constructors
#region Overloads
public override string ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
sb.Append(_dispositionType);
NameValueHeaderValue.ToString(_parameters, ';', true, sb);
return StringBuilderCache.GetStringAndRelease(sb);
}
public override bool Equals(object obj)
{
ContentDispositionHeaderValue other = obj as ContentDispositionHeaderValue;
if (other == null)
{
return false;
}
return string.Equals(_dispositionType, other._dispositionType, StringComparison.OrdinalIgnoreCase) &&
HeaderUtilities.AreEqualCollections(_parameters, other._parameters);
}
public override int GetHashCode()
{
// The dispositionType string is case-insensitive.
return StringComparer.OrdinalIgnoreCase.GetHashCode(_dispositionType) ^ NameValueHeaderValue.GetHashCode(_parameters);
}
// Implement ICloneable explicitly to allow derived types to "override" the implementation.
object ICloneable.Clone()
{
return new ContentDispositionHeaderValue(this);
}
#endregion Overloads
#region Parsing
public static ContentDispositionHeaderValue Parse(string input)
{
int index = 0;
return (ContentDispositionHeaderValue)GenericHeaderParser.ContentDispositionParser.ParseValue(input,
null, ref index);
}
public static bool TryParse(string input, out ContentDispositionHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.ContentDispositionParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (ContentDispositionHeaderValue)output;
return true;
}
return false;
}
internal static int GetDispositionTypeLength(string input, int startIndex, out object parsedValue)
{
Debug.Assert(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Caller must remove leading whitespace. If not, we'll return 0.
string dispositionType = null;
int dispositionTypeLength = GetDispositionTypeExpressionLength(input, startIndex, out dispositionType);
if (dispositionTypeLength == 0)
{
return 0;
}
int current = startIndex + dispositionTypeLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
ContentDispositionHeaderValue contentDispositionHeader = new ContentDispositionHeaderValue();
contentDispositionHeader._dispositionType = dispositionType;
// If we're not done and we have a parameter delimiter, then we have a list of parameters.
if ((current < input.Length) && (input[current] == ';'))
{
current++; // Skip delimiter.
int parameterLength = NameValueHeaderValue.GetNameValueListLength(input, current, ';',
(ObjectCollection<NameValueHeaderValue>)contentDispositionHeader.Parameters);
if (parameterLength == 0)
{
return 0;
}
parsedValue = contentDispositionHeader;
return current + parameterLength - startIndex;
}
// We have a ContentDisposition header without parameters.
parsedValue = contentDispositionHeader;
return current - startIndex;
}
private static int GetDispositionTypeExpressionLength(string input, int startIndex, out string dispositionType)
{
Debug.Assert((input != null) && (input.Length > 0) && (startIndex < input.Length));
// This method just parses the disposition type string, it does not parse parameters.
dispositionType = null;
// Parse the disposition type, i.e. <dispositiontype> in content-disposition string
// "<dispositiontype>; param1=value1; param2=value2".
int typeLength = HttpRuleParser.GetTokenLength(input, startIndex);
if (typeLength == 0)
{
return 0;
}
dispositionType = input.Substring(startIndex, typeLength);
return typeLength;
}
private static void CheckDispositionTypeFormat(string dispositionType, string parameterName)
{
if (string.IsNullOrEmpty(dispositionType))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
// When adding values using strongly typed objects, no leading/trailing LWS (whitespace) are allowed.
string tempDispositionType;
int dispositionTypeLength = GetDispositionTypeExpressionLength(dispositionType, 0, out tempDispositionType);
if ((dispositionTypeLength == 0) || (tempDispositionType.Length != dispositionType.Length))
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, dispositionType));
}
}
#endregion Parsing
#region Helpers
// Gets a parameter of the given name and attempts to extract a date.
// Returns null if the parameter is not present or the format is incorrect.
private DateTimeOffset? GetDate(string parameter)
{
NameValueHeaderValue dateParameter = NameValueHeaderValue.Find(_parameters, parameter);
DateTimeOffset date;
if (dateParameter != null)
{
string dateString = dateParameter.Value;
// Should have quotes, remove them.
if (IsQuoted(dateString))
{
dateString = dateString.Substring(1, dateString.Length - 2);
}
if (HttpDateParser.TryStringToDate(dateString, out date))
{
return date;
}
}
return null;
}
// Add the given parameter to the list. Remove if date is null.
private void SetDate(string parameter, DateTimeOffset? date)
{
NameValueHeaderValue dateParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (date == null)
{
// Remove parameter.
if (dateParameter != null)
{
_parameters.Remove(dateParameter);
}
}
else
{
// Must always be quoted.
string dateString = "\"" + HttpDateParser.DateToString(date.Value) + "\"";
if (dateParameter != null)
{
dateParameter.Value = dateString;
}
else
{
Parameters.Add(new NameValueHeaderValue(parameter, dateString));
}
}
}
// Gets a parameter of the given name and attempts to decode it if necessary.
// Returns null if the parameter is not present or the raw value if the encoding is incorrect.
private string GetName(string parameter)
{
NameValueHeaderValue nameParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (nameParameter != null)
{
string result;
// filename*=utf-8'lang'%7FMyString
if (parameter.EndsWith("*", StringComparison.Ordinal))
{
if (TryDecode5987(nameParameter.Value, out result))
{
return result;
}
return null; // Unrecognized encoding.
}
// filename="=?utf-8?B?BDFSDFasdfasdc==?="
if (TryDecodeMime(nameParameter.Value, out result))
{
return result;
}
// May not have been encoded.
return nameParameter.Value;
}
return null;
}
// Add/update the given parameter in the list, encoding if necessary.
// Remove if value is null/Empty
private void SetName(string parameter, string value)
{
NameValueHeaderValue nameParameter = NameValueHeaderValue.Find(_parameters, parameter);
if (string.IsNullOrEmpty(value))
{
// Remove parameter.
if (nameParameter != null)
{
_parameters.Remove(nameParameter);
}
}
else
{
string processedValue = string.Empty;
if (parameter.EndsWith("*", StringComparison.Ordinal))
{
processedValue = HeaderUtilities.Encode5987(value);
}
else
{
processedValue = EncodeAndQuoteMime(value);
}
if (nameParameter != null)
{
nameParameter.Value = processedValue;
}
else
{
Parameters.Add(new NameValueHeaderValue(parameter, processedValue));
}
}
}
// Returns input for decoding failures, as the content might not be encoded.
private string EncodeAndQuoteMime(string input)
{
string result = input;
bool needsQuotes = false;
// Remove bounding quotes, they'll get re-added later.
if (IsQuoted(result))
{
result = result.Substring(1, result.Length - 2);
needsQuotes = true;
}
if (result.IndexOf("\"", 0, StringComparison.Ordinal) >= 0) // Only bounding quotes are allowed.
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, input));
}
else if (RequiresEncoding(result))
{
needsQuotes = true; // Encoded data must always be quoted, the equals signs are invalid in tokens.
result = EncodeMime(result); // =?utf-8?B?asdfasdfaesdf?=
}
else if (!needsQuotes && HttpRuleParser.GetTokenLength(result, 0) != result.Length)
{
needsQuotes = true;
}
if (needsQuotes)
{
// Re-add quotes "value".
result = "\"" + result + "\"";
}
return result;
}
// Returns true if the value starts and ends with a quote.
private bool IsQuoted(string value)
{
Debug.Assert(value != null);
return value.Length > 1 && value.StartsWith("\"", StringComparison.Ordinal)
&& value.EndsWith("\"", StringComparison.Ordinal);
}
// tspecials are required to be in a quoted string. Only non-ascii needs to be encoded.
private bool RequiresEncoding(string input)
{
Debug.Assert(input != null);
foreach (char c in input)
{
if ((int)c > 0x7f)
{
return true;
}
}
return false;
}
// Encode using MIME encoding.
private string EncodeMime(string input)
{
byte[] buffer = Encoding.UTF8.GetBytes(input);
string encodedName = Convert.ToBase64String(buffer);
return "=?utf-8?B?" + encodedName + "?=";
}
// Attempt to decode MIME encoded strings.
private bool TryDecodeMime(string input, out string output)
{
Debug.Assert(input != null);
output = null;
string processedInput = input;
// Require quotes, min of "=?e?b??="
if (!IsQuoted(processedInput) || processedInput.Length < 10)
{
return false;
}
string[] parts = processedInput.Split('?');
// "=, encodingName, encodingType, encodedData, ="
if (parts.Length != 5 || parts[0] != "\"=" || parts[4] != "=\"" || parts[2].ToLowerInvariant() != "b")
{
// Not encoded.
// This does not support multi-line encoding.
// Only base64 encoding is supported, not quoted printable.
return false;
}
try
{
Encoding encoding = Encoding.GetEncoding(parts[1]);
byte[] bytes = Convert.FromBase64String(parts[3]);
output = encoding.GetString(bytes, 0, bytes.Length);
return true;
}
catch (ArgumentException)
{
// Unknown encoding or bad characters.
}
catch (FormatException)
{
// Bad base64 decoding.
}
return false;
}
// Attempt to decode using RFC 5987 encoding.
// encoding'language'my%20string
private bool TryDecode5987(string input, out string output)
{
output = null;
int quoteIndex = input.IndexOf('\'');
if (quoteIndex == -1)
{
return false;
}
int lastQuoteIndex = input.LastIndexOf('\'');
if (quoteIndex == lastQuoteIndex || input.IndexOf('\'', quoteIndex + 1) != lastQuoteIndex)
{
return false;
}
string encodingString = input.Substring(0, quoteIndex);
string dataString = input.Substring(lastQuoteIndex + 1, input.Length - (lastQuoteIndex + 1));
StringBuilder decoded = new StringBuilder();
try
{
Encoding encoding = Encoding.GetEncoding(encodingString);
byte[] unescapedBytes = new byte[dataString.Length];
int unescapedBytesCount = 0;
for (int index = 0; index < dataString.Length; index++)
{
if (Uri.IsHexEncoding(dataString, index)) // %FF
{
// Unescape and cache bytes, multi-byte characters must be decoded all at once.
unescapedBytes[unescapedBytesCount++] = (byte)Uri.HexUnescape(dataString, ref index);
index--; // HexUnescape did +=3; Offset the for loop's ++
}
else
{
if (unescapedBytesCount > 0)
{
// Decode any previously cached bytes.
decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount));
unescapedBytesCount = 0;
}
decoded.Append(dataString[index]); // Normal safe character.
}
}
if (unescapedBytesCount > 0)
{
// Decode any previously cached bytes.
decoded.Append(encoding.GetString(unescapedBytes, 0, unescapedBytesCount));
}
}
catch (ArgumentException)
{
return false; // Unknown encoding or bad characters.
}
output = decoded.ToString();
return true;
}
#endregion Helpers
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Catnap.Database;
namespace Catnap.Citeria
{
public class CriteriaPredicateBuilder<T> where T : class, new()
{
private readonly ISession session;
private readonly Expression<Func<T, bool>> predicate;
private readonly StringBuilder sql = new StringBuilder();
private readonly List<Parameter> parameters = new List<Parameter>();
private int parameterNumber;
public CriteriaPredicateBuilder(ISession session, Expression<Func<T, bool>> predicate, int startingParamterNumber)
{
this.session = session;
this.predicate = predicate;
parameterNumber = startingParamterNumber;
}
public IDbCommandSpec Build(out int lastParameterNumber)
{
Visit(predicate, false);
lastParameterNumber = parameterNumber;
return new DbCommandSpec()
.AddParameters(parameters)
.SetCommandText(sql.ToString());
}
private void Visit(Expression expression, bool isOnRightSide)
{
if (expression is LambdaExpression)
{
Visit(((LambdaExpression)expression).Body, false);
}
else if (expression is BinaryExpression)
{
Visit((BinaryExpression)expression);
}
else if (expression is MemberExpression)
{
VisitMember((MemberExpression)expression, isOnRightSide);
}
else if (expression is ConstantExpression)
{
Visit((ConstantExpression)expression);
}
else if (expression is UnaryExpression)
{
Visit(((UnaryExpression)expression).Operand, isOnRightSide);
}
else
{
throw new NotSupportedException(string.Format("The '{0}' is not supported!", expression.GetType().Name));
}
}
private void Visit(ConstantExpression expression)
{
AppendValue(expression.Value);
}
private void Visit(ConstantExpression expression, string memberName)
{
const BindingFlags types = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var fieldInfo = expression.Value.GetType().GetField(memberName, types);
if (fieldInfo != null)
{
var value = fieldInfo.GetValue(expression.Value);
AppendValue(value);
}
else
{
var propertyInfo = expression.Value.GetType().GetProperty(memberName, types);
if (propertyInfo != null)
{
var value = propertyInfo.GetValue(expression.Value, null);
AppendValue(value);
}
}
}
private void Visit(BinaryExpression expression)
{
sql.Append("(");
Visit(expression.Left, false);
sql.Append(string.Format(" {0} ", GetOperandFromExpression(expression)));
Visit(expression.Right, true);
sql.Append(")");
}
private void VisitMember(MemberExpression expression, bool isOnRightSide)
{
if (isOnRightSide)
{
AppendRightSideMember(expression);
}
else
{
var columnName = session.GetEntityMapFor<T>().GetColumnNameForProperty(expression);
sql.Append(columnName);
}
}
private void AppendRightSideMember(MemberExpression expression)
{
if (expression.Expression is ConstantExpression)
{
Visit((ConstantExpression)expression.Expression, expression.Member.Name);
}
//else if (expression.Expression == null)
//{
//var value = Expression.Lambda(expression).Compile().DynamicInvoke();
//AppendValue(sql, value);
//}
else if (expression.Expression is MemberExpression)
{
Visit(expression.Expression, true);
}
else
{
throw new ApplicationException(string.Format("Cannot process expression '{0}'", expression));
//var value = Expression.Lambda(expression.Expression).Compile().DynamicInvoke();
//AppendValue(sql, value);
//var memberExpression = (MemberExpression)expression.Expression;
//const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
//var fieldInfo = memberExpression.Type.GetField(expression.Member.Name, flags);
//if (fieldInfo != null)
//{
// var value = fieldInfo.GetValue(instance);
// AppendValue(sql, value);
//}
//else
//{
// var propertyInfo = memberExpression.Type.GetProperty(expression.Member.Name, flags);
// if (propertyInfo != null)
// {
// var value = propertyInfo.GetValue(instance, null);
// AppendValue(sql, value);
// }
//}
}
}
//NOTE: other conversions needed?
private object ConvertValue(object value)
{
if (value is bool)
{
return (bool)value ? 1 : 0;
}
if (value.GetType().IsEnum)
{
return (int)value;
}
return value;
}
private void AppendValue(object value)
{
var parameterName = session.DbAdapter.FormatParameterName(parameterNumber.ToString());
sql.Append(parameterName);
parameters.Add(new Parameter(parameterName, ConvertValue(value)));
parameterNumber++;
}
private string GetOperandFromExpression(Expression expression)
{
switch (expression.NodeType)
{
case ExpressionType.And:
case ExpressionType.AndAlso:
return "and";
case ExpressionType.Equal:
return "=";
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.ExclusiveOr:
return "or";
case ExpressionType.GreaterThan:
return ">";
case ExpressionType.GreaterThanOrEqual:
return ">=";
case ExpressionType.Not:
return "not";
case ExpressionType.NotEqual:
return "<>";
case ExpressionType.LessThan:
return "<";
case ExpressionType.LessThanOrEqual:
return "<=";
default:
throw new ApplicationException(string.Format("Cannot interpret '{0}' as an operator", expression));
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public sealed partial class ImplementInternalMethods
{
internal delegate bool Callback( MethodRepresentation md );
//
// State
//
private TypeSystemForCodeTransformation m_typeSystem;
private GrowOnlyHashTable< MethodRepresentation, Callback > m_pending;
//
// Constructor Methods
//
public ImplementInternalMethods( TypeSystemForCodeTransformation typeSystem )
{
m_typeSystem = typeSystem;
m_pending = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, Callback >();
}
//
// Helper Methods
//
public void Prepare()
{
WellKnownTypes wkt = m_typeSystem.WellKnownTypes;
WellKnownMethods wkm = m_typeSystem.WellKnownMethods;
TypeRepresentation tdMulticastDelegate = wkt.System_MulticastDelegate;
MethodRepresentation mdObject_Equals = wkm.Object_Equals;
Callback dlgImplementObjectEquals = ImplementObjectEquals;
foreach(TypeRepresentation td in m_typeSystem.Types)
{
//
// For all the user-defined value types, provide a system-generated implementation of Object.Equals and Obect.GetHashCode.
//
if(td is ValueTypeRepresentation && !(td is ScalarTypeRepresentation) && td.IsAbstract == false)
{
if(td.IsOpenType == false && td.FindMatch( mdObject_Equals, null ) == null)
{
MethodRepresentation md = td.CreateOverride( m_typeSystem, (VirtualMethodRepresentation)mdObject_Equals );
m_pending[md] = dlgImplementObjectEquals;
}
}
//
// Implement code for delegates.
//
if(td.IsSubClassOf( tdMulticastDelegate, null ) && wkm.MulticastDelegateImpl_MulticastDelegateImpl != null)
{
foreach(MethodRepresentation md in td.Methods)
{
ImplementDelegateMethods( md );
}
}
//
// Implement code for the compiler-generated methods on arrays.
//
if(td is ArrayReferenceTypeRepresentation)
{
var tdHelper = FindArrayHelper( td );
foreach(MethodRepresentation md in td.Methods)
{
if(md is RuntimeMethodRepresentation)
{
if(TypeSystemForCodeTransformation.GetCodeForMethod( md ) == null)
{
var cfg = (ControlFlowGraphStateForCodeTransformation)m_typeSystem.CreateControlFlowGraphState( md );
if(tdHelper != null)
{
LinkArrayImplementation( cfg, tdHelper );
}
else
{
ProvideThrowingStubImplementation( cfg );
}
}
}
}
}
//LON: 2/16/09
//
// Implement code for external "C/ASM" calls that have been marked as imported references
//
foreach(MethodRepresentation md in td.Methods)
{
if ((md.BuildTimeFlags & MethodRepresentation.BuildTimeAttributes.Imported) != 0)
{
ImplementExternalMethodStub( md, this.m_typeSystem );
}
}
}
//
// Implement code for singleton factories.
//
foreach(MethodRepresentation md in m_typeSystem.SingletonFactories.Keys)
{
ImplementSingletonFactory( md, m_typeSystem.SingletonFactories[md] );
}
}
private TypeRepresentation FindArrayHelper( TypeRepresentation td )
{
List< TypeRepresentation > lst;
if(m_typeSystem.GenericTypeInstantiations.TryGetValue( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_SZArrayHelper, out lst ))
{
foreach(var tdHelper in lst)
{
if(tdHelper.GenericParameters[0] == td.ContainedType)
{
return tdHelper;
}
}
}
return null;
}
private void LinkArrayImplementation( ControlFlowGraphStateForCodeTransformation cfg ,
TypeRepresentation tdHelper )
{
MethodRepresentation md = cfg.Method;
TypeRepresentation[] thisPlusArguments = md.ThisPlusArguments;
thisPlusArguments = ArrayUtility.InsertAtHeadOfNotNullArray( thisPlusArguments, tdHelper );
foreach(var mdHelper in tdHelper.Methods)
{
if(mdHelper.MatchNameAndSignature( md.Name, md.ReturnType, thisPlusArguments, null ))
{
var bb = cfg.CreateFirstNormalBasicBlock();
var rhs = m_typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdHelper, cfg.Arguments );
bb.AddOperator( StaticCallOperator.New( null, CallOperator.CallKind.Direct, mdHelper, VariableExpression.ToArray( cfg.ReturnValue ), rhs ) );
cfg.AddReturnOperator();
return;
}
}
//
// No implementation found, fallback to throwing behavior.
//
ProvideThrowingStubImplementation( cfg );
}
private void ProvideThrowingStubImplementation( ControlFlowGraphStateForCodeTransformation cfg )
{
var bb = cfg.CreateFirstNormalBasicBlock();
MethodRepresentation mdThrow = m_typeSystem.WellKnownMethods.ThreadImpl_ThrowNotImplementedException;
Expression[] rhs = m_typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdThrow );
bb.AddOperator( StaticCallOperator.New( null, CallOperator.CallKind.Direct, mdThrow, rhs ) );
cfg.ExitBasicBlock.FlowControl = DeadControlOperator.New( null );
}
public bool Complete()
{
MethodRepresentation[] mdArray = m_pending.KeysToArray();
Callback[] dlgArray = m_pending.ValuesToArray();
bool fRes = true;
m_pending.Clear();
for(int i = 0; i < mdArray.Length; i++)
{
MethodRepresentation md = mdArray[i];
if(m_typeSystem.EstimatedReachabilitySet.IsProhibited( md ) == false)
{
fRes &= dlgArray[i]( mdArray[i] );
}
}
return fRes;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.