context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reflection;
using System.Xml;
using EnvDTE;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TemplateWizard;
using NuPattern.Diagnostics;
using NuPattern.VisualStudio.Properties;
using NuPattern.VisualStudio.Solution.Templates;
namespace NuPattern.VisualStudio.TemplateWizards
{
/// <summary>
/// A template wizard that coordinates the execution of other wizards.
/// </summary>
[CLSCompliant(false)]
public class CoordinatorTemplateWizard : TemplateWizard
{
private static readonly ITracer tracer = Tracer.Get<CoordinatorTemplateWizard>();
/// <summary>
/// The expected element name under <c>WizardData</c> element in the .vstemplate
/// containing the wizard extensions to coordinate.
/// </summary>
public const string WizardDataElement = "CoordinatedWizards";
private List<IWizard> wizards = new List<IWizard>();
/// <summary>
/// Executes when the wizard starts.
/// </summary>
public override void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, Microsoft.VisualStudio.TemplateWizard.WizardRunKind runKind, object[] customParams)
{
base.RunStarted(automationObject, replacementsDictionary, runKind, customParams);
var wizardData = this.TemplateSchema.WizardData.FirstOrDefault();
if (wizardData != null)
{
LoadWizards(wizardData);
using (var services = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)automationObject))
{
var components = services.GetService<SComponentModel, IComponentModel>();
foreach (var wizard in wizards)
{
TryOrDispose(() => AttributedModelServices.SatisfyImportsOnce(components.DefaultCompositionService, wizard));
}
}
}
foreach (var wizard in wizards)
{
TryOrDispose(() => wizard.RunStarted(automationObject, replacementsDictionary, runKind, customParams));
}
}
/// <summary>
/// Executes when the wizard ends.
/// </summary>
public override void RunFinished()
{
foreach (var wizard in wizards.AsReadOnly().Reverse())
{
TryOrDispose(() => wizard.RunFinished());
}
foreach (var wizard in wizards.OfType<IDisposable>().Reverse())
{
wizard.Dispose();
}
base.RunFinished();
}
/// <summary>
/// Executed before a file is opened.
/// </summary>
public override void BeforeOpeningFile(EnvDTE.ProjectItem projectItem)
{
base.BeforeOpeningFile(projectItem);
foreach (var wizard in wizards)
{
TryOrDispose(() => wizard.BeforeOpeningFile(projectItem));
}
}
/// <summary>
/// Runs custom wizard logic when a project has finished generating.
/// </summary>
/// <param name="project">The project that finished generating.</param>
public override void ProjectFinishedGenerating(Project project)
{
base.ProjectFinishedGenerating(project);
foreach (var wizard in wizards)
{
TryOrDispose(() => wizard.ProjectFinishedGenerating(project));
}
}
/// <summary>
/// Runs custom wizard logic when a project item has finished generating.
/// </summary>
/// <param name="projectItem">The project item that finished generating.</param>
public override void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem)
{
base.ProjectItemFinishedGenerating(projectItem);
foreach (var wizard in wizards)
{
TryOrDispose(() => wizard.ProjectItemFinishedGenerating(projectItem));
}
}
/// <summary>
/// Indicates whether the specified project item should be added to the project.
/// </summary>
/// <param name="filePath">The path to the project item.</param>
/// <returns>
/// true if the project item should be added to the project; otherwise, false.
/// </returns>
public override bool ShouldAddProjectItem(string filePath)
{
return wizards.All(w => w.ShouldAddProjectItem(filePath));
}
private void TryOrDispose(Action action)
{
try
{
action();
}
catch (Exception e)
{
foreach (var disposable in this.wizards.OfType<IDisposable>())
{
try
{
disposable.Dispose();
}
catch (Exception de)
{
tracer.Error(de, Resources.CoordinatorTemplateWizard_FailedToDispose, disposable.GetType().FullName);
}
}
tracer.Error(e, Resources.CoordinatorTemplateWizard_TryFailed);
throw;
}
}
private void LoadWizards(IVsTemplateWizardData wizardData)
{
var wizardElements = from coordinator in wizardData.Elements
where coordinator.Name.Equals(@"CoordinatedWizards", StringComparison.OrdinalIgnoreCase)
from wizardNode in coordinator.ChildNodes.OfType<XmlElement>()
where wizardNode.LocalName == @"WizardExtension"
select new
{
Assembly = wizardNode.ChildNodes
.OfType<XmlElement>()
.Where(node => node.LocalName == @"Assembly")
.Select(node => node.InnerText)
.FirstOrDefault(),
TypeName = wizardNode.ChildNodes
.OfType<XmlElement>()
.Where(node => node.LocalName == @"FullClassName")
.Select(node => node.InnerText)
.FirstOrDefault(),
};
foreach (var wizardElement in wizardElements.Where(element => !string.IsNullOrEmpty(element.Assembly) && !string.IsNullOrEmpty(element.TypeName)))
{
tracer.Verbose(Resources.CoordinatorTemplateWizard_LoadingWizardType, wizardElement.TypeName, wizardElement.Assembly);
try
{
var asm = Assembly.Load(wizardElement.Assembly);
try
{
var type = asm.GetType(wizardElement.TypeName, true);
if (!typeof(IWizard).IsAssignableFrom(type))
tracer.Error((string)Resources.CoordinatorTemplateWizard_NotIWizard, type.FullName);
else
this.wizards.Add((IWizard)Activator.CreateInstance(type));
}
catch (Exception te)
{
tracer.Error(te, Resources.CoordinatorTemplateWizard_FailedToLoadType, wizardElement.TypeName, wizardElement.Assembly);
}
}
catch (Exception ae)
{
tracer.Error(ae, Resources.CoordinatorTemplateWizard_FailedToLoadAssembly, wizardElement.Assembly);
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Messaging.EventHubs.Core;
using Azure.Messaging.EventHubs.Diagnostics;
namespace Azure.Messaging.EventHubs.Primitives
{
/// <summary>
/// Handles all load balancing concerns for an event processor including claiming, stealing, and relinquishing ownership.
/// </summary>
///
internal class PartitionLoadBalancer
{
/// <summary>The random number generator to use for a specific thread.</summary>
private static readonly ThreadLocal<Random> RandomNumberGenerator = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref s_randomSeed)), false);
/// <summary>The seed to use for initializing random number generated for a given thread-specific instance.</summary>
private static int s_randomSeed = Environment.TickCount;
/// <summary>
/// Responsible for creation of checkpoints and for ownership claim.
/// </summary>
///
private readonly StorageManager StorageManager;
/// <summary>
/// A partition distribution dictionary, mapping an owner's identifier to the amount of partitions it owns and its list of partitions.
/// </summary>
///
private readonly Dictionary<string, List<EventProcessorPartitionOwnership>> ActiveOwnershipWithDistribution = new Dictionary<string, List<EventProcessorPartitionOwnership>>();
/// <summary>
/// The minimum amount of time for an ownership to be considered expired without further updates.
/// </summary>
///
private TimeSpan OwnershipExpiration;
/// <summary>
/// The fully qualified Event Hubs namespace that the processor is associated with. This is likely
/// to be similar to <c>{yournamespace}.servicebus.windows.net</c>.
/// </summary>
///
public string FullyQualifiedNamespace { get; private set; }
/// <summary>
/// The name of the Event Hub that the processor is connected to, specific to the
/// Event Hubs namespace that contains it.
/// </summary>
///
public string EventHubName { get; private set; }
/// <summary>
/// The name of the consumer group this load balancer is associated with. Events will be
/// read only in the context of this group.
/// </summary>
///
public string ConsumerGroup { get; private set; }
/// <summary>
/// The identifier of the EventProcessorClient that owns this load balancer.
/// </summary>
///
public string OwnerIdentifier { get; private set; }
/// <summary>
/// The minimum amount of time to be elapsed between two load balancing verifications.
/// </summary>
///
public TimeSpan LoadBalanceInterval { get; set; } = TimeSpan.FromSeconds(10);
/// <summary>
/// Indicates whether the load balancer believes itself to be in a balanced state
/// when considering its fair share of partitions and whether any partitions
/// remain unclaimed.
/// </summary>
///
public virtual bool IsBalanced { get; private set; }
/// <summary>
/// The partitionIds currently owned by the associated event processor.
/// </summary>
///
public virtual IEnumerable<string> OwnedPartitionIds => InstanceOwnership.Keys;
/// <summary>
/// The instance of <see cref="PartitionLoadBalancerEventSource" /> which can be mocked for testing.
/// </summary>
///
internal PartitionLoadBalancerEventSource Logger { get; set; } = PartitionLoadBalancerEventSource.Log;
/// <summary>
/// The set of partition ownership the associated event processor owns. Partition ids are used as keys.
/// </summary>
///
private Dictionary<string, EventProcessorPartitionOwnership> InstanceOwnership { get; set; } = new Dictionary<string, EventProcessorPartitionOwnership>();
/// <summary>
/// Initializes a new instance of the <see cref="PartitionLoadBalancer"/> class.
/// </summary>
///
/// <param name="storageManager">Responsible for creation of checkpoints and for ownership claim.</param>
/// <param name="identifier">The identifier of the EventProcessorClient that owns this load balancer.</param>
/// <param name="consumerGroup">The name of the consumer group this load balancer is associated with.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace that the processor is associated with.</param>
/// <param name="eventHubName">The name of the Event Hub that the processor is associated with.</param>
/// <param name="ownershipExpiration">The minimum amount of time for an ownership to be considered expired without further updates.</param>
///
public PartitionLoadBalancer(StorageManager storageManager,
string identifier,
string consumerGroup,
string fullyQualifiedNamespace,
string eventHubName,
TimeSpan ownershipExpiration)
{
Argument.AssertNotNull(storageManager, nameof(storageManager));
Argument.AssertNotNullOrEmpty(identifier, nameof(identifier));
Argument.AssertNotNullOrEmpty(consumerGroup, nameof(consumerGroup));
Argument.AssertNotNullOrEmpty(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
StorageManager = storageManager;
OwnerIdentifier = identifier;
FullyQualifiedNamespace = fullyQualifiedNamespace;
EventHubName = eventHubName;
ConsumerGroup = consumerGroup;
OwnershipExpiration = ownershipExpiration;
}
/// <summary>
/// Initializes a new instance of the <see cref="PartitionLoadBalancer"/> class.
/// </summary>
///
protected PartitionLoadBalancer()
{
}
/// <summary>
/// Performs load balancing between multiple EventProcessorClient instances, claiming others' partitions to enforce
/// a more equal distribution when necessary. It also manages its own partition processing tasks and ownership.
/// </summary>
///
/// <param name="partitionIds">The set of partitionIds available for ownership balancing.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>The claimed ownership. <c>null</c> if this instance is not eligible, if no claimable ownership was found or if the claim attempt failed.</returns>
///
public virtual async ValueTask<EventProcessorPartitionOwnership> RunLoadBalancingAsync(string[] partitionIds,
CancellationToken cancellationToken)
{
// Renew this instance's ownership so they don't expire.
await RenewOwnershipAsync(cancellationToken).ConfigureAwait(false);
// From the storage service, obtain a complete list of ownership, including expired ones. We may still need
// their eTags to claim orphan partitions.
IEnumerable<EventProcessorPartitionOwnership> completeOwnershipList;
try
{
completeOwnershipList = (await StorageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup, cancellationToken)
.ConfigureAwait(false))
.ToList();
}
catch (Exception ex)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// If ownership list retrieval fails, give up on the current cycle. There's nothing more we can do
// without an updated ownership list. Set the EventHubName to null so it doesn't modify the exception
// message. This exception message is used so the processor can retrieve the raw Operation string, and
// adding the EventHubName would append unwanted info to it.
throw new EventHubsException(true, null, Resources.OperationListOwnership, ex);
}
// There's no point in continuing the current cycle if we failed to fetch the completeOwnershipList.
if (completeOwnershipList == default)
{
return default;
}
var unclaimedPartitions = new HashSet<string>(partitionIds);
// Create a partition distribution dictionary from the complete ownership list we have, mapping an owner's identifier to the list of
// partitions it owns. When an event processor goes down and it has only expired ownership, it will not be taken into consideration
// by others. The expiration time defaults to 30 seconds, but it may be overridden by a derived class.
var utcNow = DateTimeOffset.UtcNow;
ActiveOwnershipWithDistribution.Clear();
ActiveOwnershipWithDistribution[OwnerIdentifier] = new List<EventProcessorPartitionOwnership>();
foreach (EventProcessorPartitionOwnership ownership in completeOwnershipList)
{
if (utcNow.Subtract(ownership.LastModifiedTime) < OwnershipExpiration && !string.IsNullOrEmpty(ownership.OwnerIdentifier))
{
if (ActiveOwnershipWithDistribution.ContainsKey(ownership.OwnerIdentifier))
{
ActiveOwnershipWithDistribution[ownership.OwnerIdentifier].Add(ownership);
}
else
{
ActiveOwnershipWithDistribution[ownership.OwnerIdentifier] = new List<EventProcessorPartitionOwnership> { ownership };
}
unclaimedPartitions.Remove(ownership.PartitionId);
}
}
// Find an ownership to claim and try to claim it. The method will return null if this instance was not eligible to
// increase its ownership list, if no claimable ownership could be found or if a claim attempt has failed.
var (claimAttempted, claimedOwnership) = await FindAndClaimOwnershipAsync(completeOwnershipList, unclaimedPartitions, partitionIds.Length, cancellationToken).ConfigureAwait(false);
if (claimedOwnership != null)
{
InstanceOwnership[claimedOwnership.PartitionId] = claimedOwnership;
}
// Update the balanced state. Consider the load balanced if this processor has its minimum share of partitions and did not
// attempt to claim a partition.
var minimumDesiredPartitions = partitionIds.Length / ActiveOwnershipWithDistribution.Keys.Count;
IsBalanced = ((InstanceOwnership.Count >= minimumDesiredPartitions) && (!claimAttempted));
return claimedOwnership;
}
/// <summary>
/// Relinquishes this instance's ownership so they can be claimed by other processors and clears the OwnedPartitionIds.
/// </summary>
///
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
public virtual async Task RelinquishOwnershipAsync(CancellationToken cancellationToken)
{
IEnumerable<EventProcessorPartitionOwnership> ownershipToRelinquish = InstanceOwnership.Values
.Select(ownership => new EventProcessorPartitionOwnership
{
FullyQualifiedNamespace = ownership.FullyQualifiedNamespace,
EventHubName = ownership.EventHubName,
ConsumerGroup = ownership.ConsumerGroup,
OwnerIdentifier = string.Empty, //set ownership to Empty so that it is treated as available to claim
PartitionId = ownership.PartitionId,
LastModifiedTime = ownership.LastModifiedTime,
Version = ownership.Version
});
await StorageManager.ClaimOwnershipAsync(ownershipToRelinquish, cancellationToken).ConfigureAwait(false);
InstanceOwnership.Clear();
}
/// <summary>
/// Finds and tries to claim an ownership if this processor instance is eligible to increase its ownership list.
/// </summary>
///
/// <param name="completeOwnershipEnumerable">A complete enumerable of ownership obtained from the storage service.</param>
/// <param name="unclaimedPartitions">The set of partitionIds that are currently unclaimed.</param>
/// <param name="partitionCount">The count of partitions.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>A tuple indicating whether a claim was attempted and any ownership that was claimed. The claimed ownership will be <c>null</c> if no claim was attempted or if the claim attempt failed.</returns>
///
private ValueTask<(bool wasClaimAttempted, EventProcessorPartitionOwnership claimedPartition)> FindAndClaimOwnershipAsync(IEnumerable<EventProcessorPartitionOwnership> completeOwnershipEnumerable,
HashSet<string> unclaimedPartitions,
int partitionCount,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// The minimum owned partitions count is the minimum amount of partitions every event processor needs to own when the distribution
// is balanced. If n = minimumOwnedPartitionsCount, a balanced distribution will only have processors that own n or n + 1 partitions
// each. We can guarantee the partition distribution has at least one key, which corresponds to this event processor instance, even
// if it owns no partitions.
var minimumOwnedPartitionsCount = partitionCount / ActiveOwnershipWithDistribution.Keys.Count;
Logger.MinimumPartitionsPerEventProcessor(minimumOwnedPartitionsCount);
var ownedPartitionsCount = ActiveOwnershipWithDistribution[OwnerIdentifier].Count;
Logger.CurrentOwnershipCount(ownedPartitionsCount, OwnerIdentifier);
// There are two possible situations in which we may need to claim a partition ownership.
//
// The first one is when we are below the minimum amount of owned partitions. There's nothing more to check, as we need to claim more
// partitions to enforce balancing.
//
// The second case is a bit tricky. Sometimes the claim must be performed by an event processor that already has reached the minimum
// amount of ownership. This may happen, for instance, when we have 13 partitions and 3 processors, each of them owning 4 partitions.
// The minimum amount of partitions per processor is, in fact, 4, but in this example we still have 1 orphan partition to claim. To
// avoid overlooking this kind of situation, we may want to claim an ownership when we have exactly the minimum amount of ownership,
// but we are making sure there are no better candidates among the other event processors.
if (ownedPartitionsCount < minimumOwnedPartitionsCount
|| (ownedPartitionsCount == minimumOwnedPartitionsCount && !ActiveOwnershipWithDistribution.Values.Any(partitions => partitions.Count < minimumOwnedPartitionsCount)))
{
// Look for unclaimed partitions. If any, randomly pick one of them to claim.
Logger.UnclaimedPartitions(unclaimedPartitions);
if (unclaimedPartitions.Count > 0)
{
var index = RandomNumberGenerator.Value.Next(unclaimedPartitions.Count);
var returnTask = ClaimOwnershipAsync(unclaimedPartitions.ElementAt(index), completeOwnershipEnumerable, cancellationToken);
return new ValueTask<(bool, EventProcessorPartitionOwnership)>(returnTask);
}
// Only try to steal partitions if there are no unclaimed partitions left. At first, only processors that have exceeded the
// maximum owned partition count should be targeted.
Logger.ShouldStealPartition(OwnerIdentifier);
var maximumOwnedPartitionsCount = minimumOwnedPartitionsCount + 1;
var partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount = new List<string>();
var partitionsOwnedByProcessorWithExactlyMaximumOwnedPartitionsCount = new List<string>();
// Build a list of partitions owned by processors owning exactly maximumOwnedPartitionsCount partitions
// and a list of partitions owned by processors owning more than maximumOwnedPartitionsCount partitions.
// Ignore the partitions already owned by this processor even though the current processor should never meet either criteria.
foreach (var key in ActiveOwnershipWithDistribution.Keys)
{
var ownedPartitions = ActiveOwnershipWithDistribution[key];
if (ownedPartitions.Count < maximumOwnedPartitionsCount || key == OwnerIdentifier)
{
// Skip if the common case is true.
continue;
}
if (ownedPartitions.Count == maximumOwnedPartitionsCount)
{
ownedPartitions
.ForEach(ownership => partitionsOwnedByProcessorWithExactlyMaximumOwnedPartitionsCount.Add(ownership.PartitionId));
}
else
{
ownedPartitions
.ForEach(ownership => partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount.Add(ownership.PartitionId));
}
}
// Here's the important part. If there are no processors that have exceeded the maximum owned partition count allowed, we may
// need to steal from the processors that have exactly the maximum amount. If this instance is below the minimum count, then
// we have no choice as we need to enforce balancing. Otherwise, leave it as it is because the distribution wouldn't change.
if (partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount.Count > 0)
{
// If any stealable partitions were found, randomly pick one of them to claim.
Logger.StealPartition(OwnerIdentifier);
var index = RandomNumberGenerator.Value.Next(partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount.Count);
var returnTask = ClaimOwnershipAsync(
partitionsOwnedByProcessorWithGreaterThanMaximumOwnedPartitionsCount[index],
completeOwnershipEnumerable,
cancellationToken);
return new ValueTask<(bool, EventProcessorPartitionOwnership)>(returnTask);
}
else if (ownedPartitionsCount < minimumOwnedPartitionsCount)
{
// If any stealable partitions were found, randomly pick one of them to claim.
Logger.StealPartition(OwnerIdentifier);
var index = RandomNumberGenerator.Value.Next(partitionsOwnedByProcessorWithExactlyMaximumOwnedPartitionsCount.Count);
var returnTask = ClaimOwnershipAsync(
partitionsOwnedByProcessorWithExactlyMaximumOwnedPartitionsCount[index],
completeOwnershipEnumerable,
cancellationToken);
return new ValueTask<(bool, EventProcessorPartitionOwnership)>(returnTask);
}
}
// No ownership has been claimed.
return new ValueTask<(bool, EventProcessorPartitionOwnership)>((false, default(EventProcessorPartitionOwnership)));
}
/// <summary>
/// Renews this instance's ownership so they don't expire.
/// </summary>
///
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
private async Task RenewOwnershipAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
Logger.RenewOwnershipStart(OwnerIdentifier);
IEnumerable<EventProcessorPartitionOwnership> ownershipToRenew = InstanceOwnership.Values
.Select(ownership => new EventProcessorPartitionOwnership
{
FullyQualifiedNamespace = ownership.FullyQualifiedNamespace,
EventHubName = ownership.EventHubName,
ConsumerGroup = ownership.ConsumerGroup,
OwnerIdentifier = ownership.OwnerIdentifier,
PartitionId = ownership.PartitionId,
LastModifiedTime = DateTimeOffset.UtcNow,
Version = ownership.Version
});
try
{
// Dispose of all previous partition ownership instances and get a whole new dictionary.
InstanceOwnership = (await StorageManager.ClaimOwnershipAsync(ownershipToRenew, cancellationToken)
.ConfigureAwait(false))
.ToDictionary(ownership => ownership.PartitionId);
}
catch (Exception ex)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// If ownership renewal fails just give up and try again in the next cycle. The processor may
// end up losing some of its ownership.
Logger.RenewOwnershipError(OwnerIdentifier, ex.Message);
// Set the EventHubName to null so it doesn't modify the exception message. This exception message is
// used so the processor can retrieve the raw Operation string, and adding the EventHubName would append
// unwanted info to it.
throw new EventHubsException(true, null, Resources.OperationRenewOwnership, ex);
}
finally
{
Logger.RenewOwnershipComplete(OwnerIdentifier);
}
}
/// <summary>
/// Tries to claim ownership of the specified partition.
/// </summary>
///
/// <param name="partitionId">The identifier of the Event Hub partition the ownership is associated with.</param>
/// <param name="completeOwnershipEnumerable">A complete enumerable of ownership obtained from the stored service provided by the user.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>A tuple indicating whether a claim was attempted and the claimed ownership. The claimed ownership will be <c>null</c> if the claim attempt failed.</returns>
///
private async Task<(bool wasClaimAttempted, EventProcessorPartitionOwnership claimedPartition)> ClaimOwnershipAsync(string partitionId,
IEnumerable<EventProcessorPartitionOwnership> completeOwnershipEnumerable,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
Logger.ClaimOwnershipStart(partitionId);
// We need the eTag from the most recent ownership of this partition, even if it's expired. We want to keep the offset and
// the sequence number as well.
var oldOwnership = completeOwnershipEnumerable.FirstOrDefault(ownership => ownership.PartitionId == partitionId);
var newOwnership = new EventProcessorPartitionOwnership
{
FullyQualifiedNamespace = FullyQualifiedNamespace,
EventHubName = EventHubName,
ConsumerGroup = ConsumerGroup,
OwnerIdentifier = OwnerIdentifier,
PartitionId = partitionId,
LastModifiedTime = DateTimeOffset.UtcNow,
Version = oldOwnership?.Version
};
var claimedOwnership = default(IEnumerable<EventProcessorPartitionOwnership>);
try
{
claimedOwnership = await StorageManager.ClaimOwnershipAsync(new List<EventProcessorPartitionOwnership> { newOwnership }, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// If ownership claim fails, just treat it as a usual ownership claim failure.
Logger.ClaimOwnershipError(partitionId, ex.Message);
// Set the EventHubName to null so it doesn't modify the exception message. This exception message is
// used so the processor can retrieve the raw Operation string, and adding the EventHubName would append
// unwanted info to it. This exception also communicates the PartitionId to the caller.
var exception = new EventHubsException(true, null, Resources.OperationClaimOwnership, ex);
exception.SetFailureOperation(exception.Message);
exception.SetFailureData(partitionId);
throw exception;
}
// We are expecting an enumerable with a single element if the claim attempt succeeds.
return (true, claimedOwnership.FirstOrDefault());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ASPNETCore_Core.Data;
using ASPNETCore_Core.Models;
using ASPNETCore_Core.Services;
using HtmlAgilityPack;
using Microsoft.AspNetCore.Authorization;
namespace ASPNETCore_Core.Controllers
{
[Authorize]
public class EncoresController : Controller
{
private readonly EncoreContext _context;
private readonly IEncoreCrawler _encoreCrawler;
public EncoresController(EncoreContext context, IEncoreCrawler encoreCrawler)
{
_context = context;
_encoreCrawler = encoreCrawler;
}
[AllowAnonymous]
// GET: Encores
public async Task<IActionResult> Index()
{
return View(await _context.Encores.Take(200).ToListAsync());
}
[AllowAnonymous]
// GET: Encores
public async Task<IActionResult> IndexByType(LottoTypeEnum lottoType)
{
return View("Index", await _context.Encores.Where(c => c.LottoType == lottoType)
.OrderByDescending(c => c.DrawDate)
.ThenByDescending(c => c.DrawType)
.Take(100)
.ToListAsync());
}
[AllowAnonymous]
// GET: Encores/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var encore = await _context.Encores.SingleOrDefaultAsync(m => m.EncoreID == id);
if (encore == null)
{
return NotFound();
}
//populate encore matches
encore.EncoreMatches = await _context.EncoreMatches.Where(m => m.EncoreID == encore.EncoreID).ToListAsync();
return View(encore);
}
// GET: Encores/Create
public IActionResult Create()
{
return View();
}
public async Task<IActionResult> Craw()
{
await _encoreCrawler.CrawlAsync(_context.Encores);
//save encore and encore matches
await _context.SaveChangesAsync();
return View("Index", await _context.Encores.Where(c => c.LottoType == LottoTypeEnum.LottoMAX)
.OrderByDescending(c => c.DrawDate)
.ThenByDescending(c => c.DrawType)
.Take(100)
.ToListAsync());
}
// POST: Encores/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("EncoreID,LottoType,DrawDate,DrawType,TotalCashWon,WinninNumber")] Encore encore)
{
if (ModelState.IsValid)
{
_context.Add(encore);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(encore);
}
// GET: Encores/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var encore = await _context.Encores.SingleOrDefaultAsync(m => m.EncoreID == id);
if (encore == null)
{
return NotFound();
}
return View(encore);
}
// POST: Encores/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("EncoreID,DrawDate,TotalCashWon,WinninNumber")] Encore encore)
{
if (id != encore.EncoreID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(encore);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EncoreExists(encore.EncoreID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(encore);
}
// GET: Encores/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var encore = await _context.Encores.SingleOrDefaultAsync(m => m.EncoreID == id);
if (encore == null)
{
return NotFound();
}
return View(encore);
}
// POST: Encores/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var encore = await _context.Encores.SingleOrDefaultAsync(m => m.EncoreID == id);
var encoreMatches = await _context.EncoreMatches.Where(m => m.EncoreID == encore.EncoreID).ToListAsync();
encore.EncoreMatches = encoreMatches;
_context.Encores.Remove(encore);
await _context.SaveChangesAsync();
return RedirectToAction("Index", await _context.Encores.Where(c => c.LottoType == encore.LottoType)
.OrderByDescending(c => c.DrawDate)
.ThenByDescending(c => c.DrawType)
.Take(100)
.ToListAsync());
}
private bool EncoreExists(int id)
{
return _context.Encores.Any(e => e.EncoreID == id);
}
// GET: Encores/Check
[AllowAnonymous]
public IActionResult Check()
{
return View();
}
// POST: Encores/Check
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Check([Bind("EncoreID,LottoType,DrawDate,DrawType,TotalCashWon,WinninNumber")] Encore encoreToCheck)
{
if (ModelState.IsValid)
{
try
{
var encore = await _context.Encores.SingleOrDefaultAsync(m => m.LottoType == encoreToCheck.LottoType &&
m.DrawDate == encoreToCheck.DrawDate &&
m.DrawType == encoreToCheck.DrawType);
if (encore == null)
{
return NotFound();
}
encore.EncoreMatches = await _context.EncoreMatches.Where(m => m.EncoreID == encore.EncoreID).ToListAsync();
//get the matchtype of the number to check
var matchType = _encoreCrawler.CheckEncoreMatchType(encoreToCheck.WinninNumber, encore.WinninNumber, encore.EncoreMatches);
encoreToCheck.EncoreMatches = new List<EncoreMatch>();
encoreToCheck.EncoreMatches.Add(
new EncoreMatch
{
MatchType = matchType,
Prize = encore.EncoreMatches.Where(m => m.MatchType == matchType).Select(m => m.Prize).SingleOrDefault(),
});
}
catch (Exception)
{
throw;
}
}
return View(encoreToCheck);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Net.Mail;
using System.Runtime.ExceptionServices;
namespace System.Net.Mime
{
/// <summary>
/// Summary description for MimePart.
/// </summary>
internal class MimePart : MimeBasePart, IDisposable
{
private Stream _stream = null;
private bool _streamSet = false;
private bool _streamUsedOnce = false;
private AsyncCallback _readCallback;
private AsyncCallback _writeCallback;
private const int maxBufferSize = 0x4400; //seems optimal for send based on perf analysis
internal MimePart() { }
public void Dispose()
{
if (_stream != null)
{
_stream.Close();
}
}
internal Stream Stream => _stream;
internal ContentDisposition ContentDisposition
{
get { return _contentDisposition; }
set
{
_contentDisposition = value;
if (value == null)
{
((HeaderCollection)Headers).InternalRemove(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition));
}
else
{
_contentDisposition.PersistIfNeeded((HeaderCollection)Headers, true);
}
}
}
internal TransferEncoding TransferEncoding
{
get
{
string value = Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)];
if (value.Equals("base64", StringComparison.OrdinalIgnoreCase))
{
return TransferEncoding.Base64;
}
else if (value.Equals("quoted-printable", StringComparison.OrdinalIgnoreCase))
{
return TransferEncoding.QuotedPrintable;
}
else if (value.Equals("7bit", StringComparison.OrdinalIgnoreCase))
{
return TransferEncoding.SevenBit;
}
else if (value.Equals("8bit", StringComparison.OrdinalIgnoreCase))
{
return TransferEncoding.EightBit;
}
else
{
return TransferEncoding.Unknown;
}
}
set
{
//QFE 4554
if (value == TransferEncoding.Base64)
{
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)] = "base64";
}
else if (value == TransferEncoding.QuotedPrintable)
{
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)] = "quoted-printable";
}
else if (value == TransferEncoding.SevenBit)
{
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)] = "7bit";
}
else if (value == TransferEncoding.EightBit)
{
Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)] = "8bit";
}
else
{
throw new NotSupportedException(SR.Format(SR.MimeTransferEncodingNotSupported, value));
}
}
}
internal void SetContent(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (_streamSet)
{
_stream.Close();
_stream = null;
_streamSet = false;
}
_stream = stream;
_streamSet = true;
_streamUsedOnce = false;
TransferEncoding = TransferEncoding.Base64;
}
internal void SetContent(Stream stream, string name, string mimeType)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (mimeType != null && mimeType != string.Empty)
{
_contentType = new ContentType(mimeType);
}
if (name != null && name != string.Empty)
{
ContentType.Name = name;
}
SetContent(stream);
}
internal void SetContent(Stream stream, ContentType contentType)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
_contentType = contentType;
SetContent(stream);
}
internal void Complete(IAsyncResult result, Exception e)
{
//if we already completed and we got called again,
//it mean's that there was an exception in the callback and we
//should just rethrow it.
MimePartContext context = (MimePartContext)result.AsyncState;
if (context._completed)
{
ExceptionDispatchInfo.Capture(e).Throw();
}
try
{
if (context._outputStream != null)
{
context._outputStream.Close();
}
}
catch (Exception ex)
{
if (e == null)
{
e = ex;
}
}
context._completed = true;
context._result.InvokeCallback(e);
}
internal void ReadCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
((MimePartContext)result.AsyncState)._completedSynchronously = false;
try
{
ReadCallbackHandler(result);
}
catch (Exception e)
{
Complete(result, e);
}
}
internal void ReadCallbackHandler(IAsyncResult result)
{
MimePartContext context = (MimePartContext)result.AsyncState;
context._bytesLeft = Stream.EndRead(result);
if (context._bytesLeft > 0)
{
IAsyncResult writeResult = context._outputStream.BeginWrite(context._buffer, 0, context._bytesLeft, _writeCallback, context);
if (writeResult.CompletedSynchronously)
{
WriteCallbackHandler(writeResult);
}
}
else
{
Complete(result, null);
}
}
internal void WriteCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
((MimePartContext)result.AsyncState)._completedSynchronously = false;
try
{
WriteCallbackHandler(result);
}
catch (Exception e)
{
Complete(result, e);
}
}
internal void WriteCallbackHandler(IAsyncResult result)
{
MimePartContext context = (MimePartContext)result.AsyncState;
context._outputStream.EndWrite(result);
IAsyncResult readResult = Stream.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
if (readResult.CompletedSynchronously)
{
ReadCallbackHandler(readResult);
}
}
internal Stream GetEncodedStream(Stream stream)
{
Stream outputStream = stream;
if (TransferEncoding == TransferEncoding.Base64)
{
outputStream = new Base64Stream(outputStream, new Base64WriteStateInfo());
}
else if (TransferEncoding == TransferEncoding.QuotedPrintable)
{
outputStream = new QuotedPrintableStream(outputStream, true);
}
else if (TransferEncoding == TransferEncoding.SevenBit || TransferEncoding == TransferEncoding.EightBit)
{
outputStream = new EightBitStream(outputStream);
}
return outputStream;
}
internal void ContentStreamCallbackHandler(IAsyncResult result)
{
MimePartContext context = (MimePartContext)result.AsyncState;
Stream outputStream = context._writer.EndGetContentStream(result);
context._outputStream = GetEncodedStream(outputStream);
_readCallback = new AsyncCallback(ReadCallback);
_writeCallback = new AsyncCallback(WriteCallback);
IAsyncResult readResult = Stream.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
if (readResult.CompletedSynchronously)
{
ReadCallbackHandler(readResult);
}
}
internal void ContentStreamCallback(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
((MimePartContext)result.AsyncState)._completedSynchronously = false;
try
{
ContentStreamCallbackHandler(result);
}
catch (Exception e)
{
Complete(result, e);
}
}
internal class MimePartContext
{
internal MimePartContext(BaseWriter writer, LazyAsyncResult result)
{
_writer = writer;
_result = result;
_buffer = new byte[maxBufferSize];
}
internal Stream _outputStream;
internal LazyAsyncResult _result;
internal int _bytesLeft;
internal BaseWriter _writer;
internal byte[] _buffer;
internal bool _completed;
internal bool _completedSynchronously = true;
}
internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback, bool allowUnicode, object state)
{
PrepareHeaders(allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
MimePartAsyncResult result = new MimePartAsyncResult(this, state, callback);
MimePartContext context = new MimePartContext(writer, result);
ResetStream();
_streamUsedOnce = true;
IAsyncResult contentResult = writer.BeginGetContentStream(new AsyncCallback(ContentStreamCallback), context);
if (contentResult.CompletedSynchronously)
{
ContentStreamCallbackHandler(contentResult);
}
return result;
}
internal override void Send(BaseWriter writer, bool allowUnicode)
{
if (Stream != null)
{
byte[] buffer = new byte[maxBufferSize];
PrepareHeaders(allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
Stream outputStream = writer.GetContentStream();
outputStream = GetEncodedStream(outputStream);
int read;
ResetStream();
_streamUsedOnce = true;
while ((read = Stream.Read(buffer, 0, maxBufferSize)) > 0)
{
outputStream.Write(buffer, 0, read);
}
outputStream.Close();
}
}
//Ensures that if we've used the stream once, we will either reset it to the origin, or throw.
internal void ResetStream()
{
if (_streamUsedOnce)
{
if (Stream.CanSeek)
{
Stream.Seek(0, SeekOrigin.Begin);
_streamUsedOnce = false;
}
else
{
throw new InvalidOperationException(SR.MimePartCantResetStream);
}
}
}
}
}
| |
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Logging;
namespace Orleans.Runtime
{
/// <summary>
/// The Utils class contains a variety of utility methods for use in application and grain code.
/// </summary>
public static class Utils
{
/// <summary>
/// Returns a human-readable text string that describes an IEnumerable collection of objects.
/// </summary>
/// <typeparam name="T">The type of the list elements.</typeparam>
/// <param name="collection">The IEnumerable to describe.</param>
/// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param>
/// <param name="separator">The separator to use.</param>
/// <param name="putInBrackets">Puts elements within brackets</param>
/// <returns>A string assembled by wrapping the string descriptions of the individual
/// elements with square brackets and separating them with commas.</returns>
public static string EnumerableToString<T>(IEnumerable<T> collection, Func<T, string> toString = null,
string separator = ", ", bool putInBrackets = true)
{
if (collection == null)
{
if (putInBrackets) return "[]";
else return "null";
}
var sb = new StringBuilder();
if (putInBrackets) sb.Append("[");
var enumerator = collection.GetEnumerator();
bool firstDone = false;
while (enumerator.MoveNext())
{
T value = enumerator.Current;
string val;
if (toString != null)
val = toString(value);
else
val = value == null ? "null" : value.ToString();
if (firstDone)
{
sb.Append(separator);
sb.Append(val);
}
else
{
sb.Append(val);
firstDone = true;
}
}
if (putInBrackets) sb.Append("]");
return sb.ToString();
}
/// <summary>
/// Returns a human-readable text string that describes a dictionary that maps objects to objects.
/// </summary>
/// <typeparam name="T1">The type of the dictionary keys.</typeparam>
/// <typeparam name="T2">The type of the dictionary elements.</typeparam>
/// <param name="dict">The dictionary to describe.</param>
/// <param name="toString">Converts the element to a string. If none specified, <see cref="object.ToString"/> will be used.</param>
/// <param name="separator">The separator to use. If none specified, the elements should appear separated by a new line.</param>
/// <returns>A string assembled by wrapping the string descriptions of the individual
/// pairs with square brackets and separating them with commas.
/// Each key-value pair is represented as the string description of the key followed by
/// the string description of the value,
/// separated by " -> ", and enclosed in curly brackets.</returns>
public static string DictionaryToString<T1, T2>(ICollection<KeyValuePair<T1, T2>> dict, Func<T2, string> toString = null, string separator = null)
{
if (dict == null || dict.Count == 0)
{
return "[]";
}
if (separator == null)
{
separator = Environment.NewLine;
}
var sb = new StringBuilder("[");
var enumerator = dict.GetEnumerator();
int index = 0;
while (enumerator.MoveNext())
{
var pair = enumerator.Current;
sb.Append("{");
sb.Append(pair.Key);
sb.Append(" -> ");
string val;
if (toString != null)
val = toString(pair.Value);
else
val = pair.Value == null ? "null" : pair.Value.ToString();
sb.Append(val);
sb.Append("}");
if (index++ < dict.Count - 1)
sb.Append(separator);
}
sb.Append("]");
return sb.ToString();
}
public static string TimeSpanToString(TimeSpan timeSpan)
{
//00:03:32.8289777
return String.Format("{0}h:{1}m:{2}s.{3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
}
public static long TicksToMilliSeconds(long ticks) => ticks / TimeSpan.TicksPerMillisecond;
public static float AverageTicksToMilliSeconds(float ticks) => ticks / TimeSpan.TicksPerMillisecond;
/// <summary>
/// Parse a Uri as an IPEndpoint.
/// </summary>
/// <param name="uri">The input Uri</param>
/// <returns></returns>
public static System.Net.IPEndPoint ToIPEndPoint(this Uri uri)
{
switch (uri.Scheme)
{
case "gwy.tcp":
return new System.Net.IPEndPoint(System.Net.IPAddress.Parse(uri.Host), uri.Port);
}
return null;
}
/// <summary>
/// Parse a Uri as a Silo address, excluding the generation identifier.
/// </summary>
/// <param name="uri">The input Uri</param>
public static SiloAddress ToGatewayAddress(this Uri uri)
{
switch (uri.Scheme)
{
case "gwy.tcp":
return SiloAddress.New(uri.ToIPEndPoint(), 0);
}
return null;
}
/// <summary>
/// Represent an IP end point in the gateway URI format..
/// </summary>
/// <param name="ep">The input IP end point</param>
/// <returns></returns>
public static Uri ToGatewayUri(this System.Net.IPEndPoint ep) => new Uri("gwy.tcp://" + ep.ToString() + "/0");
/// <summary>
/// Represent a silo address in the gateway URI format.
/// </summary>
/// <param name="address">The input silo address</param>
/// <returns></returns>
public static Uri ToGatewayUri(this SiloAddress address) => new Uri("gwy.tcp://" + address.Endpoint.ToString() + "/" + address.Generation.ToString());
/// <summary>
/// Calculates an integer hash value based on the consistent identity hash of a string.
/// </summary>
/// <param name="text">The string to hash.</param>
/// <returns>An integer hash for the string.</returns>
public static int CalculateIdHash(string text)
{
var input = BitConverter.IsLittleEndian ? MemoryMarshal.AsBytes(text.AsSpan()) : Encoding.Unicode.GetBytes(text);
Span<int> result = stackalloc int[256 / 8 / sizeof(int)];
var sha = SHA256.Create();
sha.TryComputeHash(input, MemoryMarshal.AsBytes(result), out _);
sha.Dispose();
var hash = 0;
for (var i = 0; i < result.Length; i++) hash ^= result[i];
return BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(hash) : hash;
}
/// <summary>
/// Calculates a Guid hash value based on the consistent identity a string.
/// </summary>
/// <param name="text">The string to hash.</param>
/// <returns>An integer hash for the string.</returns>
internal static Guid CalculateGuidHash(string text)
{
var input = BitConverter.IsLittleEndian ? MemoryMarshal.AsBytes(text.AsSpan()) : Encoding.Unicode.GetBytes(text);
Span<byte> result = stackalloc byte[256 / 8];
var sha = SHA256.Create();
sha.TryComputeHash(input, result, out _);
sha.Dispose();
MemoryMarshal.AsRef<long>(result) ^= MemoryMarshal.Read<long>(result.Slice(16));
MemoryMarshal.AsRef<long>(result.Slice(8)) ^= MemoryMarshal.Read<long>(result.Slice(24));
return BitConverter.IsLittleEndian ? MemoryMarshal.Read<Guid>(result) : new Guid(result.Slice(0, 16));
}
public static void SafeExecute(Action action, ILogger logger = null, string caller = null)
{
SafeExecute(action, logger, (object)caller);
}
// a function to safely execute an action without any exception being thrown.
// callerGetter function is called only in faulty case (now string is generated in the success case).
public static void SafeExecute(Action action, ILogger logger, Func<string> callerGetter) => SafeExecute(action, logger, (object)callerGetter);
private static void SafeExecute(Action action, ILogger logger, object callerGetter)
{
try
{
action();
}
catch (Exception exc)
{
if (logger != null)
{
try
{
string caller = null;
switch (callerGetter)
{
case string value:
caller = value;
break;
case Func<string> func:
try
{
caller = func();
}
catch
{
}
break;
}
foreach (var e in exc.FlattenAggregate())
{
logger.Warn(ErrorCode.Runtime_Error_100325,
$"Ignoring {e.GetType().FullName} exception thrown from an action called by {caller ?? String.Empty}.", exc);
}
}
catch
{
// now really, really ignore.
}
}
}
}
public static TimeSpan Since(DateTime start)
{
return DateTime.UtcNow.Subtract(start);
}
public static List<Exception> FlattenAggregate(this Exception exc)
{
var result = new List<Exception>();
if (exc is AggregateException)
result.AddRange(exc.InnerException.FlattenAggregate());
else
result.Add(exc);
return result;
}
/// <summary>
/// </summary>
public static IEnumerable<List<T>> BatchIEnumerable<T>(this IEnumerable<T> sequence, int batchSize)
{
var batch = new List<T>(batchSize);
foreach (var item in sequence)
{
batch.Add(item);
// when we've accumulated enough in the batch, send it out
if (batch.Count >= batchSize)
{
yield return batch; // batch.ToArray();
batch = new List<T>(batchSize);
}
}
if (batch.Count > 0)
{
yield return batch; //batch.ToArray();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetStackTrace(int skipFrames = 0)
{
skipFrames += 1; //skip this method from the stack trace
return new System.Diagnostics.StackTrace(skipFrames).ToString();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SqlConnectionStringBuilder.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Diagnostics.CodeAnalysis;
namespace System.Data.SqlClient {
[DefaultProperty("DataSource")]
[System.ComponentModel.TypeConverterAttribute(typeof(SqlConnectionStringBuilder.SqlConnectionStringBuilderConverter))]
public sealed class SqlConnectionStringBuilder : DbConnectionStringBuilder {
private enum Keywords { // specific ordering for ConnectionString output construction
// NamedConnection,
DataSource,
FailoverPartner,
AttachDBFilename,
InitialCatalog,
IntegratedSecurity,
PersistSecurityInfo,
UserID,
Password,
Enlist,
Pooling,
MinPoolSize,
MaxPoolSize,
AsynchronousProcessing,
ConnectionReset,
MultipleActiveResultSets,
Replication,
ConnectTimeout,
Encrypt,
TrustServerCertificate,
LoadBalanceTimeout,
NetworkLibrary,
PacketSize,
TypeSystemVersion,
ApplicationName,
CurrentLanguage,
WorkstationID,
UserInstance,
ContextConnection,
TransactionBinding,
ApplicationIntent,
MultiSubnetFailover,
TransparentNetworkIPResolution,
ConnectRetryCount,
ConnectRetryInterval,
// keep the count value last
KeywordsCount
}
internal const int KeywordsCount = (int)Keywords.KeywordsCount;
private static readonly string[] _validKeywords;
private static readonly Dictionary<string,Keywords> _keywords;
private ApplicationIntent _applicationIntent = DbConnectionStringDefaults.ApplicationIntent;
private string _applicationName = DbConnectionStringDefaults.ApplicationName;
private string _attachDBFilename = DbConnectionStringDefaults.AttachDBFilename;
private string _currentLanguage = DbConnectionStringDefaults.CurrentLanguage;
private string _dataSource = DbConnectionStringDefaults.DataSource;
private string _failoverPartner = DbConnectionStringDefaults.FailoverPartner;
private string _initialCatalog = DbConnectionStringDefaults.InitialCatalog;
// private string _namedConnection = DbConnectionStringDefaults.NamedConnection;
private string _networkLibrary = DbConnectionStringDefaults.NetworkLibrary;
private string _password = DbConnectionStringDefaults.Password;
private string _transactionBinding = DbConnectionStringDefaults.TransactionBinding;
private string _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion;
private string _userID = DbConnectionStringDefaults.UserID;
private string _workstationID = DbConnectionStringDefaults.WorkstationID;
private int _connectTimeout = DbConnectionStringDefaults.ConnectTimeout;
private int _loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout;
private int _maxPoolSize = DbConnectionStringDefaults.MaxPoolSize;
private int _minPoolSize = DbConnectionStringDefaults.MinPoolSize;
private int _packetSize = DbConnectionStringDefaults.PacketSize;
private int _connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount;
private int _connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval;
private bool _asynchronousProcessing = DbConnectionStringDefaults.AsynchronousProcessing;
private bool _connectionReset = DbConnectionStringDefaults.ConnectionReset;
private bool _contextConnection = DbConnectionStringDefaults.ContextConnection;
private bool _encrypt = DbConnectionStringDefaults.Encrypt;
private bool _trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate;
private bool _enlist = DbConnectionStringDefaults.Enlist;
private bool _integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity;
private bool _multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets;
private bool _multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
private bool _transparentNetworkIPResolution= DbConnectionStringDefaults.TransparentNetworkIPResolution;
private bool _persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
private bool _pooling = DbConnectionStringDefaults.Pooling;
private bool _replication = DbConnectionStringDefaults.Replication;
private bool _userInstance = DbConnectionStringDefaults.UserInstance;
private SqlAuthenticationMethod _authentication = DbConnectionStringDefaults.Authentication;
private SqlConnectionColumnEncryptionSetting _columnEncryptionSetting = DbConnectionStringDefaults.ColumnEncryptionSetting;
static SqlConnectionStringBuilder() {
string[] validKeywords = new string[KeywordsCount];
validKeywords[(int)Keywords.ApplicationIntent] = DbConnectionStringKeywords.ApplicationIntent;
validKeywords[(int)Keywords.ApplicationName] = DbConnectionStringKeywords.ApplicationName;
validKeywords[(int)Keywords.AsynchronousProcessing] = DbConnectionStringKeywords.AsynchronousProcessing;
validKeywords[(int)Keywords.AttachDBFilename] = DbConnectionStringKeywords.AttachDBFilename;
validKeywords[(int)Keywords.ConnectionReset] = DbConnectionStringKeywords.ConnectionReset;
validKeywords[(int)Keywords.ContextConnection] = DbConnectionStringKeywords.ContextConnection;
validKeywords[(int)Keywords.ConnectTimeout] = DbConnectionStringKeywords.ConnectTimeout;
validKeywords[(int)Keywords.CurrentLanguage] = DbConnectionStringKeywords.CurrentLanguage;
validKeywords[(int)Keywords.DataSource] = DbConnectionStringKeywords.DataSource;
validKeywords[(int)Keywords.Encrypt] = DbConnectionStringKeywords.Encrypt;
validKeywords[(int)Keywords.Enlist] = DbConnectionStringKeywords.Enlist;
validKeywords[(int)Keywords.FailoverPartner] = DbConnectionStringKeywords.FailoverPartner;
validKeywords[(int)Keywords.InitialCatalog] = DbConnectionStringKeywords.InitialCatalog;
validKeywords[(int)Keywords.IntegratedSecurity] = DbConnectionStringKeywords.IntegratedSecurity;
validKeywords[(int)Keywords.LoadBalanceTimeout] = DbConnectionStringKeywords.LoadBalanceTimeout;
validKeywords[(int)Keywords.MaxPoolSize] = DbConnectionStringKeywords.MaxPoolSize;
validKeywords[(int)Keywords.MinPoolSize] = DbConnectionStringKeywords.MinPoolSize;
validKeywords[(int)Keywords.MultipleActiveResultSets] = DbConnectionStringKeywords.MultipleActiveResultSets;
validKeywords[(int)Keywords.MultiSubnetFailover] = DbConnectionStringKeywords.MultiSubnetFailover;
validKeywords[(int)Keywords.TransparentNetworkIPResolution] = DbConnectionStringKeywords.TransparentNetworkIPResolution;
// validKeywords[(int)Keywords.NamedConnection] = DbConnectionStringKeywords.NamedConnection;
validKeywords[(int)Keywords.NetworkLibrary] = DbConnectionStringKeywords.NetworkLibrary;
validKeywords[(int)Keywords.PacketSize] = DbConnectionStringKeywords.PacketSize;
validKeywords[(int)Keywords.Password] = DbConnectionStringKeywords.Password;
validKeywords[(int)Keywords.PersistSecurityInfo] = DbConnectionStringKeywords.PersistSecurityInfo;
validKeywords[(int)Keywords.Pooling] = DbConnectionStringKeywords.Pooling;
validKeywords[(int)Keywords.Replication] = DbConnectionStringKeywords.Replication;
validKeywords[(int)Keywords.TransactionBinding] = DbConnectionStringKeywords.TransactionBinding;
validKeywords[(int)Keywords.TrustServerCertificate] = DbConnectionStringKeywords.TrustServerCertificate;
validKeywords[(int)Keywords.TypeSystemVersion] = DbConnectionStringKeywords.TypeSystemVersion;
validKeywords[(int)Keywords.UserID] = DbConnectionStringKeywords.UserID;
validKeywords[(int)Keywords.UserInstance] = DbConnectionStringKeywords.UserInstance;
validKeywords[(int)Keywords.WorkstationID] = DbConnectionStringKeywords.WorkstationID;
validKeywords[(int)Keywords.ConnectRetryCount] = DbConnectionStringKeywords.ConnectRetryCount;
validKeywords[(int)Keywords.ConnectRetryInterval] = DbConnectionStringKeywords.ConnectRetryInterval;
validKeywords[(int)Keywords.Authentication] = DbConnectionStringKeywords.Authentication;
validKeywords[(int)Keywords.ColumnEncryptionSetting] = DbConnectionStringKeywords.ColumnEncryptionSetting;
_validKeywords = validKeywords;
Dictionary<string, Keywords> hash = new Dictionary<string, Keywords>(KeywordsCount + SqlConnectionString.SynonymCount, StringComparer.OrdinalIgnoreCase);
hash.Add(DbConnectionStringKeywords.ApplicationIntent, Keywords.ApplicationIntent);
hash.Add(DbConnectionStringKeywords.ApplicationName, Keywords.ApplicationName);
hash.Add(DbConnectionStringKeywords.AsynchronousProcessing, Keywords.AsynchronousProcessing);
hash.Add(DbConnectionStringKeywords.AttachDBFilename, Keywords.AttachDBFilename);
hash.Add(DbConnectionStringKeywords.ConnectTimeout, Keywords.ConnectTimeout);
hash.Add(DbConnectionStringKeywords.ConnectionReset, Keywords.ConnectionReset);
hash.Add(DbConnectionStringKeywords.ContextConnection, Keywords.ContextConnection);
hash.Add(DbConnectionStringKeywords.CurrentLanguage, Keywords.CurrentLanguage);
hash.Add(DbConnectionStringKeywords.DataSource, Keywords.DataSource);
hash.Add(DbConnectionStringKeywords.Encrypt, Keywords.Encrypt);
hash.Add(DbConnectionStringKeywords.Enlist, Keywords.Enlist);
hash.Add(DbConnectionStringKeywords.FailoverPartner, Keywords.FailoverPartner);
hash.Add(DbConnectionStringKeywords.InitialCatalog, Keywords.InitialCatalog);
hash.Add(DbConnectionStringKeywords.IntegratedSecurity, Keywords.IntegratedSecurity);
hash.Add(DbConnectionStringKeywords.LoadBalanceTimeout, Keywords.LoadBalanceTimeout);
hash.Add(DbConnectionStringKeywords.MultipleActiveResultSets, Keywords.MultipleActiveResultSets);
hash.Add(DbConnectionStringKeywords.MaxPoolSize, Keywords.MaxPoolSize);
hash.Add(DbConnectionStringKeywords.MinPoolSize, Keywords.MinPoolSize);
hash.Add(DbConnectionStringKeywords.MultiSubnetFailover, Keywords.MultiSubnetFailover);
hash.Add(DbConnectionStringKeywords.TransparentNetworkIPResolution, Keywords.TransparentNetworkIPResolution);
// hash.Add(DbConnectionStringKeywords.NamedConnection, Keywords.NamedConnection);
hash.Add(DbConnectionStringKeywords.NetworkLibrary, Keywords.NetworkLibrary);
hash.Add(DbConnectionStringKeywords.PacketSize, Keywords.PacketSize);
hash.Add(DbConnectionStringKeywords.Password, Keywords.Password);
hash.Add(DbConnectionStringKeywords.PersistSecurityInfo, Keywords.PersistSecurityInfo);
hash.Add(DbConnectionStringKeywords.Pooling, Keywords.Pooling);
hash.Add(DbConnectionStringKeywords.Replication, Keywords.Replication);
hash.Add(DbConnectionStringKeywords.TransactionBinding, Keywords.TransactionBinding);
hash.Add(DbConnectionStringKeywords.TrustServerCertificate, Keywords.TrustServerCertificate);
hash.Add(DbConnectionStringKeywords.TypeSystemVersion, Keywords.TypeSystemVersion);
hash.Add(DbConnectionStringKeywords.UserID, Keywords.UserID);
hash.Add(DbConnectionStringKeywords.UserInstance, Keywords.UserInstance);
hash.Add(DbConnectionStringKeywords.WorkstationID, Keywords.WorkstationID);
hash.Add(DbConnectionStringKeywords.ConnectRetryCount, Keywords.ConnectRetryCount);
hash.Add(DbConnectionStringKeywords.ConnectRetryInterval, Keywords.ConnectRetryInterval);
hash.Add(DbConnectionStringKeywords.Authentication, Keywords.Authentication);
hash.Add(DbConnectionStringKeywords.ColumnEncryptionSetting, Keywords.ColumnEncryptionSetting);
hash.Add(DbConnectionStringSynonyms.APP, Keywords.ApplicationName);
hash.Add(DbConnectionStringSynonyms.Async, Keywords.AsynchronousProcessing);
hash.Add(DbConnectionStringSynonyms.EXTENDEDPROPERTIES, Keywords.AttachDBFilename);
hash.Add(DbConnectionStringSynonyms.INITIALFILENAME, Keywords.AttachDBFilename);
hash.Add(DbConnectionStringSynonyms.CONNECTIONTIMEOUT, Keywords.ConnectTimeout);
hash.Add(DbConnectionStringSynonyms.TIMEOUT, Keywords.ConnectTimeout);
hash.Add(DbConnectionStringSynonyms.LANGUAGE, Keywords.CurrentLanguage);
hash.Add(DbConnectionStringSynonyms.ADDR, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.ADDRESS, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.NETWORKADDRESS, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.SERVER, Keywords.DataSource);
hash.Add(DbConnectionStringSynonyms.DATABASE, Keywords.InitialCatalog);
hash.Add(DbConnectionStringSynonyms.TRUSTEDCONNECTION, Keywords.IntegratedSecurity);
hash.Add(DbConnectionStringSynonyms.ConnectionLifetime, Keywords.LoadBalanceTimeout);
hash.Add(DbConnectionStringSynonyms.NET, Keywords.NetworkLibrary);
hash.Add(DbConnectionStringSynonyms.NETWORK, Keywords.NetworkLibrary);
hash.Add(DbConnectionStringSynonyms.Pwd, Keywords.Password);
hash.Add(DbConnectionStringSynonyms.PERSISTSECURITYINFO, Keywords.PersistSecurityInfo);
hash.Add(DbConnectionStringSynonyms.UID, Keywords.UserID);
hash.Add(DbConnectionStringSynonyms.User, Keywords.UserID);
hash.Add(DbConnectionStringSynonyms.WSID, Keywords.WorkstationID);
Debug.Assert((KeywordsCount + SqlConnectionString.SynonymCount) == hash.Count, "initial expected size is incorrect");
_keywords = hash;
}
public SqlConnectionStringBuilder() : this((string)null) {
}
public SqlConnectionStringBuilder(string connectionString) : base() {
if (!ADP.IsEmpty(connectionString)) {
ConnectionString = connectionString;
}
}
public override object this[string keyword] {
get {
Keywords index = GetIndex(keyword);
return GetAt(index);
}
set {
if (null != value) {
Keywords index = GetIndex(keyword);
switch(index) {
case Keywords.ApplicationIntent: this.ApplicationIntent = ConvertToApplicationIntent(keyword, value); break;
case Keywords.ApplicationName: ApplicationName = ConvertToString(value); break;
case Keywords.AttachDBFilename: AttachDBFilename = ConvertToString(value); break;
case Keywords.CurrentLanguage: CurrentLanguage = ConvertToString(value); break;
case Keywords.DataSource: DataSource = ConvertToString(value); break;
case Keywords.FailoverPartner: FailoverPartner = ConvertToString(value); break;
case Keywords.InitialCatalog: InitialCatalog = ConvertToString(value); break;
// case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break;
case Keywords.NetworkLibrary: NetworkLibrary = ConvertToString(value); break;
case Keywords.Password: Password = ConvertToString(value); break;
case Keywords.UserID: UserID = ConvertToString(value); break;
case Keywords.TransactionBinding: TransactionBinding = ConvertToString(value); break;
case Keywords.TypeSystemVersion: TypeSystemVersion = ConvertToString(value); break;
case Keywords.WorkstationID: WorkstationID = ConvertToString(value); break;
case Keywords.ConnectTimeout: ConnectTimeout = ConvertToInt32(value); break;
case Keywords.LoadBalanceTimeout: LoadBalanceTimeout = ConvertToInt32(value); break;
case Keywords.MaxPoolSize: MaxPoolSize = ConvertToInt32(value); break;
case Keywords.MinPoolSize: MinPoolSize = ConvertToInt32(value); break;
case Keywords.PacketSize: PacketSize = ConvertToInt32(value); break;
case Keywords.IntegratedSecurity: IntegratedSecurity = ConvertToIntegratedSecurity(value); break;
case Keywords.Authentication: Authentication = ConvertToAuthenticationType(keyword, value); break;
case Keywords.ColumnEncryptionSetting: ColumnEncryptionSetting = ConvertToColumnEncryptionSetting(keyword, value); break;
case Keywords.AsynchronousProcessing: AsynchronousProcessing = ConvertToBoolean(value); break;
#pragma warning disable 618 // Obsolete ConnectionReset
case Keywords.ConnectionReset: ConnectionReset = ConvertToBoolean(value); break;
#pragma warning restore 618
case Keywords.ContextConnection: ContextConnection = ConvertToBoolean(value); break;
case Keywords.Encrypt: Encrypt = ConvertToBoolean(value); break;
case Keywords.TrustServerCertificate: TrustServerCertificate = ConvertToBoolean(value); break;
case Keywords.Enlist: Enlist = ConvertToBoolean(value); break;
case Keywords.MultipleActiveResultSets: MultipleActiveResultSets = ConvertToBoolean(value); break;
case Keywords.MultiSubnetFailover: MultiSubnetFailover = ConvertToBoolean(value); break;
case Keywords.TransparentNetworkIPResolution: TransparentNetworkIPResolution = ConvertToBoolean(value); break;
case Keywords.PersistSecurityInfo: PersistSecurityInfo = ConvertToBoolean(value); break;
case Keywords.Pooling: Pooling = ConvertToBoolean(value); break;
case Keywords.Replication: Replication = ConvertToBoolean(value); break;
case Keywords.UserInstance: UserInstance = ConvertToBoolean(value); break;
case Keywords.ConnectRetryCount: ConnectRetryCount = ConvertToInt32(value); break;
case Keywords.ConnectRetryInterval: ConnectRetryInterval = ConvertToInt32(value); break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(keyword);
}
}
else {
Remove(keyword);
}
}
}
[DisplayName(DbConnectionStringKeywords.ApplicationIntent)]
[ResCategoryAttribute(Res.DataCategory_Initialization)]
[ResDescriptionAttribute(Res.DbConnectionString_ApplicationIntent)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public ApplicationIntent ApplicationIntent {
get { return _applicationIntent; }
set {
if (!DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value)) {
throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)value);
}
SetApplicationIntentValue(value);
_applicationIntent = value;
}
}
[DisplayName(DbConnectionStringKeywords.ApplicationName)]
[ResCategoryAttribute(Res.DataCategory_Context)]
[ResDescriptionAttribute(Res.DbConnectionString_ApplicationName)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string ApplicationName {
get { return _applicationName; }
set {
SetValue(DbConnectionStringKeywords.ApplicationName, value);
_applicationName = value;
}
}
[DisplayName(DbConnectionStringKeywords.AsynchronousProcessing)]
[ResCategoryAttribute(Res.DataCategory_Initialization)]
[ResDescriptionAttribute(Res.DbConnectionString_AsynchronousProcessing)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool AsynchronousProcessing {
get { return _asynchronousProcessing; }
set {
SetValue(DbConnectionStringKeywords.AsynchronousProcessing, value);
_asynchronousProcessing = value;
}
}
[DisplayName(DbConnectionStringKeywords.AttachDBFilename)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_AttachDBFilename)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
//
[Editor("System.Windows.Forms.Design.FileNameEditor, " + AssemblyRef.SystemDesign, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing)]
public string AttachDBFilename {
get { return _attachDBFilename; }
set {
SetValue(DbConnectionStringKeywords.AttachDBFilename, value);
_attachDBFilename = value;
}
}
[Browsable(false)]
[DisplayName(DbConnectionStringKeywords.ConnectionReset)]
[Obsolete("ConnectionReset has been deprecated. SqlConnection will ignore the 'connection reset' keyword and always reset the connection")] // SQLPT 41700
[ResCategoryAttribute(Res.DataCategory_Pooling)]
[ResDescriptionAttribute(Res.DbConnectionString_ConnectionReset)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool ConnectionReset {
get { return _connectionReset; }
set {
SetValue(DbConnectionStringKeywords.ConnectionReset, value);
_connectionReset = value;
}
}
[DisplayName(DbConnectionStringKeywords.ContextConnection)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_ContextConnection)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool ContextConnection {
get { return _contextConnection; }
set {
SetValue(DbConnectionStringKeywords.ContextConnection, value);
_contextConnection = value;
}
}
[DisplayName(DbConnectionStringKeywords.ConnectTimeout)]
[ResCategoryAttribute(Res.DataCategory_Initialization)]
[ResDescriptionAttribute(Res.DbConnectionString_ConnectTimeout)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public int ConnectTimeout {
get { return _connectTimeout; }
set {
if (value < 0) {
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectTimeout);
}
SetValue(DbConnectionStringKeywords.ConnectTimeout, value);
_connectTimeout = value;
}
}
[DisplayName(DbConnectionStringKeywords.CurrentLanguage)]
[ResCategoryAttribute(Res.DataCategory_Initialization)]
[ResDescriptionAttribute(Res.DbConnectionString_CurrentLanguage)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string CurrentLanguage {
get { return _currentLanguage; }
set {
SetValue(DbConnectionStringKeywords.CurrentLanguage, value);
_currentLanguage = value;
}
}
[DisplayName(DbConnectionStringKeywords.DataSource)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_DataSource)]
[RefreshProperties(RefreshProperties.All)]
[TypeConverter(typeof(SqlDataSourceConverter))]
public string DataSource {
get { return _dataSource; }
set {
SetValue(DbConnectionStringKeywords.DataSource, value);
_dataSource = value;
}
}
[DisplayName(DbConnectionStringKeywords.Encrypt)]
[ResCategoryAttribute(Res.DataCategory_Security)]
[ResDescriptionAttribute(Res.DbConnectionString_Encrypt)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool Encrypt {
get { return _encrypt; }
set {
SetValue(DbConnectionStringKeywords.Encrypt, value);
_encrypt = value;
}
}
[DisplayName(DbConnectionStringKeywords.TrustServerCertificate)]
[ResCategoryAttribute(Res.DataCategory_Security)]
[ResDescriptionAttribute(Res.DbConnectionString_TrustServerCertificate)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool TrustServerCertificate {
get { return _trustServerCertificate; }
set {
SetValue(DbConnectionStringKeywords.TrustServerCertificate, value);
_trustServerCertificate = value;
}
}
[DisplayName(DbConnectionStringKeywords.Enlist)]
[ResCategoryAttribute(Res.DataCategory_Pooling)]
[ResDescriptionAttribute(Res.DbConnectionString_Enlist)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool Enlist {
get { return _enlist; }
set {
SetValue(DbConnectionStringKeywords.Enlist, value);
_enlist = value;
}
}
[DisplayName(DbConnectionStringKeywords.FailoverPartner)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_FailoverPartner)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(SqlDataSourceConverter))]
public string FailoverPartner {
get { return _failoverPartner; }
set {
SetValue(DbConnectionStringKeywords.FailoverPartner, value);
_failoverPartner= value;
}
}
[DisplayName(DbConnectionStringKeywords.InitialCatalog)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_InitialCatalog)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(SqlInitialCatalogConverter))]
public string InitialCatalog {
get { return _initialCatalog; }
set {
SetValue(DbConnectionStringKeywords.InitialCatalog, value);
_initialCatalog = value;
}
}
[DisplayName(DbConnectionStringKeywords.IntegratedSecurity)]
[ResCategoryAttribute(Res.DataCategory_Security)]
[ResDescriptionAttribute(Res.DbConnectionString_IntegratedSecurity)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool IntegratedSecurity {
get { return _integratedSecurity; }
set {
SetValue(DbConnectionStringKeywords.IntegratedSecurity, value);
_integratedSecurity = value;
}
}
[DisplayName(DbConnectionStringKeywords.LoadBalanceTimeout)]
[ResCategoryAttribute(Res.DataCategory_Pooling)]
[ResDescriptionAttribute(Res.DbConnectionString_LoadBalanceTimeout)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public int LoadBalanceTimeout {
get { return _loadBalanceTimeout; }
set {
if (value < 0) {
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.LoadBalanceTimeout);
}
SetValue(DbConnectionStringKeywords.LoadBalanceTimeout, value);
_loadBalanceTimeout = value;
}
}
[DisplayName(DbConnectionStringKeywords.MaxPoolSize)]
[ResCategoryAttribute(Res.DataCategory_Pooling)]
[ResDescriptionAttribute(Res.DbConnectionString_MaxPoolSize)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public int MaxPoolSize {
get { return _maxPoolSize; }
set {
if (value < 1) {
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MaxPoolSize);
}
SetValue(DbConnectionStringKeywords.MaxPoolSize, value);
_maxPoolSize = value;
}
}
[DisplayName(DbConnectionStringKeywords.ConnectRetryCount)]
[ResCategoryAttribute(Res.DataCategory_ConnectionResilency)]
[ResDescriptionAttribute(Res.DbConnectionString_ConnectRetryCount)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public int ConnectRetryCount {
get { return _connectRetryCount; }
set {
if ((value < 0) || (value>255)) {
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryCount);
}
SetValue(DbConnectionStringKeywords.ConnectRetryCount, value);
_connectRetryCount = value;
}
}
[DisplayName(DbConnectionStringKeywords.ConnectRetryInterval)]
[ResCategoryAttribute(Res.DataCategory_ConnectionResilency)]
[ResDescriptionAttribute(Res.DbConnectionString_ConnectRetryInterval)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public int ConnectRetryInterval {
get { return _connectRetryInterval; }
set {
if ((value < 1) || (value > 60)) {
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.ConnectRetryInterval);
}
SetValue(DbConnectionStringKeywords.ConnectRetryInterval, value);
_connectRetryInterval = value;
}
}
[DisplayName(DbConnectionStringKeywords.MinPoolSize)]
[ResCategoryAttribute(Res.DataCategory_Pooling)]
[ResDescriptionAttribute(Res.DbConnectionString_MinPoolSize)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public int MinPoolSize {
get { return _minPoolSize; }
set {
if (value < 0) {
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.MinPoolSize);
}
SetValue(DbConnectionStringKeywords.MinPoolSize, value);
_minPoolSize = value;
}
}
[DisplayName(DbConnectionStringKeywords.MultipleActiveResultSets)]
[ResCategoryAttribute(Res.DataCategory_Advanced)]
[ResDescriptionAttribute(Res.DbConnectionString_MultipleActiveResultSets)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool MultipleActiveResultSets {
get { return _multipleActiveResultSets; }
set {
SetValue(DbConnectionStringKeywords.MultipleActiveResultSets, value);
_multipleActiveResultSets = value;
}
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Reviewed and Approved by UE")]
[DisplayName(DbConnectionStringKeywords.MultiSubnetFailover)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_MultiSubnetFailover)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool MultiSubnetFailover {
get { return _multiSubnetFailover; }
set {
SetValue(DbConnectionStringKeywords.MultiSubnetFailover, value);
_multiSubnetFailover = value;
}
}
[DisplayName(DbConnectionStringKeywords.TransparentNetworkIPResolution)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_TransparentNetworkIPResolution)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool TransparentNetworkIPResolution
{
get { return _transparentNetworkIPResolution; }
set {
SetValue(DbConnectionStringKeywords.TransparentNetworkIPResolution, value);
_transparentNetworkIPResolution = value;
}
}
/*
[DisplayName(DbConnectionStringKeywords.NamedConnection)]
[ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
[ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(NamedConnectionStringConverter))]
public string NamedConnection {
get { return _namedConnection; }
set {
SetValue(DbConnectionStringKeywords.NamedConnection, value);
_namedConnection = value;
}
}
*/
[DisplayName(DbConnectionStringKeywords.NetworkLibrary)]
[ResCategoryAttribute(Res.DataCategory_Advanced)]
[ResDescriptionAttribute(Res.DbConnectionString_NetworkLibrary)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(NetworkLibraryConverter))]
public string NetworkLibrary {
get { return _networkLibrary; }
set {
if (null != value) {
switch(value.Trim().ToLower(CultureInfo.InvariantCulture)) {
case SqlConnectionString.NETLIB.AppleTalk:
value = SqlConnectionString.NETLIB.AppleTalk;
break;
case SqlConnectionString.NETLIB.BanyanVines:
value = SqlConnectionString.NETLIB.BanyanVines;
break;
case SqlConnectionString.NETLIB.IPXSPX:
value = SqlConnectionString.NETLIB.IPXSPX;
break;
case SqlConnectionString.NETLIB.Multiprotocol:
value = SqlConnectionString.NETLIB.Multiprotocol;
break;
case SqlConnectionString.NETLIB.NamedPipes:
value = SqlConnectionString.NETLIB.NamedPipes;
break;
case SqlConnectionString.NETLIB.SharedMemory:
value = SqlConnectionString.NETLIB.SharedMemory;
break;
case SqlConnectionString.NETLIB.TCPIP:
value = SqlConnectionString.NETLIB.TCPIP;
break;
case SqlConnectionString.NETLIB.VIA:
value = SqlConnectionString.NETLIB.VIA;
break;
default:
throw ADP.InvalidConnectionOptionValue(DbConnectionStringKeywords.NetworkLibrary);
}
}
SetValue(DbConnectionStringKeywords.NetworkLibrary, value);
_networkLibrary = value;
}
}
[DisplayName(DbConnectionStringKeywords.PacketSize)]
[ResCategoryAttribute(Res.DataCategory_Advanced)]
[ResDescriptionAttribute(Res.DbConnectionString_PacketSize)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public int PacketSize {
get { return _packetSize; }
set {
if ((value < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < value)) {
throw SQL.InvalidPacketSizeValue();
}
SetValue(DbConnectionStringKeywords.PacketSize, value);
_packetSize = value;
}
}
[DisplayName(DbConnectionStringKeywords.Password)]
[PasswordPropertyTextAttribute(true)]
[ResCategoryAttribute(Res.DataCategory_Security)]
[ResDescriptionAttribute(Res.DbConnectionString_Password)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string Password {
get { return _password; }
set {
SetValue(DbConnectionStringKeywords.Password, value);
_password = value;
}
}
[DisplayName(DbConnectionStringKeywords.PersistSecurityInfo)]
[ResCategoryAttribute(Res.DataCategory_Security)]
[ResDescriptionAttribute(Res.DbConnectionString_PersistSecurityInfo)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool PersistSecurityInfo {
get { return _persistSecurityInfo; }
set {
SetValue(DbConnectionStringKeywords.PersistSecurityInfo, value);
_persistSecurityInfo = value;
}
}
[DisplayName(DbConnectionStringKeywords.Pooling)]
[ResCategoryAttribute(Res.DataCategory_Pooling)]
[ResDescriptionAttribute(Res.DbConnectionString_Pooling)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool Pooling {
get { return _pooling; }
set {
SetValue(DbConnectionStringKeywords.Pooling, value);
_pooling = value;
}
}
[DisplayName(DbConnectionStringKeywords.Replication)]
[ResCategoryAttribute(Res.DataCategory_Replication)]
[ResDescriptionAttribute(Res.DbConnectionString_Replication )]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool Replication {
get { return _replication; }
set {
SetValue(DbConnectionStringKeywords.Replication, value);
_replication = value;
}
}
[DisplayName(DbConnectionStringKeywords.TransactionBinding)]
[ResCategoryAttribute(Res.DataCategory_Advanced)]
[ResDescriptionAttribute(Res.DbConnectionString_TransactionBinding)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string TransactionBinding {
get { return _transactionBinding; }
set {
SetValue(DbConnectionStringKeywords.TransactionBinding, value);
_transactionBinding = value;
}
}
[DisplayName(DbConnectionStringKeywords.TypeSystemVersion)]
[ResCategoryAttribute(Res.DataCategory_Advanced)]
[ResDescriptionAttribute(Res.DbConnectionString_TypeSystemVersion)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string TypeSystemVersion {
get { return _typeSystemVersion; }
set {
SetValue(DbConnectionStringKeywords.TypeSystemVersion, value);
_typeSystemVersion = value;
}
}
[DisplayName(DbConnectionStringKeywords.UserID)]
[ResCategoryAttribute(Res.DataCategory_Security)]
[ResDescriptionAttribute(Res.DbConnectionString_UserID)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string UserID {
get { return _userID; }
set {
SetValue(DbConnectionStringKeywords.UserID, value);
_userID = value;
}
}
[DisplayName(DbConnectionStringKeywords.UserInstance)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_UserInstance)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public bool UserInstance {
get { return _userInstance; }
set {
SetValue(DbConnectionStringKeywords.UserInstance, value);
_userInstance = value;
}
}
[DisplayName(DbConnectionStringKeywords.WorkstationID)]
[ResCategoryAttribute(Res.DataCategory_Context)]
[ResDescriptionAttribute(Res.DbConnectionString_WorkstationID)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string WorkstationID {
get { return _workstationID; }
set {
SetValue(DbConnectionStringKeywords.WorkstationID, value);
_workstationID = value;
}
}
public override bool IsFixedSize {
get {
return true;
}
}
public override ICollection Keys {
get {
return new System.Data.Common.ReadOnlyCollection<string>(_validKeywords);
}
}
public override ICollection Values {
get {
// written this way so if the ordering of Keywords & _validKeywords changes
// this is one less place to maintain
object[] values = new object[_validKeywords.Length];
for(int i = 0; i < values.Length; ++i) {
values[i] = GetAt((Keywords)i);
}
return new System.Data.Common.ReadOnlyCollection<object>(values);
}
}
public override void Clear() {
base.Clear();
for(int i = 0; i < _validKeywords.Length; ++i) {
Reset((Keywords)i);
}
}
public override bool ContainsKey(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
return _keywords.ContainsKey(keyword);
}
private static bool ConvertToBoolean(object value) {
return DbConnectionStringBuilderUtil.ConvertToBoolean(value);
}
private static int ConvertToInt32(object value) {
return DbConnectionStringBuilderUtil.ConvertToInt32(value);
}
private static bool ConvertToIntegratedSecurity(object value) {
return DbConnectionStringBuilderUtil.ConvertToIntegratedSecurity(value);
}
private static string ConvertToString(object value) {
return DbConnectionStringBuilderUtil.ConvertToString(value);
}
private static ApplicationIntent ConvertToApplicationIntent(string keyword, object value) {
return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(keyword, value);
}
private object GetAt(Keywords index) {
switch(index) {
case Keywords.ApplicationIntent: return this.ApplicationIntent;
case Keywords.ApplicationName: return ApplicationName;
case Keywords.AsynchronousProcessing: return AsynchronousProcessing;
case Keywords.AttachDBFilename: return AttachDBFilename;
case Keywords.ConnectTimeout: return ConnectTimeout;
#pragma warning disable 618 // Obsolete ConnectionReset
case Keywords.ConnectionReset: return ConnectionReset;
#pragma warning restore 618
case Keywords.ContextConnection: return ContextConnection;
case Keywords.CurrentLanguage: return CurrentLanguage;
case Keywords.DataSource: return DataSource;
case Keywords.Encrypt: return Encrypt;
case Keywords.Enlist: return Enlist;
case Keywords.FailoverPartner: return FailoverPartner;
case Keywords.InitialCatalog: return InitialCatalog;
case Keywords.IntegratedSecurity: return IntegratedSecurity;
case Keywords.LoadBalanceTimeout: return LoadBalanceTimeout;
case Keywords.MultipleActiveResultSets: return MultipleActiveResultSets;
case Keywords.MaxPoolSize: return MaxPoolSize;
case Keywords.MinPoolSize: return MinPoolSize;
case Keywords.MultiSubnetFailover: return MultiSubnetFailover;
case Keywords.TransparentNetworkIPResolution: return TransparentNetworkIPResolution;
// case Keywords.NamedConnection: return NamedConnection;
case Keywords.NetworkLibrary: return NetworkLibrary;
case Keywords.PacketSize: return PacketSize;
case Keywords.Password: return Password;
case Keywords.PersistSecurityInfo: return PersistSecurityInfo;
case Keywords.Pooling: return Pooling;
case Keywords.Replication: return Replication;
case Keywords.TransactionBinding: return TransactionBinding;
case Keywords.TrustServerCertificate: return TrustServerCertificate;
case Keywords.TypeSystemVersion: return TypeSystemVersion;
case Keywords.UserID: return UserID;
case Keywords.UserInstance: return UserInstance;
case Keywords.WorkstationID: return WorkstationID;
case Keywords.ConnectRetryCount: return ConnectRetryCount;
case Keywords.ConnectRetryInterval: return ConnectRetryInterval;
case Keywords.Authentication: return Authentication;
case Keywords.ColumnEncryptionSetting: return ColumnEncryptionSetting;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(_validKeywords[(int)index]);
}
}
private Keywords GetIndex(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
return index;
}
throw ADP.KeywordNotSupported(keyword);
}
protected override void GetProperties(Hashtable propertyDescriptors) {
foreach(PropertyDescriptor reflected in TypeDescriptor.GetProperties(this, true)) {
bool refreshOnChange = false;
bool isReadonly = false;
string displayName = reflected.DisplayName;
// 'Password' & 'User ID' will be readonly if 'Integrated Security' is true
if (DbConnectionStringKeywords.IntegratedSecurity == displayName) {
refreshOnChange = true;
isReadonly = reflected.IsReadOnly;
}
else if ((DbConnectionStringKeywords.Password == displayName) ||
(DbConnectionStringKeywords.UserID == displayName)) {
isReadonly = IntegratedSecurity;
}
else {
continue;
}
Attribute[] attributes = GetAttributesFromCollection(reflected.Attributes);
DbConnectionStringBuilderDescriptor descriptor = new DbConnectionStringBuilderDescriptor(reflected.Name,
reflected.ComponentType, reflected.PropertyType, isReadonly, attributes);
descriptor.RefreshOnChange = refreshOnChange;
propertyDescriptors[displayName] = descriptor;
}
base.GetProperties(propertyDescriptors);
}
public override bool Remove(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
if (base.Remove(_validKeywords[(int)index])) {
Reset(index);
return true;
}
}
return false;
}
private void Reset(Keywords index) {
switch(index) {
case Keywords.ApplicationIntent:
_applicationIntent = DbConnectionStringDefaults.ApplicationIntent;
break;
case Keywords.ApplicationName:
_applicationName = DbConnectionStringDefaults.ApplicationName;
break;
case Keywords.AsynchronousProcessing:
_asynchronousProcessing = DbConnectionStringDefaults.AsynchronousProcessing;
break;
case Keywords.AttachDBFilename:
_attachDBFilename = DbConnectionStringDefaults.AttachDBFilename;
break;
case Keywords.ConnectTimeout:
_connectTimeout = DbConnectionStringDefaults.ConnectTimeout;
break;
case Keywords.ConnectionReset:
_connectionReset = DbConnectionStringDefaults.ConnectionReset;
break;
case Keywords.ContextConnection:
_contextConnection = DbConnectionStringDefaults.ContextConnection;
break;
case Keywords.CurrentLanguage:
_currentLanguage = DbConnectionStringDefaults.CurrentLanguage;
break;
case Keywords.DataSource:
_dataSource = DbConnectionStringDefaults.DataSource;
break;
case Keywords.Encrypt:
_encrypt = DbConnectionStringDefaults.Encrypt;
break;
case Keywords.Enlist:
_enlist = DbConnectionStringDefaults.Enlist;
break;
case Keywords.FailoverPartner:
_failoverPartner = DbConnectionStringDefaults.FailoverPartner;
break;
case Keywords.InitialCatalog:
_initialCatalog = DbConnectionStringDefaults.InitialCatalog;
break;
case Keywords.IntegratedSecurity:
_integratedSecurity = DbConnectionStringDefaults.IntegratedSecurity;
break;
case Keywords.LoadBalanceTimeout:
_loadBalanceTimeout = DbConnectionStringDefaults.LoadBalanceTimeout;
break;
case Keywords.MultipleActiveResultSets:
_multipleActiveResultSets = DbConnectionStringDefaults.MultipleActiveResultSets;
break;
case Keywords.MaxPoolSize:
_maxPoolSize = DbConnectionStringDefaults.MaxPoolSize;
break;
case Keywords.MinPoolSize:
_minPoolSize = DbConnectionStringDefaults.MinPoolSize;
break;
case Keywords.MultiSubnetFailover:
_multiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
break;
case Keywords.TransparentNetworkIPResolution:
_transparentNetworkIPResolution = DbConnectionStringDefaults.TransparentNetworkIPResolution;
break;
// case Keywords.NamedConnection:
// _namedConnection = DbConnectionStringDefaults.NamedConnection;
// break;
case Keywords.NetworkLibrary:
_networkLibrary = DbConnectionStringDefaults.NetworkLibrary;
break;
case Keywords.PacketSize:
_packetSize = DbConnectionStringDefaults.PacketSize;
break;
case Keywords.Password:
_password = DbConnectionStringDefaults.Password;
break;
case Keywords.PersistSecurityInfo:
_persistSecurityInfo = DbConnectionStringDefaults.PersistSecurityInfo;
break;
case Keywords.Pooling:
_pooling = DbConnectionStringDefaults.Pooling;
break;
case Keywords.ConnectRetryCount:
_connectRetryCount = DbConnectionStringDefaults.ConnectRetryCount;
break;
case Keywords.ConnectRetryInterval:
_connectRetryInterval = DbConnectionStringDefaults.ConnectRetryInterval;
break;
case Keywords.Replication:
_replication = DbConnectionStringDefaults.Replication;
break;
case Keywords.TransactionBinding:
_transactionBinding = DbConnectionStringDefaults.TransactionBinding;
break;
case Keywords.TrustServerCertificate:
_trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate;
break;
case Keywords.TypeSystemVersion:
_typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion;
break;
case Keywords.UserID:
_userID = DbConnectionStringDefaults.UserID;
break;
case Keywords.UserInstance:
_userInstance = DbConnectionStringDefaults.UserInstance;
break;
case Keywords.WorkstationID:
_workstationID = DbConnectionStringDefaults.WorkstationID;
break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(_validKeywords[(int)index]);
}
}
private void SetValue(string keyword, bool value) {
base[keyword] = value.ToString((System.IFormatProvider)null);
}
private void SetValue(string keyword, int value) {
base[keyword] = value.ToString((System.IFormatProvider)null);
}
private void SetValue(string keyword, string value) {
ADP.CheckArgumentNull(value, keyword);
base[keyword] = value;
}
private void SetApplicationIntentValue(ApplicationIntent value) {
Debug.Assert(DbConnectionStringBuilderUtil.IsValidApplicationIntentValue(value), "invalid value");
base[DbConnectionStringKeywords.ApplicationIntent] = DbConnectionStringBuilderUtil.ApplicationIntentToString(value);
}
public override bool ShouldSerialize(string keyword) {
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
return _keywords.TryGetValue(keyword, out index) && base.ShouldSerialize(_validKeywords[(int)index]);
}
public override bool TryGetValue(string keyword, out object value) {
Keywords index;
if (_keywords.TryGetValue(keyword, out index)) {
value = GetAt(index);
return true;
}
value = null;
return false;
}
private sealed class NetworkLibraryConverter : TypeConverter {
// private const string AppleTalk = "Apple Talk (DBMSADSN)"; Invalid protocals
// private const string BanyanVines = "Banyan VINES (DBMSVINN)";
// private const string IPXSPX = "NWLink IPX/SPX (DBMSSPXN)";
// private const string Multiprotocol = "Multiprotocol (DBMSRPCN)";
private const string NamedPipes = "Named Pipes (DBNMPNTW)"; // valid protocols
private const string SharedMemory = "Shared Memory (DBMSLPCN)";
private const string TCPIP = "TCP/IP (DBMSSOCN)";
private const string VIA = "VIA (DBMSGNET)";
// these are correctly non-static, property grid will cache an instance
private StandardValuesCollection _standardValues;
// converter classes should have public ctor
public NetworkLibraryConverter() {
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
// Only know how to convert from a string
return ((typeof(string) == sourceType) || base.CanConvertFrom(context, sourceType));
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
string svalue = (value as string);
if (null != svalue) {
svalue = svalue.Trim();
if (StringComparer.OrdinalIgnoreCase.Equals(svalue, NamedPipes)) {
return SqlConnectionString.NETLIB.NamedPipes;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, SharedMemory)) {
return SqlConnectionString.NETLIB.SharedMemory;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, TCPIP)) {
return SqlConnectionString.NETLIB.TCPIP;
}
else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, VIA)) {
return SqlConnectionString.NETLIB.VIA;
}
else {
return svalue;
}
}
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
return ((typeof(string) == destinationType) || base.CanConvertTo(context, destinationType));
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
string svalue = (value as string);
if ((null != svalue) && (destinationType == typeof(string))) {
switch(svalue.Trim().ToLower(CultureInfo.InvariantCulture)) {
case SqlConnectionString.NETLIB.NamedPipes:
return NamedPipes;
case SqlConnectionString.NETLIB.SharedMemory:
return SharedMemory;
case SqlConnectionString.NETLIB.TCPIP:
return TCPIP;
case SqlConnectionString.NETLIB.VIA:
return VIA;
default:
return svalue;
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
return false;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
SqlConnectionStringBuilder constr = null;
if (null != context) {
constr = (context.Instance as SqlConnectionStringBuilder);
}
StandardValuesCollection standardValues = _standardValues;
if (null == standardValues) {
string[] names = new string[] {
NamedPipes,
SharedMemory,
TCPIP,
VIA,
};
standardValues = new StandardValuesCollection(names);
_standardValues = standardValues;
}
return standardValues;
}
}
private sealed class SqlDataSourceConverter : StringConverter {
private StandardValuesCollection _standardValues;
// converter classes should have public ctor
public SqlDataSourceConverter() {
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
return false;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
StandardValuesCollection dataSourceNames = _standardValues;
if (null == _standardValues) {
// Get the sources rowset for the SQLOLEDB enumerator
DataTable table = SqlClientFactory.Instance.CreateDataSourceEnumerator().GetDataSources();
DataColumn serverName = table.Columns[System.Data.Sql.SqlDataSourceEnumerator.ServerName];
DataColumn instanceName = table.Columns[System.Data.Sql.SqlDataSourceEnumerator.InstanceName];
DataRowCollection rows = table.Rows;
string[] serverNames = new string[rows.Count];
for(int i = 0; i < serverNames.Length; ++i) {
string server = rows[i][serverName] as string;
string instance = rows[i][instanceName] as string;
if ((null == instance) || (0 == instance.Length) || ("MSSQLSERVER" == instance)) {
serverNames[i] = server;
}
else {
serverNames[i] = server + @"\" + instance;
}
}
Array.Sort<string>(serverNames);
// Create the standard values collection that contains the sources
dataSourceNames = new StandardValuesCollection(serverNames);
_standardValues = dataSourceNames;
}
return dataSourceNames;
}
}
private sealed class SqlInitialCatalogConverter : StringConverter {
// converter classes should have public ctor
public SqlInitialCatalogConverter() {
}
public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
return GetStandardValuesSupportedInternal(context);
}
private bool GetStandardValuesSupportedInternal(ITypeDescriptorContext context) {
// Only say standard values are supported if the connection string has enough
// information set to instantiate a connection and retrieve a list of databases
bool flag = false;
if (null != context) {
SqlConnectionStringBuilder constr = (context.Instance as SqlConnectionStringBuilder);
if (null != constr) {
if ((0 < constr.DataSource.Length) && (constr.IntegratedSecurity || (0 < constr.UserID.Length))) {
flag = true;
}
}
}
return flag;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) {
// Although theoretically this could be true, some people may want to just type in a name
return false;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) {
// There can only be standard values if the connection string is in a state that might
// be able to instantiate a connection
if (GetStandardValuesSupportedInternal(context)) {
// Create an array list to store the database names
List<string> values = new List<string>();
try {
SqlConnectionStringBuilder constr = (SqlConnectionStringBuilder)context.Instance;
// Create a connection
using(SqlConnection connection = new SqlConnection()) {
// Create a basic connection string from current property values
connection.ConnectionString = constr.ConnectionString;
// Try to open the connection
connection.Open();
DataTable databaseTable = connection.GetSchema("DATABASES");
foreach (DataRow row in databaseTable.Rows) {
string dbName = (string)row["database_name"];
values.Add(dbName);
}
}
}
catch(SqlException e) {
ADP.TraceExceptionWithoutRethrow(e);
// silently fail
}
// Return values as a StandardValuesCollection
return new StandardValuesCollection(values);
}
return null;
}
}
sealed internal class SqlConnectionStringBuilderConverter : ExpandableObjectConverter {
// converter classes should have public ctor
public SqlConnectionStringBuilderConverter() {
}
override public bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
override public object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null) {
throw ADP.ArgumentNull("destinationType");
}
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType) {
SqlConnectionStringBuilder obj = (value as SqlConnectionStringBuilder);
if (null != obj) {
return ConvertToInstanceDescriptor(obj);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
private System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToInstanceDescriptor(SqlConnectionStringBuilder options) {
Type[] ctorParams = new Type[] { typeof(string) };
object[] ctorValues = new object[] { options.ConnectionString };
System.Reflection.ConstructorInfo ctor = typeof(SqlConnectionStringBuilder).GetConstructor(ctorParams);
return new System.ComponentModel.Design.Serialization.InstanceDescriptor(ctor, ctorValues);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim 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 Aurora.DataManager;
using Aurora.Simulation.Base;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Services
{
public class AgentInfoService : ConnectorBase, IService, IAgentInfoService
{
#region Declares
protected IAgentInfoConnector m_agentInfoConnector;
protected List<string> m_lockedUsers = new List<string>();
#endregion
#region IService Members
public string Name
{
get { return GetType().Name; }
}
public virtual void Initialize(IConfigSource config, IRegistryCore registry)
{
m_registry = registry;
IConfig handlerConfig = config.Configs["Handlers"];
if (handlerConfig.GetString("AgentInfoHandler", "") != Name)
return;
registry.RegisterModuleInterface<IAgentInfoService>(this);
Init(registry, Name);
}
public virtual void Start(IConfigSource config, IRegistryCore registry)
{
}
public virtual void FinishedStartup()
{
m_agentInfoConnector = DataManager.RequestPlugin<IAgentInfoConnector>();
}
#endregion
#region IAgentInfoService Members
public IAgentInfoService InnerService
{
get { return this; }
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual UserInfo GetUserInfo(string userID)
{
object remoteValue = DoRemote(userID);
if (remoteValue != null || m_doRemoteOnly)
return (UserInfo)remoteValue;
return GetUserInfo(userID, true);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual List<UserInfo> GetUserInfos(List<string> userIDs)
{
object remoteValue = DoRemote(userIDs);
if (remoteValue != null || m_doRemoteOnly)
return (List<UserInfo>)remoteValue;
List<UserInfo> infos = new List<UserInfo>();
for (int i = 0; i < userIDs.Count; i++)
{
var userInfo = GetUserInfo(userIDs[i]);
if(userInfo != null)
infos.Add(userInfo);
}
return infos;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual List<string> GetAgentsLocations(string requestor, List<string> userIDs)
{
string[] infos = new string[userIDs.Count];
for (int i = 0; i < userIDs.Count; i++)
{
UserInfo user = GetUserInfo(userIDs[i]);
if (user != null && user.IsOnline)
{
Interfaces.GridRegion gr =
m_registry.RequestModuleInterface<IGridService>().GetRegionByUUID(null,
user.CurrentRegionID);
if (gr != null)
infos[i] = gr.ServerURI;
else
infos[i] = "NotOnline";
}
else if (user == null)
infos[i] = "NonExistant";
else
infos[i] = "NotOnline";
}
return new List<string>(infos);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual bool SetHomePosition(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt)
{
object remoteValue = DoRemote(userID, homeID, homePosition, homeLookAt);
if (remoteValue != null || m_doRemoteOnly)
return remoteValue == null ? false : (bool)remoteValue;
m_agentInfoConnector.SetHomePosition(userID, homeID, homePosition, homeLookAt);
return true;
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Low)]
public virtual void SetLastPosition(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
{
object remoteValue = DoRemote(userID, regionID, lastPosition, lastLookAt);
if (remoteValue != null || m_doRemoteOnly)
return;
m_agentInfoConnector.SetLastPosition(userID, regionID, lastPosition, lastLookAt);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public virtual void LockLoggedInStatus(string userID, bool locked)
{
object remoteValue = DoRemote(userID, locked);
if (remoteValue != null || m_doRemoteOnly)
return;
if (locked && !m_lockedUsers.Contains(userID))
m_lockedUsers.Add(userID);
else
m_lockedUsers.Remove(userID);
}
[CanBeReflected(ThreatLevel = OpenSim.Services.Interfaces.ThreatLevel.Full)]
public virtual void SetLoggedIn(string userID, bool loggingIn, bool fireLoggedInEvent, UUID enteringRegion)
{
object remoteValue = DoRemote(userID, loggingIn, fireLoggedInEvent, enteringRegion);
if (remoteValue != null || m_doRemoteOnly)
return;
UserInfo userInfo = GetUserInfo(userID, false); //We are changing the status, so don't look
if (userInfo == null)
{
Save(new UserInfo
{
IsOnline = loggingIn,
UserID = userID,
CurrentLookAt = Vector3.Zero,
CurrentPosition = Vector3.Zero,
CurrentRegionID = enteringRegion,
HomeLookAt = Vector3.Zero,
HomePosition = Vector3.Zero,
HomeRegionID = UUID.Zero,
Info = new OSDMap(),
LastLogin = DateTime.Now.ToUniversalTime(),
LastLogout = DateTime.Now.ToUniversalTime(),
});
}
if (m_lockedUsers.Contains(userID)){
return; //User is locked, leave them alone
}
Dictionary<string, object> agentUpdateValues = new Dictionary<string, object>();
agentUpdateValues["IsOnline"] = loggingIn ? 1 : 0;
if (loggingIn)
{
agentUpdateValues["LastLogin"] = Util.ToUnixTime(DateTime.Now.ToUniversalTime());
if (enteringRegion != UUID.Zero)
{
agentUpdateValues["CurrentRegionID"] = enteringRegion;
}
}
else
{
agentUpdateValues["LastLogout"] = Util.ToUnixTime(DateTime.Now.ToUniversalTime());
}
agentUpdateValues["LastSeen"] = Util.ToUnixTime(DateTime.Now.ToUniversalTime());
m_agentInfoConnector.Update(userID, agentUpdateValues);
if (fireLoggedInEvent)
{
//Trigger an event so listeners know
m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler(
"UserStatusChange", new object[] {userID, loggingIn, enteringRegion});
}
}
#endregion
#region Helpers
private UserInfo GetUserInfo(string userID, bool checkForOfflineStatus)
{
bool changed = false;
UserInfo info = m_agentInfoConnector.Get(userID, checkForOfflineStatus, out changed);
if (changed)
if (!m_lockedUsers.Contains(userID))
m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler(
"UserStatusChange", new object[] {userID, false, UUID.Zero});
return info;
}
public virtual void Save(UserInfo userInfo)
{
m_agentInfoConnector.Set(userInfo);
}
#endregion
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gciv = Google.Cloud.Iam.V1;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
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.ArtifactRegistry.V1Beta2.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedArtifactRegistryClientTest
{
[xunit::FactAttribute]
public void GetRepositoryRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository response = client.GetRepository(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRepositoryRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository responseCallSettings = await client.GetRepositoryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Repository responseCancellationToken = await client.GetRepositoryAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRepository()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository response = client.GetRepository(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRepositoryAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository responseCallSettings = await client.GetRepositoryAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Repository responseCancellationToken = await client.GetRepositoryAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRepositoryResourceNames()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository response = client.GetRepository(request.RepositoryName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRepositoryResourceNamesAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository responseCallSettings = await client.GetRepositoryAsync(request.RepositoryName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Repository responseCancellationToken = await client.GetRepositoryAsync(request.RepositoryName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateRepositoryRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateRepositoryRequest request = new UpdateRepositoryRequest
{
Repository = new Repository(),
UpdateMask = new wkt::FieldMask(),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.UpdateRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository response = client.UpdateRepository(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateRepositoryRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateRepositoryRequest request = new UpdateRepositoryRequest
{
Repository = new Repository(),
UpdateMask = new wkt::FieldMask(),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.UpdateRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository responseCallSettings = await client.UpdateRepositoryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Repository responseCancellationToken = await client.UpdateRepositoryAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateRepository()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateRepositoryRequest request = new UpdateRepositoryRequest
{
Repository = new Repository(),
UpdateMask = new wkt::FieldMask(),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.UpdateRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository response = client.UpdateRepository(request.Repository, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateRepositoryAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateRepositoryRequest request = new UpdateRepositoryRequest
{
Repository = new Repository(),
UpdateMask = new wkt::FieldMask(),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Yum,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
MavenConfig = new Repository.Types.MavenRepositoryConfig(),
};
mockGrpcClient.Setup(x => x.UpdateRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository responseCallSettings = await client.UpdateRepositoryAsync(request.Repository, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Repository responseCancellationToken = await client.UpdateRepositoryAsync(request.Repository, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPackageRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPackageRequest request = new GetPackageRequest
{
Name = "name1c9368b0",
};
Package expectedResponse = new Package
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPackage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Package response = client.GetPackage(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPackageRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPackageRequest request = new GetPackageRequest
{
Name = "name1c9368b0",
};
Package expectedResponse = new Package
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPackageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Package>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Package responseCallSettings = await client.GetPackageAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Package responseCancellationToken = await client.GetPackageAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPackage()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPackageRequest request = new GetPackageRequest
{
Name = "name1c9368b0",
};
Package expectedResponse = new Package
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPackage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Package response = client.GetPackage(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPackageAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPackageRequest request = new GetPackageRequest
{
Name = "name1c9368b0",
};
Package expectedResponse = new Package
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPackageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Package>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Package responseCallSettings = await client.GetPackageAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Package responseCancellationToken = await client.GetPackageAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVersionRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVersionRequest request = new GetVersionRequest
{
Name = "name1c9368b0",
View = VersionView.Basic,
};
Version expectedResponse = new Version
{
VersionName = VersionName.FromProjectLocationRepositoryPackageVersion("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[VERSION]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RelatedTags = { new Tag(), },
Metadata = new wkt::Struct(),
};
mockGrpcClient.Setup(x => x.GetVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Version response = client.GetVersion(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVersionRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVersionRequest request = new GetVersionRequest
{
Name = "name1c9368b0",
View = VersionView.Basic,
};
Version expectedResponse = new Version
{
VersionName = VersionName.FromProjectLocationRepositoryPackageVersion("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[VERSION]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RelatedTags = { new Tag(), },
Metadata = new wkt::Struct(),
};
mockGrpcClient.Setup(x => x.GetVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Version>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Version responseCallSettings = await client.GetVersionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Version responseCancellationToken = await client.GetVersionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVersion()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVersionRequest request = new GetVersionRequest
{
Name = "name1c9368b0",
};
Version expectedResponse = new Version
{
VersionName = VersionName.FromProjectLocationRepositoryPackageVersion("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[VERSION]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RelatedTags = { new Tag(), },
Metadata = new wkt::Struct(),
};
mockGrpcClient.Setup(x => x.GetVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Version response = client.GetVersion(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVersionAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVersionRequest request = new GetVersionRequest
{
Name = "name1c9368b0",
};
Version expectedResponse = new Version
{
VersionName = VersionName.FromProjectLocationRepositoryPackageVersion("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[VERSION]"),
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RelatedTags = { new Tag(), },
Metadata = new wkt::Struct(),
};
mockGrpcClient.Setup(x => x.GetVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Version>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Version responseCallSettings = await client.GetVersionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Version responseCancellationToken = await client.GetVersionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFileRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFileRequest request = new GetFileRequest
{
Name = "name1c9368b0",
};
File expectedResponse = new File
{
FileName = FileName.FromProjectLocationRepositoryFile("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[FILE]"),
SizeBytes = 4628423819757039038L,
Hashes = { new Hash(), },
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Owner = "ownere92c1272",
};
mockGrpcClient.Setup(x => x.GetFile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
File response = client.GetFile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFileRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFileRequest request = new GetFileRequest
{
Name = "name1c9368b0",
};
File expectedResponse = new File
{
FileName = FileName.FromProjectLocationRepositoryFile("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[FILE]"),
SizeBytes = 4628423819757039038L,
Hashes = { new Hash(), },
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Owner = "ownere92c1272",
};
mockGrpcClient.Setup(x => x.GetFileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<File>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
File responseCallSettings = await client.GetFileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
File responseCancellationToken = await client.GetFileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFile()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFileRequest request = new GetFileRequest
{
Name = "name1c9368b0",
};
File expectedResponse = new File
{
FileName = FileName.FromProjectLocationRepositoryFile("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[FILE]"),
SizeBytes = 4628423819757039038L,
Hashes = { new Hash(), },
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Owner = "ownere92c1272",
};
mockGrpcClient.Setup(x => x.GetFile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
File response = client.GetFile(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFileAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFileRequest request = new GetFileRequest
{
Name = "name1c9368b0",
};
File expectedResponse = new File
{
FileName = FileName.FromProjectLocationRepositoryFile("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[FILE]"),
SizeBytes = 4628423819757039038L,
Hashes = { new Hash(), },
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Owner = "ownere92c1272",
};
mockGrpcClient.Setup(x => x.GetFileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<File>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
File responseCallSettings = await client.GetFileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
File responseCancellationToken = await client.GetFileAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTagRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTagRequest request = new GetTagRequest
{
Name = "name1c9368b0",
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.GetTag(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTagRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTagRequest request = new GetTagRequest
{
Name = "name1c9368b0",
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.GetTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.GetTagAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTag()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTagRequest request = new GetTagRequest
{
Name = "name1c9368b0",
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.GetTag(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTagAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTagRequest request = new GetTagRequest
{
Name = "name1c9368b0",
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.GetTagAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.GetTagAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTagRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTagRequest request = new CreateTagRequest
{
Parent = "parent7858e4d0",
TagId = "tag_idbc94f076",
Tag = new Tag(),
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.CreateTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.CreateTag(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTagRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTagRequest request = new CreateTagRequest
{
Parent = "parent7858e4d0",
TagId = "tag_idbc94f076",
Tag = new Tag(),
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.CreateTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.CreateTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.CreateTagAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTag()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTagRequest request = new CreateTagRequest
{
Parent = "parent7858e4d0",
TagId = "tag_idbc94f076",
Tag = new Tag(),
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.CreateTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.CreateTag(request.Parent, request.Tag, request.TagId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTagAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTagRequest request = new CreateTagRequest
{
Parent = "parent7858e4d0",
TagId = "tag_idbc94f076",
Tag = new Tag(),
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.CreateTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.CreateTagAsync(request.Parent, request.Tag, request.TagId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.CreateTagAsync(request.Parent, request.Tag, request.TagId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateTagRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTagRequest request = new UpdateTagRequest
{
Tag = new Tag(),
UpdateMask = new wkt::FieldMask(),
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.UpdateTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.UpdateTag(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateTagRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTagRequest request = new UpdateTagRequest
{
Tag = new Tag(),
UpdateMask = new wkt::FieldMask(),
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.UpdateTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.UpdateTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.UpdateTagAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateTag()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTagRequest request = new UpdateTagRequest
{
Tag = new Tag(),
UpdateMask = new wkt::FieldMask(),
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.UpdateTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.UpdateTag(request.Tag, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateTagAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTagRequest request = new UpdateTagRequest
{
Tag = new Tag(),
UpdateMask = new wkt::FieldMask(),
};
Tag expectedResponse = new Tag
{
TagName = TagName.FromProjectLocationRepositoryPackageTag("[PROJECT]", "[LOCATION]", "[REPOSITORY]", "[PACKAGE]", "[TAG]"),
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.UpdateTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.UpdateTagAsync(request.Tag, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.UpdateTagAsync(request.Tag, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteTagRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteTagRequest request = new DeleteTagRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
client.DeleteTag(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteTagRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteTagRequest request = new DeleteTagRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
await client.DeleteTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteTagAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteTag()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteTagRequest request = new DeleteTagRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
client.DeleteTag(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteTagAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteTagRequest request = new DeleteTagRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
await client.DeleteTagAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteTagAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetProjectSettingsRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectSettingsRequest request = new GetProjectSettingsRequest
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.GetProjectSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings response = client.GetProjectSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetProjectSettingsRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectSettingsRequest request = new GetProjectSettingsRequest
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.GetProjectSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ProjectSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings responseCallSettings = await client.GetProjectSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ProjectSettings responseCancellationToken = await client.GetProjectSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetProjectSettings()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectSettingsRequest request = new GetProjectSettingsRequest
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.GetProjectSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings response = client.GetProjectSettings(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetProjectSettingsAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectSettingsRequest request = new GetProjectSettingsRequest
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.GetProjectSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ProjectSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings responseCallSettings = await client.GetProjectSettingsAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ProjectSettings responseCancellationToken = await client.GetProjectSettingsAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetProjectSettingsResourceNames()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectSettingsRequest request = new GetProjectSettingsRequest
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.GetProjectSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings response = client.GetProjectSettings(request.ProjectSettingsName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetProjectSettingsResourceNamesAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetProjectSettingsRequest request = new GetProjectSettingsRequest
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.GetProjectSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ProjectSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings responseCallSettings = await client.GetProjectSettingsAsync(request.ProjectSettingsName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ProjectSettings responseCancellationToken = await client.GetProjectSettingsAsync(request.ProjectSettingsName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateProjectSettingsRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateProjectSettingsRequest request = new UpdateProjectSettingsRequest
{
ProjectSettings = new ProjectSettings(),
UpdateMask = new wkt::FieldMask(),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.UpdateProjectSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings response = client.UpdateProjectSettings(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateProjectSettingsRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateProjectSettingsRequest request = new UpdateProjectSettingsRequest
{
ProjectSettings = new ProjectSettings(),
UpdateMask = new wkt::FieldMask(),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.UpdateProjectSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ProjectSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings responseCallSettings = await client.UpdateProjectSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ProjectSettings responseCancellationToken = await client.UpdateProjectSettingsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateProjectSettings()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateProjectSettingsRequest request = new UpdateProjectSettingsRequest
{
ProjectSettings = new ProjectSettings(),
UpdateMask = new wkt::FieldMask(),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.UpdateProjectSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings response = client.UpdateProjectSettings(request.ProjectSettings, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateProjectSettingsAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateProjectSettingsRequest request = new UpdateProjectSettingsRequest
{
ProjectSettings = new ProjectSettings(),
UpdateMask = new wkt::FieldMask(),
};
ProjectSettings expectedResponse = new ProjectSettings
{
ProjectSettingsName = ProjectSettingsName.FromProject("[PROJECT]"),
LegacyRedirectionState = ProjectSettings.Types.RedirectionState.RedirectionFromGcrIoDisabled,
};
mockGrpcClient.Setup(x => x.UpdateProjectSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ProjectSettings>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
ProjectSettings responseCallSettings = await client.UpdateProjectSettingsAsync(request.ProjectSettings, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
ProjectSettings responseCancellationToken = await client.UpdateProjectSettingsAsync(request.ProjectSettings, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Gallery.cs
//
// Author:
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (c) 2012 SUSE LINUX Products GmbH, Nuernberg, Germany.
//
// 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.
//
/* These classes are based off the documentation at
*
* http://codex.gallery2.org/index.php/Gallery_Remote:Protocol
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Mono.Unix;
using Hyena;
using Hyena.Widgets;
namespace FSpot.Exporters.Gallery
{
public abstract class Gallery
{
#region Properties
public Uri Uri { get; protected set; }
public string Name { get; set; }
public string AuthToken { get; set; }
public GalleryVersion Version { get; protected set; }
public List<Album> Albums { get; protected set; }
#endregion
public bool expect_continue = true;
protected CookieContainer cookies = null;
public FSpot.ProgressItem Progress = null;
public abstract void Login (string username, string passwd);
public abstract List<Album> FetchAlbums ();
public abstract List<Album> FetchAlbumsPrune ();
public abstract bool MoveAlbum (Album album, string end_name);
public abstract int AddItem (Album album, string path, string filename, string caption, string description, bool autorotate);
//public abstract Album AlbumProperties (string album);
public abstract bool NewAlbum (string parent_name, string name, string title, string description);
public abstract List<Image> FetchAlbumImages (Album album, bool include_ablums);
public abstract string GetAlbumUrl (Album album);
public Gallery (string name)
{
Name = name;
cookies = new CookieContainer ();
Albums = new List<Album> ();
}
public static GalleryVersion DetectGalleryVersion (string url)
{
//Figure out if the url is for G1 or G2
Log.Debug ("Detecting Gallery version");
GalleryVersion version;
if (url.EndsWith (Gallery1.script_name))
version = GalleryVersion.Version1;
else if (url.EndsWith (Gallery2.script_name))
version = GalleryVersion.Version2;
else {
//check what script is available on the server
FormClient client = new FormClient ();
try {
client.Submit (new Uri (Gallery.FixUrl (url, Gallery1.script_name)));
version = GalleryVersion.Version1;
} catch (System.Net.WebException) {
try {
client.Submit (new Uri (Gallery.FixUrl (url, Gallery2.script_name)));
version = GalleryVersion.Version2;
} catch (System.Net.WebException) {
//Uh oh, neither version detected
version = GalleryVersion.VersionUnknown;
}
}
}
Log.Debug ("Detected: " + version.ToString ());
return version;
}
public bool IsConnected ()
{
bool retVal = true;
//Console.WriteLine ("^^^^^^^Checking IsConnected");
foreach (Cookie cookie in cookies.GetCookies(Uri)) {
bool isExpired = cookie.Expired;
//Console.WriteLine (cookie.Name + " " + (isExpired ? "expired" : "valid"));
if (isExpired)
retVal = false;
}
//return cookies.GetCookies(Uri).Count > 0;
return retVal;
}
/// <summary>
/// Reads until it finds the start of the response
/// </summary>
/// <returns>
/// The response
/// </returns>
/// <param name='response'>
/// Response.
/// </param>
protected StreamReader findResponse (HttpWebResponse response)
{
StreamReader reader = new StreamReader (response.GetResponseStream (), Encoding.UTF8);
if (reader == null)
throw new GalleryException (Catalog.GetString ("Error reading server response"));
string line;
string full_response = null;
while ((line = reader.ReadLine ()) != null) {
full_response += line;
if (line.IndexOf ("#__GR2PROTO__", 0) > -1)
break;
}
if (line == null)
// failed to find the response
throw new GalleryException (Catalog.GetString ("Server returned response without Gallery content"), full_response);
return reader;
}
protected string [] GetNextLine (StreamReader reader)
{
char [] value_split = new char[1] {'='};
bool haveLine = false;
string[] array = null;
while (!haveLine) {
string line = reader.ReadLine ();
//Console.WriteLine ("READING: " + line);
if (line != null) {
array = line.Split (value_split, 2);
haveLine = !LineIgnored (array);
} else
//end of input
return null;
}
return array;
}
private bool LineIgnored (string[] line)
{
if (line [0].StartsWith ("debug") || line [0].StartsWith ("can_create_root"))
return true;
return false;
}
protected bool ParseLogin (HttpWebResponse response)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
try {
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data [0] == "status")
status = (ResultCode)int.Parse (data [1]);
else if (data [0].StartsWith ("status_text")) {
status_text = data [1];
Log.DebugFormat ("StatusText : {0}", data [1]);
} else if (data [0].StartsWith ("server_version")) {
//FIXME we should use the to determine what capabilities the server has
} else if (data [0].StartsWith ("auth_token"))
AuthToken = data [1];
else
Log.DebugFormat ("Unparsed Line in ParseLogin(): {0}={1}", data [0], data [1]);
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
return true;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public List<Album> ParseFetchAlbums (HttpWebResponse response)
{
//Console.WriteLine ("in ParseFetchAlbums()");
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
Albums = new List<Album> ();
try {
Album current_album = null;
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
//Console.WriteLine ("Parsing Line: {0}={1}", data[0], data[1]);
if (data [0] == "status")
status = (ResultCode)int.Parse (data [1]);
else if (data [0].StartsWith ("status_text")) {
status_text = data [1];
Log.DebugFormat ("StatusText : {0}", data [1]);
} else if (data [0].StartsWith ("album.name")) {
//this is the URL name
int ref_num = -1;
if (this.Version == GalleryVersion.Version1) {
string [] segments = data [0].Split (new char[1]{'.'});
ref_num = int.Parse (segments [segments.Length - 1]);
} else
ref_num = int.Parse (data [1]);
current_album = new Album (this, data [1], ref_num);
Albums.Add (current_album);
//Console.WriteLine ("current_album: " + data[1]);
} else if (data [0].StartsWith ("album.title"))
//this is the display name
current_album.Title = data [1];
else if (data [0].StartsWith ("album.summary"))
current_album.Summary = data [1];
else if (data [0].StartsWith ("album.parent"))
//FetchAlbums and G2 FetchAlbumsPrune return ints
//G1 FetchAlbumsPrune returns album names (and 0 for root albums)
try {
current_album.ParentRefNum = int.Parse (data [1]);
} catch (System.FormatException) {
current_album.ParentRefNum = LookupAlbum (data [1]).RefNum;
}
//Console.WriteLine ("album.parent data[1]: " + data[1]);
else if (data [0].StartsWith ("album.resize_size"))
current_album.ResizeSize = int.Parse (data [1]);
else if (data [0].StartsWith ("album.thumb_size"))
current_album.ThumbSize = int.Parse (data [1]);
else if (data [0].StartsWith ("album.info.extrafields")) {
//ignore, this is the album description
} else if (data [0].StartsWith ("album.perms.add") && data [1] == "true")
current_album.Perms |= AlbumPermission.Add;
else if (data [0].StartsWith ("album.perms.write") && data [1] == "true")
current_album.Perms |= AlbumPermission.Write;
else if (data [0].StartsWith ("album.perms.del_item") && data [1] == "true")
current_album.Perms |= AlbumPermission.Delete;
else if (data [0].StartsWith ("album.perms.del_alb") && data [1] == "true")
current_album.Perms |= AlbumPermission.DeleteAlbum;
else if (data [0].StartsWith ("album.perms.create_sub") && data [1] == "true")
current_album.Perms |= AlbumPermission.CreateSubAlbum;
else if (data [0].StartsWith ("album_count"))
if (Albums.Count != int.Parse (data [1]))
Log.Warning ("Parsed album count does not match album_count. Something is amiss");
else if (data [0].StartsWith ("auth_token"))
AuthToken = data [1];
else
Log.DebugFormat ("Unparsed Line in ParseFetchAlbums(): {0}={1}", data [0], data [1]);
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
//Console.WriteLine (After parse albums.Count + " albums parsed");
return Albums;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public int ParseAddItem (HttpWebResponse response)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
int item_id = 0;
try {
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data [0] == "status")
status = (ResultCode)int.Parse (data [1]);
else if (data [0].StartsWith ("status_text")) {
status_text = data [1];
Log.DebugFormat ("StatusText : {0}", data [1]);
} else if (data [0].StartsWith ("auth_token"))
AuthToken = data [1];
else if (data [0].StartsWith ("item_name"))
item_id = int.Parse (data [1]);
else
Log.DebugFormat ("Unparsed Line in ParseAddItem(): {0}={1}", data [0], data [1]);
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
return item_id;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public bool ParseNewAlbum (HttpWebResponse response)
{
return ParseBasic (response);
}
public bool ParseMoveAlbum (HttpWebResponse response)
{
return ParseBasic (response);
}
/*
public Album ParseAlbumProperties (HttpWebResponse response)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
try {
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data[0] == "status") {
status = (ResultCode) int.Parse (data [1]);
} else if (data[0].StartsWith ("status_text")) {
status_text = data[1];
Log.Debug ("StatusText : {0}", data[1]);
} else if (data[0].StartsWith ("auto-resize")) {
//ignore
} else {
Log.Debug ("Unparsed Line in ParseBasic(): {0}={1}", data[0], data[1]);
}
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text);
throw new GalleryCommandException (status_text, status);
}
return true;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
*/
private bool ParseBasic (HttpWebResponse response)
{
string [] data;
StreamReader reader = null;
ResultCode status = ResultCode.UnknownResponse;
string status_text = "Error: Unable to parse server response";
try {
reader = findResponse (response);
while ((data = GetNextLine (reader)) != null) {
if (data [0] == "status")
status = (ResultCode)int.Parse (data [1]);
else if (data [0].StartsWith ("status_text")) {
status_text = data [1];
Log.DebugFormat ("StatusText : {0}", data [1]);
} else if (data [0].StartsWith ("auth_token"))
AuthToken = data [1];
else
Log.DebugFormat ("Unparsed Line in ParseBasic(): {0}={1}", data [0], data [1]);
}
//Console.WriteLine ("Found: {0} cookies", response.Cookies.Count);
if (status != ResultCode.Success) {
Log.Debug (status_text + " Status: " + status);
throw new GalleryCommandException (status_text, status);
}
return true;
} finally {
if (reader != null)
reader.Close ();
response.Close ();
}
}
public Album LookupAlbum (string name)
{
Album match = null;
foreach (Album album in Albums) {
if (album.Name == name) {
match = album;
break;
}
}
return match;
}
public Album LookupAlbum (int ref_num)
{
// FIXME: this is really not the best way to do this
Album match = null;
foreach (Album album in Albums) {
if (album.RefNum == ref_num) {
match = album;
break;
}
}
return match;
}
public static string FixUrl (string url, string end)
{
string fixedUrl = url;
if (!url.EndsWith (end)) {
if (!url.EndsWith ("/"))
fixedUrl = url + "/";
fixedUrl = fixedUrl + end;
}
return fixedUrl;
}
public void PopupException (GalleryCommandException e, Gtk.Dialog d)
{
Log.DebugFormat ("{0} : {1} ({2})", e.Message, e.ResponseText, e.Status);
HigMessageDialog md =
new HigMessageDialog (d,
Gtk.DialogFlags.Modal |
Gtk.DialogFlags.DestroyWithParent,
Gtk.MessageType.Error, Gtk.ButtonsType.Ok,
Catalog.GetString ("Error while creating new album"),
string.Format (Catalog.GetString ("The following error was encountered while attempting to perform the requested operation:\n{0} ({1})"), e.Message, e.Status));
md.Run ();
md.Destroy ();
}
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Authorization;
using Microsoft.Azure.Management.Authorization.Models;
namespace Microsoft.Azure.Management.Authorization
{
public static partial class RoleDefinitionOperationsExtensions
{
/// <summary>
/// Creates or updates a role definition.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <param name='roleDefinitionId'>
/// Required. Role definition id.
/// </param>
/// <param name='parameters'>
/// Required. Role definition.
/// </param>
/// <returns>
/// Role definition create or update operation result.
/// </returns>
public static RoleDefinitionCreateOrUpdateResult CreateOrUpdate(this IRoleDefinitionOperations operations, Guid roleDefinitionId, RoleDefinitionCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRoleDefinitionOperations)s).CreateOrUpdateAsync(roleDefinitionId, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a role definition.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <param name='roleDefinitionId'>
/// Required. Role definition id.
/// </param>
/// <param name='parameters'>
/// Required. Role definition.
/// </param>
/// <returns>
/// Role definition create or update operation result.
/// </returns>
public static Task<RoleDefinitionCreateOrUpdateResult> CreateOrUpdateAsync(this IRoleDefinitionOperations operations, Guid roleDefinitionId, RoleDefinitionCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(roleDefinitionId, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes the role definition.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <param name='roleDefinitionId'>
/// Required. Role definition id.
/// </param>
/// <returns>
/// Role definition delete operation result.
/// </returns>
public static RoleDefinitionDeleteResult Delete(this IRoleDefinitionOperations operations, string roleDefinitionId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRoleDefinitionOperations)s).DeleteAsync(roleDefinitionId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the role definition.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <param name='roleDefinitionId'>
/// Required. Role definition id.
/// </param>
/// <returns>
/// Role definition delete operation result.
/// </returns>
public static Task<RoleDefinitionDeleteResult> DeleteAsync(this IRoleDefinitionOperations operations, string roleDefinitionId)
{
return operations.DeleteAsync(roleDefinitionId, CancellationToken.None);
}
/// <summary>
/// Get role definition by name (GUID).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <param name='roleDefinitionName'>
/// Required. Role definition name (GUID).
/// </param>
/// <returns>
/// Role definition get operation result.
/// </returns>
public static RoleDefinitionGetResult Get(this IRoleDefinitionOperations operations, Guid roleDefinitionName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRoleDefinitionOperations)s).GetAsync(roleDefinitionName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get role definition by name (GUID).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <param name='roleDefinitionName'>
/// Required. Role definition name (GUID).
/// </param>
/// <returns>
/// Role definition get operation result.
/// </returns>
public static Task<RoleDefinitionGetResult> GetAsync(this IRoleDefinitionOperations operations, Guid roleDefinitionName)
{
return operations.GetAsync(roleDefinitionName, CancellationToken.None);
}
/// <summary>
/// Get role definition by name (GUID).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <param name='roleDefinitionId'>
/// Required. Role definition Id
/// </param>
/// <returns>
/// Role definition get operation result.
/// </returns>
public static RoleDefinitionGetResult GetById(this IRoleDefinitionOperations operations, string roleDefinitionId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRoleDefinitionOperations)s).GetByIdAsync(roleDefinitionId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get role definition by name (GUID).
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <param name='roleDefinitionId'>
/// Required. Role definition Id
/// </param>
/// <returns>
/// Role definition get operation result.
/// </returns>
public static Task<RoleDefinitionGetResult> GetByIdAsync(this IRoleDefinitionOperations operations, string roleDefinitionId)
{
return operations.GetByIdAsync(roleDefinitionId, CancellationToken.None);
}
/// <summary>
/// Get all role definitions.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <returns>
/// Role definition list operation result.
/// </returns>
public static RoleDefinitionListResult List(this IRoleDefinitionOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IRoleDefinitionOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get all role definitions.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Authorization.IRoleDefinitionOperations.
/// </param>
/// <returns>
/// Role definition list operation result.
/// </returns>
public static Task<RoleDefinitionListResult> ListAsync(this IRoleDefinitionOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2014 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
#if !UNITY
using System.Diagnostics.Contracts;
#endif // !UNITY
using System.Reflection;
using MsgPack.Serialization.DefaultSerializers;
namespace MsgPack.Serialization.ReflectionSerializers
{
/// <summary>
/// Helper static methods for reflection serializers.
/// </summary>
internal static class ReflectionSerializerHelper
{
public static MessagePackSerializer<T> CreateReflectionEnuMessagePackSerializer<T>( SerializationContext context )
{
return
Activator.CreateInstance( typeof( ReflectionEnumMessagePackSerializer<> ).MakeGenericType( typeof( T ) ), context )
as
MessagePackSerializer<T>;
}
public static MessagePackSerializer<T> CreateArraySerializer<T>(
SerializationContext context,
Type targetType,
CollectionTraits traits )
{
switch ( traits.DetailedCollectionType )
{
case CollectionDetailedKind.Array:
{
return ArraySerializer.Create<T>( context );
}
case CollectionDetailedKind.GenericList:
{
return
new ReflectionCollectionSerializer<T>(
context,
Activator.CreateInstance(
typeof( ListSerializer<> ).MakeGenericType( traits.ElementType ),
context,
targetType
) as IMessagePackSerializer
);
}
#if !NETFX_35 && !UNITY
case CollectionDetailedKind.GenericSet:
{
return
new ReflectionCollectionSerializer<T>(
context,
Activator.CreateInstance(
typeof( SetSerializer<> ).MakeGenericType( traits.ElementType ),
context,
targetType
) as IMessagePackSerializer
);
}
#endif // !NETFX_35 && !UNITY
case CollectionDetailedKind.GenericCollection:
{
return
new ReflectionCollectionSerializer<T>(
context,
Activator.CreateInstance(
typeof( CollectionSerializer<> ).MakeGenericType( traits.ElementType ),
context,
targetType
) as IMessagePackSerializer
);
}
case CollectionDetailedKind.GenericEnumerable:
{
return
new ReflectionCollectionSerializer<T>(
context,
Activator.CreateInstance(
typeof( EnumerableSerializer<> ).MakeGenericType( traits.ElementType ),
context,
targetType
) as IMessagePackSerializer
);
}
case CollectionDetailedKind.NonGenericList:
{
return
new ReflectionCollectionSerializer<T>(
context,
new NonGenericListSerializer( context, targetType )
);
}
case CollectionDetailedKind.NonGenericCollection:
{
return
new ReflectionCollectionSerializer<T>(
context,
new NonGenericCollectionSerializer( context, targetType )
);
}
default:
{
#if DEBUG && !UNITY
Contract.Assert( traits.DetailedCollectionType == CollectionDetailedKind.NonGenericEnumerable );
#endif // DEBUG && !UNITY
return
new ReflectionCollectionSerializer<T>(
context,
new NonGenericEnumerableSerializer( context, targetType )
);
}
}
}
public static MessagePackSerializer<T> CreateMapSerializer<T>(
SerializationContext context,
Type targetType,
CollectionTraits traits )
{
if ( traits.DetailedCollectionType == CollectionDetailedKind.GenericDictionary )
{
return
new ReflectionCollectionSerializer<T>(
context,
Activator.CreateInstance(
typeof( DictionarySerializer<,> ).MakeGenericType( traits.ElementType.GetGenericArguments() ),
context,
targetType
) as IMessagePackSerializer
);
}
else
{
#if DEBUG && !UNITY
Contract.Assert( traits.DetailedCollectionType == CollectionDetailedKind.NonGenericDictionary );
#endif // DEBUG && !UNITY
return
new ReflectionCollectionSerializer<T>(
context,
new NonGenericDictionarySerializer( context, targetType )
);
}
}
public static void GetMetadata(
SerializationContext context,
Type targetType,
out Func<object, object>[] getters,
out Action<object, object>[] setters,
out MemberInfo[] memberInfos,
out DataMemberContract[] contracts,
out IMessagePackSerializer[] serializers )
{
SerializationTarget.VerifyType( targetType );
var members = SerializationTarget.Prepare( context, targetType );
getters = new Func<object, object>[ members.Count ];
setters = new Action<object, object>[ members.Count ];
memberInfos = new MemberInfo[ members.Count ];
contracts = new DataMemberContract[ members.Count ];
serializers = new IMessagePackSerializer[ members.Count ];
for ( var i = 0; i < members.Count; i++ )
{
var member = members[ i ];
if ( member.Member == null )
{
continue;
}
FieldInfo asField;
if ( ( asField = member.Member as FieldInfo ) != null )
{
getters[ i ] = asField.GetValue;
setters[ i ] = asField.SetValue;
}
else
{
var property = member.Member as PropertyInfo;
#if DEBUG && !UNITY
Contract.Assert( property != null );
#endif // DEBUG && !UNITY
getters[ i ] = target => property.GetGetMethod( true ).Invoke( target, null );
var setter = property.GetSetMethod( true );
if ( setter != null )
{
setters[ i ] = ( target, value ) => setter.Invoke( target, new[] { value } );
}
}
memberInfos[ i ] = member.Member;
contracts[ i ] = member.Contract;
var memberType = member.Member.GetMemberValueType();
if ( !memberType.GetIsEnum() )
{
serializers[ i ] = context.GetSerializer( memberType );
}
else
{
serializers[ i ] =
context.GetSerializer(
memberType,
EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod(
context,
memberType,
member.GetEnumMemberSerializationMethod()
)
);
}
}
}
}
}
| |
/*
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;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing.Design;
using System.Security.Permissions;
namespace Microsoft.Xrm.Portal.Web.UI.WebControls
{
/// <summary>
/// Represents a Microsoft Dynamics CRM web service to data-bound controls.
/// </summary>
[PersistChildren(false)]
[Description("Represents a Microsoft Dynamics CRM web service to data-bound controls.")]
[DefaultProperty("FetchXml")]
[ParseChildren(true)]
[ToolboxBitmap(typeof(ObjectDataSource))]
[AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class CrmDataSource : AsyncDataSourceControl
{
/// <summary>
/// Gets or sets the name of the data context used to perform service operations.
/// </summary>
[Category("Data")]
public string CrmDataContextName { get; set; }
public class QueryByAttributeParameters : IStateManager
{
private string _entityName;
[DefaultValue(""), Description(""), Category("Data")]
public string EntityName
{
get
{
return _entityName;
}
set
{
_entityName = value;
}
}
private ListItemCollection _attributes;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[PersistenceMode(PersistenceMode.InnerProperty), MergableProperty(false), DefaultValue(null)]
public ListItemCollection Attributes
{
get
{
if (_attributes == null)
{
_attributes = new ListItemCollection();
if (_tracking)
{
(_attributes as IStateManager).TrackViewState();
}
}
return _attributes;
}
}
private ListItemCollection _values;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[PersistenceMode(PersistenceMode.InnerProperty), MergableProperty(false), DefaultValue(null)]
public ListItemCollection Values
{
get
{
if (_values == null)
{
_values = new ListItemCollection();
if (_tracking)
{
(_values as IStateManager).TrackViewState();
}
}
return _values;
}
}
private ListItemCollection _orders;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[PersistenceMode(PersistenceMode.InnerProperty), MergableProperty(false), DefaultValue(null)]
public ListItemCollection Orders
{
get
{
if (_orders == null)
{
_orders = new ListItemCollection();
if (_tracking)
{
(_orders as IStateManager).TrackViewState();
}
}
return _orders;
}
}
private ListItemCollection _columnSet;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[PersistenceMode(PersistenceMode.InnerProperty), MergableProperty(false), DefaultValue(null)]
public ListItemCollection ColumnSet
{
get
{
if (_columnSet == null)
{
_columnSet = new ListItemCollection();
if (_tracking)
{
(_columnSet as IStateManager).TrackViewState();
}
}
return _columnSet;
}
}
#region IStateManager Members
private bool _tracking;
bool IStateManager.IsTrackingViewState
{
get { return IsTrackingViewState; }
}
public bool IsTrackingViewState
{
get { return _tracking; }
}
void IStateManager.LoadViewState(object savedState)
{
LoadViewState(savedState);
}
protected virtual void LoadViewState(object savedState)
{
object[] state = savedState as object[];
if (state == null)
{
return;
}
EntityName = state[0] as string;
((IStateManager)Attributes).LoadViewState(state[1]);
((IStateManager)Values).LoadViewState(state[2]);
((IStateManager)Orders).LoadViewState(state[3]);
((IStateManager)ColumnSet).LoadViewState(state[4]);
}
object IStateManager.SaveViewState()
{
return SaveViewState();
}
protected virtual object SaveViewState()
{
object[] state = new object[5];
state[0] = EntityName;
state[1] = ((IStateManager)Attributes).SaveViewState();
state[2] = ((IStateManager)Values).SaveViewState();
state[3] = ((IStateManager)Orders).SaveViewState();
state[4] = ((IStateManager)ColumnSet).SaveViewState();
return state;
}
void IStateManager.TrackViewState()
{
TrackViewState();
}
protected virtual void TrackViewState()
{
_tracking = true;
((IStateManager)Attributes).TrackViewState();
((IStateManager)Values).TrackViewState();
((IStateManager)Orders).TrackViewState();
((IStateManager)ColumnSet).TrackViewState();
}
#endregion
}
#region Select Members
private string _fetchXml;
/// <summary>
/// Gets or sets the fetch XML query.
/// </summary>
[Editor("System.ComponentModel.Design.MultilineStringEditor,System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
[PersistenceMode(PersistenceMode.InnerProperty)]
[TypeConverter("System.ComponentModel.MultilineStringConverter,System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
[Category("Data")]
[Description("The Fetch XML query.")]
[DefaultValue("")]
public virtual string FetchXml
{
get { return _fetchXml; }
set
{
if (value != null)
{
value = value.Trim();
}
if (_fetchXml != value)
{
_fetchXml = value;
}
}
}
/// <summary>
/// Gets the QueryByAttribute parameters.
/// </summary>
[Category("Data")]
[Description("The QueryByAttribute query.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[PersistenceMode(PersistenceMode.InnerProperty), MergableProperty(false), DefaultValue((string)null)]
public QueryByAttributeParameters QueryByAttribute
{
get
{
return GetView().QueryByAttribute;
}
}
[Category("Data"), Description("")]
public event EventHandler<CrmDataSourceStatusEventArgs> Selected
{
add
{
GetView().Selected += value;
}
remove
{
GetView().Selected -= value;
}
}
[Category("Data"), Description("")]
public event EventHandler<CrmDataSourceSelectingEventArgs> Selecting
{
add
{
GetView().Selecting += value;
}
remove
{
GetView().Selecting -= value;
}
}
public IEnumerable Select()
{
return Select(DataSourceSelectArguments.Empty);
}
public IEnumerable Select(DataSourceSelectArguments arguments)
{
return GetView().Select(arguments);
}
/// <summary>
/// Gets the parameters collection that contains the parameters that are used when selecting data.
/// </summary>
[Description(""), Category("Data"), PersistenceMode(PersistenceMode.InnerProperty), DefaultValue((string)null), Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)), MergableProperty(false)]
public ParameterCollection SelectParameters
{
get
{
return GetView().SelectParameters;
}
}
/// <summary>
/// Gets the parameters collection that contains the parameters that are used when querying data.
/// </summary>
[Description(""), Category("Data"), PersistenceMode(PersistenceMode.InnerProperty), DefaultValue((string)null), Editor("System.Web.UI.Design.WebControls.ParameterCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)), MergableProperty(false)]
public ParameterCollection QueryParameters
{
get
{
return GetView().QueryParameters;
}
}
private bool _encodeParametersEnabled = true;
/// <summary>
/// Gets or sets the option to HtmlEncode the parameter values when constructing the FetchXml as a means of input validation.
/// </summary>
public bool EncodeParametersEnabled
{
get { return _encodeParametersEnabled; }
set { _encodeParametersEnabled = value; }
}
/// <summary>
/// Gets or sets the type name of the static class type to emit. The DynamicEntityWrapper is converted to an object of this type.
/// </summary>
public string StaticEntityWrapperTypeName { get; set; }
#endregion
#region Delete Members
/// <summary>
/// Deletes an entity.
/// </summary>
/// <param name="keys">The keys by which to find the entity. "ID" and "Name" must be specified.</param>
/// <param name="oldValues">The entity properties before the update. Key: Property name e.g. "firstname" Value: Value of the property e.g. "Jane"</param>
/// <returns>1 if successful; otherwise, 0.</returns>
public int Delete(IDictionary keys, IDictionary oldValues)
{
return GetView().Delete(keys, oldValues);
}
#endregion
#region Insert Members
/// <summary>
/// Creates a new entity.
/// </summary>
/// <param name="values">The entity properties. Key: Property name e.g. "firstname" Value: Value of the property e.g. "Jane"</param>
/// <param name="entityName">The type of entity to create e.g. "contact"</param>
/// <returns>1 if successful; otherwise, 0.</returns>
public int Insert(IDictionary values, string entityName)
{
return GetView().Insert(values, entityName);
}
#endregion
#region Update Members
/// <summary>
/// Updates an entity.
/// </summary>
/// <param name="keys">The keys by which to find the entity to be updated. "ID" and "Name" must be specified.</param>
/// <param name="values">The entity properties to update. Key: Property name e.g. "firstname" Value: Value of the property e.g. "Jane"</param>
/// <param name="oldValues">The entity properties before the update.</param>
/// <returns>1 if successful; otherwise, 0.</returns>
public int Update(IDictionary keys, IDictionary values, IDictionary oldValues)
{
return GetView().Update(keys, values, oldValues);
}
#endregion
#region Cache Members
private CacheParameters _cacheParameters;
/// <summary>
/// Gets the cache settings.
/// </summary>
public CacheParameters CacheParameters
{
get
{
if (_cacheParameters == null)
{
_cacheParameters = new CacheParameters();
if (IsTrackingViewState)
{
((IStateManager)_cacheParameters).TrackViewState();
}
}
return _cacheParameters;
}
}
public virtual CacheParameters GetCacheParameters()
{
if (CacheParameters.Dependencies.Count == 0)
{
CacheKeyDependency dependency = new CacheKeyDependency();
dependency.Name = "@key";
dependency.PropertyName = "EntityName";
dependency.KeyFormat = "xrm:dependency:entity:@key";
CacheParameters.Dependencies.Add(dependency);
}
if (CacheParameters.ItemDependencies.Count == 0)
{
CacheKeyDependency dependency = new CacheKeyDependency();
dependency.Name = "@key";
dependency.PropertyName = "Name";
dependency.KeyFormat = "xrm:dependency:entity:@key";
CacheParameters.ItemDependencies.Add(dependency);
}
return CacheParameters;
}
#endregion
#region IDataSource Members
private const string _defaultViewName = "DefaultView";
private static readonly string[] _defaultViewNames = { _defaultViewName };
private ICollection _viewNames;
private CrmDataSourceView _view;
protected override DataSourceView GetView(string viewName)
{
if ((viewName == null) || ((viewName.Length != 0) && !string.Equals(viewName, _defaultViewName, StringComparison.OrdinalIgnoreCase)))
{
throw new ArgumentException("An invalid view was requested.", "viewName");
}
return GetView();
}
private CrmDataSourceView GetView()
{
if (_view == null)
{
_view = new CrmDataSourceView(this, _defaultViewName, Context);
if (IsTrackingViewState)
{
((IStateManager)_view).TrackViewState();
}
}
return _view;
}
protected override ICollection GetViewNames()
{
if (_viewNames == null)
{
_viewNames = _defaultViewNames;
}
return _viewNames;
}
#endregion
#region IStateManager Members
protected override void LoadViewState(object savedState)
{
Pair state = (Pair)savedState;
if (savedState == null)
{
base.LoadViewState(null);
}
else
{
base.LoadViewState(state.First);
if (state.Second != null)
{
((IStateManager)GetView()).LoadViewState(state.Second);
}
}
}
protected override object SaveViewState()
{
Pair state = new Pair();
state.First = base.SaveViewState();
if (_view != null)
{
state.Second = ((IStateManager)_view).SaveViewState();
}
if ((state.First == null) && (state.Second == null))
{
return null;
}
return state;
}
protected override void TrackViewState()
{
base.TrackViewState();
((IStateManager)GetView()).TrackViewState();
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using System;
using System.Collections.Generic;
using UnityEngine;
using HoloToolkit.Unity;
namespace HoloToolkit.Sharing.Spawning
{
/// <summary>
/// Structure linking a prefab and a data model class.
/// </summary>
[Serializable]
public struct PrefabToDataModel
{
// TODO Should this be a Type? Or at least have a custom editor to have a dropdown list
public string DataModelClassName;
public GameObject Prefab;
}
/// <summary>
/// Spawn manager that creates a GameObject based on a prefab when a new
/// SyncSpawnedObject is created in the data model.
/// </summary>
public class PrefabSpawnManager : SpawnManager<SyncSpawnedObject>
{
/// <summary>
/// List of prefabs that can be spawned by this application.
/// </summary>
/// <remarks>It is assumed that this list is the same on all connected applications.</remarks>
[SerializeField]
private List<PrefabToDataModel> spawnablePrefabs = null;
private Dictionary<string, GameObject> typeToPrefab;
/// <summary>
/// Counter used to create objects and make sure that no two objects created
/// by the local application have the same name.
/// </summary>
private int objectCreationCounter;
private void Awake()
{
InitializePrefabs();
}
private void InitializePrefabs()
{
typeToPrefab = new Dictionary<string, GameObject>(spawnablePrefabs.Count);
for (int i = 0; i < spawnablePrefabs.Count; i++)
{
typeToPrefab.Add(spawnablePrefabs[i].DataModelClassName, spawnablePrefabs[i].Prefab);
}
}
protected override void InstantiateFromNetwork(SyncSpawnedObject spawnedObject)
{
GameObject prefab = GetPrefab(spawnedObject, null);
if (!prefab)
{
return;
}
// Find the parent object
GameObject parent = null;
if (!string.IsNullOrEmpty(spawnedObject.ParentPath.Value))
{
parent = GameObject.Find(spawnedObject.ParentPath.Value);
if (parent == null)
{
Debug.LogErrorFormat("Parent object '{0}' could not be found to instantiate object.", spawnedObject.ParentPath);
return;
}
}
CreatePrefabInstance(spawnedObject, prefab, parent, spawnedObject.Name.Value);
}
protected override void RemoveFromNetwork(SyncSpawnedObject removedObject)
{
if (removedObject.GameObject != null)
{
Destroy(removedObject.GameObject);
removedObject.GameObject = null;
}
}
protected virtual string CreateInstanceName(string baseName)
{
string instanceName = string.Format("{0}_{1}_{2}", baseName, objectCreationCounter.ToString(), NetworkManager.AppInstanceUniqueId);
objectCreationCounter++;
return instanceName;
}
protected virtual string GetPrefabLookupKey(SyncSpawnedObject dataModel, string baseName)
{
return dataModel.GetType().Name;
}
protected virtual GameObject GetPrefab(SyncSpawnedObject dataModel, string baseName)
{
GameObject prefabToSpawn;
string dataModelTypeName = GetPrefabLookupKey(dataModel, baseName);
if (dataModelTypeName == null || !typeToPrefab.TryGetValue(dataModelTypeName, out prefabToSpawn))
{
Debug.LogErrorFormat("Trying to instantiate an object from unregistered data model {0}.", dataModelTypeName);
return null;
}
return prefabToSpawn;
}
/// <summary>
/// Spawns content with the given parent. If no parent is specified it will be parented to the spawn manager itself.
/// </summary>
/// <param name="dataModel">Data model to use for spawning.</param>
/// <param name="localPosition">Local position for the new instance.</param>
/// <param name="localRotation">Local rotation for the new instance.</param>
/// <param name="localScale">optional local scale for the new instance. If not specified, uses the prefabs scale.</param>
/// <param name="parent">Parent to assign to the object.</param>
/// <param name="baseName">Base name to use to name the created game object.</param>
/// <param name="isOwnedLocally">
/// Indicates if the spawned object is owned by this device or not.
/// An object that is locally owned will be removed from the sync system when its owner leaves the session.
/// </param>
/// <returns>True if spawning succeeded, false if not.</returns>
public bool Spawn(SyncSpawnedObject dataModel, Vector3 localPosition, Quaternion localRotation, Vector3? localScale, GameObject parent, string baseName, bool isOwnedLocally)
{
if (SyncSource == null)
{
Debug.LogError("Can't spawn an object: PrefabSpawnManager is not initialized.");
return false;
}
if (dataModel == null)
{
Debug.LogError("Can't spawn an object: dataModel argument is null.");
return false;
}
if (parent == null)
{
parent = gameObject;
}
// Validate that the prefab is valid
GameObject prefabToSpawn = GetPrefab(dataModel, baseName);
if (!prefabToSpawn)
{
return false;
}
// Get a name for the object to create
string instanceName = CreateInstanceName(baseName);
// Add the data model object to the networked array, for networking and history purposes
dataModel.Initialize(instanceName, parent.transform.GetFullPath("/"));
dataModel.Transform.Position.Value = localPosition;
dataModel.Transform.Rotation.Value = localRotation;
if (localScale.HasValue)
{
dataModel.Transform.Scale.Value = localScale.Value;
}
else
{
dataModel.Transform.Scale.Value = prefabToSpawn.transform.localScale;
}
User owner = null;
if (isOwnedLocally)
{
owner = SharingStage.Instance.Manager.GetLocalUser();
}
SyncSource.AddObject(dataModel, owner);
return true;
}
/// <summary>
/// Instantiate data model on the network with the given parent. If no parent is specified it will be parented to the spawn manager itself.
/// </summary>
/// <param name="dataModel">Data model to use for spawning.</param>
/// <param name="localPosition">Local space position for the new instance.</param>
/// <param name="localRotation">Local space rotation for the new instance.</param>
/// <param name="parent">Parent to assign to the object.</param>
/// <param name="baseName">Base name to use to name the created game object.</param>
/// <param name="isOwnedLocally">
/// Indicates if the spawned object is owned by this device or not.
/// An object that is locally owned will be removed from the sync system when its owner leaves the session.
/// </param>
/// <returns>True if the function succeeded, false if not.</returns>
public bool Spawn(SyncSpawnedObject dataModel, Vector3 localPosition, Quaternion localRotation, GameObject parent, string baseName, bool isOwnedLocally)
{
return Spawn(dataModel, localPosition, localRotation, null, parent, baseName, isOwnedLocally);
}
protected override void SetDataModelSource()
{
SyncSource = NetworkManager.Root.InstantiatedPrefabs;
}
public override void Delete(SyncSpawnedObject objectToDelete)
{
SyncSource.RemoveObject(objectToDelete);
}
/// <summary>
/// Create a prefab instance in the scene, in reaction to data being added to the data model.
/// </summary>
/// <param name="dataModel">Object to spawn's data model.</param>
/// <param name="prefabToInstantiate">Prefab to instantiate.</param>
/// <param name="parentObject">Parent object under which the prefab should be.</param>
/// <param name="objectName">Name of the object.</param>
/// <returns></returns>
protected virtual GameObject CreatePrefabInstance(SyncSpawnedObject dataModel, GameObject prefabToInstantiate, GameObject parentObject, string objectName)
{
GameObject instance = Instantiate(prefabToInstantiate, dataModel.Transform.Position.Value, dataModel.Transform.Rotation.Value);
instance.transform.localScale = dataModel.Transform.Scale.Value;
instance.transform.SetParent(parentObject.transform, false);
instance.gameObject.name = objectName;
dataModel.GameObject = instance;
// Set the data model on the various ISyncModelAccessor components of the spawned game obejct
ISyncModelAccessor[] syncModelAccessors = instance.GetComponentsInChildren<ISyncModelAccessor>(true);
if (syncModelAccessors.Length <= 0)
{
// If no ISyncModelAccessor component exists, create a default one that gives access to the SyncObject instance
ISyncModelAccessor defaultAccessor = instance.EnsureComponent<DefaultSyncModelAccessor>();
defaultAccessor.SetSyncModel(dataModel);
}
for (int i = 0; i < syncModelAccessors.Length; i++)
{
syncModelAccessors[i].SetSyncModel(dataModel);
}
// Setup the transform synchronization
TransformSynchronizer transformSynchronizer = instance.EnsureComponent<TransformSynchronizer>();
transformSynchronizer.TransformDataModel = dataModel.Transform;
return instance;
}
}
}
| |
//*********************************************************
//
// 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 SDKTemplate;
using System;
using System.Collections.Generic;
using Windows.Foundation.Metadata;
using Windows.Graphics.Printing;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Printing;
namespace PrintSample
{
/// <summary>
/// This class customizes the standard PrintHelper in order to disable print preview.
/// </summary>
/// <remarks>
/// The PrintTaskRequestedMethod sets printTask.IsPreviewEnabled to false in order
/// to disable print preview.
/// Since print preview is disabled, the Paginate event will not be raised.
/// Instead, the pages to be printed are generated in response to the AddPages event.
/// </remarks>
class DisablePreviewPrintHelper : PrintHelper
{
/// <summary>
/// A list of UIElements used to store the print pages. This gives easy access
/// to any desired print page.
/// </summary>
internal List<UIElement> printPages;
public DisablePreviewPrintHelper(Page scenarioPage) : base(scenarioPage) {
printPages = new List<UIElement>();
}
/// <summary>
/// This is the event handler for PrintManager.PrintTaskRequested.
/// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified by PrintTaskRequestedEventArgs.Request.Deadline.
/// Therefore, we use this handler to only create the print task.
/// The print settings customization can be done when the print document source is requested.
/// </summary>
/// <param name="sender">PrintManager</param>
/// <param name="e">PrintTaskRequestedEventArgs</param>
protected override void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
{
PrintTask printTask = null;
printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", sourceRequestedArgs =>
{
// Print Task event handler is invoked when the print job is completed.
printTask.Completed += async (s, args) =>
{
// Notify the user when the print operation fails.
if (args.Completion == PrintTaskCompletion.Failed)
{
await scenarioPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
MainPage.Current.NotifyUser("Failed to print.", NotifyType.ErrorMessage);
});
}
};
sourceRequestedArgs.SetSource(printDocumentSource);
});
// Choose not to show the preview by setting the property on PrintTask
printTask.IsPreviewEnabled = false;
}
/// <summary>
/// This is the event handler for PrintDocument.AddPages. It provides all pages to be printed, in the form of
/// UIElements, to an instance of PrintDocument. PrintDocument subsequently converts the UIElements
/// into a pages that the Windows print system can deal with.
/// </summary>
/// <param name="sender">PrintDocument</param>
/// <param name="e">Add page event arguments containing a print task options reference</param>
protected override void AddPrintPages(object sender, AddPagesEventArgs e)
{
// Clear the cache of print pages
printPages.Clear();
// Clear the print canvas of print pages
PrintCanvas.Children.Clear();
// This variable keeps track of the last RichTextBlockOverflow element that was added to a page which will be printed
RichTextBlockOverflow lastRTBOOnPage;
// Get the PrintTaskOptions
PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions);
// Get the page description to deterimine how big the page is
PrintPageDescription pageDescription = printingOptions.GetPageDescription(0);
// We know there is at least one page to be printed. passing null as the first parameter to
// AddOnePrintPage tells the function to add the first page.
lastRTBOOnPage = AddOnePrintPage(null, pageDescription);
// We know there are more pages to be added as long as the last RichTextBoxOverflow added to a print
// page has extra content
while (lastRTBOOnPage.HasOverflowContent && (lastRTBOOnPage.Visibility == Windows.UI.Xaml.Visibility.Visible))
{
lastRTBOOnPage = AddOnePrintPage(lastRTBOOnPage, pageDescription);
}
// Loop over all of the pages and add each one to add each page to be printed
for (int i = 0; i < printPages.Count; i++)
{
// We should have all pages ready at this point...
printDocument.AddPage(printPages[i]);
}
PrintDocument printDoc = (PrintDocument)sender;
// Indicate that all of the print pages have been provided
printDoc.AddPagesComplete();
}
/// <summary>
/// This function creates and adds one print page to the internal cache of print pages
/// pages stored in printPages.
/// </summary>
/// <param name="lastRTBOAdded">Last RichTextBlockOverflow element added in the current content</param>
/// <param name="printPageDescription">Printer's page description</param>
protected RichTextBlockOverflow AddOnePrintPage(RichTextBlockOverflow lastRTBOAdded, PrintPageDescription printPageDescription)
{
// XAML element that is used to represent to "printing page"
FrameworkElement page;
// The link container for text overflowing in this page
RichTextBlockOverflow textLink;
// Check if this is the first page ( no previous RichTextBlockOverflow)
if (lastRTBOAdded == null)
{
// If this is the first page add the specific scenario content
page = firstPage;
//Hide footer since we don't know yet if it will be displayed (this might not be the last page) - wait for layout
StackPanel footer = (StackPanel)page.FindName("Footer");
footer.Visibility = Visibility.Collapsed;
}
else
{
// Flow content (text) from previous pages
page = new ContinuationPage(lastRTBOAdded);
}
// Set "paper" width
page.Width = printPageDescription.PageSize.Width;
page.Height = printPageDescription.PageSize.Height;
Grid printableArea = (Grid)page.FindName("PrintableArea");
// Get the margins size
// If the ImageableRect is smaller than the app provided margins use the ImageableRect
double marginWidth = Math.Max(printPageDescription.PageSize.Width - printPageDescription.ImageableRect.Width, printPageDescription.PageSize.Width * ApplicationContentMarginLeft * 2);
double marginHeight = Math.Max(printPageDescription.PageSize.Height - printPageDescription.ImageableRect.Height, printPageDescription.PageSize.Height * ApplicationContentMarginTop * 2);
// Set-up "printable area" on the "paper"
printableArea.Width = firstPage.Width - marginWidth;
printableArea.Height = firstPage.Height - marginHeight;
// Add the (newly created) page to the print canvas which is part of the visual tree and force it to go
// through layout so that the linked containers correctly distribute the content inside them.
PrintCanvas.Children.Add(page);
PrintCanvas.InvalidateMeasure();
PrintCanvas.UpdateLayout();
// Find the last text container and see if the content is overflowing
textLink = (RichTextBlockOverflow)page.FindName("ContinuationPageLinkedContainer");
// Check if this is the last page
if ((!textLink.HasOverflowContent) && (textLink.Visibility == Windows.UI.Xaml.Visibility.Visible))
{
StackPanel footer = (StackPanel)page.FindName("Footer");
footer.Visibility = Visibility.Visible;
}
// Add the page to the print page collection
printPages.Add(page);
return textLink;
}
}
/// <summary>
/// Scenario that demos how to disable the print preview in the Modern Print Dialog window.
/// </summary>
public sealed partial class Scenario6DisablePreview : Page
{
private DisablePreviewPrintHelper printHelper;
public Scenario6DisablePreview()
{
this.InitializeComponent();
}
/// <summary>
/// This is the click handler for the 'Print' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void OnPrintButtonClick(object sender, RoutedEventArgs e)
{
await printHelper.ShowPrintUIAsync();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (PrintManager.IsSupported())
{
// Tell the user how to print
MainPage.Current.NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType.StatusMessage);
}
else
{
// Remove the print button
InvokePrintingButton.Visibility = Visibility.Collapsed;
// Inform user that Printing is not supported
MainPage.Current.NotifyUser("Printing is not supported.", NotifyType.ErrorMessage);
// Printing-related event handlers will never be called if printing
// is not supported, but it's okay to register for them anyway.
}
// Initalize common helper class and register for printing
printHelper = new DisablePreviewPrintHelper(this);
printHelper.RegisterForPrinting();
// Initialize print content for this scenario
printHelper.PreparePrintContent(new PageToPrint());
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (printHelper != null)
{
printHelper.UnregisterForPrinting();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net
{
public abstract class WebRequest
{
internal class WebRequestPrefixElement
{
public string Prefix;
public IWebRequestCreate Creator;
public WebRequestPrefixElement(string P, IWebRequestCreate C)
{
Prefix = P;
Creator = C;
}
}
private static volatile List<WebRequestPrefixElement> s_prefixList;
private static object s_internalSyncObject = new object();
// Create a WebRequest.
//
// This is the main creation routine. We take a Uri object, look
// up the Uri in the prefix match table, and invoke the appropriate
// handler to create the object. We also have a parameter that
// tells us whether or not to use the whole Uri or just the
// scheme portion of it.
//
// Input:
// requestUri - Uri object for request.
// useUriBase - True if we're only to look at the scheme portion of the Uri.
//
// Returns:
// Newly created WebRequest.
private static WebRequest Create(Uri requestUri, bool useUriBase)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Requests, "WebRequest", "Create", requestUri.ToString());
}
string LookupUri;
WebRequestPrefixElement Current = null;
bool Found = false;
if (!useUriBase)
{
LookupUri = requestUri.AbsoluteUri;
}
else
{
// schemes are registered as <schemeName>":", so add the separator
// to the string returned from the Uri object
LookupUri = requestUri.Scheme + ':';
}
int LookupLength = LookupUri.Length;
// Copy the prefix list so that if it is updated it will
// not affect us on this thread.
List<WebRequestPrefixElement> prefixList = PrefixList;
// Look for the longest matching prefix.
// Walk down the list of prefixes. The prefixes are kept longest
// first. When we find a prefix that is shorter or the same size
// as this Uri, we'll do a compare to see if they match. If they
// do we'll break out of the loop and call the creator.
for (int i = 0; i < prefixList.Count; i++)
{
Current = prefixList[i];
// See if this prefix is short enough.
if (LookupLength >= Current.Prefix.Length)
{
// It is. See if these match.
if (String.Compare(Current.Prefix,
0,
LookupUri,
0,
Current.Prefix.Length,
StringComparison.OrdinalIgnoreCase) == 0)
{
// These match. Remember that we found it and break
// out.
Found = true;
break;
}
}
}
WebRequest webRequest = null;
if (Found)
{
// We found a match, so just call the creator and return what it does.
webRequest = Current.Creator.Create(requestUri);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Requests, "WebRequest", "Create", webRequest);
}
return webRequest;
}
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Requests, "WebRequest", "Create", null);
}
// Otherwise no match, throw an exception.
throw new NotSupportedException(SR.net_unknown_prefix);
}
// Create - Create a WebRequest.
//
// An overloaded utility version of the real Create that takes a
// string instead of an Uri object.
//
// Input:
// RequestString - Uri string to create.
//
// Returns:
// Newly created WebRequest.
public static WebRequest Create(string requestUriString)
{
if (requestUriString == null)
{
throw new ArgumentNullException("requestUriString");
}
return Create(new Uri(requestUriString), false);
}
// Create - Create a WebRequest.
//
// Another overloaded version of the Create function that doesn't
// take the UseUriBase parameter.
//
// Input:
// requestUri - Uri object for request.
//
// Returns:
// Newly created WebRequest.
public static WebRequest Create(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException("requestUri");
}
return Create(requestUri, false);
}
// CreateDefault - Create a default WebRequest.
//
// This is the creation routine that creates a default WebRequest.
// We take a Uri object and pass it to the base create routine,
// setting the useUriBase parameter to true.
//
// Input:
// RequestUri - Uri object for request.
//
// Returns:
// Newly created WebRequest.
internal static WebRequest CreateDefault(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException("requestUri");
}
return Create(requestUri, true);
}
public static HttpWebRequest CreateHttp(string requestUriString)
{
if (requestUriString == null)
{
throw new ArgumentNullException("requestUriString");
}
return CreateHttp(new Uri(requestUriString));
}
public static HttpWebRequest CreateHttp(Uri requestUri)
{
if (requestUri == null)
{
throw new ArgumentNullException("requestUri");
}
if ((requestUri.Scheme != "http") && (requestUri.Scheme != "https"))
{
throw new NotSupportedException(SR.net_unknown_prefix);
}
return (HttpWebRequest)CreateDefault(requestUri);
}
// RegisterPrefix - Register an Uri prefix for creating WebRequests.
//
// This function registers a prefix for creating WebRequests. When an
// user wants to create a WebRequest, we scan a table looking for a
// longest prefix match for the Uri they're passing. We then invoke
// the sub creator for that prefix. This function puts entries in
// that table.
//
// We don't allow duplicate entries, so if there is a dup this call
// will fail.
//
// Input:
// Prefix - Represents Uri prefix being registered.
// Creator - Interface for sub creator.
//
// Returns:
// True if the registration worked, false otherwise.
public static bool RegisterPrefix(string prefix, IWebRequestCreate creator)
{
bool Error = false;
int i;
WebRequestPrefixElement Current;
if (prefix == null)
{
throw new ArgumentNullException("prefix");
}
if (creator == null)
{
throw new ArgumentNullException("creator");
}
// Lock this object, then walk down PrefixList looking for a place to
// to insert this prefix.
lock (s_internalSyncObject)
{
// Clone the object and update the clone, thus
// allowing other threads to still read from the original.
List<WebRequestPrefixElement> prefixList = new List<WebRequestPrefixElement>(PrefixList);
// As AbsoluteUri is used later for Create, account for formating changes
// like Unicode escaping, default ports, etc.
Uri tempUri;
if (Uri.TryCreate(prefix, UriKind.Absolute, out tempUri))
{
String cookedUri = tempUri.AbsoluteUri;
// Special case for when a partial host matching is requested, drop the added trailing slash
// IE: http://host could match host or host.domain
if (!prefix.EndsWith("/", StringComparison.Ordinal)
&& tempUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.UriEscaped)
.Equals("/"))
{
cookedUri = cookedUri.Substring(0, cookedUri.Length - 1);
}
prefix = cookedUri;
}
i = 0;
// The prefix list is sorted with longest entries at the front. We
// walk down the list until we find a prefix shorter than this
// one, then we insert in front of it. Along the way we check
// equal length prefixes to make sure this isn't a dupe.
while (i < prefixList.Count)
{
Current = prefixList[i];
// See if the new one is longer than the one we're looking at.
if (prefix.Length > Current.Prefix.Length)
{
// It is. Break out of the loop here.
break;
}
// If these are of equal length, compare them.
if (prefix.Length == Current.Prefix.Length)
{
// They're the same length.
if (string.Equals(Current.Prefix, prefix, StringComparison.OrdinalIgnoreCase))
{
// ...and the strings are identical. This is an error.
Error = true;
break;
}
}
i++;
}
// When we get here either i contains the index to insert at or
// we've had an error, in which case Error is true.
if (!Error)
{
// No error, so insert.
prefixList.Insert(i, new WebRequestPrefixElement(prefix, creator));
// Assign the clone to the static object. Other threads using it
// will have copied the original object already.
PrefixList = prefixList;
}
}
return !Error;
}
internal class HttpRequestCreator : IWebRequestCreate
{
// Create - Create an HttpWebRequest.
//
// This is our method to create an HttpWebRequest. We register
// for HTTP and HTTPS Uris, and this method is called when a request
// needs to be created for one of those.
//
//
// Input:
// uri - Uri for request being created.
//
// Returns:
// The newly created HttpWebRequest.
public WebRequest Create(Uri Uri)
{
return new HttpWebRequest(Uri);
}
}
// PrefixList - Returns And Initialize our prefix list.
//
//
// This is the method that initializes the prefix list. We create
// an List for the PrefixList, then an HttpRequestCreator object,
// and then we register the HTTP and HTTPS prefixes.
//
// Returns:
// true
internal static List<WebRequestPrefixElement> PrefixList
{
get
{
// GetConfig() might use us, so we have a circular dependency issue
// that causes us to nest here. We grab the lock only if we haven't
// initialized.
if (s_prefixList == null)
{
lock (s_internalSyncObject)
{
if (s_prefixList == null)
{
List<WebRequestPrefixElement> prefixList = new List<WebRequestPrefixElement>();
prefixList.Add(new WebRequestPrefixElement("http:", new HttpRequestCreator()));
prefixList.Add(new WebRequestPrefixElement("https:", new HttpRequestCreator()));
prefixList.Add(new WebRequestPrefixElement("file:", new HttpRequestCreator()));
prefixList.Add(new WebRequestPrefixElement("ftp:", new HttpRequestCreator()));
s_prefixList = prefixList;
}
}
}
return s_prefixList;
}
set
{
s_prefixList = value;
}
}
protected WebRequest()
{
}
public abstract string Method
{
get;
set;
}
public abstract Uri RequestUri
{
get;
}
public abstract WebHeaderCollection Headers
{
get;
set;
}
public abstract string ContentType
{
get;
set;
}
public virtual ICredentials Credentials
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public virtual bool UseDefaultCredentials
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
public abstract IAsyncResult BeginGetResponse(AsyncCallback callback, object state);
public abstract WebResponse EndGetResponse(IAsyncResult asyncResult);
public abstract IAsyncResult BeginGetRequestStream(AsyncCallback callback, Object state);
public abstract Stream EndGetRequestStream(IAsyncResult asyncResult);
public virtual Task<Stream> GetRequestStreamAsync()
{
// Offload to a different thread to avoid blocking the caller during request submission.
// We use Task.Run rather than Task.Factory.StartNew even though StartNew would let us pass 'this'
// as a state argument to avoid the closure to capture 'this' and the associated delegate.
// This is because the task needs to call FromAsync and marshal the inner Task out, and
// Task.Run's implementation of this is sufficiently more efficient than what we can do with
// Unwrap() that it's worth it to just rely on Task.Run and accept the closure/delegate.
return Task.Run(() =>
Task<Stream>.Factory.FromAsync(
(callback, state) => ((WebRequest)state).BeginGetRequestStream(callback, state),
iar => ((WebRequest)iar.AsyncState).EndGetRequestStream(iar),
this));
}
public virtual Task<WebResponse> GetResponseAsync()
{
// See comment in GetRequestStreamAsync(). Same logic applies here.
return Task.Run(() =>
Task<WebResponse>.Factory.FromAsync(
(callback, state) => ((WebRequest)state).BeginGetResponse(callback, state),
iar => ((WebRequest)iar.AsyncState).EndGetResponse(iar),
this));
}
public abstract void Abort();
// Default Web Proxy implementation.
private static IWebProxy s_DefaultWebProxy;
private static bool s_DefaultWebProxyInitialized;
public static IWebProxy DefaultWebProxy
{
get
{
lock (s_internalSyncObject)
{
if (!s_DefaultWebProxyInitialized)
{
s_DefaultWebProxy = SystemWebProxy.Get();
s_DefaultWebProxyInitialized = true;
}
return s_DefaultWebProxy;
}
}
set
{
lock (s_internalSyncObject)
{
s_DefaultWebProxy = value;
s_DefaultWebProxyInitialized = true;
}
}
}
public virtual IWebProxy Proxy
{
get
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
set
{
throw NotImplemented.ByDesignWithMessage(SR.net_PropertyNotImplementedException);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp.Swizzle
{
/// <summary>
/// Temporary vector of type double with 3 components, used for implementing swizzling for dvec3.
/// </summary>
[Serializable]
[DataContract(Namespace = "swizzle")]
[StructLayout(LayoutKind.Sequential)]
public struct swizzle_dvec3
{
#region Fields
/// <summary>
/// x-component
/// </summary>
[DataMember]
internal readonly double x;
/// <summary>
/// y-component
/// </summary>
[DataMember]
internal readonly double y;
/// <summary>
/// z-component
/// </summary>
[DataMember]
internal readonly double z;
#endregion
#region Constructors
/// <summary>
/// Constructor for swizzle_dvec3.
/// </summary>
internal swizzle_dvec3(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
#endregion
#region Properties
/// <summary>
/// Returns dvec3.xx swizzling.
/// </summary>
public dvec2 xx => new dvec2(x, x);
/// <summary>
/// Returns dvec3.rr swizzling (equivalent to dvec3.xx).
/// </summary>
public dvec2 rr => new dvec2(x, x);
/// <summary>
/// Returns dvec3.xxx swizzling.
/// </summary>
public dvec3 xxx => new dvec3(x, x, x);
/// <summary>
/// Returns dvec3.rrr swizzling (equivalent to dvec3.xxx).
/// </summary>
public dvec3 rrr => new dvec3(x, x, x);
/// <summary>
/// Returns dvec3.xxxx swizzling.
/// </summary>
public dvec4 xxxx => new dvec4(x, x, x, x);
/// <summary>
/// Returns dvec3.rrrr swizzling (equivalent to dvec3.xxxx).
/// </summary>
public dvec4 rrrr => new dvec4(x, x, x, x);
/// <summary>
/// Returns dvec3.xxxy swizzling.
/// </summary>
public dvec4 xxxy => new dvec4(x, x, x, y);
/// <summary>
/// Returns dvec3.rrrg swizzling (equivalent to dvec3.xxxy).
/// </summary>
public dvec4 rrrg => new dvec4(x, x, x, y);
/// <summary>
/// Returns dvec3.xxxz swizzling.
/// </summary>
public dvec4 xxxz => new dvec4(x, x, x, z);
/// <summary>
/// Returns dvec3.rrrb swizzling (equivalent to dvec3.xxxz).
/// </summary>
public dvec4 rrrb => new dvec4(x, x, x, z);
/// <summary>
/// Returns dvec3.xxy swizzling.
/// </summary>
public dvec3 xxy => new dvec3(x, x, y);
/// <summary>
/// Returns dvec3.rrg swizzling (equivalent to dvec3.xxy).
/// </summary>
public dvec3 rrg => new dvec3(x, x, y);
/// <summary>
/// Returns dvec3.xxyx swizzling.
/// </summary>
public dvec4 xxyx => new dvec4(x, x, y, x);
/// <summary>
/// Returns dvec3.rrgr swizzling (equivalent to dvec3.xxyx).
/// </summary>
public dvec4 rrgr => new dvec4(x, x, y, x);
/// <summary>
/// Returns dvec3.xxyy swizzling.
/// </summary>
public dvec4 xxyy => new dvec4(x, x, y, y);
/// <summary>
/// Returns dvec3.rrgg swizzling (equivalent to dvec3.xxyy).
/// </summary>
public dvec4 rrgg => new dvec4(x, x, y, y);
/// <summary>
/// Returns dvec3.xxyz swizzling.
/// </summary>
public dvec4 xxyz => new dvec4(x, x, y, z);
/// <summary>
/// Returns dvec3.rrgb swizzling (equivalent to dvec3.xxyz).
/// </summary>
public dvec4 rrgb => new dvec4(x, x, y, z);
/// <summary>
/// Returns dvec3.xxz swizzling.
/// </summary>
public dvec3 xxz => new dvec3(x, x, z);
/// <summary>
/// Returns dvec3.rrb swizzling (equivalent to dvec3.xxz).
/// </summary>
public dvec3 rrb => new dvec3(x, x, z);
/// <summary>
/// Returns dvec3.xxzx swizzling.
/// </summary>
public dvec4 xxzx => new dvec4(x, x, z, x);
/// <summary>
/// Returns dvec3.rrbr swizzling (equivalent to dvec3.xxzx).
/// </summary>
public dvec4 rrbr => new dvec4(x, x, z, x);
/// <summary>
/// Returns dvec3.xxzy swizzling.
/// </summary>
public dvec4 xxzy => new dvec4(x, x, z, y);
/// <summary>
/// Returns dvec3.rrbg swizzling (equivalent to dvec3.xxzy).
/// </summary>
public dvec4 rrbg => new dvec4(x, x, z, y);
/// <summary>
/// Returns dvec3.xxzz swizzling.
/// </summary>
public dvec4 xxzz => new dvec4(x, x, z, z);
/// <summary>
/// Returns dvec3.rrbb swizzling (equivalent to dvec3.xxzz).
/// </summary>
public dvec4 rrbb => new dvec4(x, x, z, z);
/// <summary>
/// Returns dvec3.xy swizzling.
/// </summary>
public dvec2 xy => new dvec2(x, y);
/// <summary>
/// Returns dvec3.rg swizzling (equivalent to dvec3.xy).
/// </summary>
public dvec2 rg => new dvec2(x, y);
/// <summary>
/// Returns dvec3.xyx swizzling.
/// </summary>
public dvec3 xyx => new dvec3(x, y, x);
/// <summary>
/// Returns dvec3.rgr swizzling (equivalent to dvec3.xyx).
/// </summary>
public dvec3 rgr => new dvec3(x, y, x);
/// <summary>
/// Returns dvec3.xyxx swizzling.
/// </summary>
public dvec4 xyxx => new dvec4(x, y, x, x);
/// <summary>
/// Returns dvec3.rgrr swizzling (equivalent to dvec3.xyxx).
/// </summary>
public dvec4 rgrr => new dvec4(x, y, x, x);
/// <summary>
/// Returns dvec3.xyxy swizzling.
/// </summary>
public dvec4 xyxy => new dvec4(x, y, x, y);
/// <summary>
/// Returns dvec3.rgrg swizzling (equivalent to dvec3.xyxy).
/// </summary>
public dvec4 rgrg => new dvec4(x, y, x, y);
/// <summary>
/// Returns dvec3.xyxz swizzling.
/// </summary>
public dvec4 xyxz => new dvec4(x, y, x, z);
/// <summary>
/// Returns dvec3.rgrb swizzling (equivalent to dvec3.xyxz).
/// </summary>
public dvec4 rgrb => new dvec4(x, y, x, z);
/// <summary>
/// Returns dvec3.xyy swizzling.
/// </summary>
public dvec3 xyy => new dvec3(x, y, y);
/// <summary>
/// Returns dvec3.rgg swizzling (equivalent to dvec3.xyy).
/// </summary>
public dvec3 rgg => new dvec3(x, y, y);
/// <summary>
/// Returns dvec3.xyyx swizzling.
/// </summary>
public dvec4 xyyx => new dvec4(x, y, y, x);
/// <summary>
/// Returns dvec3.rggr swizzling (equivalent to dvec3.xyyx).
/// </summary>
public dvec4 rggr => new dvec4(x, y, y, x);
/// <summary>
/// Returns dvec3.xyyy swizzling.
/// </summary>
public dvec4 xyyy => new dvec4(x, y, y, y);
/// <summary>
/// Returns dvec3.rggg swizzling (equivalent to dvec3.xyyy).
/// </summary>
public dvec4 rggg => new dvec4(x, y, y, y);
/// <summary>
/// Returns dvec3.xyyz swizzling.
/// </summary>
public dvec4 xyyz => new dvec4(x, y, y, z);
/// <summary>
/// Returns dvec3.rggb swizzling (equivalent to dvec3.xyyz).
/// </summary>
public dvec4 rggb => new dvec4(x, y, y, z);
/// <summary>
/// Returns dvec3.xyz swizzling.
/// </summary>
public dvec3 xyz => new dvec3(x, y, z);
/// <summary>
/// Returns dvec3.rgb swizzling (equivalent to dvec3.xyz).
/// </summary>
public dvec3 rgb => new dvec3(x, y, z);
/// <summary>
/// Returns dvec3.xyzx swizzling.
/// </summary>
public dvec4 xyzx => new dvec4(x, y, z, x);
/// <summary>
/// Returns dvec3.rgbr swizzling (equivalent to dvec3.xyzx).
/// </summary>
public dvec4 rgbr => new dvec4(x, y, z, x);
/// <summary>
/// Returns dvec3.xyzy swizzling.
/// </summary>
public dvec4 xyzy => new dvec4(x, y, z, y);
/// <summary>
/// Returns dvec3.rgbg swizzling (equivalent to dvec3.xyzy).
/// </summary>
public dvec4 rgbg => new dvec4(x, y, z, y);
/// <summary>
/// Returns dvec3.xyzz swizzling.
/// </summary>
public dvec4 xyzz => new dvec4(x, y, z, z);
/// <summary>
/// Returns dvec3.rgbb swizzling (equivalent to dvec3.xyzz).
/// </summary>
public dvec4 rgbb => new dvec4(x, y, z, z);
/// <summary>
/// Returns dvec3.xz swizzling.
/// </summary>
public dvec2 xz => new dvec2(x, z);
/// <summary>
/// Returns dvec3.rb swizzling (equivalent to dvec3.xz).
/// </summary>
public dvec2 rb => new dvec2(x, z);
/// <summary>
/// Returns dvec3.xzx swizzling.
/// </summary>
public dvec3 xzx => new dvec3(x, z, x);
/// <summary>
/// Returns dvec3.rbr swizzling (equivalent to dvec3.xzx).
/// </summary>
public dvec3 rbr => new dvec3(x, z, x);
/// <summary>
/// Returns dvec3.xzxx swizzling.
/// </summary>
public dvec4 xzxx => new dvec4(x, z, x, x);
/// <summary>
/// Returns dvec3.rbrr swizzling (equivalent to dvec3.xzxx).
/// </summary>
public dvec4 rbrr => new dvec4(x, z, x, x);
/// <summary>
/// Returns dvec3.xzxy swizzling.
/// </summary>
public dvec4 xzxy => new dvec4(x, z, x, y);
/// <summary>
/// Returns dvec3.rbrg swizzling (equivalent to dvec3.xzxy).
/// </summary>
public dvec4 rbrg => new dvec4(x, z, x, y);
/// <summary>
/// Returns dvec3.xzxz swizzling.
/// </summary>
public dvec4 xzxz => new dvec4(x, z, x, z);
/// <summary>
/// Returns dvec3.rbrb swizzling (equivalent to dvec3.xzxz).
/// </summary>
public dvec4 rbrb => new dvec4(x, z, x, z);
/// <summary>
/// Returns dvec3.xzy swizzling.
/// </summary>
public dvec3 xzy => new dvec3(x, z, y);
/// <summary>
/// Returns dvec3.rbg swizzling (equivalent to dvec3.xzy).
/// </summary>
public dvec3 rbg => new dvec3(x, z, y);
/// <summary>
/// Returns dvec3.xzyx swizzling.
/// </summary>
public dvec4 xzyx => new dvec4(x, z, y, x);
/// <summary>
/// Returns dvec3.rbgr swizzling (equivalent to dvec3.xzyx).
/// </summary>
public dvec4 rbgr => new dvec4(x, z, y, x);
/// <summary>
/// Returns dvec3.xzyy swizzling.
/// </summary>
public dvec4 xzyy => new dvec4(x, z, y, y);
/// <summary>
/// Returns dvec3.rbgg swizzling (equivalent to dvec3.xzyy).
/// </summary>
public dvec4 rbgg => new dvec4(x, z, y, y);
/// <summary>
/// Returns dvec3.xzyz swizzling.
/// </summary>
public dvec4 xzyz => new dvec4(x, z, y, z);
/// <summary>
/// Returns dvec3.rbgb swizzling (equivalent to dvec3.xzyz).
/// </summary>
public dvec4 rbgb => new dvec4(x, z, y, z);
/// <summary>
/// Returns dvec3.xzz swizzling.
/// </summary>
public dvec3 xzz => new dvec3(x, z, z);
/// <summary>
/// Returns dvec3.rbb swizzling (equivalent to dvec3.xzz).
/// </summary>
public dvec3 rbb => new dvec3(x, z, z);
/// <summary>
/// Returns dvec3.xzzx swizzling.
/// </summary>
public dvec4 xzzx => new dvec4(x, z, z, x);
/// <summary>
/// Returns dvec3.rbbr swizzling (equivalent to dvec3.xzzx).
/// </summary>
public dvec4 rbbr => new dvec4(x, z, z, x);
/// <summary>
/// Returns dvec3.xzzy swizzling.
/// </summary>
public dvec4 xzzy => new dvec4(x, z, z, y);
/// <summary>
/// Returns dvec3.rbbg swizzling (equivalent to dvec3.xzzy).
/// </summary>
public dvec4 rbbg => new dvec4(x, z, z, y);
/// <summary>
/// Returns dvec3.xzzz swizzling.
/// </summary>
public dvec4 xzzz => new dvec4(x, z, z, z);
/// <summary>
/// Returns dvec3.rbbb swizzling (equivalent to dvec3.xzzz).
/// </summary>
public dvec4 rbbb => new dvec4(x, z, z, z);
/// <summary>
/// Returns dvec3.yx swizzling.
/// </summary>
public dvec2 yx => new dvec2(y, x);
/// <summary>
/// Returns dvec3.gr swizzling (equivalent to dvec3.yx).
/// </summary>
public dvec2 gr => new dvec2(y, x);
/// <summary>
/// Returns dvec3.yxx swizzling.
/// </summary>
public dvec3 yxx => new dvec3(y, x, x);
/// <summary>
/// Returns dvec3.grr swizzling (equivalent to dvec3.yxx).
/// </summary>
public dvec3 grr => new dvec3(y, x, x);
/// <summary>
/// Returns dvec3.yxxx swizzling.
/// </summary>
public dvec4 yxxx => new dvec4(y, x, x, x);
/// <summary>
/// Returns dvec3.grrr swizzling (equivalent to dvec3.yxxx).
/// </summary>
public dvec4 grrr => new dvec4(y, x, x, x);
/// <summary>
/// Returns dvec3.yxxy swizzling.
/// </summary>
public dvec4 yxxy => new dvec4(y, x, x, y);
/// <summary>
/// Returns dvec3.grrg swizzling (equivalent to dvec3.yxxy).
/// </summary>
public dvec4 grrg => new dvec4(y, x, x, y);
/// <summary>
/// Returns dvec3.yxxz swizzling.
/// </summary>
public dvec4 yxxz => new dvec4(y, x, x, z);
/// <summary>
/// Returns dvec3.grrb swizzling (equivalent to dvec3.yxxz).
/// </summary>
public dvec4 grrb => new dvec4(y, x, x, z);
/// <summary>
/// Returns dvec3.yxy swizzling.
/// </summary>
public dvec3 yxy => new dvec3(y, x, y);
/// <summary>
/// Returns dvec3.grg swizzling (equivalent to dvec3.yxy).
/// </summary>
public dvec3 grg => new dvec3(y, x, y);
/// <summary>
/// Returns dvec3.yxyx swizzling.
/// </summary>
public dvec4 yxyx => new dvec4(y, x, y, x);
/// <summary>
/// Returns dvec3.grgr swizzling (equivalent to dvec3.yxyx).
/// </summary>
public dvec4 grgr => new dvec4(y, x, y, x);
/// <summary>
/// Returns dvec3.yxyy swizzling.
/// </summary>
public dvec4 yxyy => new dvec4(y, x, y, y);
/// <summary>
/// Returns dvec3.grgg swizzling (equivalent to dvec3.yxyy).
/// </summary>
public dvec4 grgg => new dvec4(y, x, y, y);
/// <summary>
/// Returns dvec3.yxyz swizzling.
/// </summary>
public dvec4 yxyz => new dvec4(y, x, y, z);
/// <summary>
/// Returns dvec3.grgb swizzling (equivalent to dvec3.yxyz).
/// </summary>
public dvec4 grgb => new dvec4(y, x, y, z);
/// <summary>
/// Returns dvec3.yxz swizzling.
/// </summary>
public dvec3 yxz => new dvec3(y, x, z);
/// <summary>
/// Returns dvec3.grb swizzling (equivalent to dvec3.yxz).
/// </summary>
public dvec3 grb => new dvec3(y, x, z);
/// <summary>
/// Returns dvec3.yxzx swizzling.
/// </summary>
public dvec4 yxzx => new dvec4(y, x, z, x);
/// <summary>
/// Returns dvec3.grbr swizzling (equivalent to dvec3.yxzx).
/// </summary>
public dvec4 grbr => new dvec4(y, x, z, x);
/// <summary>
/// Returns dvec3.yxzy swizzling.
/// </summary>
public dvec4 yxzy => new dvec4(y, x, z, y);
/// <summary>
/// Returns dvec3.grbg swizzling (equivalent to dvec3.yxzy).
/// </summary>
public dvec4 grbg => new dvec4(y, x, z, y);
/// <summary>
/// Returns dvec3.yxzz swizzling.
/// </summary>
public dvec4 yxzz => new dvec4(y, x, z, z);
/// <summary>
/// Returns dvec3.grbb swizzling (equivalent to dvec3.yxzz).
/// </summary>
public dvec4 grbb => new dvec4(y, x, z, z);
/// <summary>
/// Returns dvec3.yy swizzling.
/// </summary>
public dvec2 yy => new dvec2(y, y);
/// <summary>
/// Returns dvec3.gg swizzling (equivalent to dvec3.yy).
/// </summary>
public dvec2 gg => new dvec2(y, y);
/// <summary>
/// Returns dvec3.yyx swizzling.
/// </summary>
public dvec3 yyx => new dvec3(y, y, x);
/// <summary>
/// Returns dvec3.ggr swizzling (equivalent to dvec3.yyx).
/// </summary>
public dvec3 ggr => new dvec3(y, y, x);
/// <summary>
/// Returns dvec3.yyxx swizzling.
/// </summary>
public dvec4 yyxx => new dvec4(y, y, x, x);
/// <summary>
/// Returns dvec3.ggrr swizzling (equivalent to dvec3.yyxx).
/// </summary>
public dvec4 ggrr => new dvec4(y, y, x, x);
/// <summary>
/// Returns dvec3.yyxy swizzling.
/// </summary>
public dvec4 yyxy => new dvec4(y, y, x, y);
/// <summary>
/// Returns dvec3.ggrg swizzling (equivalent to dvec3.yyxy).
/// </summary>
public dvec4 ggrg => new dvec4(y, y, x, y);
/// <summary>
/// Returns dvec3.yyxz swizzling.
/// </summary>
public dvec4 yyxz => new dvec4(y, y, x, z);
/// <summary>
/// Returns dvec3.ggrb swizzling (equivalent to dvec3.yyxz).
/// </summary>
public dvec4 ggrb => new dvec4(y, y, x, z);
/// <summary>
/// Returns dvec3.yyy swizzling.
/// </summary>
public dvec3 yyy => new dvec3(y, y, y);
/// <summary>
/// Returns dvec3.ggg swizzling (equivalent to dvec3.yyy).
/// </summary>
public dvec3 ggg => new dvec3(y, y, y);
/// <summary>
/// Returns dvec3.yyyx swizzling.
/// </summary>
public dvec4 yyyx => new dvec4(y, y, y, x);
/// <summary>
/// Returns dvec3.gggr swizzling (equivalent to dvec3.yyyx).
/// </summary>
public dvec4 gggr => new dvec4(y, y, y, x);
/// <summary>
/// Returns dvec3.yyyy swizzling.
/// </summary>
public dvec4 yyyy => new dvec4(y, y, y, y);
/// <summary>
/// Returns dvec3.gggg swizzling (equivalent to dvec3.yyyy).
/// </summary>
public dvec4 gggg => new dvec4(y, y, y, y);
/// <summary>
/// Returns dvec3.yyyz swizzling.
/// </summary>
public dvec4 yyyz => new dvec4(y, y, y, z);
/// <summary>
/// Returns dvec3.gggb swizzling (equivalent to dvec3.yyyz).
/// </summary>
public dvec4 gggb => new dvec4(y, y, y, z);
/// <summary>
/// Returns dvec3.yyz swizzling.
/// </summary>
public dvec3 yyz => new dvec3(y, y, z);
/// <summary>
/// Returns dvec3.ggb swizzling (equivalent to dvec3.yyz).
/// </summary>
public dvec3 ggb => new dvec3(y, y, z);
/// <summary>
/// Returns dvec3.yyzx swizzling.
/// </summary>
public dvec4 yyzx => new dvec4(y, y, z, x);
/// <summary>
/// Returns dvec3.ggbr swizzling (equivalent to dvec3.yyzx).
/// </summary>
public dvec4 ggbr => new dvec4(y, y, z, x);
/// <summary>
/// Returns dvec3.yyzy swizzling.
/// </summary>
public dvec4 yyzy => new dvec4(y, y, z, y);
/// <summary>
/// Returns dvec3.ggbg swizzling (equivalent to dvec3.yyzy).
/// </summary>
public dvec4 ggbg => new dvec4(y, y, z, y);
/// <summary>
/// Returns dvec3.yyzz swizzling.
/// </summary>
public dvec4 yyzz => new dvec4(y, y, z, z);
/// <summary>
/// Returns dvec3.ggbb swizzling (equivalent to dvec3.yyzz).
/// </summary>
public dvec4 ggbb => new dvec4(y, y, z, z);
/// <summary>
/// Returns dvec3.yz swizzling.
/// </summary>
public dvec2 yz => new dvec2(y, z);
/// <summary>
/// Returns dvec3.gb swizzling (equivalent to dvec3.yz).
/// </summary>
public dvec2 gb => new dvec2(y, z);
/// <summary>
/// Returns dvec3.yzx swizzling.
/// </summary>
public dvec3 yzx => new dvec3(y, z, x);
/// <summary>
/// Returns dvec3.gbr swizzling (equivalent to dvec3.yzx).
/// </summary>
public dvec3 gbr => new dvec3(y, z, x);
/// <summary>
/// Returns dvec3.yzxx swizzling.
/// </summary>
public dvec4 yzxx => new dvec4(y, z, x, x);
/// <summary>
/// Returns dvec3.gbrr swizzling (equivalent to dvec3.yzxx).
/// </summary>
public dvec4 gbrr => new dvec4(y, z, x, x);
/// <summary>
/// Returns dvec3.yzxy swizzling.
/// </summary>
public dvec4 yzxy => new dvec4(y, z, x, y);
/// <summary>
/// Returns dvec3.gbrg swizzling (equivalent to dvec3.yzxy).
/// </summary>
public dvec4 gbrg => new dvec4(y, z, x, y);
/// <summary>
/// Returns dvec3.yzxz swizzling.
/// </summary>
public dvec4 yzxz => new dvec4(y, z, x, z);
/// <summary>
/// Returns dvec3.gbrb swizzling (equivalent to dvec3.yzxz).
/// </summary>
public dvec4 gbrb => new dvec4(y, z, x, z);
/// <summary>
/// Returns dvec3.yzy swizzling.
/// </summary>
public dvec3 yzy => new dvec3(y, z, y);
/// <summary>
/// Returns dvec3.gbg swizzling (equivalent to dvec3.yzy).
/// </summary>
public dvec3 gbg => new dvec3(y, z, y);
/// <summary>
/// Returns dvec3.yzyx swizzling.
/// </summary>
public dvec4 yzyx => new dvec4(y, z, y, x);
/// <summary>
/// Returns dvec3.gbgr swizzling (equivalent to dvec3.yzyx).
/// </summary>
public dvec4 gbgr => new dvec4(y, z, y, x);
/// <summary>
/// Returns dvec3.yzyy swizzling.
/// </summary>
public dvec4 yzyy => new dvec4(y, z, y, y);
/// <summary>
/// Returns dvec3.gbgg swizzling (equivalent to dvec3.yzyy).
/// </summary>
public dvec4 gbgg => new dvec4(y, z, y, y);
/// <summary>
/// Returns dvec3.yzyz swizzling.
/// </summary>
public dvec4 yzyz => new dvec4(y, z, y, z);
/// <summary>
/// Returns dvec3.gbgb swizzling (equivalent to dvec3.yzyz).
/// </summary>
public dvec4 gbgb => new dvec4(y, z, y, z);
/// <summary>
/// Returns dvec3.yzz swizzling.
/// </summary>
public dvec3 yzz => new dvec3(y, z, z);
/// <summary>
/// Returns dvec3.gbb swizzling (equivalent to dvec3.yzz).
/// </summary>
public dvec3 gbb => new dvec3(y, z, z);
/// <summary>
/// Returns dvec3.yzzx swizzling.
/// </summary>
public dvec4 yzzx => new dvec4(y, z, z, x);
/// <summary>
/// Returns dvec3.gbbr swizzling (equivalent to dvec3.yzzx).
/// </summary>
public dvec4 gbbr => new dvec4(y, z, z, x);
/// <summary>
/// Returns dvec3.yzzy swizzling.
/// </summary>
public dvec4 yzzy => new dvec4(y, z, z, y);
/// <summary>
/// Returns dvec3.gbbg swizzling (equivalent to dvec3.yzzy).
/// </summary>
public dvec4 gbbg => new dvec4(y, z, z, y);
/// <summary>
/// Returns dvec3.yzzz swizzling.
/// </summary>
public dvec4 yzzz => new dvec4(y, z, z, z);
/// <summary>
/// Returns dvec3.gbbb swizzling (equivalent to dvec3.yzzz).
/// </summary>
public dvec4 gbbb => new dvec4(y, z, z, z);
/// <summary>
/// Returns dvec3.zx swizzling.
/// </summary>
public dvec2 zx => new dvec2(z, x);
/// <summary>
/// Returns dvec3.br swizzling (equivalent to dvec3.zx).
/// </summary>
public dvec2 br => new dvec2(z, x);
/// <summary>
/// Returns dvec3.zxx swizzling.
/// </summary>
public dvec3 zxx => new dvec3(z, x, x);
/// <summary>
/// Returns dvec3.brr swizzling (equivalent to dvec3.zxx).
/// </summary>
public dvec3 brr => new dvec3(z, x, x);
/// <summary>
/// Returns dvec3.zxxx swizzling.
/// </summary>
public dvec4 zxxx => new dvec4(z, x, x, x);
/// <summary>
/// Returns dvec3.brrr swizzling (equivalent to dvec3.zxxx).
/// </summary>
public dvec4 brrr => new dvec4(z, x, x, x);
/// <summary>
/// Returns dvec3.zxxy swizzling.
/// </summary>
public dvec4 zxxy => new dvec4(z, x, x, y);
/// <summary>
/// Returns dvec3.brrg swizzling (equivalent to dvec3.zxxy).
/// </summary>
public dvec4 brrg => new dvec4(z, x, x, y);
/// <summary>
/// Returns dvec3.zxxz swizzling.
/// </summary>
public dvec4 zxxz => new dvec4(z, x, x, z);
/// <summary>
/// Returns dvec3.brrb swizzling (equivalent to dvec3.zxxz).
/// </summary>
public dvec4 brrb => new dvec4(z, x, x, z);
/// <summary>
/// Returns dvec3.zxy swizzling.
/// </summary>
public dvec3 zxy => new dvec3(z, x, y);
/// <summary>
/// Returns dvec3.brg swizzling (equivalent to dvec3.zxy).
/// </summary>
public dvec3 brg => new dvec3(z, x, y);
/// <summary>
/// Returns dvec3.zxyx swizzling.
/// </summary>
public dvec4 zxyx => new dvec4(z, x, y, x);
/// <summary>
/// Returns dvec3.brgr swizzling (equivalent to dvec3.zxyx).
/// </summary>
public dvec4 brgr => new dvec4(z, x, y, x);
/// <summary>
/// Returns dvec3.zxyy swizzling.
/// </summary>
public dvec4 zxyy => new dvec4(z, x, y, y);
/// <summary>
/// Returns dvec3.brgg swizzling (equivalent to dvec3.zxyy).
/// </summary>
public dvec4 brgg => new dvec4(z, x, y, y);
/// <summary>
/// Returns dvec3.zxyz swizzling.
/// </summary>
public dvec4 zxyz => new dvec4(z, x, y, z);
/// <summary>
/// Returns dvec3.brgb swizzling (equivalent to dvec3.zxyz).
/// </summary>
public dvec4 brgb => new dvec4(z, x, y, z);
/// <summary>
/// Returns dvec3.zxz swizzling.
/// </summary>
public dvec3 zxz => new dvec3(z, x, z);
/// <summary>
/// Returns dvec3.brb swizzling (equivalent to dvec3.zxz).
/// </summary>
public dvec3 brb => new dvec3(z, x, z);
/// <summary>
/// Returns dvec3.zxzx swizzling.
/// </summary>
public dvec4 zxzx => new dvec4(z, x, z, x);
/// <summary>
/// Returns dvec3.brbr swizzling (equivalent to dvec3.zxzx).
/// </summary>
public dvec4 brbr => new dvec4(z, x, z, x);
/// <summary>
/// Returns dvec3.zxzy swizzling.
/// </summary>
public dvec4 zxzy => new dvec4(z, x, z, y);
/// <summary>
/// Returns dvec3.brbg swizzling (equivalent to dvec3.zxzy).
/// </summary>
public dvec4 brbg => new dvec4(z, x, z, y);
/// <summary>
/// Returns dvec3.zxzz swizzling.
/// </summary>
public dvec4 zxzz => new dvec4(z, x, z, z);
/// <summary>
/// Returns dvec3.brbb swizzling (equivalent to dvec3.zxzz).
/// </summary>
public dvec4 brbb => new dvec4(z, x, z, z);
/// <summary>
/// Returns dvec3.zy swizzling.
/// </summary>
public dvec2 zy => new dvec2(z, y);
/// <summary>
/// Returns dvec3.bg swizzling (equivalent to dvec3.zy).
/// </summary>
public dvec2 bg => new dvec2(z, y);
/// <summary>
/// Returns dvec3.zyx swizzling.
/// </summary>
public dvec3 zyx => new dvec3(z, y, x);
/// <summary>
/// Returns dvec3.bgr swizzling (equivalent to dvec3.zyx).
/// </summary>
public dvec3 bgr => new dvec3(z, y, x);
/// <summary>
/// Returns dvec3.zyxx swizzling.
/// </summary>
public dvec4 zyxx => new dvec4(z, y, x, x);
/// <summary>
/// Returns dvec3.bgrr swizzling (equivalent to dvec3.zyxx).
/// </summary>
public dvec4 bgrr => new dvec4(z, y, x, x);
/// <summary>
/// Returns dvec3.zyxy swizzling.
/// </summary>
public dvec4 zyxy => new dvec4(z, y, x, y);
/// <summary>
/// Returns dvec3.bgrg swizzling (equivalent to dvec3.zyxy).
/// </summary>
public dvec4 bgrg => new dvec4(z, y, x, y);
/// <summary>
/// Returns dvec3.zyxz swizzling.
/// </summary>
public dvec4 zyxz => new dvec4(z, y, x, z);
/// <summary>
/// Returns dvec3.bgrb swizzling (equivalent to dvec3.zyxz).
/// </summary>
public dvec4 bgrb => new dvec4(z, y, x, z);
/// <summary>
/// Returns dvec3.zyy swizzling.
/// </summary>
public dvec3 zyy => new dvec3(z, y, y);
/// <summary>
/// Returns dvec3.bgg swizzling (equivalent to dvec3.zyy).
/// </summary>
public dvec3 bgg => new dvec3(z, y, y);
/// <summary>
/// Returns dvec3.zyyx swizzling.
/// </summary>
public dvec4 zyyx => new dvec4(z, y, y, x);
/// <summary>
/// Returns dvec3.bggr swizzling (equivalent to dvec3.zyyx).
/// </summary>
public dvec4 bggr => new dvec4(z, y, y, x);
/// <summary>
/// Returns dvec3.zyyy swizzling.
/// </summary>
public dvec4 zyyy => new dvec4(z, y, y, y);
/// <summary>
/// Returns dvec3.bggg swizzling (equivalent to dvec3.zyyy).
/// </summary>
public dvec4 bggg => new dvec4(z, y, y, y);
/// <summary>
/// Returns dvec3.zyyz swizzling.
/// </summary>
public dvec4 zyyz => new dvec4(z, y, y, z);
/// <summary>
/// Returns dvec3.bggb swizzling (equivalent to dvec3.zyyz).
/// </summary>
public dvec4 bggb => new dvec4(z, y, y, z);
/// <summary>
/// Returns dvec3.zyz swizzling.
/// </summary>
public dvec3 zyz => new dvec3(z, y, z);
/// <summary>
/// Returns dvec3.bgb swizzling (equivalent to dvec3.zyz).
/// </summary>
public dvec3 bgb => new dvec3(z, y, z);
/// <summary>
/// Returns dvec3.zyzx swizzling.
/// </summary>
public dvec4 zyzx => new dvec4(z, y, z, x);
/// <summary>
/// Returns dvec3.bgbr swizzling (equivalent to dvec3.zyzx).
/// </summary>
public dvec4 bgbr => new dvec4(z, y, z, x);
/// <summary>
/// Returns dvec3.zyzy swizzling.
/// </summary>
public dvec4 zyzy => new dvec4(z, y, z, y);
/// <summary>
/// Returns dvec3.bgbg swizzling (equivalent to dvec3.zyzy).
/// </summary>
public dvec4 bgbg => new dvec4(z, y, z, y);
/// <summary>
/// Returns dvec3.zyzz swizzling.
/// </summary>
public dvec4 zyzz => new dvec4(z, y, z, z);
/// <summary>
/// Returns dvec3.bgbb swizzling (equivalent to dvec3.zyzz).
/// </summary>
public dvec4 bgbb => new dvec4(z, y, z, z);
/// <summary>
/// Returns dvec3.zz swizzling.
/// </summary>
public dvec2 zz => new dvec2(z, z);
/// <summary>
/// Returns dvec3.bb swizzling (equivalent to dvec3.zz).
/// </summary>
public dvec2 bb => new dvec2(z, z);
/// <summary>
/// Returns dvec3.zzx swizzling.
/// </summary>
public dvec3 zzx => new dvec3(z, z, x);
/// <summary>
/// Returns dvec3.bbr swizzling (equivalent to dvec3.zzx).
/// </summary>
public dvec3 bbr => new dvec3(z, z, x);
/// <summary>
/// Returns dvec3.zzxx swizzling.
/// </summary>
public dvec4 zzxx => new dvec4(z, z, x, x);
/// <summary>
/// Returns dvec3.bbrr swizzling (equivalent to dvec3.zzxx).
/// </summary>
public dvec4 bbrr => new dvec4(z, z, x, x);
/// <summary>
/// Returns dvec3.zzxy swizzling.
/// </summary>
public dvec4 zzxy => new dvec4(z, z, x, y);
/// <summary>
/// Returns dvec3.bbrg swizzling (equivalent to dvec3.zzxy).
/// </summary>
public dvec4 bbrg => new dvec4(z, z, x, y);
/// <summary>
/// Returns dvec3.zzxz swizzling.
/// </summary>
public dvec4 zzxz => new dvec4(z, z, x, z);
/// <summary>
/// Returns dvec3.bbrb swizzling (equivalent to dvec3.zzxz).
/// </summary>
public dvec4 bbrb => new dvec4(z, z, x, z);
/// <summary>
/// Returns dvec3.zzy swizzling.
/// </summary>
public dvec3 zzy => new dvec3(z, z, y);
/// <summary>
/// Returns dvec3.bbg swizzling (equivalent to dvec3.zzy).
/// </summary>
public dvec3 bbg => new dvec3(z, z, y);
/// <summary>
/// Returns dvec3.zzyx swizzling.
/// </summary>
public dvec4 zzyx => new dvec4(z, z, y, x);
/// <summary>
/// Returns dvec3.bbgr swizzling (equivalent to dvec3.zzyx).
/// </summary>
public dvec4 bbgr => new dvec4(z, z, y, x);
/// <summary>
/// Returns dvec3.zzyy swizzling.
/// </summary>
public dvec4 zzyy => new dvec4(z, z, y, y);
/// <summary>
/// Returns dvec3.bbgg swizzling (equivalent to dvec3.zzyy).
/// </summary>
public dvec4 bbgg => new dvec4(z, z, y, y);
/// <summary>
/// Returns dvec3.zzyz swizzling.
/// </summary>
public dvec4 zzyz => new dvec4(z, z, y, z);
/// <summary>
/// Returns dvec3.bbgb swizzling (equivalent to dvec3.zzyz).
/// </summary>
public dvec4 bbgb => new dvec4(z, z, y, z);
/// <summary>
/// Returns dvec3.zzz swizzling.
/// </summary>
public dvec3 zzz => new dvec3(z, z, z);
/// <summary>
/// Returns dvec3.bbb swizzling (equivalent to dvec3.zzz).
/// </summary>
public dvec3 bbb => new dvec3(z, z, z);
/// <summary>
/// Returns dvec3.zzzx swizzling.
/// </summary>
public dvec4 zzzx => new dvec4(z, z, z, x);
/// <summary>
/// Returns dvec3.bbbr swizzling (equivalent to dvec3.zzzx).
/// </summary>
public dvec4 bbbr => new dvec4(z, z, z, x);
/// <summary>
/// Returns dvec3.zzzy swizzling.
/// </summary>
public dvec4 zzzy => new dvec4(z, z, z, y);
/// <summary>
/// Returns dvec3.bbbg swizzling (equivalent to dvec3.zzzy).
/// </summary>
public dvec4 bbbg => new dvec4(z, z, z, y);
/// <summary>
/// Returns dvec3.zzzz swizzling.
/// </summary>
public dvec4 zzzz => new dvec4(z, z, z, z);
/// <summary>
/// Returns dvec3.bbbb swizzling (equivalent to dvec3.zzzz).
/// </summary>
public dvec4 bbbb => new dvec4(z, z, z, z);
#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.Net.Http.Headers;
using Xunit;
namespace System.Net.Http.Tests
{
public class RetryConditionHeaderValueTest
{
[Fact]
public void Ctor_EntityTagOverload_MatchExpectation()
{
RetryConditionHeaderValue retryCondition = new RetryConditionHeaderValue(new TimeSpan(0, 0, 3));
Assert.Equal(new TimeSpan(0, 0, 3), retryCondition.Delta);
Assert.Null(retryCondition.Date);
Assert.Throws<ArgumentOutOfRangeException>(() => { new RetryConditionHeaderValue(new TimeSpan(1234567, 0, 0)); });
}
[Fact]
public void Ctor_DateOverload_MatchExpectation()
{
RetryConditionHeaderValue retryCondition = new RetryConditionHeaderValue(
new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero));
Assert.Null(retryCondition.Delta);
Assert.Equal(new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero), retryCondition.Date);
}
[Fact]
public void ToString_UseDifferentRetryConditions_AllSerializedCorrectly()
{
RetryConditionHeaderValue retryCondition = new RetryConditionHeaderValue(new TimeSpan(0, 0, 50000000));
Assert.Equal("50000000", retryCondition.ToString());
retryCondition = new RetryConditionHeaderValue(new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero));
Assert.Equal("Thu, 15 Jul 2010 12:33:57 GMT", retryCondition.ToString());
}
[Fact]
public void GetHashCode_UseSameAndDifferentRetryConditions_SameOrDifferentHashCodes()
{
RetryConditionHeaderValue retryCondition1 = new RetryConditionHeaderValue(new TimeSpan(0, 0, 1000000));
RetryConditionHeaderValue retryCondition2 = new RetryConditionHeaderValue(new TimeSpan(0, 0, 1000000));
RetryConditionHeaderValue retryCondition3 = new RetryConditionHeaderValue(
new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero));
RetryConditionHeaderValue retryCondition4 = new RetryConditionHeaderValue(
new DateTimeOffset(2008, 8, 16, 13, 44, 10, TimeSpan.Zero));
RetryConditionHeaderValue retryCondition5 = new RetryConditionHeaderValue(
new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero));
RetryConditionHeaderValue retryCondition6 = new RetryConditionHeaderValue(new TimeSpan(0, 0, 2000000));
Assert.Equal(retryCondition1.GetHashCode(), retryCondition2.GetHashCode());
Assert.NotEqual(retryCondition1.GetHashCode(), retryCondition3.GetHashCode());
Assert.NotEqual(retryCondition3.GetHashCode(), retryCondition4.GetHashCode());
Assert.Equal(retryCondition3.GetHashCode(), retryCondition5.GetHashCode());
Assert.NotEqual(retryCondition1.GetHashCode(), retryCondition6.GetHashCode());
}
[Fact]
public void Equals_UseSameAndDifferentRetrys_EqualOrNotEqualNoExceptions()
{
RetryConditionHeaderValue retryCondition1 = new RetryConditionHeaderValue(new TimeSpan(0, 0, 1000000));
RetryConditionHeaderValue retryCondition2 = new RetryConditionHeaderValue(new TimeSpan(0, 0, 1000000));
RetryConditionHeaderValue retryCondition3 = new RetryConditionHeaderValue(
new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero));
RetryConditionHeaderValue retryCondition4 = new RetryConditionHeaderValue(
new DateTimeOffset(2008, 8, 16, 13, 44, 10, TimeSpan.Zero));
RetryConditionHeaderValue retryCondition5 = new RetryConditionHeaderValue(
new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero));
RetryConditionHeaderValue retryCondition6 = new RetryConditionHeaderValue(new TimeSpan(0, 0, 2000000));
Assert.False(retryCondition1.Equals(null), "delta vs. <null>");
Assert.True(retryCondition1.Equals(retryCondition2), "delta vs. delta");
Assert.False(retryCondition1.Equals(retryCondition3), "delta vs. date");
Assert.False(retryCondition3.Equals(retryCondition1), "date vs. delta");
Assert.False(retryCondition3.Equals(retryCondition4), "date vs. different date");
Assert.True(retryCondition3.Equals(retryCondition5), "date vs. date");
Assert.False(retryCondition1.Equals(retryCondition6), "delta vs. different delta");
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
RetryConditionHeaderValue source = new RetryConditionHeaderValue(new TimeSpan(0, 0, 123456789));
RetryConditionHeaderValue clone = (RetryConditionHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Delta, clone.Delta);
Assert.Null(clone.Date);
source = new RetryConditionHeaderValue(new DateTimeOffset(2010, 7, 15, 12, 33, 57, TimeSpan.Zero));
clone = (RetryConditionHeaderValue)((ICloneable)source).Clone();
Assert.Null(clone.Delta);
Assert.Equal(source.Date, clone.Date);
}
[Fact]
public void GetRetryConditionLength_DifferentValidScenarios_AllReturnNonZero()
{
RetryConditionHeaderValue result = null;
CallGetRetryConditionLength(" 1234567890 ", 1, 11, out result);
Assert.Equal(new TimeSpan(0, 0, 1234567890), result.Delta);
Assert.Null(result.Date);
CallGetRetryConditionLength("1", 0, 1, out result);
Assert.Equal(new TimeSpan(0, 0, 1), result.Delta);
Assert.Null(result.Date);
CallGetRetryConditionLength("001", 0, 3, out result);
Assert.Equal(new TimeSpan(0, 0, 1), result.Delta);
Assert.Null(result.Date);
CallGetRetryConditionLength("Wed, 09 Nov 1994 08:49:37 GMT", 0, 29, out result);
Assert.Null(result.Delta);
Assert.Equal(new DateTimeOffset(1994, 11, 9, 8, 49, 37, TimeSpan.Zero), result.Date);
CallGetRetryConditionLength("Sun, 06 Nov 1994 08:49:37 GMT ", 0, 34, out result);
Assert.Null(result.Delta);
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), result.Date);
}
[Fact]
public void GetRetryConditionLength_DifferentInvalidScenarios_AllReturnZero()
{
CheckInvalidGetRetryConditionLength(" 1", 0); // no leading whitespaces allowed
CheckInvalidGetRetryConditionLength(" Wed 09 Nov 1994 08:49:37 GMT", 0);
CheckInvalidGetRetryConditionLength("-5", 0);
// Even though the first char is a valid 'delta', GetRetryConditionLength() expects the whole string to be
// a valid 'delta'.
CheckInvalidGetRetryConditionLength("1.5", 0);
CheckInvalidGetRetryConditionLength("5123,", 0);
CheckInvalidGetRetryConditionLength("123456789012345678901234567890", 0); // >>Int32.MaxValue
CheckInvalidGetRetryConditionLength("9999999999", 0); // >Int32.MaxValue but same amount of digits
CheckInvalidGetRetryConditionLength("Wed, 09 Nov", 0);
CheckInvalidGetRetryConditionLength("W/Wed 09 Nov 1994 08:49:37 GMT", 0);
CheckInvalidGetRetryConditionLength("Wed 09 Nov 1994 08:49:37 GMT,", 0);
CheckInvalidGetRetryConditionLength("", 0);
CheckInvalidGetRetryConditionLength(null, 0);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidParse(" 123456789 ", new RetryConditionHeaderValue(new TimeSpan(0, 0, 123456789)));
CheckValidParse(" Sun, 06 Nov 1994 08:49:37 GMT ",
new RetryConditionHeaderValue(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero)));
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse("123 ,"); // no delimiter allowed
CheckInvalidParse("Sun, 06 Nov 1994 08:49:37 GMT ,"); // no delimiter allowed
CheckInvalidParse("123 Sun, 06 Nov 1994 08:49:37 GMT");
CheckInvalidParse("Sun, 06 Nov 1994 08:49:37 GMT \"x\"");
CheckInvalidParse(null);
CheckInvalidParse(string.Empty);
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidTryParse(" 123456789 ", new RetryConditionHeaderValue(new TimeSpan(0, 0, 123456789)));
CheckValidTryParse(" Sun, 06 Nov 1994 08:49:37 GMT ",
new RetryConditionHeaderValue(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero)));
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse("123 ,"); // no delimiter allowed
CheckInvalidTryParse("Sun, 06 Nov 1994 08:49:37 GMT ,"); // no delimiter allowed
CheckInvalidTryParse("123 Sun, 06 Nov 1994 08:49:37 GMT");
CheckInvalidTryParse("Sun, 06 Nov 1994 08:49:37 GMT \"x\"");
CheckInvalidTryParse(null);
CheckInvalidTryParse(string.Empty);
}
#region Helper methods
private void CheckValidParse(string input, RetryConditionHeaderValue expectedResult)
{
RetryConditionHeaderValue result = RetryConditionHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input)
{
Assert.Throws<FormatException>(() => { RetryConditionHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, RetryConditionHeaderValue expectedResult)
{
RetryConditionHeaderValue result = null;
Assert.True(RetryConditionHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input)
{
RetryConditionHeaderValue result = null;
Assert.False(RetryConditionHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
private static void CallGetRetryConditionLength(string input, int startIndex, int expectedLength,
out RetryConditionHeaderValue result)
{
object temp = null;
Assert.Equal(expectedLength, RetryConditionHeaderValue.GetRetryConditionLength(input, startIndex,
out temp));
result = temp as RetryConditionHeaderValue;
}
private static void CheckInvalidGetRetryConditionLength(string input, int startIndex)
{
object result = null;
Assert.Equal(0, RetryConditionHeaderValue.GetRetryConditionLength(input, startIndex, out result));
Assert.Null(result);
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="UInt32Storage.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.Xml;
using System.Data.SqlTypes;
using System.Collections;
internal sealed class UInt32Storage : DataStorage {
private static readonly UInt32 defaultValue = UInt32.MinValue;
private UInt32[] values;
public UInt32Storage(DataColumn column)
: base(column, typeof(UInt32), defaultValue, StorageType.UInt32) {
}
override public Object Aggregate(int[] records, AggregateType kind) {
bool hasData = false;
try {
switch (kind) {
case AggregateType.Sum:
UInt64 sum = defaultValue;
foreach (int record in records) {
if (HasValue(record)) {
checked { sum += (UInt64) values[record];}
hasData = true;
}
}
if (hasData) {
return sum;
}
return NullValue;
case AggregateType.Mean:
Int64 meanSum = (Int64)defaultValue;
int meanCount = 0;
foreach (int record in records) {
if (HasValue(record)) {
checked { meanSum += (Int64)values[record];}
meanCount++;
hasData = true;
}
}
if (hasData) {
UInt32 mean;
checked {mean = (UInt32)(meanSum / meanCount);}
return mean;
}
return NullValue;
case AggregateType.Var:
case AggregateType.StDev:
int count = 0;
double var = 0.0f;
double prec = 0.0f;
double dsum = 0.0f;
double sqrsum = 0.0f;
foreach (int record in records) {
if (HasValue(record)) {
dsum += (double)values[record];
sqrsum += (double)values[record]*(double)values[record];
count++;
}
}
if (count > 1) {
var = ((double)count * sqrsum - (dsum * dsum));
prec = var / (dsum * dsum);
// we are dealing with the risk of a cancellation error
// double is guaranteed only for 15 digits so a difference
// with a result less than 1e-15 should be considered as zero
if ((prec < 1e-15) || (var <0))
var = 0;
else
var = var / (count * (count -1));
if (kind == AggregateType.StDev) {
return Math.Sqrt(var);
}
return var;
}
return NullValue;
case AggregateType.Min:
UInt32 min = UInt32.MaxValue;
for (int i = 0; i < records.Length; i++) {
int record = records[i];
if (HasValue(record)) {
min=Math.Min(values[record], min);
hasData = true;
}
}
if (hasData) {
return min;
}
return NullValue;
case AggregateType.Max:
UInt32 max = UInt32.MinValue;
for (int i = 0; i < records.Length; i++) {
int record = records[i];
if (HasValue(record)) {
max=Math.Max(values[record], max);
hasData = true;
}
}
if (hasData) {
return max;
}
return NullValue;
case AggregateType.First:
if (records.Length > 0) {
return values[records[0]];
}
return null;
case AggregateType.Count:
count = 0;
for (int i = 0; i < records.Length; i++) {
if (HasValue(records[i]))
count++;
}
return count;
}
}
catch (OverflowException) {
throw ExprException.Overflow(typeof(UInt32));
}
throw ExceptionBuilder.AggregateException(kind, DataType);
}
override public int Compare(int recordNo1, int recordNo2) {
UInt32 valueNo1 = values[recordNo1];
UInt32 valueNo2 = values[recordNo2];
if (valueNo1 == defaultValue || valueNo2 == defaultValue) {
int bitCheck = CompareBits(recordNo1, recordNo2);
if (0 != bitCheck) {
return bitCheck;
}
}
//return valueNo1.CompareTo(valueNo2);
return(valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to UInt32.CompareTo(UInt32)
}
public override int CompareValueTo(int recordNo, object value) {
System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record");
System.Diagnostics.Debug.Assert(null != value, "null value");
if (NullValue == value) {
return (HasValue(recordNo) ? 1 : 0);
}
UInt32 valueNo1 = values[recordNo];
if ((defaultValue == valueNo1) && !HasValue(recordNo)) {
return -1;
}
return valueNo1.CompareTo((UInt32)value);
//return(valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to UInt32.CompareTo(UInt32)
}
public override object ConvertValue(object value) {
if (NullValue != value) {
if (null != value) {
value = ((IConvertible)value).ToUInt32(FormatProvider);
}
else {
value = NullValue;
}
}
return value;
}
override public void Copy(int recordNo1, int recordNo2) {
CopyBits(recordNo1, recordNo2);
values[recordNo2] = values[recordNo1];
}
override public Object Get(int record) {
UInt32 value = values[record];
if (!value.Equals(defaultValue)) {
return value;
}
return GetBits(record);
}
override public void Set(int record, Object value) {
System.Diagnostics.Debug.Assert(null != value, "null value");
if (NullValue == value) {
values[record] = defaultValue;
SetNullBit(record, true);
}
else {
values[record] = ((IConvertible)value).ToUInt32(FormatProvider);
SetNullBit(record, false);
}
}
override public void SetCapacity(int capacity) {
UInt32[] newValues = new UInt32[capacity];
if (null != values) {
Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length));
}
values = newValues;
base.SetCapacity(capacity);
}
override public object ConvertXmlToObject(string s) {
return XmlConvert.ToUInt32(s);
}
override public string ConvertObjectToXml(object value) {
return XmlConvert.ToString((UInt32)value);
}
override protected object GetEmptyStorage(int recordCount) {
return new UInt32[recordCount];
}
override protected void CopyValue(int record, object store, BitArray nullbits, int storeIndex) {
UInt32[] typedStore = (UInt32[]) store;
typedStore[storeIndex] = values[record];
nullbits.Set(storeIndex, !HasValue(record));
}
override protected void SetStorage(object store, BitArray nullbits) {
values = (UInt32[]) store;
SetNullStorage(nullbits);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
/// <summary>
/// Service to maintain information about the suppression state of specific set of items in the error list.
/// </summary>
[Export(typeof(IVisualStudioDiagnosticListSuppressionStateService))]
internal class VisualStudioDiagnosticListSuppressionStateService : IVisualStudioDiagnosticListSuppressionStateService
{
private readonly VisualStudioWorkspace _workspace;
private readonly IVsUIShell _shellService;
private readonly IWpfTableControl _tableControl;
private int _selectedActiveItems;
private int _selectedSuppressedItems;
private int _selectedRoslynItems;
private int _selectedCompilerDiagnosticItems;
private int _selectedNoLocationDiagnosticItems;
private int _selectedNonSuppressionStateItems;
[ImportingConstructor]
public VisualStudioDiagnosticListSuppressionStateService(
SVsServiceProvider serviceProvider,
VisualStudioWorkspace workspace)
{
_workspace = workspace;
_shellService = (IVsUIShell)serviceProvider.GetService(typeof(SVsUIShell));
var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList;
_tableControl = errorList?.TableControl;
ClearState();
InitializeFromTableControlIfNeeded();
}
private int SelectedItems => _selectedActiveItems + _selectedSuppressedItems + _selectedNonSuppressionStateItems;
// If we can suppress either in source or in suppression file, we enable suppress context menu.
public bool CanSuppressSelectedEntries => CanSuppressSelectedEntriesInSource || CanSuppressSelectedEntriesInSuppressionFiles;
// If at least one suppressed item is selected, we enable remove suppressions.
public bool CanRemoveSuppressionsSelectedEntries => _selectedSuppressedItems > 0;
// If at least one Roslyn active item with location is selected, we enable suppress in source.
// Note that we do not support suppress in source when mix of Roslyn and non-Roslyn items are selected as in-source suppression has different meaning and implementation for these.
public bool CanSuppressSelectedEntriesInSource => _selectedActiveItems > 0 &&
_selectedRoslynItems == _selectedActiveItems &&
(_selectedRoslynItems - _selectedNoLocationDiagnosticItems) > 0;
// If at least one Roslyn active item is selected, we enable suppress in suppression file.
// Also, compiler diagnostics cannot be suppressed in suppression file, so there must be at least one non-compiler item.
public bool CanSuppressSelectedEntriesInSuppressionFiles => _selectedActiveItems > 0 &&
(_selectedRoslynItems - _selectedCompilerDiagnosticItems) > 0;
private void ClearState()
{
_selectedActiveItems = 0;
_selectedSuppressedItems = 0;
_selectedRoslynItems = 0;
_selectedCompilerDiagnosticItems = 0;
_selectedNoLocationDiagnosticItems = 0;
_selectedNonSuppressionStateItems = 0;
}
private void InitializeFromTableControlIfNeeded()
{
if (_tableControl == null)
{
return;
}
if (SelectedItems == _tableControl.SelectedEntries.Count())
{
// We already have up-to-date state data, so don't need to re-compute.
return;
}
ClearState();
if (ProcessEntries(_tableControl.SelectedEntries, added: true))
{
UpdateQueryStatus();
}
}
/// <summary>
/// Updates suppression state information when the selected entries change in the error list.
/// </summary>
public void ProcessSelectionChanged(TableSelectionChangedEventArgs e)
{
var hasAddedSuppressionStateEntry = ProcessEntries(e.AddedEntries, added: true);
var hasRemovedSuppressionStateEntry = ProcessEntries(e.RemovedEntries, added: false);
// If any entry that supports suppression state was ever involved, update query status since each item in the error list
// can have different context menu.
if (hasAddedSuppressionStateEntry || hasRemovedSuppressionStateEntry)
{
UpdateQueryStatus();
}
InitializeFromTableControlIfNeeded();
}
private bool ProcessEntries(IEnumerable<ITableEntryHandle> entryHandles, bool added)
{
bool isRoslynEntry, isSuppressedEntry, isCompilerDiagnosticEntry, isNoLocationDiagnosticEntry;
var hasSuppressionStateEntry = false;
foreach (var entryHandle in entryHandles)
{
if (EntrySupportsSuppressionState(entryHandle, out isRoslynEntry, out isSuppressedEntry, out isCompilerDiagnosticEntry, out isNoLocationDiagnosticEntry))
{
hasSuppressionStateEntry = true;
HandleSuppressionStateEntry(isRoslynEntry, isSuppressedEntry, isCompilerDiagnosticEntry, isNoLocationDiagnosticEntry, added);
}
else
{
HandleNonSuppressionStateEntry(added);
}
}
return hasSuppressionStateEntry;
}
private static bool EntrySupportsSuppressionState(ITableEntryHandle entryHandle, out bool isRoslynEntry, out bool isSuppressedEntry, out bool isCompilerDiagnosticEntry, out bool isNoLocationDiagnosticEntry)
{
string filePath;
isNoLocationDiagnosticEntry = !entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out filePath) ||
string.IsNullOrEmpty(filePath);
int index;
var roslynSnapshot = GetEntriesSnapshot(entryHandle, out index);
if (roslynSnapshot == null)
{
isRoslynEntry = false;
isCompilerDiagnosticEntry = false;
return IsNonRoslynEntrySupportingSuppressionState(entryHandle, out isSuppressedEntry);
}
var diagnosticData = roslynSnapshot?.GetItem(index)?.Primary;
if (!IsEntryWithConfigurableSuppressionState(diagnosticData))
{
isRoslynEntry = false;
isSuppressedEntry = false;
isCompilerDiagnosticEntry = false;
return false;
}
isRoslynEntry = true;
isSuppressedEntry = diagnosticData.IsSuppressed;
isCompilerDiagnosticEntry = SuppressionHelpers.IsCompilerDiagnostic(diagnosticData);
return true;
}
private static bool IsNonRoslynEntrySupportingSuppressionState(ITableEntryHandle entryHandle, out bool isSuppressedEntry)
{
string suppressionStateValue;
if (entryHandle.TryGetValue(SuppressionStateColumnDefinition.ColumnName, out suppressionStateValue))
{
isSuppressedEntry = suppressionStateValue == ServicesVSResources.Suppressed;
return true;
}
isSuppressedEntry = false;
return false;
}
/// <summary>
/// Returns true if an entry's suppression state can be modified.
/// </summary>
/// <returns></returns>
private static bool IsEntryWithConfigurableSuppressionState(DiagnosticData entry)
{
// Compiler diagnostics with severity 'Error' are not configurable.
// Additionally, diagnostics coming from build are from a snapshot (as opposed to live diagnostics) and cannot be configured.
return entry != null &&
!SuppressionHelpers.IsNotConfigurableDiagnostic(entry) &&
!entry.IsBuildDiagnostic();
}
private static AbstractTableEntriesSnapshot<DiagnosticData> GetEntriesSnapshot(ITableEntryHandle entryHandle)
{
int index;
return GetEntriesSnapshot(entryHandle, out index);
}
private static AbstractTableEntriesSnapshot<DiagnosticData> GetEntriesSnapshot(ITableEntryHandle entryHandle, out int index)
{
ITableEntriesSnapshot snapshot;
if (!entryHandle.TryGetSnapshot(out snapshot, out index))
{
return null;
}
return snapshot as AbstractTableEntriesSnapshot<DiagnosticData>;
}
/// <summary>
/// Gets <see cref="DiagnosticData"/> objects for selected error list entries.
/// For remove suppression, the method also returns selected external source diagnostics.
/// </summary>
public async Task<ImmutableArray<DiagnosticData>> GetSelectedItemsAsync(bool isAddSuppression, CancellationToken cancellationToken)
{
var builder = ImmutableArray.CreateBuilder<DiagnosticData>();
Dictionary<string, Project> projectNameToProjectMapOpt = null;
Dictionary<Project, ImmutableDictionary<string, Document>> filePathToDocumentMapOpt = null;
foreach (var entryHandle in _tableControl.SelectedEntries)
{
cancellationToken.ThrowIfCancellationRequested();
DiagnosticData diagnosticData = null;
int index;
var roslynSnapshot = GetEntriesSnapshot(entryHandle, out index);
if (roslynSnapshot != null)
{
diagnosticData = roslynSnapshot.GetItem(index)?.Primary;
}
else if (!isAddSuppression)
{
// For suppression removal, we also need to handle FxCop entries.
bool isSuppressedEntry;
if (!IsNonRoslynEntrySupportingSuppressionState(entryHandle, out isSuppressedEntry) ||
!isSuppressedEntry)
{
continue;
}
string errorCode = null, category = null, message = null, filePath = null, projectName = null;
int line = -1; // FxCop only supports line, not column.
DiagnosticDataLocation location = null;
if (entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCode, out errorCode) && !string.IsNullOrEmpty(errorCode) &&
entryHandle.TryGetValue(StandardTableColumnDefinitions.ErrorCategory, out category) && !string.IsNullOrEmpty(category) &&
entryHandle.TryGetValue(StandardTableColumnDefinitions.Text, out message) && !string.IsNullOrEmpty(message) &&
entryHandle.TryGetValue(StandardTableColumnDefinitions.ProjectName, out projectName) && !string.IsNullOrEmpty(projectName))
{
if (projectNameToProjectMapOpt == null)
{
projectNameToProjectMapOpt = new Dictionary<string, Project>();
foreach (var p in _workspace.CurrentSolution.Projects)
{
projectNameToProjectMapOpt[p.Name] = p;
}
}
cancellationToken.ThrowIfCancellationRequested();
Project project;
if (!projectNameToProjectMapOpt.TryGetValue(projectName, out project))
{
// bail out
continue;
}
Document document = null;
var hasLocation = (entryHandle.TryGetValue(StandardTableColumnDefinitions.DocumentName, out filePath) && !string.IsNullOrEmpty(filePath)) &&
(entryHandle.TryGetValue(StandardTableColumnDefinitions.Line, out line) && line >= 0);
if (hasLocation)
{
if (string.IsNullOrEmpty(filePath) || line < 0)
{
// bail out
continue;
}
ImmutableDictionary<string, Document> filePathMap;
filePathToDocumentMapOpt = filePathToDocumentMapOpt ?? new Dictionary<Project, ImmutableDictionary<string, Document>>();
if (!filePathToDocumentMapOpt.TryGetValue(project, out filePathMap))
{
filePathMap = await GetFilePathToDocumentMapAsync(project, cancellationToken).ConfigureAwait(false);
filePathToDocumentMapOpt[project] = filePathMap;
}
if (!filePathMap.TryGetValue(filePath, out document))
{
// bail out
continue;
}
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var linePosition = new LinePosition(line, 0);
var linePositionSpan = new LinePositionSpan(start: linePosition, end: linePosition);
var textSpan = (await tree.GetTextAsync(cancellationToken).ConfigureAwait(false)).Lines.GetTextSpan(linePositionSpan);
location = new DiagnosticDataLocation(document.Id, textSpan, filePath,
originalStartLine: linePosition.Line, originalStartColumn: linePosition.Character,
originalEndLine: linePosition.Line, originalEndColumn: linePosition.Character);
}
Contract.ThrowIfNull(project);
Contract.ThrowIfFalse((document != null) == (location != null));
// Create a diagnostic with correct values for fields we care about: id, category, message, isSuppressed, location
// and default values for the rest of the fields (not used by suppression fixer).
diagnosticData = new DiagnosticData(
id: errorCode,
category: category,
message: message,
enuMessageForBingSearch: message,
severity: DiagnosticSeverity.Warning,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
warningLevel: 1,
isSuppressed: isSuppressedEntry,
title: message,
location: location,
customTags: SuppressionHelpers.SynthesizedExternalSourceDiagnosticCustomTags,
properties: ImmutableDictionary<string, string>.Empty,
workspace: _workspace,
projectId: project.Id);
}
}
if (IsEntryWithConfigurableSuppressionState(diagnosticData))
{
builder.Add(diagnosticData);
}
}
return builder.ToImmutable();
}
private static async Task<ImmutableDictionary<string, Document>> GetFilePathToDocumentMapAsync(Project project, CancellationToken cancellationToken)
{
var builder = ImmutableDictionary.CreateBuilder<string, Document>();
foreach (var document in project.Documents)
{
cancellationToken.ThrowIfCancellationRequested();
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var filePath = tree.FilePath;
if (filePath != null)
{
builder.Add(filePath, document);
}
}
return builder.ToImmutable();
}
private static void UpdateSelectedItems(bool added, ref int count)
{
if (added)
{
count++;
}
else
{
count--;
}
}
private void HandleSuppressionStateEntry(bool isRoslynEntry, bool isSuppressedEntry, bool isCompilerDiagnosticEntry, bool isNoLocationDiagnosticEntry, bool added)
{
if (isRoslynEntry)
{
UpdateSelectedItems(added, ref _selectedRoslynItems);
}
if (isCompilerDiagnosticEntry)
{
UpdateSelectedItems(added, ref _selectedCompilerDiagnosticItems);
}
if (isNoLocationDiagnosticEntry)
{
UpdateSelectedItems(added, ref _selectedNoLocationDiagnosticItems);
}
if (isSuppressedEntry)
{
UpdateSelectedItems(added, ref _selectedSuppressedItems);
}
else
{
UpdateSelectedItems(added, ref _selectedActiveItems);
}
}
private void HandleNonSuppressionStateEntry(bool added)
{
UpdateSelectedItems(added, ref _selectedNonSuppressionStateItems);
}
private void UpdateQueryStatus()
{
// Force the shell to refresh the QueryStatus for all the command since default behavior is it only does query
// when focus on error list has changed, not individual items.
if (_shellService != null)
{
_shellService.UpdateCommandUI(0);
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public struct CustomAttributeArgument {
readonly TypeReference type;
readonly object value;
public TypeReference Type {
get { return type; }
}
public object Value {
get { return value; }
}
public CustomAttributeArgument (TypeReference type, object value)
{
Mixin.CheckType (type);
this.type = type;
this.value = value;
}
}
public struct CustomAttributeNamedArgument {
readonly string name;
readonly CustomAttributeArgument argument;
public string Name {
get { return name; }
}
public CustomAttributeArgument Argument {
get { return argument; }
}
public CustomAttributeNamedArgument (string name, CustomAttributeArgument argument)
{
Mixin.CheckName (name);
this.name = name;
this.argument = argument;
}
}
public interface ICustomAttribute {
TypeReference AttributeType { get; }
bool HasFields { get; }
bool HasProperties { get; }
bool HasConstructorArguments { get; }
Collection<CustomAttributeNamedArgument> Fields { get; }
Collection<CustomAttributeNamedArgument> Properties { get; }
Collection<CustomAttributeArgument> ConstructorArguments { get; }
}
public sealed class CustomAttribute : ICustomAttribute {
internal CustomAttributeValueProjection projection;
readonly internal uint signature;
internal bool resolved;
MethodReference constructor;
byte [] blob;
internal Collection<CustomAttributeArgument> arguments;
internal Collection<CustomAttributeNamedArgument> fields;
internal Collection<CustomAttributeNamedArgument> properties;
public MethodReference Constructor {
get { return constructor; }
set { constructor = value; }
}
public TypeReference AttributeType {
get { return constructor.DeclaringType; }
}
public bool IsResolved {
get { return resolved; }
}
public bool HasConstructorArguments {
get {
Resolve ();
return !arguments.IsNullOrEmpty ();
}
}
public Collection<CustomAttributeArgument> ConstructorArguments {
get {
Resolve ();
return arguments ?? (arguments = new Collection<CustomAttributeArgument> ());
}
}
public bool HasFields {
get {
Resolve ();
return !fields.IsNullOrEmpty ();
}
}
public Collection<CustomAttributeNamedArgument> Fields {
get {
Resolve ();
return fields ?? (fields = new Collection<CustomAttributeNamedArgument> ());
}
}
public bool HasProperties {
get {
Resolve ();
return !properties.IsNullOrEmpty ();
}
}
public Collection<CustomAttributeNamedArgument> Properties {
get {
Resolve ();
return properties ?? (properties = new Collection<CustomAttributeNamedArgument> ());
}
}
internal bool HasImage {
get { return constructor != null && constructor.HasImage; }
}
internal ModuleDefinition Module {
get { return constructor.Module; }
}
internal CustomAttribute (uint signature, MethodReference constructor)
{
this.signature = signature;
this.constructor = constructor;
this.resolved = false;
}
public CustomAttribute (MethodReference constructor)
{
this.constructor = constructor;
this.resolved = true;
}
public CustomAttribute (MethodReference constructor, byte [] blob)
{
this.constructor = constructor;
this.resolved = false;
this.blob = blob;
}
public byte [] GetBlob ()
{
if (blob != null)
return blob;
if (!HasImage)
throw new NotSupportedException ();
return Module.Read (ref blob, this, (attribute, reader) => reader.ReadCustomAttributeBlob (attribute.signature));
}
void Resolve ()
{
if (resolved || !HasImage)
return;
Module.Read (this, (attribute, reader) => {
try {
reader.ReadCustomAttributeSignature (attribute);
resolved = true;
} catch (ResolutionException) {
if (arguments != null)
arguments.Clear ();
if (fields != null)
fields.Clear ();
if (properties != null)
properties.Clear ();
resolved = false;
}
});
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Text;
using MLifter.DAL;
using MLifter.DAL.Interfaces;
namespace MLifter.DAL.Transformer.V17
{
/// <summary>
/// This class can convert a MemoryLifter V1.7 dictionary to a newer format.
/// </summary>
public sealed class Converter
{
private string m_applicationPath = String.Empty;
private int m_nrBox = 10;
private int m_defaultCategory = Category.DefaultCategory;
private const int m_releaseYear = 2006;
private const int m_oldFileVersion = 0x0109;
private const string m_odfFileHeaderString = "OMICRON dictionary file";
private GetLoginInformation m_loginCallback = null;
private Encoding m_SourceEncoding = Encoding.Default;
private BackgroundWorker m_BackgroundWorker;
/// <summary>
/// Initializes a new instance of the <see cref="Converter"/> class.
/// </summary>
public Converter()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Converter"/> class.
/// </summary>
/// <param name="backgroundWorker">The background worker.</param>
public Converter(BackgroundWorker backgroundWorker)
{
m_BackgroundWorker = backgroundWorker;
}
/// <summary>
/// Gets or sets the source encoding.
/// </summary>
/// <value>
/// The source encoding.
/// </value>
public Encoding SourceEncoding
{
get { return m_SourceEncoding; }
set { m_SourceEncoding = value; }
}
/// <summary>
/// Gets or sets the application path.
/// </summary>
/// <value>
/// The application path.
/// </value>
public string ApplicationPath
{
get { return m_applicationPath; }
set { m_applicationPath = value; }
}
/// <summary>
/// Gets or sets the number of boxes.
/// </summary>
/// <value>
/// The number of boxes.
/// </value>
public int NumberOfBoxes
{
get { return m_nrBox; }
set { m_nrBox = value; }
}
/// <summary>
/// Gets or sets the default category.
/// </summary>
/// <value>
/// The default category.
/// </value>
public int DefaultCategory
{
get { return m_defaultCategory; }
set { m_defaultCategory = value; }
}
/// <summary>
/// Gets or sets the login callback.
/// </summary>
/// <value>The login callback.</value>
/// <remarks>Documented by Dev03, 2008-09-08</remarks>
public GetLoginInformation LoginCallback
{
get { return m_loginCallback; }
set { m_loginCallback = value; }
}
/// <summary>
/// This enumerator defines the available multimedia resources for old version dictionaries.
/// </summary>
private enum TCardPart { None = 0, SentSrc = 1, SentDst = 2, Image = 4, AudioSrc = 8, AudioDst = 16 };
/// <summary>
/// This enumerator defines the available blob types for the import of old version dictionary files.
/// </summary>
private enum TBlobType
{
questionaudio = 0, answeraudio, questionexampleaudio, answerexampleaudio,
questionvideo, answervideo, image
};
/// <summary>
/// Enumeration which defines the values for the 'Synonyms' options:
/// Full - all synonyms need to be known,
/// Half - half need to be known,
/// One - one need to be known,
/// First - the card is promoted when the first synonym is known,
/// Promp - prompt when not all were correct
/// </summary>
/// <remarks>Documented by Dev03, 2007-07-26</remarks>
private enum TSynonymGrading { Full = 0, Half, One, First, Prompt };
#region nested classes required to load old import files
/// <summary>
/// rBox (-> tabBox) stores data for each box - required for the import of v1 dictionaries
/// </summary>
/// <remarks>Documented by Dev03, 2007-07-20</remarks>
private class _rBox_
{
public int First, Last, MaxLen, Len; //First & last card ID, max size
public _rBox_()
{
First = 0;
Last = 0;
MaxLen = 0;
Len = 0;
}
}
/// <summary>
/// rChapter (-> tabChapter) stores chapter data - required for the import of v1 dictionaries
/// </summary>
/// <remarks>Documented by Dev03, 2007-07-20</remarks>
private class _rChapter_
{
public string Title; //Title
public string Description; //Description
public _rChapter_()
{
Title = string.Empty;
Description = string.Empty;
}
}
/// <summary>
/// rCards (-> tabCards) contains the actual cards - required for the import of v1 dictionaries
/// </summary>
/// <remarks>Documented by Dev03, 2007-07-20</remarks>
private class _rCards_
{
public StringList Src, Dst; //Q & A
public string SentSrc, SentDst; //examples
public int ChapterID; //ID pointing to tabChapter
public byte CardParts; //used parts of the card
//public byte Pr; //probability
public _rCards_()
{
Src = new StringList();
Dst = new StringList();
SentSrc = string.Empty;
SentDst = string.Empty;
ChapterID = 0;
CardParts = (byte)TCardPart.None;
//Pr = 0;
}
}
/// <summary>
/// rBoxes (-> tabBoxes) orders the cards in arrayList box - required for the import of v1 dictionaries
/// </summary>
/// <remarks>Documented by Dev03, 2007-07-20</remarks>
private class _rBoxes_
{
public int BoxID; //ID pointing to tabBox
public int CardID; //ID pointing to tabCards
public int Prior, Next; //prior & next in Box (dl list)
public _rBoxes_()
{
BoxID = 1;
CardID = 0;
Prior = 0;
Next = 0;
}
}
/// <summary>
/// rBlob (-> tabBlobs) stores blob data - only used for importing old files!
/// </summary>
/// <remarks>Documented by Dev03, 2007-07-20</remarks>
private class _rBlob_
{
public TBlobType SrcDst; //the blob type
public string Link; //link to the blob (relative)
public int CardID; //CardID it belongs to
public _rBlob_()
{
SrcDst = TBlobType.image;
Link = string.Empty;
CardID = 0;
}
}
/// <summary>
/// rStats (-> tabStats) stores statistics - required for the import of v1 dictionaries
/// </summary>
/// <remarks>Documented by Dev03, 2007-07-20</remarks>
private class _rStats_
{
public System.DateTime SStart, SEnd; //Start & End of session
public int Right, Wrong; //Number of rights & wrongs
public int[] Boxes; //Number of card in boxes
public _rStats_(int nrBox)
{
SStart = System.DateTime.Now.ToUniversalTime();
SEnd = System.DateTime.Now.ToUniversalTime();
Right = 0;
Wrong = 0;
Boxes = new int[nrBox];
}
}
#endregion
#region helper methods
private System.Array SetLength(System.Array oldArray, int newSize)
{
int oldSize = oldArray.Length;
System.Type elementType = oldArray.GetType().GetElementType();
System.Array newArray = System.Array.CreateInstance(elementType, newSize);
int preserveLength = System.Math.Min(oldSize, newSize);
if (preserveLength > 0)
System.Array.Copy(oldArray, newArray, preserveLength);
return newArray;
}
/// <summary>
/// Converts arrayList byte array to arrayList string.
/// </summary>
/// <param name="data">byte array</param>
/// <returns>string</returns>
/// <remarks>Documented by Dev03, 2007-07-26</remarks>
private string byte2string(byte[] data)
{
return m_SourceEncoding.GetString(data);
}
/// <summary>
/// This method translates the skin path given in the old dictionary format to the new format.
/// Only required during import of old version dictionaries.
/// </summary>
/// <param name="sdir">Old version skin path</param>
/// <param name="dicPath">The dicionary path.</param>
/// <param name="appPath">The application path.</param>
/// <returns>Translated skin path</returns>
/// <remarks>Documented by Dev03, 2007-07-26</remarks>
public string SkinDir2RealDir(string sdir, string dicPath, string appPath)
{
if (sdir.Equals("") || File.Exists(sdir))
return sdir;
if (sdir.IndexOf("($SKINS)") == 0)
return sdir.Replace("($SKINS)", Path.Combine(appPath, "skins"));
else if (sdir.IndexOf("($PRGM)") == 0)
return sdir.Replace("($PRGM)", appPath);
else
return Path.Combine(dicPath, sdir);
}
#endregion
/// <summary>
/// Reports the progress update.
/// </summary>
/// <param name="percent">The process advancement percent.</param>
/// <returns>True if the process has been canceled.</returns>
/// <remarks>Documented by Dev03, 2007-09-03</remarks>
private bool ReportProgressUpdate(int percent)
{
bool cancelProcess = false;
if (m_BackgroundWorker != null)
{
if (m_BackgroundWorker.CancellationPending)
{
cancelProcess = true;
}
else
{
m_BackgroundWorker.ReportProgress(percent);
}
}
return !cancelProcess;
}
/// <summary>
/// Loads dictionary from the old database format (ODF) and stores it to the current format.
/// </summary>
/// <param name="srcFile">The source database file.</param>
/// <param name="dstFile">The destination database file.</param>
/// <remarks>Documented by Dev03, 2007-07-26</remarks>
public MLifter.DAL.Interfaces.IDictionary Load(string srcFile, string dstFile)
{
MLifter.DAL.Interfaces.IDictionary dictionary = null;
int wbVersion;
#if !DEBUG
try
{
#endif
string srcPath = Path.GetDirectoryName(srcFile);
_rBox_[] box_data = new _rBox_[0];
_rChapter_[] chapter_data = new _rChapter_[0];
_rCards_[] cards_data = new _rCards_[0];
_rBoxes_[] boxes_data = new _rBoxes_[0];
_rBlob_[] blob_data = new _rBlob_[0];
_rStats_[] stats_data = new _rStats_[0];
string headerstr = string.Empty;
UInt16 ssize;
int len, rsize;
using (FileStream DicFile = new FileStream(srcFile, FileMode.Open))
{
BinaryReader Dic = new BinaryReader(DicFile, System.Text.UnicodeEncoding.UTF8);
// Check header first
len = Dic.ReadInt32();
if (len < 30)
headerstr = byte2string(Dic.ReadBytes(len));
else
headerstr = string.Empty;
// Check version byte
wbVersion = Dic.ReadInt16();
// Some code to correct "bugs" in previous dictionary versions
if (wbVersion <= 0x0104)
{
throw new DictionaryFormatNotSupported(wbVersion);
}
// Header has to be okay, and Version smaller than prog's version
if (headerstr.Equals(m_odfFileHeaderString) && (wbVersion <= m_oldFileVersion))
{
if (File.Exists(dstFile))
{
throw new DictionaryPathExistsException(dstFile);
}
IUser user = UserFactory.Create(m_loginCallback, new ConnectionStringStruct(DatabaseType.Xml, dstFile, false),
(DataAccessErrorDelegate)delegate { return; }, this);
dictionary =user.Open();
len = Dic.ReadByte();
dictionary.DefaultSettings.QuestionCaption = byte2string(Dic.ReadBytes(20)).Substring(0, len);
len = Dic.ReadByte();
dictionary.DefaultSettings.AnswerCaption = byte2string(Dic.ReadBytes(20)).Substring(0, len);
Dic.ReadBytes(82); //SrcFont & DstFont
Dic.ReadBytes(2); //SrcCharSet & DstCharSet
Dic.ReadBoolean(); //ReadOnly
ssize = Dic.ReadUInt16();
dictionary.Author = byte2string(Dic.ReadBytes(ssize));
ssize = Dic.ReadUInt16();
dictionary.Description = byte2string(Dic.ReadBytes(ssize));
if (wbVersion >= 0x0104)
{
ssize = Dic.ReadUInt16();
string mediafolder = byte2string(Dic.ReadBytes(ssize)).TrimEnd(new char[] { Path.DirectorySeparatorChar });
if (Directory.Exists(mediafolder))
dictionary.MediaDirectory = mediafolder;
}
if (wbVersion >= 0x0107)
{
for (int i = 0; i < 12; i++)
{
ssize = Dic.ReadUInt16();
dictionary.DefaultSettings.CommentarySounds[CommentarySoundIdentifier.Create(i > 6 ? Side.Answer : Side.Question,
(ECommentarySoundType)(i > 6 ? i - 6 : i))] =
new MLifter.DAL.XML.XmlAudio(SkinDir2RealDir(byte2string(Dic.ReadBytes(ssize)), Path.GetDirectoryName(dstFile), m_applicationPath),
new MLifter.DAL.Tools.ParentClass(user, dictionary));
}
}
if (wbVersion >= 0x0108)
{
Dic.ReadBytes(10); //Pwd
}
if (wbVersion >= 0x0109)
{
dictionary.Category = new Category((int)Dic.ReadByte(), false);
}
else
{
dictionary.Category = new Category(m_defaultCategory, true);
}
(dictionary as MLifter.DAL.XML.XmlDictionary).score = Dic.ReadInt32();
dictionary.HighScore = Dic.ReadInt32();
int queryChapter = 0;
rsize = Dic.ReadInt32();
dictionary.DefaultSettings.SelectedLearnChapters.Clear();
for (int i = 0; i < rsize; i++)
{
queryChapter = Math.Abs(Dic.ReadInt32()); // BUG?? what is the minus for??
if (queryChapter < 0) //chapterID starts with 1, should be zero-based
queryChapter++;
else
queryChapter--;
dictionary.DefaultSettings.SelectedLearnChapters.Add(queryChapter);
}
Dic.ReadUInt16(); //the LastBox user property is not used anymore
EQueryDirection dir = (EQueryDirection)Dic.ReadByte();
switch (dir)
{
case EQueryDirection.Question2Answer:
dictionary.DefaultSettings.QueryDirections.Question2Answer = true;
break;
case EQueryDirection.Answer2Question:
dictionary.DefaultSettings.QueryDirections.Answer2Question = true;
break;
case EQueryDirection.Mixed:
dictionary.DefaultSettings.QueryDirections.Mixed = true;
break;
}
int queryType = Convert.ToInt32(Dic.ReadByte());
dictionary.DefaultSettings.QueryTypes.ImageRecognition = ((((int)EQueryType.ImageRecognition) & queryType) > 0);
dictionary.DefaultSettings.QueryTypes.ListeningComprehension = ((((int)EQueryType.ListeningComprehension) & queryType) > 0);
dictionary.DefaultSettings.QueryTypes.MultipleChoice = ((((int)EQueryType.MultipleChoice) & queryType) > 0);
dictionary.DefaultSettings.QueryTypes.Sentence = ((((int)EQueryType.Sentences) & queryType) > 0);
dictionary.DefaultSettings.QueryTypes.Word = ((((int)EQueryType.Word) & queryType) > 0);
int queryOptions;
if (wbVersion >= 0x0103)
{
queryOptions = Convert.ToInt32(Dic.ReadUInt16());
}
else
{
queryOptions = Convert.ToInt32(Dic.ReadByte());
}
dictionary.DefaultSettings.CaseSensitive = ((((int)EQueryOption.CaseSensitive) & queryOptions) > 0);
dictionary.DefaultSettings.EnableTimer = ((((int)EQueryOption.CountDown) & queryOptions) > 0);
dictionary.DefaultSettings.ShowStatistics = ((((int)EQueryOption.Stats) & queryOptions) > 0);
dictionary.DefaultSettings.ShowImages = ((((int)EQueryOption.Images) & queryOptions) > 0);
dictionary.DefaultSettings.AutoplayAudio = ((((int)EQueryOption.Sounds) & queryOptions) > 0);
dictionary.DefaultSettings.EnableCommentary = ((((int)EQueryOption.Commentary) & queryOptions) > 0);
dictionary.DefaultSettings.CorrectOnTheFly = ((((int)EQueryOption.Correct) & queryOptions) > 0);
dictionary.DefaultSettings.SkipCorrectAnswers = ((((int)EQueryOption.Skip) & queryOptions) > 0);
dictionary.DefaultSettings.SelfAssessment = ((((int)EQueryOption.Self) & queryOptions) > 0);
dictionary.DefaultSettings.RandomPool = ((((int)EQueryOption.RandomPool) & queryOptions) > 0);
dictionary.DefaultSettings.ConfirmDemote = ((((int)EQueryOption.ConfirmDemote) & queryOptions) > 0);
if (wbVersion >= 0x0101)
{
EGradeSynonyms gradeS = (EGradeSynonyms)Dic.ReadByte();
switch (gradeS)
{
case EGradeSynonyms.AllKnown:
dictionary.DefaultSettings.GradeSynonyms.AllKnown = true;
break;
case EGradeSynonyms.HalfKnown:
dictionary.DefaultSettings.GradeSynonyms.HalfKnown = true;
break;
case EGradeSynonyms.OneKnown:
dictionary.DefaultSettings.GradeSynonyms.OneKnown = true;
break;
case EGradeSynonyms.FirstKnown:
dictionary.DefaultSettings.GradeSynonyms.FirstKnown = true;
break;
case EGradeSynonyms.Prompt:
dictionary.DefaultSettings.GradeSynonyms.Prompt = true;
break;
}
}
else
{
dictionary.DefaultSettings.GradeSynonyms.OneKnown = true;
}
dictionary.DefaultSettings.PoolEmptyMessageShown = Dic.ReadBoolean();
dictionary.DefaultSettings.UseLMStylesheets = false;
ssize = Dic.ReadUInt16();
Dic.ReadBytes(ssize); //Skin
Dic.ReadBoolean(); //UseSkin
string stripchars = String.Empty;
if (wbVersion >= 0x0102)
{
byte[] temp = Dic.ReadBytes(32);
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if ((temp[i] & (0x0001 << j)) > 0)
{
stripchars += (char)(i * 8 + j);
}
}
}
dictionary.DefaultSettings.StripChars = stripchars;
}
EGradeTyping gradeT = (EGradeTyping)Dic.ReadByte();
switch (gradeT)
{
case EGradeTyping.AllCorrect:
dictionary.DefaultSettings.GradeTyping.AllCorrect = true;
break;
case EGradeTyping.HalfCorrect:
dictionary.DefaultSettings.GradeTyping.HalfCorrect = true;
break;
case EGradeTyping.NoneCorrect:
dictionary.DefaultSettings.GradeTyping.NoneCorrect = true;
break;
case EGradeTyping.Prompt:
dictionary.DefaultSettings.GradeTyping.Prompt = true;
break;
default:
break;
}
if ((((int)ESnoozeMode.QuitProgram) & queryOptions) > 0)
{
dictionary.DefaultSettings.SnoozeOptions.SnoozeMode = ESnoozeMode.QuitProgram;
}
if ((((int)ESnoozeMode.SendToTray) & queryOptions) > 0)
{
dictionary.DefaultSettings.SnoozeOptions.SnoozeMode = ESnoozeMode.SendToTray;
}
if (!ReportProgressUpdate(5)) return null;
if (wbVersion >= 0x0103)
{
int snoozeTime = Convert.ToInt32(Dic.ReadByte());
int snoozeRights = Convert.ToInt32(Dic.ReadByte());
int snoozeCards = Convert.ToInt32(Dic.ReadByte());
int snoozeTimeLow = Convert.ToInt32(Dic.ReadByte());
int snoozeTimeHigh = Convert.ToInt32(Dic.ReadByte());
if ((((int)ESnoozeMode.Time) & queryType) > 0)
{
dictionary.DefaultSettings.SnoozeOptions.EnableTime(snoozeTime);
}
if ((((int)ESnoozeMode.Rights) & queryType) > 0)
{
dictionary.DefaultSettings.SnoozeOptions.EnableRights(snoozeRights);
}
if ((((int)ESnoozeMode.Cards) & queryType) > 0)
{
dictionary.DefaultSettings.SnoozeOptions.EnableCards(snoozeCards);
}
dictionary.DefaultSettings.SnoozeOptions.SetSnoozeTimes(snoozeTimeLow, snoozeTimeHigh);
}
//box_data -> user
rsize = Dic.ReadInt32();
box_data = (_rBox_[])SetLength(box_data, rsize);
for (int i = 0; i < box_data.Length; i++)
{
box_data[i] = new _rBox_();
box_data[i].First = Dic.ReadInt32();
Dic.ReadInt32(); // box_data[i].Last
if (i < box_data.Length - 2)
{
dictionary.Boxes.Box[i].MaximalSize = Dic.ReadInt32();
}
else
{
Dic.ReadInt32(); //MaxLen for the last two boxes - not needed
}
if (wbVersion > 0x0106)
{
Dic.ReadInt32(); // box_data[i].Len
}
}
// end of user -----------------------------------------------------------------
if (!ReportProgressUpdate(10)) return null;
//chapter_data
rsize = Dic.ReadInt32();
chapter_data = (_rChapter_[])SetLength(chapter_data, rsize);
for (int i = 0; i < chapter_data.Length; i++)
{
chapter_data[i] = new _rChapter_();
Dic.ReadUInt16(); //ID
Dic.ReadUInt16(); // SubID
len = Dic.ReadByte();
chapter_data[i].Title = byte2string(Dic.ReadBytes(30)).Substring(0, len);
len = Dic.ReadByte();
chapter_data[i].Description = byte2string(Dic.ReadBytes(256)).Substring(0, len);
}
if (!ReportProgressUpdate(15)) return null;
//cards_data
rsize = Dic.ReadInt32();
cards_data = (_rCards_[])SetLength(cards_data, rsize);
for (int i = 0; i < cards_data.Length; i++)
{
cards_data[i] = new _rCards_();
ssize = Dic.ReadUInt16();
cards_data[i].Src.SpecialImportFormat = byte2string(Dic.ReadBytes(ssize));
ssize = Dic.ReadUInt16();
cards_data[i].Dst.SpecialImportFormat = byte2string(Dic.ReadBytes(ssize));
ssize = Dic.ReadUInt16();
cards_data[i].SentSrc = byte2string(Dic.ReadBytes(ssize));
ssize = Dic.ReadUInt16();
cards_data[i].SentDst = byte2string(Dic.ReadBytes(ssize));
cards_data[i].ChapterID = Dic.ReadUInt16() - 1; //chapterID starts with 1, should be zero-based
cards_data[i].CardParts = Dic.ReadByte();
if (wbVersion >= 0x0107)
Dic.ReadByte(); // Probability
}
if (!ReportProgressUpdate(20)) return null;
//boxes_data
rsize = Dic.ReadInt32();
boxes_data = (_rBoxes_[])SetLength(boxes_data, rsize);
for (int i = 0; i < boxes_data.Length; i++)
{
boxes_data[i] = new _rBoxes_();
boxes_data[i].BoxID = Dic.ReadByte();
Dic.ReadBytes(3); //TODO BUG ?
boxes_data[i].CardID = Dic.ReadInt32();
boxes_data[i].Prior = Dic.ReadInt32();
boxes_data[i].Next = Dic.ReadInt32();
}
if (!ReportProgressUpdate(25)) return null;
//blob_data
rsize = Dic.ReadInt32();
blob_data = (_rBlob_[])SetLength(blob_data, rsize);
for (int i = 0; i < blob_data.Length; i++)
{
blob_data[i] = new _rBlob_();
blob_data[i].SrcDst = (TBlobType)Dic.ReadByte();
len = Dic.ReadByte();
string tstr = byte2string(Dic.ReadBytes(101));
blob_data[i].Link = tstr.Substring(0, len);
blob_data[i].Link = blob_data[i].Link.Replace('/', '\\'); // repair work
blob_data[i].Link = blob_data[i].Link.Replace("\\\\", "\\"); // repair work
Dic.ReadByte();
blob_data[i].CardID = Dic.ReadInt32();
}
if (!ReportProgressUpdate(30)) return null;
//stats_data
rsize = Dic.ReadInt32();
stats_data = (_rStats_[])SetLength(stats_data, rsize);
for (int i = 0; i < stats_data.Length; i++)
{
stats_data[i] = new _rStats_(m_nrBox);
stats_data[i].SStart = new System.DateTime(1899, 12, 30, 0, 0, 0); // startdate in delphi
stats_data[i].SStart = stats_data[i].SStart.AddDays(Dic.ReadDouble());
stats_data[i].SEnd = new System.DateTime(1899, 12, 30, 0, 0, 0); // startdate in delphi
stats_data[i].SEnd = stats_data[i].SEnd.AddDays(Dic.ReadDouble());
stats_data[i].Right = Dic.ReadInt32();
stats_data[i].Wrong = Dic.ReadInt32();
for (int j = 0; j < m_nrBox; j++)
stats_data[i].Boxes[j] = Dic.ReadInt32();
}
if (!ReportProgressUpdate(35)) return null;
//chapters
for (int i = 0; i < chapter_data.Length; i++)
{
IChapter chapter = dictionary.Chapters.AddNew();
//chapter.Id = i; //Interface change
chapter.Title = chapter_data[i].Title;
chapter.Description = chapter_data[i].Description;
}
if (!ReportProgressUpdate(40)) return null;
//cards
for (int i = 0; i < cards_data.Length; i++)
{
if ((i % 10) == 0)
{
int progress = (int)Math.Floor(35.0 + ((90.0 - 35.0) * (i + 1) / cards_data.Length));
if (!ReportProgressUpdate(progress)) return null;
}
ICard card = dictionary.Cards.AddNew();
//card.Id = i; //Interface change
StringList words = new StringList();
words.CommaText = cards_data[i].Src.CommaText;
for (int k = 0; k < words.Count; k++)
{
IWord word = card.Question.CreateWord(words[k], WordType.Word, (k == 0));
card.Question.AddWord(word);
}
card.QuestionExample.AddWord(card.QuestionExample.CreateWord(cards_data[i].SentSrc, WordType.Sentence, false));
words.CommaText = cards_data[i].Dst.CommaText;
for (int k = 0; k < words.Count; k++)
{
IWord word = card.Answer.CreateWord(words[k], WordType.Word, (k == 0));
card.Answer.AddWord(word);
}
card.AnswerExample.AddWord(card.AnswerExample.CreateWord(cards_data[i].SentDst, WordType.Sentence, false));
card.Chapter = cards_data[i].ChapterID;
card.Box = 0;
card.Timestamp = DateTime.Now;
for (int j = 0; j < blob_data.Length; j++)
{
if (blob_data[j].CardID == i)
{
if (File.Exists(Path.Combine(srcPath, blob_data[j].Link)))
{
blob_data[j].Link = Path.Combine(srcPath, blob_data[j].Link);
if (blob_data[j].SrcDst.ToString().Equals("image"))
{
IMedia media = card.CreateMedia(EMedia.Image, blob_data[j].Link, true, false, false);
card.AddMedia(media, Side.Question);
card.AddMedia(media, Side.Answer);
}
else
{
IMedia media = null;
Side side = Side.Question;
switch (blob_data[j].SrcDst.ToString())
{
case "questionaudio":
media = card.CreateMedia(EMedia.Audio, blob_data[j].Link, true, true, false);
side = Side.Question;
break;
case "questionexampleaudio":
media = card.CreateMedia(EMedia.Audio, blob_data[j].Link, true, false, true);
side = Side.Question;
break;
case "questionvideo":
media = card.CreateMedia(EMedia.Video, blob_data[j].Link, true, false, false);
side = Side.Question;
break;
case "questionimage":
media = card.CreateMedia(EMedia.Image, blob_data[j].Link, true, false, false);
side = Side.Question;
break;
case "answeraudio":
media = card.CreateMedia(EMedia.Audio, blob_data[j].Link, true, true, false);
side = Side.Answer;
break;
case "answerexampleaudio":
media = card.CreateMedia(EMedia.Audio, blob_data[j].Link, true, false, true);
side = Side.Answer;
break;
case "answervideo":
media = card.CreateMedia(EMedia.Video, blob_data[j].Link, true, false, false);
side = Side.Answer;
break;
case "answerimage":
media = card.CreateMedia(EMedia.Image, blob_data[j].Link, true, false, false);
side = Side.Answer;
break;
case "unusedmedia":
default:
try
{
EMedia mType = Helper.GetMediaType(blob_data[j].Link);
if (mType == EMedia.Unknown)
{
media = card.CreateMedia(mType, blob_data[j].Link, false, false, false);
side = Side.Question; //doesn't matter
}
}
catch { }
break;
}
if (media != null)
{
card.AddMedia(media, side);
}
}
}
}
}
}
if (!ReportProgressUpdate(95)) return null;
//stats
for (int i = 0; i < stats_data.Length; i++)
{
IStatistic stat = new MLifter.DAL.XML.XmlStatistic(dictionary as MLifter.DAL.XML.XmlDictionary, i, true);
dictionary.Statistics.Add(stat);
stat.StartTimestamp = stats_data[i].SStart;
stat.EndTimestamp = stats_data[i].SEnd;
stat.Right = stats_data[i].Right;
stat.Wrong = stats_data[i].Wrong;
stat.Boxes.Clear();
for (int j = 0; j < stats_data[i].Boxes.Length; j++)
{
stat.Boxes.Add(stats_data[i].Boxes[j]);
}
}
DateTime start_of_year = new DateTime(m_releaseYear, 1, 1);
int additional_seconds = 1;
for (int i = box_data.Length - 1; i >= 0; i--)
{
int exitCounter = 0;
for (int j = box_data[i].First; j != (-1); j = boxes_data[j].Next)
{
try
{
ICard card = dictionary.Cards.Get(boxes_data[j].CardID);
card.Box = boxes_data[j].BoxID;
card.Timestamp = start_of_year.AddSeconds(additional_seconds++).ToUniversalTime();
}
catch { }
//boxes_data seems to be a linked list which sometimes may be broken - this is the emergency exit
if (exitCounter++ > dictionary.Cards.Count) break;
}
}
dictionary.Save();
}
else
{
throw new InvalidImportFormatException(dstFile);
}
Dic.Close();
}
#if !DEBUG
}
catch (DictionaryPathExistsException ex)
{
throw ex;
}
catch (DictionaryFormatNotSupported ex)
{
throw ex;
}
catch (InvalidImportFormatException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
#endif
return dictionary;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Tests;
using System.Diagnostics;
using Xunit;
namespace System.Collections.Generic.Tests
{
public class ComparerTests
{
[Theory]
[MemberData(nameof(IComparableComparisonsData))]
[MemberData(nameof(ULongEnumComparisonsData))]
[MemberData(nameof(IntEnumComparisonsData))]
[MemberData(nameof(UIntEnumComparisonsData))]
[MemberData(nameof(LongEnumComparisonsData))]
[MemberData(nameof(PlainObjectComparisonsData))]
public void MostComparisons<T>(T left, T right, int expected)
{
var comparer = Comparer<T>.Default;
Assert.Equal(expected, Math.Sign(comparer.Compare(left, right)));
// Because of these asserts we don't need to explicitly add tests for
// 0 being an expected value, it is done automatically for every input
Assert.Equal(0, comparer.Compare(left, left));
Assert.Equal(0, comparer.Compare(right, right));
IComparer nonGenericComparer = comparer;
// If both sides are Ts then the explicit implementation of IComparer.Compare
// should also succeed, with the same results
Assert.Equal(expected, Math.Sign(nonGenericComparer.Compare(left, right)));
Assert.Equal(0, nonGenericComparer.Compare(left, left));
Assert.Equal(0, nonGenericComparer.Compare(right, right));
// All comparers returned by Comparer<T>.Default should be able
// to handle nulls before dispatching to IComparable<T>.CompareTo()
if (default(T) == null) // This will be true if T is a reference type or nullable
{
T nil = default(T);
Assert.Equal(0, comparer.Compare(nil, nil));
// null should be ordered before/equal to everything (never after)
// We assert that it's -1 or 0 in case left/right is null, as well
// We assert that it's -1 rather than any negative number since these
// values are hardcoded in the comparer logic, rather than being left
// to the object being compared
Assert.InRange(comparer.Compare(nil, left), -1, 0);
Assert.InRange(comparer.Compare(nil, right), -1, 0);
Assert.InRange(comparer.Compare(left, nil), 0, 1);
Assert.InRange(comparer.Compare(right, nil), 0, 1);
// Validate behavior for the IComparer.Compare implementation, as well
Assert.Equal(0, nonGenericComparer.Compare(nil, nil));
Assert.InRange(nonGenericComparer.Compare(nil, left), -1, 0);
Assert.InRange(nonGenericComparer.Compare(nil, right), -1, 0);
Assert.InRange(nonGenericComparer.Compare(left, nil), 0, 1);
Assert.InRange(nonGenericComparer.Compare(right, nil), 0, 1);
}
}
// NOTE: The test cases from the MemberData don't include 0 as the expected value,
// since for each case we automatically test that Compare(lhs, lhs) and Compare(rhs, rhs)
// are both 0.
public static IEnumerable<object[]> IComparableComparisonsData()
{
var testCases = new[]
{
Tuple.Create(new GenericComparable(3), new GenericComparable(4), -1),
Tuple.Create(new GenericComparable(5), new GenericComparable(2), 1),
// GenericComparable's CompareTo does not handle nulls intentionally, the Comparer should check both
// inputs for null before dispatching to CompareTo
Tuple.Create(new GenericComparable(int.MinValue), default(GenericComparable), 1)
};
foreach (var testCase in testCases)
{
yield return new object[] { testCase.Item1, testCase.Item2, testCase.Item3 };
yield return new object[] { testCase.Item2, testCase.Item1, -testCase.Item3 }; // Do the comparison in reverse as well
}
}
public static IEnumerable<object[]> ULongEnumComparisonsData()
{
var testCases = new[]
{
Tuple.Create(3UL, 5UL, -1),
// Catch any attempt to cast the enum value to a signed type,
// which may result in overflow and an incorrect comparison
Tuple.Create(ulong.MaxValue, (ulong)long.MaxValue, 1),
Tuple.Create(ulong.MaxValue - 3, ulong.MaxValue, -1)
};
foreach (var testCase in testCases)
{
yield return new object[] { (ULongEnum)testCase.Item1, (ULongEnum)testCase.Item2, testCase.Item3 };
yield return new object[] { (ULongEnum)testCase.Item2, (ULongEnum)testCase.Item1, -testCase.Item3 };
}
}
public static IEnumerable<object[]> IntEnumComparisonsData()
{
var testCases = new[]
{
Tuple.Create(-1, 4, -1),
Tuple.Create(-222, -375, 1),
// The same principle applies for overflow in signed types as above,
// the implementation should not cast to an unsigned type
Tuple.Create(int.MaxValue, int.MinValue, 1),
Tuple.Create(int.MinValue + 1, int.MinValue, 1)
};
foreach (var testCase in testCases)
{
yield return new object[] { (IntEnum)testCase.Item1, (IntEnum)testCase.Item2, testCase.Item3 };
yield return new object[] { (IntEnum)testCase.Item2, (IntEnum)testCase.Item1, -testCase.Item3 };
}
}
public static IEnumerable<object[]> UIntEnumComparisonsData()
{
var testCases = new[]
{
Tuple.Create(445u, 123u, 1),
Tuple.Create(uint.MaxValue, 111u, 1),
Tuple.Create(uint.MaxValue - 333, uint.MaxValue, -1)
};
foreach (var testCase in testCases)
{
yield return new object[] { (UIntEnum)testCase.Item1, (UIntEnum)testCase.Item2, testCase.Item3 };
yield return new object[] { (UIntEnum)testCase.Item2, (UIntEnum)testCase.Item1, -testCase.Item3 };
}
}
public static IEnumerable<object[]> LongEnumComparisonsData()
{
var testCases = new[]
{
Tuple.Create(182912398L, 33L, 1),
Tuple.Create(long.MinValue, long.MaxValue, -1),
Tuple.Create(long.MinValue + 9, long.MinValue, 1)
};
foreach (var testCase in testCases)
{
yield return new object[] { (LongEnum)testCase.Item1, (LongEnum)testCase.Item2, testCase.Item3 };
yield return new object[] { (LongEnum)testCase.Item2, (LongEnum)testCase.Item1, -testCase.Item3 };
}
}
public static IEnumerable<object[]> PlainObjectComparisonsData()
{
var obj = new object(); // this needs to be cached into a local so we can pass the same ref in twice
var testCases = new[]
{
Tuple.Create(obj, obj, 0), // even if it doesn't implement IComparable, if 2 refs are the same then the result should be 0
Tuple.Create(default(object), obj, -1) // even if it doesn't implement IComparable, if one side is null -1 or 1 should be returned
};
foreach (var testCase in testCases)
{
yield return new object[] { testCase.Item1, testCase.Item2, testCase.Item3 };
yield return new object[] { testCase.Item2, testCase.Item1, -testCase.Item3 };
}
}
[Fact]
public void IComparableComparisonsShouldTryToCallLeftHandCompareToFirst()
{
var left = new MutatingComparable(0);
var right = new MutatingComparable(0);
var comparer = Comparer<MutatingComparable>.Default;
// Every CompareTo() call yields the comparable's current
// state and then increments it
Assert.Equal(0, comparer.Compare(left, right));
Assert.Equal(1, comparer.Compare(left, right));
Assert.Equal(0, comparer.Compare(right, left));
}
[Fact]
public void NonGenericIComparableComparisonsShouldTryToCallLeftHandCompareToFirst()
{
var left = new MutatingComparable(0);
var right = new object();
var comparer = Comparer<object>.Default;
Assert.Equal(0, comparer.Compare(left, right));
Assert.Equal(1, comparer.Compare(left, right));
// If the lhs does not implement IComparable, the rhs should be checked
// Additionally the result from rhs.CompareTo should be negated
Assert.Equal(-2, comparer.Compare(right, left));
}
[Fact]
public void DifferentNonNullObjectsThatDoNotImplementIComparableShouldThrowWhenCompared()
{
var left = new object();
var right = new object();
var comparer = Comparer<object>.Default;
Assert.Throws<ArgumentException>(() => comparer.Compare(left, right));
}
[Fact]
public void ComparerDefaultShouldAttemptToUseTheGenericIComparableInterfaceFirst()
{
// IComparable<>.CompareTo returns 1 for this type,
// non-generic overload returns -1
var left = new BadlyBehavingComparable();
var right = new BadlyBehavingComparable();
var comparer = Comparer<BadlyBehavingComparable>.Default;
// The comparer should pick up on the generic implementation first
Assert.Equal(1, comparer.Compare(left, right));
Assert.Equal(1, comparer.Compare(right, left));
}
// The runtime treats nullables specially when they're boxed,
// for example `object o = new int?(3); o is int` is true.
// This messes with the xUnit type inference for generic theories,
// so we need to write another theory (accepting non-nullable parameters)
// just for nullables.
[Theory]
[MemberData(nameof(NullableOfIntComparisonsData))]
[MemberData(nameof(NullableOfIntEnumComparisonsData))]
public void NullableComparisons<T>(T leftValue, bool leftHasValue, T rightValue, bool rightHasValue, int expected) where T : struct
{
// Comparer<T> is specialized (for perf reasons) when T : U? where U : IComparable<U>
T? left = leftHasValue ? new T?(leftValue) : null;
T? right = rightHasValue ? new T?(rightValue) : null;
var comparer = Comparer<T?>.Default;
Assert.Equal(expected, Math.Sign(comparer.Compare(left, right)));
Assert.Equal(0, comparer.Compare(left, left));
Assert.Equal(0, comparer.Compare(right, right));
// Converting the comparer to a non-generic IComparer lets us
// test the explicit implementation of IComparer.Compare as well,
// which accepts 2 objects rather than nullables.
IComparer nonGenericComparer = comparer;
// The way this works is that, assuming two non-null nullables,
// T? will get boxed to a object with GetType() == typeof(T),
// (object is T?) will be true, and then it will get converted
// back to a T?.
// If one of the inputs is null, it will get boxed to a null object
// and then IComparer.Compare() should take care of it itself.
Assert.Equal(expected, Math.Sign(nonGenericComparer.Compare(left, right)));
Assert.Equal(0, nonGenericComparer.Compare(left, left));
Assert.Equal(0, nonGenericComparer.Compare(right, right));
// As above, the comparer should handle null inputs itself and only
// return -1, 0, or 1 in such circumstances
Assert.Equal(0, comparer.Compare(null, null)); // null and null should have the same sorting order
Assert.InRange(comparer.Compare(null, left), -1, 0); // "null" values should come before anything else
Assert.InRange(comparer.Compare(null, right), -1, 0);
Assert.InRange(comparer.Compare(left, null), 0, 1);
Assert.InRange(comparer.Compare(right, null), 0, 1);
Assert.Equal(0, nonGenericComparer.Compare(null, null));
Assert.InRange(nonGenericComparer.Compare(null, left), -1, 0);
Assert.InRange(nonGenericComparer.Compare(null, right), -1, 0);
Assert.InRange(nonGenericComparer.Compare(left, null), 0, 1);
Assert.InRange(nonGenericComparer.Compare(right, null), 0, 1);
// new T?() < new T?(default(T))
Assert.Equal(-1, comparer.Compare(null, default(T)));
Assert.Equal(1, comparer.Compare(default(T), null));
Assert.Equal(0, comparer.Compare(default(T), default(T)));
Assert.Equal(-1, nonGenericComparer.Compare(null, default(T)));
Assert.Equal(1, nonGenericComparer.Compare(default(T), null));
Assert.Equal(0, nonGenericComparer.Compare(default(T), default(T)));
}
public static IEnumerable<object[]> NullableOfIntComparisonsData()
{
var testCases = new[]
{
Tuple.Create(default(int), false, int.MinValue, true, -1), // "null" values should come before anything else
Tuple.Create(int.MaxValue, true, int.MinValue, true, 1) // Comparisons between two non-null nullables should work as normal
};
foreach (var testCase in testCases)
{
yield return new object[] { testCase.Item1, testCase.Item2, testCase.Item3, testCase.Item4, testCase.Item5 };
yield return new object[] { testCase.Item3, testCase.Item4, testCase.Item1, testCase.Item2, -testCase.Item5 };
}
}
public static IEnumerable<object[]> NullableOfIntEnumComparisonsData()
{
// Currently the default Comparer/EqualityComparer is optimized for when
// T : U? where U : IComparable<U> or T : enum, but not T : U? where
// U : enum (aka T is a nullable enum).
// So, let's cover that codepath in case that changes/regresses in the future.
var testCases = new[]
{
Tuple.Create(int.MinValue, true, default(int), false, 1), // "null" values should come first
Tuple.Create(-1, true, 4, true, -1)
};
foreach (var testCase in testCases)
{
yield return new object[] { testCase.Item1, testCase.Item2, testCase.Item3, testCase.Item4, testCase.Item5 };
yield return new object[] { testCase.Item3, testCase.Item4, testCase.Item1, testCase.Item2, -testCase.Item5 };
}
}
[Fact]
public void NullableOfIComparableComparisonsShouldTryToCallLeftHandCompareToFirst()
{
// If two non-null nullables are passed in, Default<T?>.Compare
// should try to call the left-hand side's CompareTo() first
// Would have liked to reuse MutatingComparable here, but it is
// a class and can't be nullable, so it's necessary to wrap it
// in a struct
var leftValue = new MutatingComparable(0);
var rightValue = new MutatingComparable(0);
var left = new ValueComparable<MutatingComparable>?(ValueComparable.Create(leftValue));
var right = new ValueComparable<MutatingComparable>?(ValueComparable.Create(rightValue));
var comparer = Comparer<ValueComparable<MutatingComparable>?>.Default;
Assert.Equal(0, comparer.Compare(left, right));
Assert.Equal(1, comparer.Compare(left, right));
Assert.Equal(0, comparer.Compare(right, left));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace T5CANLib
{
class srec2bin
{
public bool ConvertSrecToBin(string filename, out string newfilename)
{
string readline = string.Empty;
string readhex = string.Empty;
newfilename = string.Empty;
string outputfile = string.Empty;
try
{
outputfile = Path.GetDirectoryName(filename);
outputfile = Path.Combine(outputfile, Path.GetFileNameWithoutExtension(filename) + ".bin");
int bytecount = 0;
FileStream fswrite = new FileStream(outputfile, FileMode.Create);
BinaryWriter binwrite = new BinaryWriter(fswrite);
using (StreamReader streamread = new StreamReader(filename))
{
while ((readline = streamread.ReadLine()) != null)
{
if (readline.StartsWith("S2") && readline.Length > 75)
{
readhex = readline.Substring(10, 64);
for (int t = 0; t < 64; t += 2)
{
byte b = Convert.ToByte(readhex.Substring(t, 2), 16);
binwrite.Write(b);
bytecount++;
}
//Console.WriteLine("S2: " + bytecount.ToString());
}
else if (readline.StartsWith("S2") && readline.Length > 43)
{
readhex = readline.Substring(10, 32);
for (int t = 0; t < 32; t += 2)
{
byte b = Convert.ToByte(readhex.Substring(t, 2), 16);
binwrite.Write(b);
bytecount++;
}
// Console.WriteLine("S2: " + bytecount.ToString());
}
else if (readline.StartsWith("S1") && readline.Length > 41 && readline.Length <= 44)
{
readhex = readline.Substring(8, 32);
for (int t = 0; t < 32; t += 2)
{
byte b = Convert.ToByte(readhex.Substring(t, 2), 16);
binwrite.Write(b);
bytecount++;
}
Console.WriteLine("S1: " + bytecount.ToString());
}
}
}
Console.WriteLine("Bytes written: " + bytecount.ToString());
binwrite.Close();
fswrite.Close();
newfilename = outputfile;
return true;
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
return false;
}
public bool ConvertBinToSrec(string filename)
{
string outputfile = string.Empty;
outputfile = Path.GetDirectoryName(filename);
outputfile = Path.Combine(outputfile, Path.GetFileNameWithoutExtension(filename) + ".s19");
return ConvertBinToSrec(filename, outputfile);
}
private bool CheckBytesAllFF(byte[] bts)
{
bool retval = false;
if (bts != null)
{
retval = true;
foreach (byte b in bts)
{
if (b != 0xFF)
{
retval = false;
break; // faster
}
}
}
return retval;
}
public bool ConvertBinToSrec(string filename, string newfilename)
{
int record_count = 0;
int addr_bytes= 3;
string outputfile = string.Empty;
try
{
//outputfile = Path.GetDirectoryName(filename);
//outputfile = Path.Combine(outputfile, Path.GetFileNameWithoutExtension(filename) + ".s19");
outputfile = newfilename;
FileStream fsread = new FileStream(filename, FileMode.Open);
BinaryReader binread = new BinaryReader(fsread);
if (fsread.Length != 0x40000 && fsread.Length != 0x20000) return false;
using (StreamWriter streamwriter = new StreamWriter(outputfile, false))
{
// header naar bestand zetten
streamwriter.WriteLine("S00600004844521B");
byte c;
byte checksum = 0;
byte byte_count = 0;
string outpline = string.Empty;
for (int address = 0; address < fsread.Length; address += 15) // line-length = 32 (default)
{
byte[] inpbytes = binread.ReadBytes(15);
if (!CheckBytesAllFF(inpbytes))
{
byte_count = (byte)(addr_bytes + 1 + inpbytes.Length);
outpline = "S2" + byte_count.ToString("X2");
checksum = (byte)byte_count;
for (int i = addr_bytes - 1; i >= 0; i--)
{
c = (byte)((address >> (i << 3)) & 0xff);
//printf("%02lX", c);
outpline += c.ToString("X2");
checksum += c;
}
for (int i = 0; i < inpbytes.Length; i++)
{
//printf("%02X", inpbytes.[i]);
byte b = (byte)inpbytes.GetValue(i);
outpline += b.ToString("X2");
checksum += b;
}
checksum = (byte)(255 - checksum);
outpline += checksum.ToString("X2");
//printf("%02X\n", 255 - checksum);
streamwriter.WriteLine(outpline);
record_count++;
}
}
checksum = (byte)((byte)3 + (byte)(record_count & 0xff) + (byte)((record_count >> 8) & 0xff));
checksum = (byte)(255 - checksum);
outpline = "S503" + record_count.ToString("X4") + checksum.ToString("X2");
streamwriter.WriteLine(outpline);
//printf("S503%04X%02X\n", record_count, 255 - checksum);
byte_count = (byte)(addr_bytes + 1);
int temp = 11 - addr_bytes;
outpline = "S" + temp.ToString() + byte_count.ToString("X2");
//streamwriter.WriteLine(outpline);
//printf("S%d%02X", 11 - addr_bytes, byte_count);
checksum = byte_count;
//outpline = string.Empty;
for (int i = addr_bytes - 1; i >= 0; i--)
{
c = (byte)((0 >> (i << 3)) & 0xff);
outpline += c.ToString("X2");
//printf("%02lX", c);
checksum += c;
}
checksum = (byte)(255 - checksum);
outpline += checksum.ToString("X2");
streamwriter.WriteLine(outpline);
//printf("%02X\n", 255 - checksum);
}
binread.Close();
fsread.Close();
return true;
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
return false;
}
public bool ConvertBinToSrecS2Format(string filename)
{
int record_count = 0;
int addr_bytes = 3;
string outputfile = string.Empty;
try
{
outputfile = Path.GetDirectoryName(filename);
outputfile = Path.Combine(outputfile, Path.GetFileNameWithoutExtension(filename) + ".s2");
FileStream fsread = new FileStream(filename, FileMode.Open);
BinaryReader binread = new BinaryReader(fsread);
if (fsread.Length != 0x40000 && fsread.Length != 0x20000) return false;
using (StreamWriter streamwriter = new StreamWriter(outputfile, false))
{
// header naar bestand zetten
// streamwriter.WriteLine("S00600004844521B");
byte c;
byte checksum = 0;
byte byte_count = 0;
string outpline = string.Empty;
for (int address = (int)fsread.Length; address < (fsread.Length + fsread.Length); address += 32) // line-length = 32 (default)
{
byte[] inpbytes = binread.ReadBytes(32);
byte_count = (byte)(addr_bytes + 1 + inpbytes.Length);
outpline = "S2" + byte_count.ToString("X2");
checksum = (byte)byte_count;
for (int i = addr_bytes - 1; i >= 0; i--)
{
c = (byte)((address >> (i << 3)) & 0xff);
//printf("%02lX", c);
outpline += c.ToString("X2");
checksum += c;
}
for (int i = 0; i < inpbytes.Length; i++)
{
//printf("%02X", inpbytes.[i]);
byte b = (byte)inpbytes.GetValue(i);
outpline += b.ToString("X2");
checksum += b;
}
checksum = (byte)(255 - checksum);
outpline += checksum.ToString("X2");
//printf("%02X\n", 255 - checksum);
streamwriter.WriteLine(outpline);
record_count++;
}
/*checksum = (byte)((byte)3 + (byte)(record_count & 0xff) + (byte)((record_count >> 8) & 0xff));
checksum = (byte)(255 - checksum);
outpline = "S503" + record_count.ToString("X4") + checksum.ToString("X2");
streamwriter.WriteLine(outpline);
//printf("S503%04X%02X\n", record_count, 255 - checksum);
byte_count = (byte)(addr_bytes + 1);
int temp = 11 - addr_bytes;
outpline = "S" + temp.ToString() + byte_count.ToString("X2");
//streamwriter.WriteLine(outpline);
//printf("S%d%02X", 11 - addr_bytes, byte_count);
checksum = byte_count;
//outpline = string.Empty;
for (int i = addr_bytes - 1; i >= 0; i--)
{
c = (byte)((0 >> (i << 3)) & 0xff);
outpline += c.ToString("X2");
//printf("%02lX", c);
checksum += c;
}
checksum = (byte)(255 - checksum);
outpline += checksum.ToString("X2");
streamwriter.WriteLine(outpline);*/
//printf("%02X\n", 255 - checksum);
}
binread.Close();
fsread.Close();
return true;
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
return false;
}
// printf("S00600004844521B\n"); /* Header record */
/* for (address = addr_offset; address <= max_addr; address += line_length)
{
if (verbose)
fprintf(stderr, "Processing %08lXh\r", address);
this_line = min(line_length, 1 + max_addr - address);
byte_count = (addr_bytes + this_line + 1);
printf("S%d%02X", addr_bytes - 1, byte_count);
checksum = byte_count;
for (i = addr_bytes - 1; i >= 0; i--)
{
c = (address >> (i << 3)) & 0xff;
printf("%02lX", c);
checksum += c;
}
fread(buf, 1, this_line, infile);
for (i = 0; i < this_line; i++)
{
printf("%02X", buf[i]);
checksum += buf[i];
}
printf("%02X\n", 255 - checksum);
record_count++;
}*/
/*
checksum = 3 + (record_count & 0xff) + ((record_count >> 8) & 0xff);
printf("S503%04X%02X\n", record_count, 255 - checksum);
byte_count = (addr_bytes + 1);
printf("S%d%02X", 11 - addr_bytes, byte_count);
checksum = byte_count;
for (i = addr_bytes - 1; i >= 0; i--)
{
c = (addr_offset >> (i << 3)) & 0xff;
printf("%02lX", c);
checksum += c;
}
printf("%02X\n", 255 - checksum);
* */
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Search
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for IndexersOperations.
/// </summary>
public static partial class IndexersOperationsExtensions
{
/// <summary>
/// Resets the change tracking state associated with an Azure Search indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Reset-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to reset.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static void Reset(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
Task.Factory.StartNew(s => ((IIndexersOperations)s).ResetAsync(indexerName, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Resets the change tracking state associated with an Azure Search indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Reset-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to reset.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task ResetAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.ResetWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Runs an Azure Search indexer on-demand.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Run-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to run.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static void Run(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
Task.Factory.StartNew(s => ((IIndexersOperations)s).RunAsync(indexerName, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Runs an Azure Search indexer on-demand.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Run-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to run.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task RunAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.RunWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates a new Azure Search indexer or updates an indexer if it already
/// exists.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Create-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to create or update.
/// </param>
/// <param name='indexer'>
/// The definition of the indexer to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
public static Indexer CreateOrUpdate(this IIndexersOperations operations, string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition))
{
return Task.Factory.StartNew(s => ((IIndexersOperations)s).CreateOrUpdateAsync(indexerName, indexer, searchRequestOptions, accessCondition), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure Search indexer or updates an indexer if it already
/// exists.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Create-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to create or update.
/// </param>
/// <param name='indexer'>
/// The definition of the indexer to create or update.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Indexer> CreateOrUpdateAsync(this IIndexersOperations operations, string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(indexerName, indexer, searchRequestOptions, accessCondition, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an Azure Search indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Delete-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
public static void Delete(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition))
{
Task.Factory.StartNew(s => ((IIndexersOperations)s).DeleteAsync(indexerName, searchRequestOptions, accessCondition), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an Azure Search indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Delete-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to delete.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='accessCondition'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), AccessCondition accessCondition = default(AccessCondition), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(indexerName, searchRequestOptions, accessCondition, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves an indexer definition from Azure Search.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Get-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static Indexer Get(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return Task.Factory.StartNew(s => ((IIndexersOperations)s).GetAsync(indexerName, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieves an indexer definition from Azure Search.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Get-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer to retrieve.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Indexer> GetAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all indexers available for an Azure Search service.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/List-Indexers" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static IndexerListResult List(this IIndexersOperations operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return Task.Factory.StartNew(s => ((IIndexersOperations)s).ListAsync(searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all indexers available for an Azure Search service.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/List-Indexers" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IndexerListResult> ListAsync(this IIndexersOperations operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new Azure Search indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Create-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexer'>
/// The definition of the indexer to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static Indexer Create(this IIndexersOperations operations, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return Task.Factory.StartNew(s => ((IIndexersOperations)s).CreateAsync(indexer, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new Azure Search indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Create-Indexer" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexer'>
/// The definition of the indexer to create.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Indexer> CreateAsync(this IIndexersOperations operations, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(indexer, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns the current status and execution history of an indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Get-Indexer-Status" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer for which to retrieve status.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
public static IndexerExecutionInfo GetStatus(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions))
{
return Task.Factory.StartNew(s => ((IIndexersOperations)s).GetStatusAsync(indexerName, searchRequestOptions), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the current status and execution history of an indexer.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/Get-Indexer-Status" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='indexerName'>
/// The name of the indexer for which to retrieve status.
/// </param>
/// <param name='searchRequestOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IndexerExecutionInfo> GetStatusAsync(this IIndexersOperations operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetStatusWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Streams;
using Orleans.Configuration;
namespace Orleans.Providers
{
/// <summary>
/// Adapter factory for in memory stream provider.
/// This factory acts as the adapter and the adapter factory. The events are stored in an in-memory grain that
/// behaves as an event queue, this provider adapter is primarily used for testing
/// </summary>
public class MemoryAdapterFactory<TSerializer> : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache
where TSerializer : class, IMemoryMessageBodySerializer
{
private readonly StreamCacheEvictionOptions cacheOptions;
private readonly StreamStatisticOptions statisticOptions;
private readonly HashRingStreamQueueMapperOptions queueMapperOptions;
private readonly IGrainFactory grainFactory;
private readonly ITelemetryProducer telemetryProducer;
private readonly ILoggerFactory loggerFactory;
private readonly ILogger logger;
private readonly TSerializer serializer;
private IStreamQueueMapper streamQueueMapper;
private ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain> queueGrains;
private IObjectPool<FixedSizeBuffer> bufferPool;
private BlockPoolMonitorDimensions blockPoolMonitorDimensions;
private IStreamFailureHandler streamFailureHandler;
private TimePurgePredicate purgePredicate;
/// <summary>
/// Name of the adapter. Primarily for logging purposes
/// </summary>
public string Name { get; }
/// <summary>
/// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time.
/// </summary>
/// <returns>True if this is a rewindable stream adapter, false otherwise.</returns>
public bool IsRewindable => true;
/// <summary>
/// Direction of this queue adapter: Read, Write or ReadWrite.
/// </summary>
/// <returns>The direction in which this adapter provides data.</returns>
public StreamProviderDirection Direction => StreamProviderDirection.ReadWrite;
/// <summary>
/// Creates a failure handler for a partition.
/// </summary>
protected Func<string, Task<IStreamFailureHandler>> StreamFailureHandlerFactory { get; set; }
/// <summary>
/// Create a cache monitor to report cache related metrics
/// Return a ICacheMonitor
/// </summary>
protected Func<CacheMonitorDimensions, ITelemetryProducer, ICacheMonitor> CacheMonitorFactory;
/// <summary>
/// Create a block pool monitor to monitor block pool related metrics
/// Return a IBlockPoolMonitor
/// </summary>
protected Func<BlockPoolMonitorDimensions, ITelemetryProducer, IBlockPoolMonitor> BlockPoolMonitorFactory;
/// <summary>
/// Create a monitor to monitor QueueAdapterReceiver related metrics
/// Return a IQueueAdapterReceiverMonitor
/// </summary>
protected Func<ReceiverMonitorDimensions, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory;
public MemoryAdapterFactory(string providerName, StreamCacheEvictionOptions cacheOptions, StreamStatisticOptions statisticOptions, HashRingStreamQueueMapperOptions queueMapperOptions,
IServiceProvider serviceProvider, IGrainFactory grainFactory, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory)
{
this.Name = providerName;
this.queueMapperOptions = queueMapperOptions ?? throw new ArgumentNullException(nameof(queueMapperOptions));
this.cacheOptions = cacheOptions ?? throw new ArgumentNullException(nameof(cacheOptions));
this.statisticOptions = statisticOptions ?? throw new ArgumentException(nameof(statisticOptions));
this.grainFactory = grainFactory ?? throw new ArgumentNullException(nameof(grainFactory));
this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer));
this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
this.logger = loggerFactory.CreateLogger<ILogger<MemoryAdapterFactory<TSerializer>>>();
this.serializer = MemoryMessageBodySerializerFactory<TSerializer>.GetOrCreateSerializer(serviceProvider);
}
/// <summary>
/// Factory initialization.
/// </summary>
public void Init()
{
this.queueGrains = new ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain>();
if (CacheMonitorFactory == null)
this.CacheMonitorFactory = (dimensions, telemetryProducer) => new DefaultCacheMonitor(dimensions, telemetryProducer);
if (this.BlockPoolMonitorFactory == null)
this.BlockPoolMonitorFactory = (dimensions, telemetryProducer) => new DefaultBlockPoolMonitor(dimensions, telemetryProducer);
if (this.ReceiverMonitorFactory == null)
this.ReceiverMonitorFactory = (dimensions, telemetryProducer) => new DefaultQueueAdapterReceiverMonitor(dimensions, telemetryProducer);
this.purgePredicate = new TimePurgePredicate(this.cacheOptions.DataMinTimeInCache, this.cacheOptions.DataMaxAgeInCache);
this.streamQueueMapper = new HashRingBasedStreamQueueMapper(this.queueMapperOptions, this.Name);
}
private void CreateBufferPoolIfNotCreatedYet()
{
if (this.bufferPool == null)
{
// 1 meg block size pool
this.blockPoolMonitorDimensions = new BlockPoolMonitorDimensions($"BlockPool-{Guid.NewGuid()}");
var oneMb = 1 << 20;
var objectPoolMonitor = new ObjectPoolMonitorBridge(this.BlockPoolMonitorFactory(blockPoolMonitorDimensions, this.telemetryProducer), oneMb);
this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneMb), objectPoolMonitor, this.statisticOptions.StatisticMonitorWriteInterval);
}
}
/// <summary>
/// Create queue adapter.
/// </summary>
/// <returns></returns>
public Task<IQueueAdapter> CreateAdapter()
{
return Task.FromResult<IQueueAdapter>(this);
}
/// <summary>
/// Create queue message cache adapter
/// </summary>
/// <returns></returns>
public IQueueAdapterCache GetQueueAdapterCache()
{
return this;
}
/// <summary>
/// Create queue mapper
/// </summary>
/// <returns></returns>
public IStreamQueueMapper GetStreamQueueMapper()
{
return streamQueueMapper;
}
/// <summary>
/// Creates a queue receiver for the specified queueId
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public IQueueAdapterReceiver CreateReceiver(QueueId queueId)
{
var dimensions = new ReceiverMonitorDimensions(queueId.ToString());
var receiverLogger = this.loggerFactory.CreateLogger($"{typeof(MemoryAdapterReceiver<TSerializer>).FullName}.{this.Name}.{queueId}");
var receiverMonitor = this.ReceiverMonitorFactory(dimensions, this.telemetryProducer);
IQueueAdapterReceiver receiver = new MemoryAdapterReceiver<TSerializer>(GetQueueGrain(queueId), receiverLogger, this.serializer, receiverMonitor);
return receiver;
}
/// <summary>
/// Writes a set of events to the queue as a single batch associated with the provided streamId.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="streamId"></param>
/// <param name="events"></param>
/// <param name="token"></param>
/// <param name="requestContext"></param>
/// <returns></returns>
public async Task QueueMessageBatchAsync<T>(StreamId streamId, IEnumerable<T> events, StreamSequenceToken token, Dictionary<string, object> requestContext)
{
try
{
var queueId = streamQueueMapper.GetQueueForStream(streamId);
ArraySegment<byte> bodyBytes = serializer.Serialize(new MemoryMessageBody(events.Cast<object>(), requestContext));
var messageData = MemoryMessageData.Create(streamId, bodyBytes);
IMemoryStreamQueueGrain queueGrain = GetQueueGrain(queueId);
await queueGrain.Enqueue(messageData);
}
catch (Exception exc)
{
logger.LogError((int)ProviderErrorCode.MemoryStreamProviderBase_QueueMessageBatchAsync, exc, "Exception thrown in MemoryAdapterFactory.QueueMessageBatchAsync.");
throw;
}
}
/// <summary>
/// Create a cache for a given queue id
/// </summary>
/// <param name="queueId"></param>
public IQueueCache CreateQueueCache(QueueId queueId)
{
//move block pool creation from init method to here, to avoid unnecessary block pool creation when stream provider is initialized in client side.
CreateBufferPoolIfNotCreatedYet();
var logger = this.loggerFactory.CreateLogger($"{typeof(MemoryPooledCache<TSerializer>).FullName}.{this.Name}.{queueId}");
var monitor = this.CacheMonitorFactory(new CacheMonitorDimensions(queueId.ToString(), this.blockPoolMonitorDimensions.BlockPoolId), this.telemetryProducer);
return new MemoryPooledCache<TSerializer>(bufferPool, purgePredicate, logger, this.serializer, monitor, this.statisticOptions.StatisticMonitorWriteInterval);
}
/// <summary>
/// Acquire delivery failure handler for a queue
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId)
{
return Task.FromResult(streamFailureHandler ?? (streamFailureHandler = new NoOpStreamDeliveryFailureHandler()));
}
/// <summary>
/// Generate a deterministic Guid from a queue Id.
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
private Guid GenerateDeterministicGuid(QueueId queueId)
{
// provider name hash code
int providerNameGuidHash = (int)JenkinsHash.ComputeHash(this.Name);
// get queueId hash code
uint queueIdHash = queueId.GetUniformHashCode();
byte[] queIdHashByes = BitConverter.GetBytes(queueIdHash);
short s1 = BitConverter.ToInt16(queIdHashByes, 0);
short s2 = BitConverter.ToInt16(queIdHashByes, 2);
// build guid tailing 8 bytes from providerNameGuidHash and queIdHashByes.
var tail = new List<byte>();
tail.AddRange(BitConverter.GetBytes(providerNameGuidHash));
tail.AddRange(queIdHashByes);
// make guid.
// - First int is provider name hash
// - Two shorts from queue Id hash
// - 8 byte tail from provider name hash and queue Id hash.
return new Guid(providerNameGuidHash, s1, s2, tail.ToArray());
}
/// <summary>
/// Get a MemoryStreamQueueGrain instance by queue Id.
/// </summary>
/// <param name="queueId"></param>
/// <returns></returns>
private IMemoryStreamQueueGrain GetQueueGrain(QueueId queueId)
{
return queueGrains.GetOrAdd(queueId, id => grainFactory.GetGrain<IMemoryStreamQueueGrain>(GenerateDeterministicGuid(id)));
}
public static MemoryAdapterFactory<TSerializer> Create(IServiceProvider services, string name)
{
var cachePurgeOptions = services.GetOptionsByName<StreamCacheEvictionOptions>(name);
var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name);
var queueMapperOptions = services.GetOptionsByName<HashRingStreamQueueMapperOptions>(name);
var factory = ActivatorUtilities.CreateInstance<MemoryAdapterFactory<TSerializer>>(services, name, cachePurgeOptions, statisticOptions, queueMapperOptions);
factory.Init();
return factory;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Resource
{
using System;
using System.Collections.Generic;
using System.Reflection;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Resource;
/// <summary>
/// Resource type descriptor.
/// </summary>
internal class ResourceTypeDescriptor
{
/** Attribute type: InstanceResourceAttribute. */
private static readonly Type TypAttrIgnite = typeof(InstanceResourceAttribute);
/** Attribute type: StoreSessionResourceAttribute. */
private static readonly Type TypAttrStoreSes = typeof(StoreSessionResourceAttribute);
/** Type: IGrid. */
private static readonly Type TypIgnite = typeof(IIgnite);
/** Type: ICacheStoreSession. */
private static readonly Type TypStoreSes = typeof (ICacheStoreSession);
/** Type: ComputeTaskNoResultCacheAttribute. */
private static readonly Type TypComputeTaskNoResCache = typeof(ComputeTaskNoResultCacheAttribute);
/** Cached binding flags. */
private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
/** Ignite injectors. */
private readonly IList<IResourceInjector> _igniteInjectors;
/** Session injectors. */
private readonly IList<IResourceInjector> _storeSesInjectors;
/** Task "no result cache" flag. */
private readonly bool _taskNoResCache;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type">Type.</param>
internal ResourceTypeDescriptor(Type type)
{
Collector gridCollector = new Collector(TypAttrIgnite, TypIgnite);
Collector storeSesCollector = new Collector(TypAttrStoreSes, TypStoreSes);
Type curType = type;
while (curType != null)
{
CreateInjectors(curType, gridCollector, storeSesCollector);
curType = curType.BaseType;
}
_igniteInjectors = gridCollector.Injectors;
_storeSesInjectors = storeSesCollector.Injectors;
_taskNoResCache = ContainsAttribute(type, TypComputeTaskNoResCache, true);
}
/// <summary>
/// Inject resources to the given object.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="ignite">Grid.</param>
public void InjectIgnite(object target, Ignite ignite)
{
Inject0(target, ignite, _igniteInjectors);
}
/// <summary>
/// Inject store session.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="ses">Store session.</param>
public void InjectStoreSession(object target, ICacheStoreSession ses)
{
Inject0(target, ses, _storeSesInjectors);
}
/// <summary>
/// Perform injection.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="injectee">Injectee.</param>
/// <param name="injectors">Injectors.</param>
private static void Inject0(object target, object injectee, ICollection<IResourceInjector> injectors)
{
if (injectors != null)
{
foreach (IResourceInjector injector in injectors)
injector.Inject(target, injectee);
}
}
/// <summary>
/// Task "no result cache" flag.
/// </summary>
public bool TaskNoResultCache
{
get
{
return _taskNoResCache;
}
}
/// <summary>
/// Create gridInjectors for the given type.
/// </summary>
/// <param name="type">Type.</param>
/// <param name="collectors">Collectors.</param>
private static void CreateInjectors(Type type, params Collector[] collectors)
{
FieldInfo[] fields = type.GetFields(Flags);
foreach (FieldInfo field in fields)
{
foreach (var collector in collectors)
{
if (!ContainsAttribute(field, collector.AttributeType, false))
continue;
if (!field.FieldType.IsAssignableFrom(collector.ResourceType))
throw new IgniteException("Invalid field type for resource attribute [" +
"type=" + type.Name +
", field=" + field.Name +
", fieldType=" + field.FieldType.Name +
", resourceType=" + collector.ResourceType.Name + ']');
collector.Add(new ResourceFieldInjector(field));
}
}
PropertyInfo[] props = type.GetProperties(Flags);
foreach (var prop in props)
{
foreach (var collector in collectors)
{
if (!ContainsAttribute(prop, collector.AttributeType, false))
continue;
if (!prop.CanWrite)
throw new IgniteException("Property with resource attribute is not writable [" +
"type=" + type.Name +
", property=" + prop.Name +
", resourceType=" + collector.ResourceType.Name + ']');
if (!prop.PropertyType.IsAssignableFrom(collector.ResourceType))
throw new IgniteException("Invalid property type for resource attribute [" +
"type=" + type.Name +
", property=" + prop.Name +
", propertyType=" + prop.PropertyType.Name +
", resourceType=" + collector.ResourceType.Name + ']');
collector.Add(new ResourcePropertyInjector(prop));
}
}
MethodInfo[] mthds = type.GetMethods(Flags);
foreach (MethodInfo mthd in mthds)
{
foreach (var collector in collectors)
{
if (!ContainsAttribute(mthd, collector.AttributeType, false))
continue;
ParameterInfo[] parameters = mthd.GetParameters();
if (parameters.Length != 1)
throw new IgniteException("Method with resource attribute must have only one parameter [" +
"type=" + type.Name +
", method=" + mthd.Name +
", resourceType=" + collector.ResourceType.Name + ']');
if (!parameters[0].ParameterType.IsAssignableFrom(collector.ResourceType))
throw new IgniteException("Invalid method parameter type for resource attribute [" +
"type=" + type.Name +
", method=" + mthd.Name +
", methodParameterType=" + parameters[0].ParameterType.Name +
", resourceType=" + collector.ResourceType.Name + ']');
collector.Add(new ResourceMethodInjector(mthd));
}
}
}
/// <summary>
/// Check whether the given member contains the given attribute.
/// </summary>
/// <param name="member">Mmeber.</param>
/// <param name="attrType">Attribute type.</param>
/// <param name="inherit">Inherit flag.</param>
/// <returns>True if contains</returns>
private static bool ContainsAttribute(MemberInfo member, Type attrType, bool inherit)
{
return member.GetCustomAttributes(attrType, inherit).Length > 0;
}
/// <summary>
/// Collector.
/// </summary>
private class Collector
{
/** Attribute type. */
private readonly Type _attrType;
/** Resource type. */
private readonly Type _resType;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="attrType">Atrribute type.</param>
/// <param name="resType">Resource type.</param>
public Collector(Type attrType, Type resType)
{
_attrType = attrType;
_resType = resType;
}
/// <summary>
/// Attribute type.
/// </summary>
public Type AttributeType
{
get { return _attrType; }
}
/// <summary>
/// Resource type.
/// </summary>
public Type ResourceType
{
get { return _resType; }
}
/// <summary>
/// Add injector.
/// </summary>
/// <param name="injector">Injector.</param>
public void Add(IResourceInjector injector)
{
if (Injectors == null)
Injectors = new List<IResourceInjector> { injector };
else
Injectors.Add(injector);
}
/// <summary>
/// Injectors.
/// </summary>
public List<IResourceInjector> Injectors { get; private set; }
}
}
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERCLevel;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H06_Country (editable child object).<br/>
/// This is a generated base class of <see cref="H06_Country"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="H07_RegionObjects"/> of type <see cref="H07_RegionColl"/> (1:M relation to <see cref="H08_Region"/>)<br/>
/// This class is an item of <see cref="H05_CountryColl"/> collection.
/// </remarks>
[Serializable]
public partial class H06_Country : BusinessBase<H06_Country>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Country_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Countries ID");
/// <summary>
/// Gets the Countries ID.
/// </summary>
/// <value>The Countries ID.</value>
public int Country_ID
{
get { return GetProperty(Country_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Country_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Countries Name");
/// <summary>
/// Gets or sets the Countries Name.
/// </summary>
/// <value>The Countries Name.</value>
public string Country_Name
{
get { return GetProperty(Country_NameProperty); }
set { SetProperty(Country_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H07_Country_SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H07_Country_Child> H07_Country_SingleObjectProperty = RegisterProperty<H07_Country_Child>(p => p.H07_Country_SingleObject, "H07 Country Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H07 Country Single Object ("self load" child property).
/// </summary>
/// <value>The H07 Country Single Object.</value>
public H07_Country_Child H07_Country_SingleObject
{
get { return GetProperty(H07_Country_SingleObjectProperty); }
private set { LoadProperty(H07_Country_SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H07_Country_ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<H07_Country_ReChild> H07_Country_ASingleObjectProperty = RegisterProperty<H07_Country_ReChild>(p => p.H07_Country_ASingleObject, "H07 Country ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the H07 Country ASingle Object ("self load" child property).
/// </summary>
/// <value>The H07 Country ASingle Object.</value>
public H07_Country_ReChild H07_Country_ASingleObject
{
get { return GetProperty(H07_Country_ASingleObjectProperty); }
private set { LoadProperty(H07_Country_ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="H07_RegionObjects"/> property.
/// </summary>
public static readonly PropertyInfo<H07_RegionColl> H07_RegionObjectsProperty = RegisterProperty<H07_RegionColl>(p => p.H07_RegionObjects, "H07 Region Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the H07 Region Objects ("self load" child property).
/// </summary>
/// <value>The H07 Region Objects.</value>
public H07_RegionColl H07_RegionObjects
{
get { return GetProperty(H07_RegionObjectsProperty); }
private set { LoadProperty(H07_RegionObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H06_Country"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="H06_Country"/> object.</returns>
internal static H06_Country NewH06_Country()
{
return DataPortal.CreateChild<H06_Country>();
}
/// <summary>
/// Factory method. Loads a <see cref="H06_Country"/> object from the given H06_CountryDto.
/// </summary>
/// <param name="data">The <see cref="H06_CountryDto"/>.</param>
/// <returns>A reference to the fetched <see cref="H06_Country"/> object.</returns>
internal static H06_Country GetH06_Country(H06_CountryDto data)
{
H06_Country obj = new H06_Country();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H06_Country"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H06_Country()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="H06_Country"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Country_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(H07_Country_SingleObjectProperty, DataPortal.CreateChild<H07_Country_Child>());
LoadProperty(H07_Country_ASingleObjectProperty, DataPortal.CreateChild<H07_Country_ReChild>());
LoadProperty(H07_RegionObjectsProperty, DataPortal.CreateChild<H07_RegionColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="H06_Country"/> object from the given <see cref="H06_CountryDto"/>.
/// </summary>
/// <param name="data">The H06_CountryDto to use.</param>
private void Fetch(H06_CountryDto data)
{
// Value properties
LoadProperty(Country_IDProperty, data.Country_ID);
LoadProperty(Country_NameProperty, data.Country_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(H07_Country_SingleObjectProperty, H07_Country_Child.GetH07_Country_Child(Country_ID));
LoadProperty(H07_Country_ASingleObjectProperty, H07_Country_ReChild.GetH07_Country_ReChild(Country_ID));
LoadProperty(H07_RegionObjectsProperty, H07_RegionColl.GetH07_RegionColl(Country_ID));
}
/// <summary>
/// Inserts a new <see cref="H06_Country"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(H04_SubContinent parent)
{
var dto = new H06_CountryDto();
dto.Parent_SubContinent_ID = parent.SubContinent_ID;
dto.Country_Name = Country_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IH06_CountryDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
LoadProperty(Country_IDProperty, resultDto.Country_ID);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="H06_Country"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
if (!IsDirty)
return;
var dto = new H06_CountryDto();
dto.Country_ID = Country_ID;
dto.Country_Name = Country_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IH06_CountryDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="H06_Country"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
// flushes all pending data operations
FieldManager.UpdateChildren(this);
OnDeletePre(args);
var dal = dalManager.GetProvider<IH06_CountryDal>();
using (BypassPropertyChecks)
{
dal.Delete(ReadProperty(Country_IDProperty));
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.BackupServices;
using Microsoft.Azure.Management.BackupServices.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.BackupServices
{
/// <summary>
/// Definition of Recovery Point operations for the Azure Backup extension.
/// </summary>
internal partial class RecoveryPointOperations : IServiceOperations<BackupServicesManagementClient>, IRecoveryPointOperations
{
/// <summary>
/// Initializes a new instance of the RecoveryPointOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RecoveryPointOperations(BackupServicesManagementClient client)
{
this._client = client;
}
private BackupServicesManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.BackupServices.BackupServicesManagementClient.
/// </summary>
public BackupServicesManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Get the recovery point.
/// </summary>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='containerName'>
/// Optional.
/// </param>
/// <param name='itemName'>
/// Optional.
/// </param>
/// <param name='recoveryPointName'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The definition of a CSMRecoveryPointGetOperationResponse.
/// </returns>
public async Task<CSMRecoveryPointGetOperationResponse> GetAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string containerName, string itemName, string recoveryPointName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("itemName", itemName);
tracingParameters.Add("recoveryPointName", recoveryPointName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/registeredContainers/";
if (containerName != null)
{
url = url + Uri.EscapeDataString(containerName);
}
url = url + "/protectedItems/";
if (itemName != null)
{
url = url + Uri.EscapeDataString(itemName);
}
url = url + "/recoveryPoints/";
if (recoveryPointName != null)
{
url = url + Uri.EscapeDataString(recoveryPointName);
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-09-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CSMRecoveryPointGetOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CSMRecoveryPointGetOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
CSMRecoveryPointResponse cSMRecoveryPointResponseInstance = new CSMRecoveryPointResponse();
result.CSMRecoveryPointResponse = cSMRecoveryPointResponseInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CSMRecoveryPointProperties propertiesInstance = new CSMRecoveryPointProperties();
cSMRecoveryPointResponseInstance.Properties = propertiesInstance;
JToken recoveryPointTypeValue = propertiesValue["recoveryPointType"];
if (recoveryPointTypeValue != null && recoveryPointTypeValue.Type != JTokenType.Null)
{
string recoveryPointTypeInstance = ((string)recoveryPointTypeValue);
propertiesInstance.RecoveryPointType = recoveryPointTypeInstance;
}
JToken recoveryPointTimeValue = propertiesValue["recoveryPointTime"];
if (recoveryPointTimeValue != null && recoveryPointTimeValue.Type != JTokenType.Null)
{
DateTime recoveryPointTimeInstance = ((DateTime)recoveryPointTimeValue);
propertiesInstance.RecoveryPointTime = recoveryPointTimeInstance;
}
JToken recoveryPointAdditionalInfoValue = propertiesValue["recoveryPointAdditionalInfo"];
if (recoveryPointAdditionalInfoValue != null && recoveryPointAdditionalInfoValue.Type != JTokenType.Null)
{
string recoveryPointAdditionalInfoInstance = ((string)recoveryPointAdditionalInfoValue);
propertiesInstance.RecoveryPointAdditionalInfo = recoveryPointAdditionalInfoInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
cSMRecoveryPointResponseInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
cSMRecoveryPointResponseInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
cSMRecoveryPointResponseInstance.Type = typeInstance;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the list of all recovery points.
/// </summary>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='customRequestHeaders'>
/// Optional. Request header parameters.
/// </param>
/// <param name='containerName'>
/// Optional.
/// </param>
/// <param name='itemName'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The definition of a CSMRecoveryPointListOperationResponse.
/// </returns>
public async Task<CSMRecoveryPointListOperationResponse> ListAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, string containerName, string itemName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("resourceName", resourceName);
tracingParameters.Add("customRequestHeaders", customRequestHeaders);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("itemName", itemName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Backup";
url = url + "/";
url = url + "BackupVault";
url = url + "/";
url = url + Uri.EscapeDataString(resourceName);
url = url + "/registeredContainers/";
if (containerName != null)
{
url = url + Uri.EscapeDataString(containerName);
}
url = url + "/protectedItems/";
if (itemName != null)
{
url = url + Uri.EscapeDataString(itemName);
}
url = url + "/recoveryPoints";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-09-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept-Language", "en-us");
httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId);
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CSMRecoveryPointListOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CSMRecoveryPointListOperationResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
CSMRecoveryPointListResponse cSMRecoveryPointListResponseInstance = new CSMRecoveryPointListResponse();
result.CSMRecoveryPointListResponse = cSMRecoveryPointListResponseInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
CSMRecoveryPointResponse cSMRecoveryPointResponseInstance = new CSMRecoveryPointResponse();
cSMRecoveryPointListResponseInstance.Value.Add(cSMRecoveryPointResponseInstance);
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CSMRecoveryPointProperties propertiesInstance = new CSMRecoveryPointProperties();
cSMRecoveryPointResponseInstance.Properties = propertiesInstance;
JToken recoveryPointTypeValue = propertiesValue["recoveryPointType"];
if (recoveryPointTypeValue != null && recoveryPointTypeValue.Type != JTokenType.Null)
{
string recoveryPointTypeInstance = ((string)recoveryPointTypeValue);
propertiesInstance.RecoveryPointType = recoveryPointTypeInstance;
}
JToken recoveryPointTimeValue = propertiesValue["recoveryPointTime"];
if (recoveryPointTimeValue != null && recoveryPointTimeValue.Type != JTokenType.Null)
{
DateTime recoveryPointTimeInstance = ((DateTime)recoveryPointTimeValue);
propertiesInstance.RecoveryPointTime = recoveryPointTimeInstance;
}
JToken recoveryPointAdditionalInfoValue = propertiesValue["recoveryPointAdditionalInfo"];
if (recoveryPointAdditionalInfoValue != null && recoveryPointAdditionalInfoValue.Type != JTokenType.Null)
{
string recoveryPointAdditionalInfoInstance = ((string)recoveryPointAdditionalInfoValue);
propertiesInstance.RecoveryPointAdditionalInfo = recoveryPointAdditionalInfoInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
cSMRecoveryPointResponseInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
cSMRecoveryPointResponseInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
cSMRecoveryPointResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
cSMRecoveryPointListResponseInstance.NextLink = nextLinkInstance;
}
JToken idValue2 = responseDoc["id"];
if (idValue2 != null && idValue2.Type != JTokenType.Null)
{
string idInstance2 = ((string)idValue2);
cSMRecoveryPointListResponseInstance.Id = idInstance2;
}
JToken nameValue2 = responseDoc["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
cSMRecoveryPointListResponseInstance.Name = nameInstance2;
}
JToken typeValue2 = responseDoc["type"];
if (typeValue2 != null && typeValue2.Type != JTokenType.Null)
{
string typeInstance2 = ((string)typeValue2);
cSMRecoveryPointListResponseInstance.Type = typeInstance2;
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Projectile.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace CatapultGame
{
public enum ProjectileState
{
InFlight,
HitGround,
Destroyed
}
class Projectile : DrawableGameComponent
{
#region Fields/Properties
protected SpriteBatch spriteBatch;
protected Game curGame;
// List of currently active projectiles. This allows projectiles
// to spawn other projectiles.
protected List<Projectile> activeProjectiles;
// Texture name for projectile
string textureName;
// Movement related fields
protected Vector2 projectileInitialVelocity = Vector2.Zero;
protected Vector2 projectileRotationPosition = Vector2.Zero;
protected float gravity;
public virtual float Wind { get; set; }
protected float flightTime;
protected float projectileRotation;
// State related fields
protected bool isAI;
protected float hitOffset;
Vector2 projectileStartPosition;
public Vector2 ProjectileStartPosition
{
get
{
return projectileStartPosition;
}
set
{
projectileStartPosition = value;
}
}
Vector2 currentVelocity = Vector2.Zero;
public Vector2 CurrentVelocity
{
get
{
return currentVelocity;
}
}
Vector2 projectilePosition = Vector2.Zero;
public Vector2 ProjectilePosition
{
get
{
return projectilePosition;
}
set
{
projectilePosition = value;
}
}
/// <summary>
/// Gets the position where the projectile hit the ground.
/// Only valid after a hit occurs.
/// </summary>
public Vector2 ProjectileHitPosition { get; private set; }
public ProjectileState State { get; private set; }
Texture2D projectileTexture;
public Texture2D ProjectileTexture
{
get
{
return projectileTexture;
}
set
{
projectileTexture = value;
}
}
/// <summary>
/// This property can be used to set a hit animation for the projectile.
/// Must be set and manually initialized before the projectile attempts to
/// draw frames from the hit animation (after its state changes to "HitGround").
/// </summary>
public Animation HitAnimation { get; set; }
/// <summary>
/// Used to mark whether or not the projectile's hit was handled.
/// </summary>
public bool HitHandled { get; set; }
#endregion
#region Initialization
public Projectile(Game game)
: base(game)
{
curGame = game;
}
public Projectile(Game game, SpriteBatch screenSpriteBatch,
List<Projectile> activeProjectiles, string textureName,
Vector2 startPosition, float groundHitOffset, bool isAI,
float gravity)
: this(game)
{
spriteBatch = screenSpriteBatch;
this.activeProjectiles = activeProjectiles;
projectileStartPosition = startPosition;
this.textureName = textureName;
this.isAI = isAI;
hitOffset = groundHitOffset;
this.gravity = gravity;
}
public override void Initialize()
{
// Load a projectile texture
projectileTexture = curGame.Content.Load<Texture2D>(textureName);
}
#endregion
#region Render/Update
public override void Update(GameTime gameTime)
{
switch (State)
{
case ProjectileState.InFlight:
UpdateProjectileFlight(gameTime);
break;
case ProjectileState.HitGround:
UpdateProjectileHit(gameTime);
break;
default:
// Nothing to update in other states
break;
}
base.Update(gameTime);
}
/// <summary>
/// This method is used to update the projectile after it has hit the ground.
/// This allows derived projectile types to alter the projectile's hit
/// phase more easily.
/// </summary>
protected void UpdateProjectileHit(GameTime gameTime)
{
if (HitAnimation.IsActive == false)
{
State = ProjectileState.Destroyed;
return;
}
HitAnimation.Update();
}
/// <summary>
/// This method is used to update the projectile while it is in flight.
/// This allows derived projectile types to alter the projectile's flight
/// phase more easily.
/// </summary>
protected virtual void UpdateProjectileFlight(GameTime gameTime)
{
UpdateProjectileFlightData(gameTime, Wind, gravity);
}
public override void Draw(GameTime gameTime)
{
switch (State)
{
case ProjectileState.InFlight:
spriteBatch.Draw(projectileTexture, projectilePosition, null,
Color.White, projectileRotation,
new Vector2(projectileTexture.Width / 2,
projectileTexture.Height / 2),
1.0f, SpriteEffects.None, 0);
break;
case ProjectileState.HitGround:
HitAnimation.Draw(spriteBatch, ProjectileHitPosition,
SpriteEffects.None);
break;
default:
// Nothing to draw in this case
break;
}
base.Draw(gameTime);
}
#endregion
#region Public functionality
/// <summary>
/// Helper function - calculates the projectile position and velocity
/// based on time.
/// </summary>
/// <param name="gameTime">The time since last calculation</param>
private void UpdateProjectileFlightData(GameTime gameTime, float wind, float gravity)
{
flightTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
// Calculate new projectile position using standard
// formulas, taking the wind as a force.
int direction = isAI ? -1 : 1;
float previousXPosition = projectilePosition.X;
float previousYPosition = projectilePosition.Y;
projectilePosition.X = projectileStartPosition.X +
(direction * projectileInitialVelocity.X * flightTime) +
0.5f * (8 * wind * (float)Math.Pow(flightTime, 2));
currentVelocity.X = projectileInitialVelocity.X + 8 * wind * flightTime;
projectilePosition.Y = projectileStartPosition.Y -
(projectileInitialVelocity.Y * flightTime) +
0.5f * (gravity * (float)Math.Pow(flightTime, 2));
currentVelocity.Y = projectileInitialVelocity.Y - gravity * flightTime;
// Calculate the projectile rotation
projectileRotation += MathHelper.ToRadians(projectileInitialVelocity.X * 0.5f);
// Check if projectile hit the ground or even passed it
// (could happen during normal calculation)
if (projectilePosition.Y >= 332 + hitOffset)
{
projectilePosition.X = previousXPosition;
projectilePosition.Y = previousYPosition;
ProjectileHitPosition = new Vector2(previousXPosition, 332);
State = ProjectileState.HitGround;
}
}
public void Fire(float velocityX, float velocityY)
{
// Set initial projectile velocity
projectilePosition = projectileStartPosition;
projectileInitialVelocity.X = velocityX;
projectileInitialVelocity.Y = velocityY;
currentVelocity.X = velocityX;
currentVelocity.Y = velocityY;
// Reset calculation variables
flightTime = 0;
State = ProjectileState.InFlight;
HitHandled = false;
}
#endregion
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.widget.CursorTreeAdapter_))]
public abstract partial class CursorTreeAdapter : android.widget.BaseExpandableListAdapter, Filterable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected CursorTreeAdapter(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override long getGroupId(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "getGroupId", "(I)J", ref global::android.widget.CursorTreeAdapter._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::android.widget.Filter getFilter()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "getFilter", "()Landroid/widget/Filter;", ref global::android.widget.CursorTreeAdapter._m1) as android.widget.Filter;
}
private static global::MonoJavaBridge.MethodId _m2;
public override bool hasStableIds()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "hasStableIds", "()Z", ref global::android.widget.CursorTreeAdapter._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public override int getGroupCount()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "getGroupCount", "()I", ref global::android.widget.CursorTreeAdapter._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
public override int getChildrenCount(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "getChildrenCount", "(I)I", ref global::android.widget.CursorTreeAdapter._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public override global::java.lang.Object getGroup(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "getGroup", "(I)Ljava/lang/Object;", ref global::android.widget.CursorTreeAdapter._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m6;
public override global::java.lang.Object getChild(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "getChild", "(II)Ljava/lang/Object;", ref global::android.widget.CursorTreeAdapter._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m7;
public override long getChildId(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "getChildId", "(II)J", ref global::android.widget.CursorTreeAdapter._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m8;
public override global::android.view.View getGroupView(int arg0, bool arg1, android.view.View arg2, android.view.ViewGroup arg3)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "getGroupView", "(IZLandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;", ref global::android.widget.CursorTreeAdapter._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m9;
public override global::android.view.View getChildView(int arg0, int arg1, bool arg2, android.view.View arg3, android.view.ViewGroup arg4)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "getChildView", "(IIZLandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;", ref global::android.widget.CursorTreeAdapter._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m10;
public override bool isChildSelectable(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "isChildSelectable", "(II)Z", ref global::android.widget.CursorTreeAdapter._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m11;
public override void onGroupCollapsed(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "onGroupCollapsed", "(I)V", ref global::android.widget.CursorTreeAdapter._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual global::android.database.Cursor getCursor()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.database.Cursor>(this, global::android.widget.CursorTreeAdapter.staticClass, "getCursor", "()Landroid/database/Cursor;", ref global::android.widget.CursorTreeAdapter._m12) as android.database.Cursor;
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void notifyDataSetChanged(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "notifyDataSetChanged", "(Z)V", ref global::android.widget.CursorTreeAdapter._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public override void notifyDataSetChanged()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "notifyDataSetChanged", "()V", ref global::android.widget.CursorTreeAdapter._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
public override void notifyDataSetInvalidated()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "notifyDataSetInvalidated", "()V", ref global::android.widget.CursorTreeAdapter._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void changeCursor(android.database.Cursor arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "changeCursor", "(Landroid/database/Cursor;)V", ref global::android.widget.CursorTreeAdapter._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual global::java.lang.String convertToString(android.database.Cursor arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.widget.CursorTreeAdapter.staticClass, "convertToString", "(Landroid/database/Cursor;)Ljava/lang/String;", ref global::android.widget.CursorTreeAdapter._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual global::android.database.Cursor runQueryOnBackgroundThread(java.lang.CharSequence arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.database.Cursor>(this, global::android.widget.CursorTreeAdapter.staticClass, "runQueryOnBackgroundThread", "(Ljava/lang/CharSequence;)Landroid/database/Cursor;", ref global::android.widget.CursorTreeAdapter._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.database.Cursor;
}
public android.database.Cursor runQueryOnBackgroundThread(string arg0)
{
return runQueryOnBackgroundThread((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual global::android.widget.FilterQueryProvider getFilterQueryProvider()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.widget.FilterQueryProvider>(this, global::android.widget.CursorTreeAdapter.staticClass, "getFilterQueryProvider", "()Landroid/widget/FilterQueryProvider;", ref global::android.widget.CursorTreeAdapter._m19) as android.widget.FilterQueryProvider;
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setFilterQueryProvider(android.widget.FilterQueryProvider arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "setFilterQueryProvider", "(Landroid/widget/FilterQueryProvider;)V", ref global::android.widget.CursorTreeAdapter._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setFilterQueryProvider(global::android.widget.FilterQueryProviderDelegate arg0)
{
setFilterQueryProvider((global::android.widget.FilterQueryProviderDelegateWrapper)arg0);
}
private static global::MonoJavaBridge.MethodId _m21;
protected abstract global::android.database.Cursor getChildrenCursor(android.database.Cursor arg0);
private static global::MonoJavaBridge.MethodId _m22;
public virtual void setGroupCursor(android.database.Cursor arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "setGroupCursor", "(Landroid/database/Cursor;)V", ref global::android.widget.CursorTreeAdapter._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual void setChildrenCursor(int arg0, android.database.Cursor arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter.staticClass, "setChildrenCursor", "(ILandroid/database/Cursor;)V", ref global::android.widget.CursorTreeAdapter._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m24;
protected abstract global::android.view.View newGroupView(android.content.Context arg0, android.database.Cursor arg1, bool arg2, android.view.ViewGroup arg3);
private static global::MonoJavaBridge.MethodId _m25;
protected abstract void bindGroupView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2, bool arg3);
private static global::MonoJavaBridge.MethodId _m26;
protected abstract global::android.view.View newChildView(android.content.Context arg0, android.database.Cursor arg1, bool arg2, android.view.ViewGroup arg3);
private static global::MonoJavaBridge.MethodId _m27;
protected abstract void bindChildView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2, bool arg3);
private static global::MonoJavaBridge.MethodId _m28;
public CursorTreeAdapter(android.database.Cursor arg0, android.content.Context arg1, bool arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.CursorTreeAdapter._m28.native == global::System.IntPtr.Zero)
global::android.widget.CursorTreeAdapter._m28 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "<init>", "(Landroid/database/Cursor;Landroid/content/Context;Z)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m29;
public CursorTreeAdapter(android.database.Cursor arg0, android.content.Context arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.widget.CursorTreeAdapter._m29.native == global::System.IntPtr.Zero)
global::android.widget.CursorTreeAdapter._m29 = @__env.GetMethodIDNoThrow(global::android.widget.CursorTreeAdapter.staticClass, "<init>", "(Landroid/database/Cursor;Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.CursorTreeAdapter.staticClass, global::android.widget.CursorTreeAdapter._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
static CursorTreeAdapter()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.CursorTreeAdapter.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/CursorTreeAdapter"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.CursorTreeAdapter))]
internal sealed partial class CursorTreeAdapter_ : android.widget.CursorTreeAdapter
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal CursorTreeAdapter_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
protected override global::android.database.Cursor getChildrenCursor(android.database.Cursor arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.database.Cursor>(this, global::android.widget.CursorTreeAdapter_.staticClass, "getChildrenCursor", "(Landroid/database/Cursor;)Landroid/database/Cursor;", ref global::android.widget.CursorTreeAdapter_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.database.Cursor;
}
private static global::MonoJavaBridge.MethodId _m1;
protected override global::android.view.View newGroupView(android.content.Context arg0, android.database.Cursor arg1, bool arg2, android.view.ViewGroup arg3)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.CursorTreeAdapter_.staticClass, "newGroupView", "(Landroid/content/Context;Landroid/database/Cursor;ZLandroid/view/ViewGroup;)Landroid/view/View;", ref global::android.widget.CursorTreeAdapter_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m2;
protected override void bindGroupView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2, bool arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter_.staticClass, "bindGroupView", "(Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;Z)V", ref global::android.widget.CursorTreeAdapter_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m3;
protected override global::android.view.View newChildView(android.content.Context arg0, android.database.Cursor arg1, bool arg2, android.view.ViewGroup arg3)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.widget.CursorTreeAdapter_.staticClass, "newChildView", "(Landroid/content/Context;Landroid/database/Cursor;ZLandroid/view/ViewGroup;)Landroid/view/View;", ref global::android.widget.CursorTreeAdapter_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m4;
protected override void bindChildView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2, bool arg3)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.widget.CursorTreeAdapter_.staticClass, "bindChildView", "(Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;Z)V", ref global::android.widget.CursorTreeAdapter_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
static CursorTreeAdapter_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.CursorTreeAdapter_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/CursorTreeAdapter"));
}
}
}
| |
//Copyright (C) 2006 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the PTBHeadFinder.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//This library is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//This library is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections.Generic;
namespace OpenNLP.Tools.Coreference.Mention
{
/// <summary>
/// Finds head information from Penn Treebank style parses.
/// </summary>
public sealed class PennTreebankHeadFinder : IHeadFinder
{
private static PennTreebankHeadFinder mInstance;
private static Util.Set<string> mSkipSet = new Util.HashSet<string>();
/// <summary>
/// Returns an instance of this head finder.
/// </summary>
/// <returns>
/// An instance of this head finder.
/// </returns>
public static IHeadFinder Instance
{
get
{
if (mInstance == null)
{
mInstance = new PennTreebankHeadFinder();
}
return mInstance;
}
}
private PennTreebankHeadFinder()
{
}
public IParse GetHead(IParse parse)
{
if (parse == null)
{
return null;
}
if (parse.IsNounPhrase)
{
List<IParse> parts = parse.SyntacticChildren;
//shallow parse POS
if (parts.Count > 2)
{
if (parts[1].IsToken && parts[1].SyntacticType == PartsOfSpeech.PossessiveEnding
&& parts[0].IsNounPhrase && parts[2].IsNounPhrase)
{
return (parts[2]);
}
}
//full parse POS
if (parts.Count > 1)
{
if (parts[0].IsNounPhrase)
{
List<IParse> childTokens = parts[0].Tokens;
if (childTokens.Count == 0)
{
Console.Error.WriteLine("PTBHeadFinder: NP " + parts[0] + " with no tokens");
}
IParse tok = childTokens[childTokens.Count - 1];
if (tok.SyntacticType == PartsOfSpeech.PossessiveEnding)
{
return null;
}
}
}
//coordinated nps are their own entities
if (parts.Count > 1)
{
for (int currentPart = 1; currentPart < parts.Count - 1; currentPart++)
{
if (parts[currentPart].IsToken && parts[currentPart].SyntacticType == PartsOfSpeech.CoordinatingConjunction)
{
return null;
}
}
}
//all other NPs
for (int currentPart = 0; currentPart < parts.Count; currentPart++)
{
if (parts[currentPart].IsNounPhrase)
{
return parts[currentPart];
}
}
return null;
}
else
{
return null;
}
}
public int GetHeadIndex(IParse parse)
{
List<IParse> syntacticChildren = parse.SyntacticChildren;
bool countTokens = false;
int tokenCount = 0;
//check for NP -> NN S type structures and return last token before S as head.
for (int currentSyntacticChild = 0; currentSyntacticChild < syntacticChildren.Count; currentSyntacticChild++)
{
IParse syntacticChild = syntacticChildren[currentSyntacticChild];
if (syntacticChild.SyntacticType.StartsWith("S"))
{
if (currentSyntacticChild != 0)
{
countTokens = true;
}
}
if (countTokens)
{
tokenCount += syntacticChild.Tokens.Count;
}
}
List<IParse> tokens = parse.Tokens;
if (tokens.Count == 0)
{
Console.Error.WriteLine("PTBHeadFinder.getHeadIndex(): empty tok list for parse " + parse);
}
for (int currentToken = tokens.Count - tokenCount - 1; currentToken >= 0; currentToken--)
{
IParse token = tokens[currentToken];
if (!mSkipSet.Contains(token.SyntacticType))
{
return currentToken;
}
}
return (tokens.Count - tokenCount - 1);
}
/// <summary>
/// Returns the bottom-most head of a <code>IParse</code>. If no
/// head is available which is a child of <code>parse</code> then
/// <code>parse</code> is returned.
/// </summary>
public IParse GetLastHead(IParse parse)
{
IParse head;
while (null != (head = GetHead(parse)))
{
parse = head;
}
return parse;
}
public IParse GetHeadToken(IParse parse)
{
List<IParse> tokens = parse.Tokens;
return tokens[GetHeadIndex(parse)];
}
static PennTreebankHeadFinder()
{
mSkipSet.Add(PartsOfSpeech.PossessiveEnding);
mSkipSet.Add(PartsOfSpeech.Comma);
mSkipSet.Add(PartsOfSpeech.ColonSemiColon);
mSkipSet.Add(PartsOfSpeech.SentenceFinalPunctuation);
mSkipSet.Add(PartsOfSpeech.RightCloseDoubleQuote);
mSkipSet.Add("-RRB-");
mSkipSet.Add("-RCB-");
}
}
}
| |
// 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.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
using System.Linq;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public abstract partial class DecryptTests
{
private bool _useExplicitPrivateKey;
public static bool SupportsCngCertificates { get; } = (!PlatformDetection.IsFullFramework || PlatformDetection.IsNetfx462OrNewer);
public static bool SupportsIndefiniteLengthEncoding { get; } = !PlatformDetection.IsFullFramework;
public DecryptTests(bool useExplicitPrivateKey)
{
_useExplicitPrivateKey = useExplicitPrivateKey;
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_IssuerAndSerial()
{
byte[] content = { 5, 112, 233, 43 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_Ski()
{
byte[] content = { 6, 3, 128, 33, 44 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.SubjectKeyIdentifier);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_Capi()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_256()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha256KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_384()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha384KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_512()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha512KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_FixedValue()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
byte[] message = (
"3082012506092A864886F70D010703A0820116308201120201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77196303C06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B48010B78CDFECFF32A8" +
"E86D448989382A93E7"
).HexToByteArray();
VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content));
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_NoData_FixedValue()
{
// This is the Decrypt_512_FixedData test re-encoded to remove the
// encryptedContentInfo.encryptedContent optional value.
byte[] content = Array.Empty<byte>();
byte[] message = (
"3082011306092A864886F70D010703A0820104308201000201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77196302A06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B4"
).HexToByteArray();
if (PlatformDetection.IsFullFramework)
{
// On NetFx when Array.Empty should be returned an array of 6 zeros is
// returned instead.
content = new byte[6];
}
VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content));
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_CekDoesNotDecrypt_FixedValue()
{
// This is the Decrypt_512_NoData_FixedValue test except that the last
// byte of the recipient encrypted key has been changed from 0x96 to 0x95
// (the sequence 7195 identifies the changed byte)
byte[] content = Array.Empty<byte>();
byte[] message = (
"3082011306092A864886F70D010703A0820104308201000201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77195302A06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B4"
).HexToByteArray();
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content)));
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_SignedWithinEnveloped()
{
byte[] content =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_EnvelopedWithinEnveloped()
{
byte[] content =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818013"
+ "dc0eb2984a445d04a1f6246b8fe41f1d24507548d449d454d5bb5e0638d75ed101bf78c0155a5d208eb746755fbccbc86923"
+ "8443760a9ae94770d6373e0197be23a6a891f0c522ca96b3e8008bf23547474b7e24e7f32e8134df3862d84f4dea2470548e"
+ "c774dd74f149a56cdd966e141122900d00ad9d10ea1848541294a1302b06092a864886f70d010701301406082a864886f70d"
+ "030704089c8119f6cf6b174c8008bcea3a10d0737eb9").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7SignedEnveloped), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
public void EncryptToNegativeSerialNumber()
{
CertLoader negativeSerial = Certificates.NegativeSerialNumber;
const string expectedSerial = "FD319CB1514B06AF49E00522277E43C8";
byte[] content = { 1, 2, 3 };
ContentInfo contentInfo = new ContentInfo(content);
EnvelopedCms cms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = negativeSerial.GetCertificate())
{
Assert.Equal(expectedSerial, cert.SerialNumber);
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
cms.Encrypt(recipient);
}
EnvelopedCms cms2 = new EnvelopedCms();
cms2.Decode(cms.Encode());
RecipientInfoCollection recipients = cms2.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, recipientInfo.RecipientIdentifier.Type);
X509IssuerSerial issuerSerial = (X509IssuerSerial)recipientInfo.RecipientIdentifier.Value;
Assert.Equal(expectedSerial, issuerSerial.SerialNumber);
using (X509Certificate2 cert = negativeSerial.TryGetCertificateWithPrivateKey())
{
Assert.Equal(expectedSerial, cert.SerialNumber);
cms2.Decrypt(new X509Certificate2Collection(cert));
}
Assert.Equal(content, cms2.ContentInfo.Content);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes128_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm is Aes128
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D0101073000048180862175CD3B2932235A67C6A025F75CDA1A43B53E785370895BA9AC8D0DD"
+ "318EB36DFAE275B16ABD497FEBBFCF2D4B3F38C75B91DC40941A2CC1F7F47E701EEA2D5A770C485565F8726"
+ "DC0D59DDE17AA6DB0F9384C919FC8BC6CB561A980A9AE6095486FDF9F52249FB466B3676E4AEFE4035C15DC"
+ "EE769F25E4660D4BE664E7F303C06092A864886F70D010701301D060960864801650304010204100A068EE9"
+ "03E085EA5A03D1D8B4B73DD88010740E5DE9B798AA062B449F104D0F5D35").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes192_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes192
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D010107300004818029B82454B4C301F277D7872A14695A41ED24FD37AC4C9942F9EE96774E0"
+ "C6ACC18E756993A38AB215E5702CD34F244E52402DA432E8B79DF748405135E8A6D8CB78D88D9E4C142565C"
+ "06F9FAFB32F5A9A4074E10FCCB0758A708CA758C12A17A4961969FCB3B2A6E6C9EB49F5E688D107E1B1DF3D"
+ "531BC684B944FCE6BD4550C303C06092A864886F70D010701301D06096086480165030401160410FD7CBBF5"
+ "6101854387E584C1B6EF3B08801034BD11C68228CB683E0A43AB5D27A8A4").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D01010730000481800215BF7505BCD5D083F8EFDA01A4F91D61DE3967779B2F5E4360593D4CB"
+ "96474E36198531A5E20E417B04C5C7E3263C3301DF8FA888FFBECC796500D382858379059C986285AFD605C"
+ "B5DE125487CCA658DF261C836720E2E14440DA60E2F12D6D5E3992A0DB59973929DF6FC23D8E891F97CA956"
+ "2A7AD160B502FA3C10477AA303C06092A864886F70D010701301D060960864801650304012A04101287FE80"
+ "93F3C517AE86AFB95E599D7E80101823D88F47191857BE0743C4C730E39E").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleTripleDes_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is 3DES-CBC
byte[] encryptedMessage =
("3082010C06092A864886F70D010703A081FE3081FB0201003181C83081C5020100302E301A3118301606035"
+ "50403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D06092A86"
+ "4886F70D0101010500048180062F6F16637C8F35B73924AD85BA47D99DBB4800CB8F0C4094F6896050B7C1F"
+ "11CE79BEE55A638EAAE70F2C32C01FC24B8D09D9D574CB7373788C8BC3A4748124154338C74B644A2A11750"
+ "9E97D1B3535FAE70E4E7C8F2F866232CBFC6448E89CF9D72B948EDCF9C9FC9C153BCC7104680282A4BBBC1E"
+ "E367F094F627EE45FCD302B06092A864886F70D010701301406082A864886F70D030704081E3F12D42E4041"
+ "58800877A4A100165DD0F2").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_Ski()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type SubjectKeyIdentifier. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082010306092A864886F70D010703A081F53081F20201023181AE3081AB0201028014F2008AA9FA3742E83"
+ "70CB1674CE1D1582921DCC3300D06092A864886F70D010101050004818055F258073615B95426A7021E1B30"
+ "9CFE8DD135B58D29F174B9FE19AE80CFC84621BCE3DBD63A5422AF30A6FAA3E2DFC05CB1AB5AB4FBA6C84EB"
+ "1C2E17D5BE5C4959DBE8F96BF1A9701F55B697843032EEC7AFEC58A36815168F017DCFD70C74AD05C48B5E4"
+ "D9DDEE409FDC9DC3326B6C5BA9F433A9E031FF9B09473176637F50303C06092A864886F70D010701301D060"
+ "960864801650304012A0410314DA87435ED110DFE4F52FA70CEF7B080104DDA6C617338DEBDD10913A9141B"
+ "EE52").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaTransferCapi()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransferCapi1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012306092A864886F70D010703A0820114308201100201003181CC3081C90201003032301E311C301A0"
+ "60355040313135253414B65795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA"
+ "300D06092A864886F70D01010730000481804F3F4A6707B329AB9A7343C62F20D5C1EAF4E74ECBB2DC66D1C"
+ "642FC4AA3E40FC4C13547C6C9F73D525EE2FE4147B2043B8FEBF8604C0E4091C657B48DFD83A322F0879580"
+ "FA002C9B27AD1FCF9B8AF24EDDA927BB6728D11530B3F96EBFC859ED6B9F7B009F992171FACB587A7D05E8B"
+ "467B3A1DACC08B2F3341413A7E96576303C06092A864886F70D010701301D060960864801650304012A0410"
+ "6F911E14D9D991DAB93C0B7738D1EC208010044264D201501735F73052FFCA4B2A95").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha256()
{
// Message encrypted on framework for a recipient using the certificate returned by
// Certificates.RSASha256KeyTransfer1.GetCertificate() and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613235364B65795472616E7366657231021072C6C7734916468C4D608253DA01"
+ "7676300D06092A864886F70D01010730000481805C32FA32EBDCFFC3595166EEDACFC9E9D60842105B581E1"
+ "8B85DE1409F4C999995637153480438530955EE4481A3B27B866FF4E106A525CDFFC6941BDD01EFECCC6CCC"
+ "82A3D7F743F7543AB20A61A7831FE4DFB24A1652B072B3758FE4B2588D3B94A29575B6422DC5EF52E432565"
+ "36CA25A11BB92817D61FEAFBDDDEC6EE331303C06092A864886F70D010701301D060960864801650304012A"
+ "041021D59FDB89C13A3EC3766EF32FB333D080105AE8DEB71DF50DD85F66FEA63C8113F4").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha256KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha384()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSASha384KeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613338344B65795472616E736665723102103C724FB7A0159A9345CAAC9E3DF5"
+ "F136300D06092A864886F70D010107300004818011C1B85914331C005EA89E30D00364821B29BC0C459A22D"
+ "917494A1092CDBDA2022792E46C5E88BAD0EE3FD4927B856722311F9B17934FB29CAB8FE595C2AB2B20096B"
+ "9E2FC6F9D7B92125F571CBFC945C892EE4764D9B63369350FD2DAEFE455B367F48E100CB461F112808E792A"
+ "8AA49B66C79E511508A877530BBAA896696303C06092A864886F70D010701301D060960864801650304012A"
+ "0410D653E25E06BFF2EEB0BED4A90D00FE2680106B7EF143912ABA5C24F5E2C151E59D7D").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha384KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha512()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSASha512KeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613531324B65795472616E736665723102102F5D9D58A5F41B844650AA233E68"
+ "F105300D06092A864886F70D01010730000481802156D42FF5ED2F0338302E7298EF79BA1D04E20E68B079D"
+ "B3239120E1FC03FEDA8B544F59142AACAFBC5E58205E8A0D124AAD17B5DCAA39BFC6BA634E820DE623BFDB6"
+ "582BC48AF1B3DEF6849A57D2033586AF01079D67C9AB3AA9F6B51754BCC479A19581D4045EBE23145370219"
+ "98ECB6F5E1BCF8D6BED6A75FE957A40077D303C06092A864886F70D010701301D060960864801650304012A"
+ "04100B696608E489E7C35914D0A3DB9EB27F80103D362181B54721FB2CB7CE461CB31030").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha512KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_ExplicitSki()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer_ExplicitSki.GetCertificate()
// and of type SubjectKeyIdentifier. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082018806092A864886F70D010703A082017930820175020102318201303082012C020102801401952851C"
+ "55DB594B0C6167F5863C5B6B67AEFE6300D06092A864886F70D010101050004820100269EAF029262C87125"
+ "314DD3FB02302FA212EB3CC06F73DF1474382BBA2A92845F39FF5A7F5020482849C36B4BC6BC82F7AF0E2E3"
+ "9143548CC32B93B72EF0659C6895F77E6B5839962678532392185C9431658B34D1ABD31F64F4C4A9B348A77"
+ "56783D60244519ADDD33560405E9377A91617127C2EECF2BAE53AB930FC13AFD25723FB60DB763286EDF6F1"
+ "187D8124B6A569AA2BD19294A7D551A0D90F8436274690231520A2254C19EA9BF877FC99566059A29CDF503"
+ "6BEA1D517916BA2F20AC9F1D8F164B6E8ACDD52BA8B2650EBBCC2ED9103561E11AF422D10DF7405404195FA"
+ "EF79A1FDC680F3A3DC395E3E9C0B10394DF35AE134E6CB719E35152F8E5303C06092A864886F70D01070130"
+ "1D060960864801650304012A041085072D8771A2A2BB403E3236A7C60C2A80105C71A04E73C57FE75C1DEDD"
+ "94B57FD01").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer_ExplicitSki;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_Pkcs7Signed_GeneratedOnWindows()
{
byte[] expectedContent =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), expectedContent);
byte[] encodedMessage = Convert.FromBase64String(
"MIIERwYJKoZIhvcNAQcDoIIEODCCBDQCAQAxgcwwgckCAQAwMjAeMRwwGgYDVQQDExNSU0FLZXlU" +
"cmFuc2ZlckNhcGkxAhBdL//4Y7q8m008gKsXikzKMA0GCSqGSIb3DQEBAQUABIGAngdmU69zGsgJ" +
"mx+hXmTjlefr1oazKRK8VGOeqNMm++J3yHxwz68CLoN4FIEyS/HE3NQE6qb3M80HOpk5fmVVMw7Z" +
"3mrsZlPLOEjJIxEFqAC/JFEzvyE/BL+1OvwRoHpxHsAvZNlz5f9g18wQVE7X5TkkbOJV/6F2disK" +
"H0jik68wggNeBgkqhkiG9w0BBwIwHQYJYIZIAWUDBAEqBBDr3I8NYAnetX+2h9D/nVAggIIDMOlW" +
"7mDuuScuXhCXgZaPy0/zEWy/sYDzxhj1G1X2qBwhB7m6Ez6giibAEYwfRNYaOiVIitIJAUU9LSKg" +
"n0FL1o0eCcgvo04w+zoaBH8pFFk78kuR+T73kflz+O3Eno1pIFpy+2cz2B0QvQSC7lYikbZ4J+/C" +
"7F/uqRoK7sdafNdyUnKhDL+vvP6ToGf9C4g0TjoFEC2ycyJxIBh1F57pqjht6HMQcYm+/fQoBtkt" +
"NrvZxJPlBhbQad/9pSCd0G6NDoPnDuFAicaxGVa7yI2BbvGTCc6NSnbdCzv2EgvsI10Yko+XO4/i" +
"oPnk9pquZBzC3p61XRKbBDrd5RsbkvPDXUHJKD5NQ3W3z9Bnc3bjNyilgDSIB01dE4AcWzdg+RGb" +
"TA7iAbAQKp2zjxb/prmxw1mhO9g6OkDovSTqmQQt7MlHFYFcX9wH8yEe+huIechmiy7famofluJX" +
"vBIz4m3JozlodyNX0nu9QwW58WWcFu6OyoPjFhlB+tLIHUElq9/AAEgwwgfsAj6jEQaHiFG+CYSJ" +
"RjX9+DHFJXMDyzW+eJw8Z/mvbZzzKF553xlAGpfUHHq4CywTyVTHn4nu9HPOeFzoirj1lzFvqmQd" +
"Dgp3T8NOPrns9ZIUBmdNNs/vUxNZqEeN4d0nD5lBG4aZnjsxr4i25rR3Jpe3kKrFtJQ74efkRM37" +
"1ntz9HGiA95G41fuaMw7lgOOfTL+AENNvwRGRCAhinajvQLDkFEuX5ErTtmBxJWU3ZET46u/vRiK" +
"NiRteFiN0hLv1jy+RJK+d+B/QEH3FeVMm3Tz5ll2LfO2nn/QR51hth7qFsvtFpwQqkkhMac6dMf/" +
"bb62pZY15U3y2x5jSn+MZVrNbL4ZK/JO5JFomqKVRjLH1/IZ+kuFNaaTrKFWB4U2gxrMdcjMCZvx" +
"ylbuf01Ajxo74KhPY9sIRztG4BU8ZaE69Ke50wJTE3ulm+g6hzNECdQS/yjuA8AUReGRj2NH/U4M" +
"lEUiR/rMHB/Mq/Vj6lsRFEVxHJSzek6jvrQ4UzVgWGrH4KnP3Rca8CfBTQX79RcZPu+0kI3KI+4H" +
"0Q+UBbb72FHnWsw3uqPEyA==");
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_Pkcs7Signed_GeneratedOnLinux()
{
byte[] expectedContent =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), expectedContent);
byte[] encodedMessage = Convert.FromBase64String(
"MIIERwYJKoZIhvcNAQcDoIIEODCCBDQCAQAxgcwwgckCAQAwMjAeMRwwGgYDVQQDExNSU0FLZXlU" +
"cmFuc2ZlckNhcGkxAhBdL//4Y7q8m008gKsXikzKMA0GCSqGSIb3DQEBAQUABIGAfsH5F4ZlwIcH" +
"nzqn8sOn+ZwK884en7HZrQbgEfedy5ti0ituKn70yTDz4iuNJtpguukCfCAsOT/n3eQn+T6etIa9" +
"byRGQst3F6QtgjAzdb5P1N6c5Mpz1o6k0mbNP/f0FqAaNtuAOnYwlEMwWOz9x4eEYpOhhlc6agRG" +
"qWItNVgwggNeBgkqhkiG9w0BBwIwHQYJYIZIAWUDBAEqBBCA8qaTiT+6IkrO8Ks9WOBggIIDMIkr" +
"7OGlPd3CfzO2CfJA3Sis/1ulDm1ioMCS9V5kLHVx4GWDETORG/YTPA54luxJkvIdU5VwO86+QuXf" +
"rgaly38XHTLZv+RBxUwCaWI0pgvaykEki5CnDu4j9uRQxqz6iU5bY6SKxG3bwcnUzGhWFdQVcNJn" +
"xzuMEcbrix5zfqmoeqemaYyqVqgMPNOnc5kmMOqHrha76qMdbYOSpwx81zYwstBlg+S9+AgOMR+W" +
"qrV9aXJTovjiJEVHPEPJFx0v/wCthhXso51mSU091Cs8qVfvokzlzXcK2dPF5d8EdmZCcmHsoq35" +
"/DfAL4DkfKucwiP9W7rT1a2BmVMquFTMI+KXyDvNhMVasjhKq5eM2G+oUDc3kGa3akaPZ+hNEHA+" +
"BNAS7iIpRft2GMNfTqpkBqnS6pB0+SSf02/JVkcFuHXZ9oZJsvZRm8M1i4WdVauBJ34rInQBdhaO" +
"yaFDx69tBvolclYnMzvdHLiP2TZbiR6kM0vqD1DGjEHNDE+m/jxL7HXcNotW84J9CWlDnm9zaNhL" +
"sB4PJNiNjKhkAsO+2HaNWlEPrmgmWKvNi/Qyrz1qUryqz2/2HGrFDqmjTeEf1+yy35N3Pqv5uvAj" +
"f/ySihknnAh77nI0yOPy0Uto+hbO+xraeujrEifaII8izcz6UG6LHNPxOyscne7HNcqPSAFLsNFJ" +
"1oOlKO0SwhPkGQsk4W5tjVfvLvJiPNcL7SY/eof4vVsRRwX6Op5WUjhJIagY1Vij+4hOcn5TqdmU" +
"OZDh/FC3x4DI556BeMfbWxHNlGvptROQwQ6BasfdiVWCWzMHwLpz27Y47vKbMQ+8TL9668ilT83f" +
"6eo6mHZ590pzuDB+gFrjEK44ov0rvHBK5jHwnSObQvChN0ElizWBdMSUbx9SkcnReH6Fd29SSXdu" +
"RaVspnhmFNXWg7qGYHpEChnIGSr/WIKETZ84f7FRCxCNSYoQtrHs0SskiEGJYEbB6KDMFimEZ4YN" +
"b4cV8VLC9Pxa1Qe1Oa05FBzG2DAP2PfObeKR34afF5wo6vIZfQE0WWoPo9YS326vz1iA5rE0F6qw" +
"zCNmZl8+rW6x73MTEcWhvg==");
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha256()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha256 --aes256 -keyopt rsa_oaep_md:sha256
byte[] encodedMessage = Convert.FromBase64String(
"MIIBUAYJKoZIhvcNAQcDoIIBQTCCAT0CAQAxgfkwgfYCAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwOAYJKoZI" +
"hvcNAQEHMCugDTALBglghkgBZQMEAgGhGjAYBgkqhkiG9w0BAQgwCwYJYIZIAWUD" +
"BAIBBIGAuobMSz1Q4OHRX2aX9AutOPdZX2phA6WATQTOKOWCD//LQwrHYtuNIPAG" +
"Tld+JTZ1EMQD9PoEMyxdkllyie2dn/PSvnE0q/WU+IrHzGzoWofuNs9M6g9Gvpg5" +
"qCGAXK9cL3WkZ9S+M1r6BqlCLwU03bJr6292PiLyjIH80CdMuRUwPAYJKoZIhvcN" +
"AQcBMB0GCWCGSAFlAwQBKgQQezbMDGrefOaUPpfIXBpw7oAQazcOoj9GkvzZMR9Z" +
"NU22nQ==");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha384()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha384 --aes256 -keyopt rsa_oaep_md:sha384
byte[] encodedMessage = Convert.FromBase64String(
"MIIB0AYJKoZIhvcNAQcDoIIBwTCCAb0CAQAxggF4MIIBdAIBADAxMCQxIjAgBgNV" +
"BAMMGVJTQTIwNDhTaGEyNTZLZXlUcmFuc2ZlcjECCQDc5NcqfzyljjA4BgkqhkiG" +
"9w0BAQcwK6ANMAsGCWCGSAFlAwQCAqEaMBgGCSqGSIb3DQEBCDALBglghkgBZQME" +
"AgIEggEAIqqdx5zCFnGSNzV+/N0Mu8S8CVABuPv+RcpV8fiFj5TLcHe84lYI/ptr" +
"F7FwyQRfHVDWgJrJqDS/wYfzD6Ar8qLRdfBswCotn/QYm/VLzBXNRLM402t3lWq+" +
"2pgucyGghpnf2I1aZo8U9hJGUOUPISQqkiol9I1O/JYfo9B7sBTW8Vp22W/c8nTI" +
"huQx+tOhzqGAMElrsd+cEaTiVqAMmNU20B2du0wWs0nckzg4KLbz2g/g8L699luU" +
"t8OluQclxfVgruLY28RY8R5w7OH2LZSEhyKxq3PG3KqXqR+E1MCkpdg8PhTJkeYO" +
"Msz1J70aVA8L8nrhtS9xXq0dd8jyfzA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEq" +
"BBA/xHlg1Der3mxzmvPvUcqogBDEEZmz+ECEWMeNGBv/Cw82");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSA2048Sha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha512()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha512 --aes256 -keyopt rsa_oaep_md:sha512
byte[] encodedMessage = Convert.FromBase64String(
"MIIB0AYJKoZIhvcNAQcDoIIBwTCCAb0CAQAxggF4MIIBdAIBADAxMCQxIjAgBgNV" +
"BAMMGVJTQTIwNDhTaGEyNTZLZXlUcmFuc2ZlcjECCQDc5NcqfzyljjA4BgkqhkiG" +
"9w0BAQcwK6ANMAsGCWCGSAFlAwQCA6EaMBgGCSqGSIb3DQEBCDALBglghkgBZQME" +
"AgMEggEAc6QULhpkV7C63HhSbdYM7QFDTtRj8Wch3QHrFB0jIYlLGxcMuOB3Kw6f" +
"P1Q4W8qmVJgH+dyeKcpu2J6OrjlZVDtK166DrmKCflTMCGhCsPsmCMbKlpBihuXo" +
"7xQ13Fzs9QhudY/B/jUNjOTb3nONBqOdDJVLFsoMxm9cJqnDcdFPJVgIFl3IQW7X" +
"I1ZFdnS6FVKybR94jU4ASx8awQ+zDOgnCsyZ7t5cOwca2NgyQxZCf92WEJjdXqbl" +
"3ax/ULfSWD104Fp4N7lf8Z9BAkjIVJh3EeROzWgDkP5FQ9bDqkn3x+IlVKHfu+3r" +
"fmaUWI/sZCMXnUnLFEEILwCBcZlvBzA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEq" +
"BBDJhteA5Rpug15ksuJ9o/9vgBDQzvGRyFU8AKtfSpF6jBkB");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSA2048Sha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaepSha1_Default()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha1 --aes256 -keyopt rsa_oaep_md:sha1
byte[] encodedMessage = Convert.FromBase64String(
"MIIBJQYJKoZIhvcNAQcDoIIBFjCCARICAQAxgc4wgcsCAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwDQYJKoZI" +
"hvcNAQEHMAAEgYCLNNE4H03P0aP1lBDwKrm549DajTVSeyseWxv7TDDdVVWOTNgh" +
"c5OEVT2lmzxWD6lq28aZqmV8PPxJhvOZl4mnY9ycA5hgwmFRdKyI2hBTWQL8GQcF" +
"nYKc54BMKNaJsfIUIwN89knw7AEYEchGF+USKgQY1qsvdag6ZNBuhs5uwTA8Bgkq" +
"hkiG9w0BBwEwHQYJYIZIAWUDBAEqBBB/OyPGgn42q2XoDE4o8+2ggBDRXtH4O1xQ" +
"BHevgmD2Ev8V");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaep_MaskGenFunc_HashFunc_Mismatch()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep -keyopt rsa_mgf1_md:sha1 --aes256 -keyopt rsa_oaep_md:sha256
byte[] encodedMessage = Convert.FromBase64String(
"MIIBNAYJKoZIhvcNAQcDoIIBJTCCASECAQAxgd0wgdoCAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwHAYJKoZI" +
"hvcNAQEHMA+gDTALBglghkgBZQMEAgEEgYCw85yDulRtibSZm0xy1mOTIGjDu4yy" +
"pMT++3dV5Cy2GF4vp3mxp89Ylq2boYZ8b4B86IcJqUfyU/fG19O+vXyjn/0VUP3f" +
"OjMM71oqvQc/Qou/LvgDYQZY1koDldoeH89waZ1hgFaVpFEwGZUPSHmzgfsxMOpj" +
"RoToifiTsP3PkjA8BgkqhkiG9w0BBwEwHQYJYIZIAWUDBAEqBBCCufI08zVL4KVc" +
"WgKwZxCNgBA9M9KpJHmKwm5dMtvdcs/Q");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo));
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaOaep_PSpecified_NonDefault()
{
// Generated with:
// openssl cms -encrypt -in input.txt -out out.msg -recip cert.pem -keyopt rsa_padding_mode:oaep \
// -keyopt rsa_mgf1_md:sha1 --aes256 -keyopt rsa_oaep_md:sha1 -keyopt rsa_oaep_label:0102030405
byte[] encodedMessage = Convert.FromBase64String(
"MIIBOwYJKoZIhvcNAQcDoIIBLDCCASgCAQAxgeQwgeECAQAwNDAgMR4wHAYDVQQD" +
"ExVSU0FTaGEyNTZLZXlUcmFuc2ZlcjECEHLGx3NJFkaMTWCCU9oBdnYwIwYJKoZI" +
"hvcNAQEHMBaiFDASBgkqhkiG9w0BAQkEBQECAwQFBIGAoJ7P69rwtexRcLbK+K8z" +
"UrKROLk2tVU8xGA056j8o2GfqQPxGsHl1w8Q3lsnSPsjGHY30+KYmQMQrZJd5zIW" +
"2OpgriYeqnHUwNCd9CrRFVvEqqACZlzTw/L+DgeDXwSNPRzNghjIqWo79FFT9kRI" +
"DHUB10A+sIZevVYtFrWxbVQwPAYJKoZIhvcNAQcBMB0GCWCGSAFlAwQBKgQQfxMe" +
"56xuPm9lTJYYozmQ6oAQd1RIE2hhgx1kdJmIW1Z4/w==");
byte[] content = "68690D0A".HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Data), content);
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(encodedMessage, Certificates.RSASha256KeyTransfer1, expectedContentInfo));
}
[Fact]
public void DecryptEnvelopedOctetStringWithDefiniteLength()
{
// enveloped content consists of 5 bytes: <id: 1 byte><length: 1 byte><content: 3 bytes>
// <id>:
// 04 - Octet string
// 30 - Sequence
// <length>: 03 => length is 3 (encoded with definite length)
// <content>: 010203
// Note: we expect invalid ASN.1 sequence
byte[] content = "0403010203".HexToByteArray();
byte[] expectedContent = "3003010203".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedOctetStringWithInefficientlyEncodedLength()
{
// enveloped content consists of 5 or 6 bytes: <id: 1 byte><length: 1 or 2 bytes><content: 3 bytes>
// <id>:
// 04 - Octet string
// 30 - Sequence
// <length>: 03 => length is 3 (encoded with definite length)
// 81 03 => length is 3 (encoded with inefficiently encoded length)
// <content>: 010203
// Note: we expect invalid ASN.1 sequence
byte[] content = "048103010203".HexToByteArray();
byte[] expectedContent = "3003010203".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx does not allow it")]
public void DecryptEnvelopedEmptyArray()
{
byte[] content = Array.Empty<byte>();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedEmptyOctetString()
{
byte[] content = "0400".HexToByteArray();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedOctetStringWithExtraData()
{
byte[] content = "04010203".HexToByteArray();
byte[] expectedContent = "300102".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedDataWithNonPkcs7Oid()
{
byte[] content = "3003010203".HexToByteArray();
string nonPkcs7Oid = "0.0";
ContentInfo contentInfo = new ContentInfo(new Oid(nonPkcs7Oid), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsIndefiniteLengthEncoding))]
public void DecryptEnvelopedEmptyOctetStringWithIndefiniteLength()
{
byte[] content = "30800000".HexToByteArray();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[ConditionalFact(nameof(SupportsIndefiniteLengthEncoding))]
public void DecryptEnvelopedOctetStringWithIndefiniteLength()
{
byte[] content = "308004000000".HexToByteArray();
byte[] expectedContent = "30020400".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
private void TestSimpleDecrypt_RoundTrip(CertLoader certLoader, ContentInfo contentInfo, string algorithmOidValue, SubjectIdentifierType type, ContentInfo expectedContentInfo = null)
{
// Deep-copy the contentInfo since the real ContentInfo doesn't do this. This defends against a bad implementation changing
// our "expectedContentInfo" to match what it produces.
expectedContentInfo = expectedContentInfo ?? new ContentInfo(new Oid(contentInfo.ContentType), (byte[])(contentInfo.Content.Clone()));
string certSubjectName;
byte[] encodedMessage;
byte[] originalCopy = (byte[])(contentInfo.Content.Clone());
using (X509Certificate2 certificate = certLoader.GetCertificate())
{
certSubjectName = certificate.Subject;
AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(algorithmOidValue));
EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg);
CmsRecipient cmsRecipient = new CmsRecipient(type, certificate);
ecms.Encrypt(cmsRecipient);
Assert.Equal(originalCopy.ByteArrayToHex(), ecms.ContentInfo.Content.ByteArrayToHex());
encodedMessage = ecms.Encode();
}
// We don't pass "certificate" down because it's expected that the certificate used for encrypting doesn't have a private key (part of the purpose of this test is
// to ensure that you don't need the recipient's private key to encrypt.) The decrypt phase will have to locate the matching cert with the private key.
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
internal void VerifySimpleDecrypt(byte[] encodedMessage, CertLoader certLoader, ContentInfo expectedContent)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = certLoader.TryGetCertificateWithPrivateKey())
{
if (cert == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
#if netcoreapp // API not present on netfx
if (_useExplicitPrivateKey)
{
using (X509Certificate2 pubCert = certLoader.GetCertificate())
{
RecipientInfo recipient = ecms.RecipientInfos.Cast<RecipientInfo>().Where((r) => r.RecipientIdentifier.MatchesCertificate(cert)).Single();
ecms.Decrypt(recipient, cert.PrivateKey);
}
}
else
#endif
{
X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
ecms.Decrypt(extraStore);
}
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal(expectedContent.ContentType.Value, contentInfo.ContentType.Value);
Assert.Equal(expectedContent.Content.ByteArrayToHex(), contentInfo.Content.ByteArrayToHex());
}
}
}
}
| |
// 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 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.AIPlatform.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedEndpointServiceClientTest
{
[xunit::FactAttribute]
public void GetEndpointRequestObject()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEndpointRequest request = new GetEndpointRequest
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint response = client.GetEndpoint(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEndpointRequestObjectAsync()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEndpointRequest request = new GetEndpointRequest
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Endpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint responseCallSettings = await client.GetEndpointAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Endpoint responseCancellationToken = await client.GetEndpointAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEndpoint()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEndpointRequest request = new GetEndpointRequest
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint response = client.GetEndpoint(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEndpointAsync()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEndpointRequest request = new GetEndpointRequest
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Endpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint responseCallSettings = await client.GetEndpointAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Endpoint responseCancellationToken = await client.GetEndpointAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetEndpointResourceNames()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEndpointRequest request = new GetEndpointRequest
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint response = client.GetEndpoint(request.EndpointName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetEndpointResourceNamesAsync()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetEndpointRequest request = new GetEndpointRequest
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Endpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint responseCallSettings = await client.GetEndpointAsync(request.EndpointName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Endpoint responseCancellationToken = await client.GetEndpointAsync(request.EndpointName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateEndpointRequestObject()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateEndpointRequest request = new UpdateEndpointRequest
{
Endpoint = new Endpoint(),
UpdateMask = new wkt::FieldMask(),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.UpdateEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint response = client.UpdateEndpoint(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateEndpointRequestObjectAsync()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateEndpointRequest request = new UpdateEndpointRequest
{
Endpoint = new Endpoint(),
UpdateMask = new wkt::FieldMask(),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.UpdateEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Endpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint responseCallSettings = await client.UpdateEndpointAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Endpoint responseCancellationToken = await client.UpdateEndpointAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateEndpoint()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateEndpointRequest request = new UpdateEndpointRequest
{
Endpoint = new Endpoint(),
UpdateMask = new wkt::FieldMask(),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.UpdateEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint response = client.UpdateEndpoint(request.Endpoint, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateEndpointAsync()
{
moq::Mock<EndpointService.EndpointServiceClient> mockGrpcClient = new moq::Mock<EndpointService.EndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateEndpointRequest request = new UpdateEndpointRequest
{
Endpoint = new Endpoint(),
UpdateMask = new wkt::FieldMask(),
};
Endpoint expectedResponse = new Endpoint
{
EndpointName = EndpointName.FromProjectLocationEndpoint("[PROJECT]", "[LOCATION]", "[ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedModels =
{
new DeployedModel(),
},
TrafficSplit =
{
{
"key8a0b6e3c",
1623286560
},
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
EncryptionSpec = new EncryptionSpec(),
NetworkAsNetworkName = NetworkName.FromProjectNetwork("[PROJECT]", "[NETWORK]"),
ModelDeploymentMonitoringJobAsModelDeploymentMonitoringJobName = ModelDeploymentMonitoringJobName.FromProjectLocationModelDeploymentMonitoringJob("[PROJECT]", "[LOCATION]", "[MODEL_DEPLOYMENT_MONITORING_JOB]"),
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.UpdateEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Endpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
EndpointServiceClient client = new EndpointServiceClientImpl(mockGrpcClient.Object, null);
Endpoint responseCallSettings = await client.UpdateEndpointAsync(request.Endpoint, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Endpoint responseCancellationToken = await client.UpdateEndpointAsync(request.Endpoint, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace TemperatureAndHumidityApi.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);
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
//#if HAVE_ASYNC
using System;
using System.Globalization;
using System.Threading;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
public partial class JsonTextReader
{
// It's not safe to perform the async methods here in a derived class as if the synchronous equivalent
// has been overriden then the asychronous method will no longer be doing the same operation
#if HAVE_ASYNC // Double-check this isn't included inappropriately.
private readonly bool _safeAsync;
#endif
/// <summary>
/// Asynchronously reads the next JSON token from the source.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns <c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsync(cancellationToken) : base.ReadAsync(cancellationToken);
}
internal Task<bool> DoReadAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValueAsync(cancellationToken);
case State.Object:
case State.ObjectStart:
return ParseObjectAsync(cancellationToken);
case State.PostValue:
return LoopReadAsync(cancellationToken);
case State.Finished:
return ReadFromFinishedAsync(cancellationToken);
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<bool> LoopReadAsync(CancellationToken cancellationToken)
{
while (_currentState == State.PostValue)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_currentState = State.Finished;
}
}
else
{
_charPos++;
}
break;
case '}':
_charPos++;
SetToken(JsonToken.EndObject);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case ',':
_charPos++;
// finished parsing
SetStateBasedOnCurrent();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
break;
}
}
return await DoReadAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<bool> ReadFromFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return false;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
}
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
SetToken(JsonToken.None);
return false;
}
private Task<int> ReadDataAsync(bool append, CancellationToken cancellationToken)
{
return ReadDataAsync(append, 0, cancellationToken);
}
private async Task<int> ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken)
{
if (_isEndOfFile)
{
return 0;
}
PrepareBufferForReadData(append, charsRequired);
int charsRead = await _reader.ReadAsync(_chars, _charsUsed, _chars.Length - _charsUsed - 1, cancellationToken).ConfigureAwait(false);
_charsUsed += charsRead;
if (charsRead == 0)
{
_isEndOfFile = true;
}
_chars[_charsUsed] = '\0';
return charsRead;
}
private async Task<bool> ParseValueAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 't':
await ParseTrueAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'f':
await ParseFalseAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'n':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
switch (_chars[_charPos + 1])
{
case 'u':
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
break;
case 'e':
await ParseConstructorAsync(cancellationToken).ConfigureAwait(false);
break;
default:
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
}
else
{
_charPos++;
throw CreateUnexpectedEndException();
}
return true;
case 'N':
await ParseNumberNaNAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 'I':
await ParseNumberPositiveInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
await ParseNumberNegativeInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case 'u':
await ParseUndefinedAsync(cancellationToken).ConfigureAwait(false);
return true;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
return true;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ',':
// don't increment position, the next call to read will handle comma
// this is done to handle multiple empty comma values
SetToken(JsonToken.Undefined);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
break;
}
if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
{
ParseNumber(ReadType.Read);
return true;
}
throw CreateUnexpectedCharacterException(currentChar);
}
}
}
private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken)
{
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
_stringBuffer.Position = 0;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
}
break;
case '\\':
_charPos = charPos;
if (!await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
// start of escape sequence
int escapeStartPos = charPos - 1;
char currentChar = _chars[charPos];
charPos++;
char writeChar;
switch (currentChar)
{
case 'b':
writeChar = '\b';
break;
case 't':
writeChar = '\t';
break;
case 'n':
writeChar = '\n';
break;
case 'f':
writeChar = '\f';
break;
case 'r':
writeChar = '\r';
break;
case '\\':
writeChar = '\\';
break;
case '"':
case '\'':
case '/':
writeChar = currentChar;
break;
case 'u':
_charPos = charPos;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// low surrogate with no preceding high surrogate; this char is replaced
writeChar = UnicodeReplacementChar;
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
bool anotherHighSurrogate;
// loop for handling situations where there are multiple consecutive high surrogates
do
{
anotherHighSurrogate = false;
// potential start of a surrogate pair
if (await EnsureCharsAsync(2, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
{
char highSurrogate = writeChar;
_charPos += 2;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// a valid surrogate pair!
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
// another high surrogate; replace current and start check over
highSurrogate = UnicodeReplacementChar;
anotherHighSurrogate = true;
}
else
{
// high surrogate not followed by low surrogate; original char is replaced
highSurrogate = UnicodeReplacementChar;
}
EnsureBufferNotEmpty();
WriteCharToBuffer(highSurrogate, lastWritePosition, escapeStartPos);
lastWritePosition = _charPos;
}
else
{
// there are not enough remaining chars for the low surrogate or is not follow by unicode sequence
// replace high surrogate and continue on as usual
writeChar = UnicodeReplacementChar;
}
} while (anotherHighSurrogate);
}
charPos = _charPos;
break;
default:
_charPos = charPos;
throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
}
EnsureBufferNotEmpty();
WriteCharToBuffer(writeChar, lastWritePosition, escapeStartPos);
lastWritePosition = charPos;
break;
case StringUtils.CarriageReturn:
_charPos = charPos - 1;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
charPos = _charPos;
break;
case StringUtils.LineFeed:
_charPos = charPos - 1;
ProcessLineFeed();
charPos = _charPos;
break;
case '"':
case '\'':
if (_chars[charPos - 1] == quote)
{
FinishReadStringIntoBuffer(charPos - 1, initialPosition, lastWritePosition);
return;
}
break;
}
}
}
private Task ProcessCarriageReturnAsync(bool append, CancellationToken cancellationToken)
{
_charPos++;
Task<bool> task = EnsureCharsAsync(1, append, cancellationToken);
if (task.Status == TaskStatus.RanToCompletion)
{
case TaskStatus.RanToCompletion:
SetNewLine(task.Result);
return AsyncUtils.CompletedTask;
case TaskStatus.Canceled:
case TaskStatus.Faulted:
return task;
}
return ProcessCarriageReturnAsync(task);
}
private async Task ProcessCarriageReturnAsync(Task<bool> task)
{
SetNewLine(await task.ConfigureAwait(false));
}
private async Task<char> ParseUnicodeAsync(CancellationToken cancellationToken)
{
return ConvertUnicode(await EnsureCharsAsync(4, true, cancellationToken).ConfigureAwait(false));
}
private Task<bool> EnsureCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
if (_charPos + relativePosition < _charsUsed)
{
return AsyncUtils.True;
}
if (_isEndOfFile)
{
return AsyncUtils.False;
}
return ReadCharsAsync(relativePosition, append, cancellationToken);
}
private async Task<bool> ReadCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
int charsRequired = _charPos + relativePosition - _charsUsed + 1;
// it is possible that the TextReader doesn't return all data at once
// repeat read until the required text is returned or the reader is out of content
do
{
int charsRead = await ReadDataAsync(append, charsRequired, cancellationToken).ConfigureAwait(false);
// no more content
if (charsRead == 0)
{
return false;
}
charsRequired -= charsRead;
} while (charsRequired > 0);
return true;
}
private async Task<bool> ParseObjectAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
SetToken(JsonToken.EndObject);
_charPos++;
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
return await ParsePropertyAsync(cancellationToken).ConfigureAwait(false);
}
break;
}
}
}
private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken)
{
// should have already parsed / character before reaching this method
_charPos++;
if (!await EnsureCharsAsync(1, false, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
bool singlelineComment;
if (_chars[_charPos] == '*')
{
singlelineComment = false;
}
else if (_chars[_charPos] == '/')
{
singlelineComment = true;
}
else
{
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
int initialPosition = _charPos;
while (true)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
if (!singlelineComment)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
EndComment(setToken, initialPosition, _charPos);
return;
}
}
else
{
_charPos++;
}
break;
case '*':
_charPos++;
if (!singlelineComment)
{
if (await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos] == '/')
{
EndComment(setToken, initialPosition, _charPos - 1);
_charPos++;
return;
}
}
}
break;
case StringUtils.CarriageReturn:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
ProcessLineFeed();
break;
default:
_charPos++;
break;
}
}
}
private async Task EatWhitespaceAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
_charPos++;
}
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
_charPos++;
}
else
{
return;
}
break;
}
}
}
private async Task ParseStringAsync(char quote, ReadType readType, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
_charPos++;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quote, cancellationToken).ConfigureAwait(false);
ParseReadString(quote, readType);
}
private async Task<bool> MatchValueAsync(string value, CancellationToken cancellationToken)
{
return MatchValue(await EnsureCharsAsync(value.Length - 1, true, cancellationToken).ConfigureAwait(false), value);
}
private async Task<bool> MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken)
{
// will match value and then move to the next character, checking that it is a separator character
if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false))
{
return false;
}
if (!await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
return true;
}
return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false))
{
SetToken(newToken, tokenValue);
}
else
{
throw JsonReaderException.Create(this, "Error parsing " + newToken.ToString().ToLowerInvariant() + " value.");
}
}
private Task ParseTrueAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.True, JsonToken.Boolean, true, cancellationToken);
}
private Task ParseFalseAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.False, JsonToken.Boolean, false, cancellationToken);
}
private Task ParseNullAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Null, JsonToken.Null, null, cancellationToken);
}
private async Task ParseConstructorAsync(CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
int initialPosition = _charPos;
int endPosition;
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
}
}
else
{
endPosition = _charPos;
_charPos++;
break;
}
}
else if (char.IsLetterOrDigit(currentChar))
{
_charPos++;
}
else if (currentChar == StringUtils.CarriageReturn)
{
endPosition = _charPos;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
}
else if (currentChar == StringUtils.LineFeed)
{
endPosition = _charPos;
ProcessLineFeed();
break;
}
else if (char.IsWhiteSpace(currentChar))
{
endPosition = _charPos;
_charPos++;
break;
}
else if (currentChar == '(')
{
endPosition = _charPos;
break;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
_stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
string constructorName = _stringReference.ToString();
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != '(')
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
ClearRecentString();
SetToken(JsonToken.StartConstructor, constructorName);
}
else
{
throw JsonReaderException.Create(this, "Unexpected content while parsing JSON.");
}
}
private async Task<object> ParseNumberNaNAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNaN(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NaN, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberPositiveInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberPositiveInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.PositiveInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberNegativeInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNegativeInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NegativeInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken)
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
await ReadNumberIntoBufferAsync(cancellationToken).ConfigureAwait(false);
ParseReadNumber(readType, firstChar, initialPosition);
}
private Task ParseUndefinedAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Undefined, JsonToken.Undefined, null, cancellationToken);
}
private async Task<bool> ParsePropertyAsync(CancellationToken cancellationToken)
{
char firstChar = _chars[_charPos];
char quoteChar;
if (firstChar == '"' || firstChar == '\'')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quoteChar, cancellationToken).ConfigureAwait(false);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '\0';
ShiftBufferIfNeeded();
await ParseUnquotedPropertyAsync(cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
string propertyName;
if (NameTable != null)
{
propertyName = NameTable.Get(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length)
// no match in name table
?? _stringReference.ToString();
}
else
{
propertyName = _stringReference.ToString();
}
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != ':')
{
throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
SetToken(JsonToken.PropertyName, propertyName);
_quoteChar = quoteChar;
ClearRecentString();
return true;
}
private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken)
{
int charPos = _charPos;
while (true)
{
char currentChar = _chars[charPos];
if (currentChar == '\0')
{
_charPos = charPos;
if (_charsUsed == charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
return;
}
}
else if (ReadNumberCharIntoBuffer(currentChar, charPos))
{
return;
}
else
{
charPos++;
}
}
}
private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken)
{
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
}
continue;
}
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
}
if (ReadUnquotedPropertyReportIfDone(currentChar, initialPosition))
{
return;
}
}
}
private async Task<bool> ReadNullCharAsync(CancellationToken cancellationToken)
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_isEndOfFile = true;
return true;
}
}
else
{
_charPos++;
}
return false;
}
private async Task HandleNullAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos + 1] == 'u')
{
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
return;
}
_charPos += 2;
throw CreateUnexpectedCharacterException(_chars[_charPos - 1]);
}
_charPos = _charsUsed;
throw CreateUnexpectedEndException();
}
private async Task ReadFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
}
SetToken(JsonToken.None);
}
private async Task<object> ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedStringValue(readType);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return ParseNumberNegativeInfinity(readType);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
await ParseNumberAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
return Value;
case 't':
case 'f':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
string expected = currentChar == 't' ? JsonConvert.True : JsonConvert.False;
if (!await MatchValueWithTrailingSeparatorAsync(expected, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.String, expected);
return expected;
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<object> ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedNumber(readType);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return await ParseNumberNegativeInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="bool"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="bool"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBooleanAsync(cancellationToken) : base.ReadAsBooleanAsync(cancellationToken);
}
internal async Task<bool?> DoReadAsBooleanAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return ReadBooleanString(_stringReference.ToString());
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
bool b;
#if HAVE_BIG_INTEGER
if (Value is BigInteger)
{
b = (BigInteger)Value != 0;
}
else
#endif
{
b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Boolean, b, false);
return b;
case 't':
case 'f':
bool isTrue = currentChar == 't';
if (!await MatchValueWithTrailingSeparatorAsync(isTrue ? JsonConvert.True : JsonConvert.False, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.Boolean, isTrue);
return isTrue;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="byte"/>[].
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<byte[]> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken);
}
internal async Task<byte[]> DoReadAsBytesAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
bool isWrapped = false;
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false);
byte[] data = (byte[])Value;
if (isWrapped)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (TokenType != JsonToken.EndObject)
{
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
SetToken(JsonToken.Bytes, data, false);
}
return data;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
await ReadIntoWrappedTypeObjectAsync(cancellationToken).ConfigureAwait(false);
isWrapped = true;
break;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return await ReadArrayIntoByteArrayAsync(cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task ReadIntoWrappedTypeObjectAsync(CancellationToken cancellationToken)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeAsync(cancellationToken) : base.ReadAsDateTimeAsync(cancellationToken);
}
internal async Task<DateTime?> DoReadAsDateTimeAsync(CancellationToken cancellationToken)
{
return (DateTime?)await ReadStringValueAsync(ReadType.ReadAsDateTime, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeOffsetAsync(cancellationToken) : base.ReadAsDateTimeOffsetAsync(cancellationToken);
}
internal async Task<DateTimeOffset?> DoReadAsDateTimeOffsetAsync(CancellationToken cancellationToken)
{
return (DateTimeOffset?)await ReadStringValueAsync(ReadType.ReadAsDateTimeOffset, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="decimal"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="decimal"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDecimalAsync(cancellationToken) : base.ReadAsDecimalAsync(cancellationToken);
}
internal async Task<decimal?> DoReadAsDecimalAsync(CancellationToken cancellationToken)
{
return (decimal?)await ReadNumberValueAsync(ReadType.ReadAsDecimal, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="double"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="double"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDoubleAsync(cancellationToken) : base.ReadAsDoubleAsync(cancellationToken);
}
internal async Task<double?> DoReadAsDoubleAsync(CancellationToken cancellationToken)
{
return (double?)await ReadNumberValueAsync(ReadType.ReadAsDouble, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="int"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="int"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsInt32Async(cancellationToken) : base.ReadAsInt32Async(cancellationToken);
}
internal async Task<int?> DoReadAsInt32Async(CancellationToken cancellationToken)
{
return (int?)await ReadNumberValueAsync(ReadType.ReadAsInt32, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="string"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<string> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken);
}
internal async Task<string> DoReadAsStringAsync(CancellationToken cancellationToken)
{
return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
}
}
}
//#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
namespace System.DirectoryServices.AccountManagement
{
internal class TrackedCollection<T> : ICollection<T>, ICollection, IEnumerable<T>, IEnumerable
{
//
// ICollection
//
void ICollection.CopyTo(Array array, int index)
{
// Parameter validation
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (array == null)
throw new ArgumentNullException("array");
if (array.Rank != 1)
throw new ArgumentException(SR.TrackedCollectionNotOneDimensional);
if (index >= array.GetLength(0))
throw new ArgumentException(SR.TrackedCollectionIndexNotInArray);
// Make sure the array has enough space, allowing for the "index" offset
if ((array.GetLength(0) - index) < this.combinedValues.Count)
throw new ArgumentException(SR.TrackedCollectionArrayTooSmall);
// Copy out the original and inserted values
foreach (ValueEl el in this.combinedValues)
{
array.SetValue(el.GetCurrentValue(), index);
checked { index++; }
}
}
int ICollection.Count
{
get
{
return Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
// The classes that wrap us should expose themselves as the sync root.
// Hence, this should never be called.
Debug.Fail("TrackedCollection.SyncRoot: shouldn't be here.");
return this;
}
}
//
// IEnumerable
//
IEnumerator IEnumerable.GetEnumerator()
{
Debug.Fail("TrackedCollection.IEnumerable.GetEnumerator(): should not be here");
return (IEnumerator)GetEnumerator();
}
//
// ICollection<T>
//
public void CopyTo(T[] array, int index)
{
((ICollection)this).CopyTo((Array)array, index);
}
public bool IsReadOnly
{
get
{
return false;
}
}
public int Count
{
get
{
// Note that any values removed by the application have already been removed
// from combinedValues, so we don't need to adjust for that here
return this.combinedValues.Count;
}
}
//
// IEnumerable<T>
//
public IEnumerator<T> GetEnumerator()
{
Debug.Fail("TrackedCollection.GetEnumerator(): should not be here");
return new TrackedCollectionEnumerator<T>("TrackedCollectionEnumerator", this, this.combinedValues);
}
//
//
//
public bool Contains(T value)
{
// Is it one of the inserted or original values?
foreach (ValueEl el in this.combinedValues)
{
if (el.GetCurrentValue().Equals(value))
return true;
}
return false;
}
public void Clear()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "TrackedCollection", "Clear");
MarkChange();
// Move all original values to the removed values list
foreach (ValueEl el in this.combinedValues)
{
if (!el.isInserted)
{
this.removedValues.Add(el.originalValue.Left);
}
}
// Remove all inserted values, and clean up the original values
// (which have been moved onto the removed value list)
this.combinedValues.Clear();
}
// Adds obj to the end of the list by inserting it into combinedValues.
public void Add(T o)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "TrackedCollection", "Add({0})", o.ToString());
MarkChange();
ValueEl el = new ValueEl();
el.isInserted = true;
el.insertedValue = o;
this.combinedValues.Add(el);
}
// If obj is an inserted value, removes it.
// Otherwise, if obj is in the right-side of a pair of an original value, removes that pair from combinedValues
// and adds the left-side of that pair to removedValues, to record the removal.
public bool Remove(T value)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "TrackedCollection", "Remove({0})", value.ToString());
MarkChange();
foreach (ValueEl el in this.combinedValues)
{
if (el.isInserted && el.insertedValue.Equals(value))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "TrackedCollection", "found value to remove on inserted");
this.combinedValues.Remove(el);
return true;
}
if (!el.isInserted && el.originalValue.Right.Equals(value))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "TrackedCollection", "found value to remove on original");
this.combinedValues.Remove(el);
this.removedValues.Add(el.originalValue.Left);
return true;
}
}
return false;
}
//
// Private implementation
//
internal class ValueEl
{
public bool isInserted;
//public T insertedValue = T.default;
public T insertedValue;
public Pair<T, T> originalValue = null;
public T GetCurrentValue()
{
if (this.isInserted)
return this.insertedValue;
else
return this.originalValue.Right; // Right == current value
}
}
// Contains both the values retrieved from the store object backing this property.
// If isInserted == true, it is an inserted value and is stored in insertedValue.
// If isInserted == false, it is an original value and is stored in originalValue.
// For each originalValue Pair, the left side contains a copy of the value as it was originally retrieved from the store,
// while the right side contains the current value (which differs from the left side iff the application
// modified the value).
internal List<ValueEl> combinedValues = new List<ValueEl>();
// Contains values removed by the application for which the removal has not yet been committed
// to the store.
internal List<T> removedValues = new List<T>();
// Used so our enumerator can detect changes to the collection and throw an exception
private DateTime _lastChange = DateTime.UtcNow;
internal DateTime LastChange
{
get { return _lastChange; }
}
internal void MarkChange()
{
_lastChange = DateTime.UtcNow;
}
//
// Shared Load/Store implementation
//
internal List<T> Inserted
{
get
{
List<T> insertedValues = new List<T>();
foreach (ValueEl el in this.combinedValues)
{
if (el.isInserted)
insertedValues.Add(el.insertedValue);
}
return insertedValues;
}
}
internal List<T> Removed
{
get
{
return this.removedValues;
}
}
internal List<Pair<T, T>> ChangedValues
{
get
{
List<Pair<T, T>> changedList = new List<Pair<T, T>>();
foreach (ValueEl el in this.combinedValues)
{
if (!el.isInserted)
{
if (!el.originalValue.Left.Equals(el.originalValue.Right))
{
// Don't need to worry about whether we need to copy the T,
// since we're not handing it out to the app and we'll internally treat it as read-only
changedList.Add(new Pair<T, T>(el.originalValue.Left, el.originalValue.Right));
}
}
}
return changedList;
}
}
internal bool Changed
{
get
{
// Do the cheap test first: have any values been removed?
if (this.removedValues.Count > 0)
return true;
// have to do the comparatively expensive test: have any values been inserted or changed?
foreach (ValueEl el in this.combinedValues)
{
// Inserted
if (el.isInserted)
return true;
// Changed
if (!el.originalValue.Left.Equals(el.originalValue.Right))
return true;
}
return false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Reflection.Tests
{
public class MemberInfoTests
{
[Fact]
public static void TestReflectedType()
{
Type t = typeof(Derived);
MemberInfo[] members = t.GetMembers();
foreach (MemberInfo member in members)
{
Assert.Equal(t, member.ReflectedType);
}
}
[Fact]
public static void TestPropertyReflectedType()
{
Type t = typeof(Base);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1));
Assert.Equal(t, p.ReflectedType);
Assert.NotNull(p.GetMethod);
Assert.NotNull(p.SetMethod);
}
[Fact]
public static void TestInheritedPropertiesHidePrivateAccessorMethods()
{
Type t = typeof(Derived);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1));
Assert.Equal(t, p.ReflectedType);
Assert.NotNull(p.GetMethod);
Assert.Null(p.SetMethod);
}
[Fact]
public static void TestGenericMethodsInheritTheReflectedTypeOfTheirTemplate()
{
Type t = typeof(Derived);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
MethodInfo mooInst = moo.MakeGenericMethod(typeof(int));
Assert.Equal(t, mooInst.ReflectedType);
}
[Fact]
public static void TestDeclaringMethodOfTypeParametersOfInheritedMethods()
{
Type t = typeof(Derived);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
Type theM = moo.GetGenericArguments()[0];
MethodBase moo1 = theM.DeclaringMethod;
Type reflectedTypeOfMoo1 = moo1.ReflectedType;
Assert.Equal(typeof(Base), reflectedTypeOfMoo1);
}
[Fact]
public static void TestDeclaringMethodOfTypeParametersOfInheritedMethods2()
{
Type t = typeof(GDerived<int>);
MethodInfo moo = t.GetMethod("Moo");
Assert.Equal(t, moo.ReflectedType);
Type theM = moo.GetGenericArguments()[0];
MethodBase moo1 = theM.DeclaringMethod;
Type reflectedTypeOfMoo1 = moo1.ReflectedType;
Assert.Equal(typeof(GBase<>), reflectedTypeOfMoo1);
}
[Fact]
public static void TestInheritedPropertyAccessors()
{
Type t = typeof(Derived);
PropertyInfo p = t.GetProperty(nameof(Base.MyProperty));
MethodInfo getter = p.GetMethod;
MethodInfo setter = p.SetMethod;
Assert.Equal(t, getter.ReflectedType);
Assert.Equal(t, setter.ReflectedType);
}
[Fact]
public static void TestInheritedEventAccessors()
{
Type t = typeof(Derived);
EventInfo e = t.GetEvent(nameof(Base.MyEvent));
MethodInfo adder = e.AddMethod;
MethodInfo remover = e.RemoveMethod;
Assert.Equal(t, adder.ReflectedType);
Assert.Equal(t, remover.ReflectedType);
}
[Fact]
public static void TestReflectedTypeIsPartOfIdentity()
{
Type b = typeof(Base);
Type d = typeof(Derived);
{
EventInfo e = b.GetEvent(nameof(Base.MyEvent));
EventInfo ei = d.GetEvent(nameof(Derived.MyEvent));
Assert.False(e.Equals(ei));
}
{
FieldInfo f = b.GetField(nameof(Base.MyField));
FieldInfo fi = d.GetField(nameof(Derived.MyField));
Assert.False(f.Equals(fi));
}
{
MethodInfo m = b.GetMethod(nameof(Base.Moo));
MethodInfo mi = d.GetMethod(nameof(Derived.Moo));
Assert.False(m.Equals(mi));
}
{
PropertyInfo p = b.GetProperty(nameof(Base.MyProperty));
PropertyInfo pi = d.GetProperty(nameof(Derived.MyProperty));
Assert.False(p.Equals(pi));
}
}
[Fact]
public static void TestFieldInfoReflectedTypeDoesNotSurviveRuntimeHandles()
{
Type t = typeof(Derived);
FieldInfo f = t.GetField(nameof(Base.MyField));
Assert.Equal(typeof(Derived), f.ReflectedType);
RuntimeFieldHandle h = f.FieldHandle;
FieldInfo f2 = FieldInfo.GetFieldFromHandle(h);
Assert.Equal(typeof(Base), f2.ReflectedType);
}
[Fact]
public static void TestMethodInfoReflectedTypeDoesNotSurviveRuntimeHandles()
{
Type t = typeof(Derived);
MethodInfo m = t.GetMethod(nameof(Base.Moo));
Assert.Equal(typeof(Derived), m.ReflectedType);
RuntimeMethodHandle h = m.MethodHandle;
MethodBase m2 = MethodBase.GetMethodFromHandle(h);
Assert.Equal(typeof(Base), m2.ReflectedType);
}
[Fact]
public void TestGetCustomAttributesData()
{
MemberInfo[] m = typeof(MemberInfoTests).GetMember("SampleClass");
Assert.Equal(1, m.Count());
foreach(CustomAttributeData cad in m[0].GetCustomAttributesData())
{
if (cad.AttributeType == typeof(ComVisibleAttribute))
{
ConstructorInfo c = cad.Constructor;
Assert.False(c.IsStatic);
Assert.Equal(typeof(ComVisibleAttribute), c.DeclaringType);
ParameterInfo[] p = c.GetParameters();
Assert.Equal(1, p.Length);
Assert.Equal(typeof(bool), p[0].ParameterType);
return;
}
}
Assert.True(false, "Expected to find ComVisibleAttribute");
}
public static IEnumerable<object[]> EqualityOperator_TestData()
{
yield return new object[] { typeof(SampleClass) };
yield return new object[] { new MemberInfoTests().GetType() };
yield return new object[] { typeof(int) };
yield return new object[] { typeof(Dictionary<,>) };
}
[Theory]
[MemberData(nameof(EqualityOperator_TestData))]
public void EqualityOperator_Equal_ReturnsTrue(Type type)
{
MemberInfo[] members1 = GetOrderedMembers(type);
MemberInfo[] members2 = GetOrderedMembers(type);
Assert.Equal(members1.Length, members2.Length);
for (int i = 0; i < members1.Length; i++)
{
Assert.True(members1[i] == members2[i]);
Assert.False(members1[i] != members2[i]);
}
}
private MemberInfo[] GetOrderedMembers(Type type) => GetMembers(type).OrderBy(member => member.Name).ToArray();
private MemberInfo[] GetMembers(Type type)
{
return type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
}
private class Base
{
public event Action MyEvent { add { } remove { } }
#pragma warning disable 0649
public int MyField;
#pragma warning restore 0649
public int MyProperty { get; set; }
public int MyProperty1 { get; private set; }
public int MyProperty2 { private get; set; }
public void Moo<M>() { }
}
private class Derived : Base
{
}
private class GBase<T>
{
public void Moo<M>() { }
}
private class GDerived<T> : GBase<T>
{
}
#pragma warning disable 0067, 0169
[ComVisible(false)]
public class SampleClass
{
public int PublicField;
private int PrivateField;
public SampleClass(bool y) { }
private SampleClass(int x) { }
public void PublicMethod() { }
private void PrivateMethod() { }
public int PublicProp { get; set; }
private int PrivateProp { get; set; }
public event EventHandler PublicEvent;
private event EventHandler PrivateEvent;
}
#pragma warning restore 0067, 0169
}
}
| |
/* ====================================================================
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.Drawing;
using System.IO;
using NPOI.OpenXml4Net.OPC;
using NPOI.OpenXmlFormats.Dml;
using NPOI.OpenXmlFormats.Dml.Spreadsheet;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.Util;
using System.Xml;
using NPOI.SS.Util;
namespace NPOI.XSSF.UserModel
{
/**
* Represents a picture shape in a SpreadsheetML Drawing.
*
* @author Yegor Kozlov
*/
public class XSSFPicture : XSSFShape, IPicture
{
private static POILogger logger = POILogFactory.GetLogger(typeof(XSSFPicture));
/**
* Column width measured as the number of characters of the maximum digit width of the
* numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin
* pAdding (two on each side), plus 1 pixel pAdding for the gridlines.
*
* This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial)
*/
//private static float DEFAULT_COLUMN_WIDTH = 9.140625f;
/**
* A default instance of CTShape used for creating new shapes.
*/
private static CT_Picture prototype = null;
/**
* This object specifies a picture object and all its properties
*/
private CT_Picture ctPicture;
/**
* Construct a new XSSFPicture object. This constructor is called from
* {@link XSSFDrawing#CreatePicture(XSSFClientAnchor, int)}
*
* @param Drawing the XSSFDrawing that owns this picture
*/
public XSSFPicture(XSSFDrawing drawing, CT_Picture ctPicture)
{
this.drawing = drawing;
this.ctPicture = ctPicture;
}
/**
* Returns a prototype that is used to construct new shapes
*
* @return a prototype that is used to construct new shapes
*/
public XSSFPicture(XSSFDrawing drawing, XmlNode ctPicture)
{
this.drawing = drawing;
this.ctPicture =CT_Picture.Parse(ctPicture, POIXMLDocumentPart.NamespaceManager);
}
internal static CT_Picture Prototype()
{
CT_Picture pic = new CT_Picture();
CT_PictureNonVisual nvpr = pic.AddNewNvPicPr();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_NonVisualDrawingProps nvProps = nvpr.AddNewCNvPr();
nvProps.id = (1);
nvProps.name = ("Picture 1");
nvProps.descr = ("Picture");
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_NonVisualPictureProperties nvPicProps = nvpr.AddNewCNvPicPr();
nvPicProps.AddNewPicLocks().noChangeAspect = true;
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_BlipFillProperties blip = pic.AddNewBlipFill();
blip.AddNewBlip().embed = "";
blip.AddNewStretch().AddNewFillRect();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_ShapeProperties sppr = pic.AddNewSpPr();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_Transform2D t2d = sppr.AddNewXfrm();
CT_PositiveSize2D ext = t2d.AddNewExt();
//should be original picture width and height expressed in EMUs
ext.cx = (0);
ext.cy = (0);
CT_Point2D off = t2d.AddNewOff();
off.x=(0);
off.y=(0);
CT_PresetGeometry2D prstGeom = sppr.AddNewPrstGeom();
prstGeom.prst = (ST_ShapeType.rect);
prstGeom.AddNewAvLst();
prototype = pic;
return prototype;
}
/**
* Link this shape with the picture data
*
* @param rel relationship referring the picture data
*/
internal void SetPictureReference(PackageRelationship rel)
{
ctPicture.blipFill.blip.embed = rel.Id;
}
/**
* Return the underlying CT_Picture bean that holds all properties for this picture
*
* @return the underlying CT_Picture bean
*/
internal CT_Picture GetCTPicture()
{
return ctPicture;
}
/**
* Reset the image to the original size.
*
* <p>
* Please note, that this method works correctly only for workbooks
* with the default font size (Calibri 11pt for .xlsx).
* If the default font is Changed the resized image can be streched vertically or horizontally.
* </p>
*/
public void Resize()
{
Resize(double.MaxValue);
}
/**
* Resize the image proportionally.
*
* @see #resize(double, double)
*/
public void Resize(double scale)
{
Resize(scale, scale);
}
/**
* Resize the image relatively to its current size.
* <p>
* Please note, that this method works correctly only for workbooks
* with the default font size (Calibri 11pt for .xlsx).
* If the default font is changed the resized image can be streched vertically or horizontally.
* </p>
* <p>
* <code>resize(1.0,1.0)</code> keeps the original size,<br/>
* <code>resize(0.5,0.5)</code> resize to 50% of the original,<br/>
* <code>resize(2.0,2.0)</code> resizes to 200% of the original.<br/>
* <code>resize({@link Double#MAX_VALUE},{@link Double#MAX_VALUE})</code> resizes to the dimension of the embedded image.
* </p>
*
* @param scaleX the amount by which the image width is multiplied relative to the original width,
* when set to {@link java.lang.Double#MAX_VALUE} the width of the embedded image is used
* @param scaleY the amount by which the image height is multiplied relative to the original height,
* when set to {@link java.lang.Double#MAX_VALUE} the height of the embedded image is used
*/
public void Resize(double scaleX, double scaleY)
{
IClientAnchor anchor = (XSSFClientAnchor)GetAnchor();
IClientAnchor pref = GetPreferredSize(scaleX, scaleY);
int row2 = anchor.Row1 + (pref.Row2 - pref.Row1);
int col2 = anchor.Col1 + (pref.Col2 - pref.Col1);
anchor.Col2=(col2);
//anchor.Dx1=(0);
anchor.Dx2=(pref.Dx2);
anchor.Row2=(row2);
//anchor.Dy1=(0);
anchor.Dy2=(pref.Dy2);
}
/**
* Calculate the preferred size for this picture.
*
* @return XSSFClientAnchor with the preferred size for this image
*/
public IClientAnchor GetPreferredSize()
{
return GetPreferredSize(1);
}
/**
* Calculate the preferred size for this picture.
*
* @param scale the amount by which image dimensions are multiplied relative to the original size.
* @return XSSFClientAnchor with the preferred size for this image
*/
public IClientAnchor GetPreferredSize(double scale)
{
return GetPreferredSize(scale, scale);
}
/**
* Calculate the preferred size for this picture.
*
* @param scaleX the amount by which image width is multiplied relative to the original width.
* @param scaleY the amount by which image height is multiplied relative to the original height.
* @return XSSFClientAnchor with the preferred size for this image
*/
public IClientAnchor GetPreferredSize(double scaleX, double scaleY)
{
Size dim = ImageUtils.SetPreferredSize(this, scaleX, scaleY);
CT_PositiveSize2D size2d = ctPicture.spPr.xfrm.ext;
size2d.cx = (dim.Width);
size2d.cy = (dim.Height);
return ClientAnchor;
}
/**
* Return the dimension of this image
*
* @param part the namespace part holding raw picture data
* @param type type of the picture: {@link Workbook#PICTURE_TYPE_JPEG},
* {@link Workbook#PICTURE_TYPE_PNG} or {@link Workbook#PICTURE_TYPE_DIB}
*
* @return image dimension in pixels
*/
protected static Size GetImageDimension(PackagePart part, PictureType type)
{
try
{
//return Image.FromStream(part.GetInputStream()).Size;
//java can only read png,jpeg,dib image
//C# read the image that format defined by PictureType , maybe.
return ImageUtils.GetImageDimension(part.GetInputStream());
}
catch (IOException e)
{
//return a "singulariry" if ImageIO failed to read the image
logger.Log(POILogger.WARN, e);
return new Size();
}
}
/**
* Return the dimension of the embedded image in pixel
*
* @return image dimension in pixels
*/
public Size GetImageDimension()
{
XSSFPictureData picData = PictureData as XSSFPictureData;
return GetImageDimension(picData.GetPackagePart(), picData.PictureType);
}
protected internal override NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_ShapeProperties GetShapeProperties()
{
return ctPicture.spPr;
}
#region IShape Members
public int CountOfAllChildren
{
get { throw new NotImplementedException(); }
}
public int FillColor
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public LineStyle LineStyle
{
get
{
throw new NotImplementedException();
}
set
{
base.LineStyle = value;
}
}
public int LineStyleColor
{
get { throw new NotImplementedException(); }
}
public int LineWidth
{
get
{
throw new NotImplementedException();
}
set
{
base.LineWidth = (value);
}
}
public void SetLineStyleColor(int lineStyleColor)
{
throw new NotImplementedException();
}
#endregion
public IPictureData PictureData
{
get
{
String blipId = ctPicture.blipFill.blip.embed;
return (XSSFPictureData)GetDrawing().GetRelationById(blipId);
}
}
/**
* @return the anchor that is used by this shape.
*/
public IClientAnchor ClientAnchor
{
get
{
XSSFAnchor a = GetAnchor() as XSSFAnchor;
return (a is XSSFClientAnchor) ? (XSSFClientAnchor)a : null;
}
}
/**
* @return the sheet which contains the picture shape
*/
public ISheet Sheet
{
get
{
return (XSSFSheet)this.GetDrawing().GetParent();
}
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using EasyNetQ;
using EasyNetQ.Topology;
using Microsoft.Extensions.DependencyInjection;
using NetFusion.Base.Serialization;
using NetFusion.Bootstrap.Plugins;
using NetFusion.Common.Extensions.Collections;
using NetFusion.Messaging.Internal;
using NetFusion.Messaging.Logging;
using NetFusion.Messaging.Plugin;
using NetFusion.RabbitMQ.Metadata;
using NetFusion.RabbitMQ.Subscriber;
using NetFusion.RabbitMQ.Subscriber.Internal;
namespace NetFusion.RabbitMQ.Plugin.Modules
{
/// <summary>
/// Plugin module responsible for determining message handler methods that should be
/// subscribed to queues. Any IMessageConsumer class method decorated with a derived
/// SubscriberQueue attribute is considered a handler that should be bound to a queue.
/// </summary>
public class SubscriberModule : PluginModule
{
// Dependent Modules:
protected IBusModule BusModule { get; set; }
protected IMessageDispatchModule MessagingModule { get; set; }
private IQueueResponseService _queueResponse;
private ISerializationManager _serializationManager;
private IMessageLogger _messageLogger;
// Message handlers subscribed to queues:
private MessageQueueSubscriber[] _subscribers = Array.Empty<MessageQueueSubscriber>();
public override void RegisterDefaultServices(IServiceCollection services)
{
services.AddSingleton<IQueueResponseService, QueueResponseService>();
}
// ------------------------- [Plugin Execution] --------------------------
protected override Task OnStartModuleAsync(IServiceProvider services)
{
// Dependent Services:
_queueResponse = services.GetRequiredService<IQueueResponseService>();
_serializationManager = services.GetRequiredService<ISerializationManager>();
_messageLogger = services.GetRequiredService<IMessageLogger>();
BusModule.Reconnection += async (sender, args) => await HandleReconnection(args);
_subscribers = GetQueueSubscribers(MessagingModule);
return SubscribeToQueues(BusModule, _subscribers);
}
protected override Task OnStopModuleAsync(IServiceProvider services)
{
_subscribers.ForEach(s => s.Consumer?.Dispose());
return base.OnStopModuleAsync(services);
}
// Delegates to the core message dispatch module to find all message dispatch
// handlers and filters the list to only those that should be bound to a queue.
private MessageQueueSubscriber[] GetQueueSubscribers(IMessageDispatchModule messageDispatch)
{
var hostId = BusModule.HostAppId;
return messageDispatch.AllMessageTypeDispatchers
.Values().Where(MessageQueueSubscriber.IsSubscriber)
.Select(d => new MessageQueueSubscriber(hostId, d))
.ToArray();
}
// For each message handler identified as being associated with an exchange/queue, create the
// exchange and queue then bind it to the in-process handler.
private async Task SubscribeToQueues(IBusModule busModule, IEnumerable<MessageQueueSubscriber> subscribers)
{
// Tracks the RPC queue that have been already bound. For a given named RPC queue, we only
// want to bind once since the command action namespace is used to determine the actual
// handler to be called (multiple commands are sent on a single queue).
HashSet<string> boundToRpcQueues = new HashSet<string>();
foreach (var subscriber in subscribers)
{
busModule.ApplyQueueSettings(subscriber.QueueMeta);
if (subscriber.QueueMeta.ExchangeMeta.IsRpcExchange
&& boundToRpcQueues.Contains(subscriber.QueueMeta.QueueName))
{
continue;
}
var bus = busModule.GetBus(subscriber.QueueMeta.ExchangeMeta.BusName);
IQueue queue = await QueueDeclareAsync(bus, subscriber.QueueMeta);
ConsumeMessageQueue(bus, queue, subscriber);
if (subscriber.QueueMeta.ExchangeMeta.IsRpcExchange)
{
boundToRpcQueues.Add(queue.Name);
}
}
}
protected virtual Task<IQueue> QueueDeclareAsync(IBus bus, QueueMeta queueMeta)
{
return bus.Advanced.QueueDeclare(queueMeta);
}
// Defines a callback function to be called when a message arrives on the queue.
protected virtual void ConsumeMessageQueue(IBus bus, IQueue queue, MessageQueueSubscriber subscriber)
{
QueueMeta definition = subscriber.QueueMeta;
subscriber.Consumer = bus.Advanced.Consume(queue,
(bytes, msgProps, receiveInfo) =>
{
// Create context containing the received message information and
// additional services required to process the message.
var consumerContext = CreateContext(subscriber, msgProps, receiveInfo, bytes);
// Delegate to the queue strategy, associated with the definition, and
// allow it to determine how the received message should be processed.
return definition.QueueStrategy.OnMessageReceivedAsync(consumerContext);
},
config =>
{
if (definition.PrefetchCount > 0)
{
config.WithPrefetchCount(definition.PrefetchCount);
}
if (definition.IsExclusive)
{
config.WithExclusive();
}
config.WithPriority(definition.Priority);
});
}
private ConsumeContext CreateContext(MessageQueueSubscriber subscriber,
MessageProperties messageProps,
MessageReceivedInfo messageReceivedInfo,
byte[] messageBytes)
{
return new (subscriber, messageProps, messageReceivedInfo, messageBytes)
{
LoggerFactory = Context.LoggerFactory,
GetRpcMessageHandler = GetRpcMessageHandler,
// Dependent Services:
BusModule = BusModule,
MessagingModule = MessagingModule,
QueueResponse = _queueResponse,
Serialization = _serializationManager,
MessageLogger = _messageLogger
};
}
// Called when a reconnection to the the broker is detected. The IBus will reestablish
// the connection when available. However, the reconnection could mean that the broker
// was restarted. In this case, any auto-delete queues will need to be recreated.
private async Task HandleReconnection(ReconnectionEventArgs eventArgs)
{
var busSubscribers = _subscribers
.Where(s => s.QueueMeta.ExchangeMeta.BusName == eventArgs.Connection.BusName)
.ToArray();
busSubscribers.ForEach(s => s.Consumer?.Dispose());
await SubscribeToQueues(BusModule, busSubscribers);
}
// Looks up the dispatch information that should be used to handle the RPC style message.
private MessageDispatchInfo GetRpcMessageHandler(string queueName, string actionNamespace)
{
if (queueName == null) throw new ArgumentNullException(nameof(queueName));
if (actionNamespace == null) throw new ArgumentNullException(nameof(actionNamespace));
var matchingDispatchers = _subscribers.Where(s =>
s.QueueMeta.QueueName == queueName &&
s.QueueMeta.ExchangeMeta.ActionNamespace == actionNamespace).ToArray();
if (matchingDispatchers.Length == 0)
{
throw new InvalidOperationException(
$"A RPC command message handler could not be found for Queue: {queueName} with " +
$"action namespace: {actionNamespace}");
}
if (matchingDispatchers.Length > 1)
{
throw new InvalidOperationException(
$"More than one RPC command message handler was found for Queue: {queueName} with " +
$"action namespace: {actionNamespace}");
}
return matchingDispatchers.First().DispatchInfo;
}
// ------------------------ [Public Logging] --------------------------
public override void Log(IDictionary<string, object> moduleLog)
{
moduleLog["SubscriberQueues"] = _subscribers.Select(s =>
{
var queueLog = new Dictionary<string, object>();
s.QueueMeta.LogProperties(queueLog);
queueLog["ConsumerType"] = s.DispatchInfo.ConsumerType.FullName;
queueLog["MessageType"] = s.DispatchInfo.MessageType.FullName;
queueLog["HandlerMethod"] = s.DispatchInfo.MessageHandlerMethod.Name;
return queueLog;
}).ToArray();
}
}
}
| |
// Copyright 2016 Robin Sue
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
namespace SerilogAnalyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SerilogAnalyzerAnalyzer : DiagnosticAnalyzer
{
public const string ExceptionDiagnosticId = "Serilog001";
private static readonly LocalizableString ExceptionTitle = new LocalizableResourceString(nameof(Resources.ExceptionAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString ExceptionMessageFormat = new LocalizableResourceString(nameof(Resources.ExceptionAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString ExceptionDescription = new LocalizableResourceString(nameof(Resources.ExceptionAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
private static DiagnosticDescriptor ExceptionRule = new DiagnosticDescriptor(ExceptionDiagnosticId, ExceptionTitle, ExceptionMessageFormat, "CodeQuality", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: ExceptionDescription);
public const string TemplateDiagnosticId = "Serilog002";
private static readonly LocalizableString TemplateTitle = new LocalizableResourceString(nameof(Resources.TemplateAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString TemplateMessageFormat = new LocalizableResourceString(nameof(Resources.TemplateAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString TemplateDescription = new LocalizableResourceString(nameof(Resources.TemplateAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
private static DiagnosticDescriptor TemplateRule = new DiagnosticDescriptor(TemplateDiagnosticId, TemplateTitle, TemplateMessageFormat, "CodeQuality", DiagnosticSeverity.Error, isEnabledByDefault: true, description: TemplateDescription);
public const string PropertyBindingDiagnosticId = "Serilog003";
private static readonly LocalizableString PropertyBindingTitle = new LocalizableResourceString(nameof(Resources.PropertyBindingAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString PropertyBindingMessageFormat = new LocalizableResourceString(nameof(Resources.PropertyBindingAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString PropertyBindingDescription = new LocalizableResourceString(nameof(Resources.PropertyBindingAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
private static DiagnosticDescriptor PropertyBindingRule = new DiagnosticDescriptor(PropertyBindingDiagnosticId, PropertyBindingTitle, PropertyBindingMessageFormat, "CodeQuality", DiagnosticSeverity.Error, isEnabledByDefault: true, description: PropertyBindingDescription);
public const string ConstantMessageTemplateDiagnosticId = "Serilog004";
private static readonly LocalizableString ConstantMessageTemplateTitle = new LocalizableResourceString(nameof(Resources.ConstantMessageTemplateAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString ConstantMessageTemplateMessageFormat = new LocalizableResourceString(nameof(Resources.ConstantMessageTemplateAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString ConstantMessageTemplateDescription = new LocalizableResourceString(nameof(Resources.ConstantMessageTemplateAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
private static DiagnosticDescriptor ConstantMessageTemplateRule = new DiagnosticDescriptor(ConstantMessageTemplateDiagnosticId, ConstantMessageTemplateTitle, ConstantMessageTemplateMessageFormat, "CodeQuality", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: ConstantMessageTemplateDescription);
public const string UniquePropertyNameDiagnosticId = "Serilog005";
private static readonly LocalizableString UniquePropertyNameTitle = new LocalizableResourceString(nameof(Resources.UniquePropertyNameAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString UniquePropertyNameMessageFormat = new LocalizableResourceString(nameof(Resources.UniquePropertyNameAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString UniquePropertyNameDescription = new LocalizableResourceString(nameof(Resources.UniquePropertyNameAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
private static DiagnosticDescriptor UniquePropertyNameRule = new DiagnosticDescriptor(UniquePropertyNameDiagnosticId, UniquePropertyNameTitle, UniquePropertyNameMessageFormat, "CodeQuality", DiagnosticSeverity.Error, isEnabledByDefault: true, description: UniquePropertyNameDescription);
public const string PascalPropertyNameDiagnosticId = "Serilog006";
private static readonly LocalizableString PascalPropertyNameTitle = new LocalizableResourceString(nameof(Resources.PascalPropertyNameAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString PascalPropertyNameMessageFormat = new LocalizableResourceString(nameof(Resources.PascalPropertyNameAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString PascalPropertyNameDescription = new LocalizableResourceString(nameof(Resources.PascalPropertyNameAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
private static DiagnosticDescriptor PascalPropertyNameRule = new DiagnosticDescriptor(PascalPropertyNameDiagnosticId, PascalPropertyNameTitle, PascalPropertyNameMessageFormat, "CodeQuality", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: PascalPropertyNameDescription);
public const string DestructureAnonymousObjectsDiagnosticId = "Serilog007";
private static readonly LocalizableString DestructureAnonymousObjectsTitle = new LocalizableResourceString(nameof(Resources.DestructureAnonymousObjectsAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString DestructureAnonymousObjectsMessageFormat = new LocalizableResourceString(nameof(Resources.DestructureAnonymousObjectsAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString DestructureAnonymousObjectsDescription = new LocalizableResourceString(nameof(Resources.DestructureAnonymousObjectsAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
private static DiagnosticDescriptor DestructureAnonymousObjectsRule = new DiagnosticDescriptor(DestructureAnonymousObjectsDiagnosticId, DestructureAnonymousObjectsTitle, DestructureAnonymousObjectsMessageFormat, "CodeQuality", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: DestructureAnonymousObjectsDescription);
public const string UseCorrectContextualLoggerDiagnosticId = "Serilog008";
private static readonly LocalizableString UseCorrectContextualLoggerTitle = new LocalizableResourceString(nameof(Resources.UseCorrectContextualLoggerAnalyzerTitle), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString UseCorrectContextualLoggerMessageFormat = new LocalizableResourceString(nameof(Resources.UseCorrectContextualLoggerAnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
private static readonly LocalizableString UseCorrectContextualLoggerDescription = new LocalizableResourceString(nameof(Resources.UseCorrectContextualLoggerAnalyzerDescription), Resources.ResourceManager, typeof(Resources));
private static DiagnosticDescriptor UseCorrectContextualLoggerRule = new DiagnosticDescriptor(UseCorrectContextualLoggerDiagnosticId, UseCorrectContextualLoggerTitle, UseCorrectContextualLoggerMessageFormat, "CodeQuality", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: UseCorrectContextualLoggerDescription);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ExceptionRule, TemplateRule, PropertyBindingRule, ConstantMessageTemplateRule, UniquePropertyNameRule, PascalPropertyNameRule, DestructureAnonymousObjectsRule, UseCorrectContextualLoggerRule);
private const string ILogger = "Serilog.ILogger";
private const string ForContext = "ForContext";
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeSymbol, SyntaxKind.InvocationExpression);
}
private static void AnalyzeSymbol(SyntaxNodeAnalysisContext context)
{
var invocation = context.Node as InvocationExpressionSyntax;
var info = context.SemanticModel.GetSymbolInfo(invocation, context.CancellationToken);
var method = info.Symbol as IMethodSymbol;
if (method == null)
{
return;
}
// is serilog even present in the compilation?
var messageTemplateAttribute = context.SemanticModel.Compilation.GetTypeByMetadataName("Serilog.Core.MessageTemplateFormatMethodAttribute");
if (messageTemplateAttribute == null)
{
return;
}
// check if ForContext<T> / ForContext(typeof(T)) calls use the containing type as T
if (method.Name == ForContext && method.ReturnType.ToString() == ILogger)
{
CheckForContextCorrectness(ref context, invocation, method);
}
// is it a serilog logging method?
var attributes = method.GetAttributes();
var attributeData = attributes.FirstOrDefault(x => x.AttributeClass == messageTemplateAttribute);
if (attributeData == null)
{
return;
}
string messageTemplateName = attributeData.ConstructorArguments.First().Value as string;
// check for errors in the MessageTemplate
var arguments = default(List<SourceArgument>);
var properties = new List<PropertyToken>();
var hasErrors = false;
var literalSpan = default(TextSpan);
var exactPositions = true;
var stringText = default(string);
var invocationArguments = invocation.ArgumentList.Arguments;
foreach (var argument in invocationArguments)
{
var parameter = RoslynHelper.DetermineParameter(argument, context.SemanticModel, true, context.CancellationToken);
if (parameter.Name == messageTemplateName)
{
string messageTemplate;
// is it a simple string literal?
if (argument.Expression is LiteralExpressionSyntax literal)
{
stringText = literal.Token.Text;
exactPositions = true;
messageTemplate = literal.Token.ValueText;
}
else
{
// can we at least get a computed constant value for it?
var constantValue = context.SemanticModel.GetConstantValue(argument.Expression, context.CancellationToken);
if (!constantValue.HasValue || !(constantValue.Value is string constString))
{
INamedTypeSymbol StringType() => context.SemanticModel.Compilation.GetTypeByMetadataName("System.String");
if (context.SemanticModel.GetSymbolInfo(argument.Expression, context.CancellationToken).Symbol is IFieldSymbol field && field.Name == "Empty" && field.Type == StringType())
{
constString = "";
}
else
{
context.ReportDiagnostic(Diagnostic.Create(ConstantMessageTemplateRule, argument.Expression.GetLocation(), argument.Expression.ToString()));
continue;
}
}
// we can't map positions back from the computed string into the real positions
exactPositions = false;
messageTemplate = constString;
}
literalSpan = argument.Expression.GetLocation().SourceSpan;
var messageTemplateDiagnostics = AnalyzingMessageTemplateParser.Analyze(messageTemplate);
foreach (var templateDiagnostic in messageTemplateDiagnostics)
{
if (templateDiagnostic is PropertyToken property)
{
properties.Add(property);
continue;
}
if (templateDiagnostic is MessageTemplateDiagnostic diagnostic)
{
hasErrors = true;
ReportDiagnostic(ref context, ref literalSpan, stringText, exactPositions, TemplateRule, diagnostic);
}
}
var messageTemplateArgumentIndex = invocationArguments.IndexOf(argument);
arguments = invocationArguments.Skip(messageTemplateArgumentIndex + 1).Select(x =>
{
var location = x.GetLocation().SourceSpan;
return new SourceArgument { Argument = x, StartIndex = location.Start, Length = location.Length };
}).ToList();
break;
}
}
// do properties match up?
if (!hasErrors && literalSpan != default(TextSpan) && (arguments.Count > 0 || properties.Count > 0))
{
var diagnostics = PropertyBindingAnalyzer.AnalyzeProperties(properties, arguments);
foreach (var diagnostic in diagnostics)
{
ReportDiagnostic(ref context, ref literalSpan, stringText, exactPositions, PropertyBindingRule, diagnostic);
}
// check that all anonymous objects have destructuring hints in the message template
if (arguments.Count == properties.Count)
{
for (int i = 0; i < arguments.Count; i++)
{
var argument = arguments[i];
var argumentInfo = context.SemanticModel.GetTypeInfo(argument.Argument.Expression, context.CancellationToken);
if (argumentInfo.Type?.IsAnonymousType ?? false)
{
var property = properties[i];
if (!property.RawText.StartsWith("{@", StringComparison.Ordinal))
{
ReportDiagnostic(ref context, ref literalSpan, stringText, exactPositions, DestructureAnonymousObjectsRule, new MessageTemplateDiagnostic(property.StartIndex, property.Length, property.PropertyName));
}
}
}
}
// are there duplicate property names?
var usedNames = new HashSet<string>();
foreach (var property in properties)
{
if (!property.IsPositional && !usedNames.Add(property.PropertyName))
{
ReportDiagnostic(ref context, ref literalSpan, stringText, exactPositions, UniquePropertyNameRule, new MessageTemplateDiagnostic(property.StartIndex, property.Length, property.PropertyName));
}
var firstCharacter = property.PropertyName[0];
if (!Char.IsDigit(firstCharacter) && !Char.IsUpper(firstCharacter))
{
ReportDiagnostic(ref context, ref literalSpan, stringText, exactPositions, PascalPropertyNameRule, new MessageTemplateDiagnostic(property.StartIndex, property.Length, property.PropertyName));
}
}
}
// is this an overload where the exception argument is used?
var exception = context.SemanticModel.Compilation.GetTypeByMetadataName("System.Exception");
if (HasConventionalExceptionParameter(method))
{
return;
}
// is there an overload with the exception argument?
if (!method.ContainingType.GetMembers().OfType<IMethodSymbol>().Any(x => x.Name == method.Name && HasConventionalExceptionParameter(x)))
{
return;
}
// check wether any of the format arguments is an exception
foreach (var argument in invocationArguments)
{
var arginfo = context.SemanticModel.GetTypeInfo(argument.Expression);
if (IsException(exception, arginfo.Type))
{
context.ReportDiagnostic(Diagnostic.Create(ExceptionRule, argument.GetLocation(), argument.Expression.ToFullString()));
}
}
// Check if there is an Exception parameter at position 1 (position 2 for static extension method invocations)?
bool HasConventionalExceptionParameter(IMethodSymbol methodSymbol)
{
return methodSymbol.Parameters.FirstOrDefault()?.Type == exception ||
methodSymbol.IsExtensionMethod && methodSymbol.Parameters.Skip(1).FirstOrDefault()?.Type == exception;
}
}
private static void CheckForContextCorrectness(ref SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocation, IMethodSymbol method)
{
// is this really a field / property?
var decl = invocation.Ancestors().OfType<MemberDeclarationSyntax>().FirstOrDefault();
if (!(decl is PropertyDeclarationSyntax || decl is FieldDeclarationSyntax))
{
return;
}
ITypeSymbol contextType = null;
// extract T from ForContext<T>
if (method.IsGenericMethod && method.TypeArguments.Length == 1)
{
contextType = method.TypeArguments[0];
}
// or extract T from ForContext(typeof(T))
else if (method.Parameters.Length == 1 & method.Parameters[0].Type.ToString() == "System.Type")
{
if (invocation.ArgumentList.Arguments.FirstOrDefault().Expression is TypeOfExpressionSyntax type && context.SemanticModel.GetTypeInfo(type.Type).Type is ITypeSymbol tsymbol)
{
contextType = tsymbol;
}
}
// if there's no T...
if (contextType == null)
{
return;
}
// find the type this field / property is contained in
var declaringTypeSyntax = invocation.Ancestors().OfType<TypeDeclarationSyntax>().FirstOrDefault();
if (declaringTypeSyntax != null && context.SemanticModel.GetDeclaredSymbol(declaringTypeSyntax) is INamedTypeSymbol declaringType && !declaringType.Equals(contextType))
{
// if there are multiple field / properties of ILogger, we can't be certain, so do nothing
if (declaringType.GetMembers().Count(x => (x as IPropertySymbol)?.Type.ToString() == ILogger || (x as IFieldSymbol)?.Type.ToString() == ILogger) > 1)
{
return;
}
// get the location of T to report on
Location location;
if (method.IsGenericMethod && invocation.Expression is MemberAccessExpressionSyntax member && member.Name is GenericNameSyntax generic)
{
location = generic.TypeArgumentList.Arguments.First().GetLocation();
}
else
{
location = (invocation.ArgumentList.Arguments.First().Expression as TypeOfExpressionSyntax).Type.GetLocation();
}
// get the name of the logger variable
string loggerName = null;
var declaringMember = invocation.Ancestors().OfType<MemberDeclarationSyntax>().FirstOrDefault();
if (declaringMember is PropertyDeclarationSyntax property)
{
loggerName = property.Identifier.ToString();
}
else if (declaringMember is FieldDeclarationSyntax field && field.Declaration.Variables.FirstOrDefault() is VariableDeclaratorSyntax fieldVariable)
{
loggerName = fieldVariable.Identifier.ToString();
}
string correctMethod = method.IsGenericMethod ? $"ForContext<{declaringType}>()" : $"ForContext(typeof({declaringType}))";
string incorrectMethod = method.IsGenericMethod ? $"ForContext<{contextType}>()" : $"ForContext(typeof({contextType}))";
context.ReportDiagnostic(Diagnostic.Create(UseCorrectContextualLoggerRule, location, loggerName, correctMethod, incorrectMethod));
}
}
private static void ReportDiagnostic(ref SyntaxNodeAnalysisContext context, ref TextSpan literalSpan, string stringText, bool exactPositions, DiagnosticDescriptor rule, MessageTemplateDiagnostic diagnostic)
{
TextSpan textSpan;
if (diagnostic.MustBeRemapped)
{
if (!exactPositions)
{
textSpan = literalSpan;
}
else
{
int remappedStart = GetPositionInLiteral(stringText, diagnostic.StartIndex);
int remappedEnd = GetPositionInLiteral(stringText, diagnostic.StartIndex + diagnostic.Length);
textSpan = new TextSpan(literalSpan.Start + remappedStart, remappedEnd - remappedStart);
}
}
else
{
textSpan = new TextSpan(diagnostic.StartIndex, diagnostic.Length);
}
var sourceLocation = Location.Create(context.Node.SyntaxTree, textSpan);
context.ReportDiagnostic(Diagnostic.Create(rule, sourceLocation, diagnostic.Diagnostic));
}
/// <summary>
/// Remaps a string position into the position in a string literal
/// </summary>
/// <param name="literal">The literal string as string</param>
/// <param name="unescapedPosition">The position in the non literal string</param>
/// <returns></returns>
public static int GetPositionInLiteral(string literal, int unescapedPosition)
{
if (literal[0] == '@')
{
for (int i = 2; i < literal.Length; i++)
{
char c = literal[i];
if (c == '"' && i + 1 < literal.Length && literal[i + 1] == '"')
{
i++;
}
unescapedPosition--;
if (unescapedPosition == -1)
{
return i;
}
}
}
else
{
for (int i = 1; i < literal.Length; i++)
{
char c = literal[i];
if (c == '\\' && i + 1 < literal.Length)
{
c = literal[++i];
if (c == 'x' || c == 'u' || c == 'U')
{
int max = Math.Min((c == 'U' ? 8 : 4) + i + 1, literal.Length);
for (i++; i < max; i++)
{
c = literal[i];
if (!IsHexDigit(c))
{
break;
}
}
i--;
}
}
unescapedPosition--;
if (unescapedPosition == -1)
{
return i;
}
}
}
return unescapedPosition;
}
/// <summary>
/// Returns true if the Unicode character is a hexadecimal digit.
/// </summary>
/// <param name="c">The Unicode character.</param>
/// <returns>true if the character is a hexadecimal digit 0-9, A-F, a-f.</returns>
internal static bool IsHexDigit(char c)
{
return (c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'F') ||
(c >= 'a' && c <= 'f');
}
private static bool IsException(ITypeSymbol exceptionSymbol, ITypeSymbol type)
{
for (ITypeSymbol symbol = type; symbol != null; symbol = symbol.BaseType)
{
if (symbol == exceptionSymbol)
{
return true;
}
}
return false;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
namespace Xamarin.Forms
{
[DebuggerDisplay("R={R}, G={G}, B={B}, A={A}, Hue={Hue}, Saturation={Saturation}, Luminosity={Luminosity}")]
[TypeConverter(typeof(ColorTypeConverter))]
public struct Color
{
readonly Mode _mode;
enum Mode
{
Default,
Rgb,
Hsl
}
public static Color Default
{
get { return new Color(-1d, -1d, -1d, -1d, Mode.Default); }
}
internal bool IsDefault
{
get { return _mode == Mode.Default; }
}
public static Color Accent { get; internal set; }
readonly float _a;
public double A
{
get { return _a; }
}
readonly float _r;
public double R
{
get { return _r; }
}
readonly float _g;
public double G
{
get { return _g; }
}
readonly float _b;
public double B
{
get { return _b; }
}
readonly float _hue;
public double Hue
{
get { return _hue; }
}
readonly float _saturation;
public double Saturation
{
get { return _saturation; }
}
readonly float _luminosity;
public double Luminosity
{
get { return _luminosity; }
}
public Color(double r, double g, double b, double a) : this(r, g, b, a, Mode.Rgb)
{
}
Color(double w, double x, double y, double z, Mode mode)
{
_mode = mode;
switch (mode)
{
default:
case Mode.Default:
_r = _g = _b = _a = -1;
_hue = _saturation = _luminosity = -1;
break;
case Mode.Rgb:
_r = (float)w.Clamp(0, 1);
_g = (float)x.Clamp(0, 1);
_b = (float)y.Clamp(0, 1);
_a = (float)z.Clamp(0, 1);
ConvertToHsl(_r, _g, _b, mode, out _hue, out _saturation, out _luminosity);
break;
case Mode.Hsl:
_hue = (float)w.Clamp(0, 1);
_saturation = (float)x.Clamp(0, 1);
_luminosity = (float)y.Clamp(0, 1);
_a = (float)z.Clamp(0, 1);
ConvertToRgb(_hue, _saturation, _luminosity, mode, out _r, out _g, out _b);
break;
}
}
public Color(double r, double g, double b) : this(r, g, b, 1)
{
}
public Color(double value) : this(value, value, value, 1)
{
}
public Color MultiplyAlpha(double alpha)
{
switch (_mode)
{
default:
case Mode.Default:
throw new InvalidOperationException("Invalid on Color.Default");
case Mode.Rgb:
return new Color(_r, _g, _b, _a * alpha, Mode.Rgb);
case Mode.Hsl:
return new Color(_hue, _saturation, _luminosity, _a * alpha, Mode.Hsl);
}
}
public Color AddLuminosity(double delta)
{
if (_mode == Mode.Default)
throw new InvalidOperationException("Invalid on Color.Default");
return new Color(_hue, _saturation, _luminosity + delta, _a, Mode.Hsl);
}
public Color WithHue(double hue)
{
if (_mode == Mode.Default)
throw new InvalidOperationException("Invalid on Color.Default");
return new Color(hue, _saturation, _luminosity, _a, Mode.Hsl);
}
public Color WithSaturation(double saturation)
{
if (_mode == Mode.Default)
throw new InvalidOperationException("Invalid on Color.Default");
return new Color(_hue, saturation, _luminosity, _a, Mode.Hsl);
}
public Color WithLuminosity(double luminosity)
{
if (_mode == Mode.Default)
throw new InvalidOperationException("Invalid on Color.Default");
return new Color(_hue, _saturation, luminosity, _a, Mode.Hsl);
}
static void ConvertToRgb(float hue, float saturation, float luminosity, Mode mode, out float r, out float g, out float b)
{
if (mode != Mode.Hsl)
throw new InvalidOperationException();
if (luminosity == 0)
{
r = g = b = 0;
return;
}
if (saturation == 0)
{
r = g = b = luminosity;
return;
}
float temp2 = luminosity <= 0.5f ? luminosity * (1.0f + saturation) : luminosity + saturation - luminosity * saturation;
float temp1 = 2.0f * luminosity - temp2;
var t3 = new[] { hue + 1.0f / 3.0f, hue, hue - 1.0f / 3.0f };
var clr = new float[] { 0, 0, 0 };
for (var i = 0; i < 3; i++)
{
if (t3[i] < 0)
t3[i] += 1.0f;
if (t3[i] > 1)
t3[i] -= 1.0f;
if (6.0 * t3[i] < 1.0)
clr[i] = temp1 + (temp2 - temp1) * t3[i] * 6.0f;
else if (2.0 * t3[i] < 1.0)
clr[i] = temp2;
else if (3.0 * t3[i] < 2.0)
clr[i] = temp1 + (temp2 - temp1) * (2.0f / 3.0f - t3[i]) * 6.0f;
else
clr[i] = temp1;
}
r = clr[0];
g = clr[1];
b = clr[2];
}
static void ConvertToHsl(float r, float g, float b, Mode mode, out float h, out float s, out float l)
{
float v = Math.Max(r, g);
v = Math.Max(v, b);
float m = Math.Min(r, g);
m = Math.Min(m, b);
l = (m + v) / 2.0f;
if (l <= 0.0)
{
h = s = l = 0;
return;
}
float vm = v - m;
s = vm;
if (s > 0.0)
{
s /= l <= 0.5f ? v + m : 2.0f - v - m;
}
else
{
h = 0;
s = 0;
return;
}
float r2 = (v - r) / vm;
float g2 = (v - g) / vm;
float b2 = (v - b) / vm;
if (r == v)
{
h = g == m ? 5.0f + b2 : 1.0f - g2;
}
else if (g == v)
{
h = b == m ? 1.0f + r2 : 3.0f - b2;
}
else
{
h = r == m ? 3.0f + g2 : 5.0f - r2;
}
h /= 6.0f;
}
public static bool operator ==(Color color1, Color color2)
{
return EqualsInner(color1, color2);
}
public static bool operator !=(Color color1, Color color2)
{
return !EqualsInner(color1, color2);
}
public override int GetHashCode()
{
unchecked
{
int hashcode = _r.GetHashCode();
hashcode = (hashcode * 397) ^ _g.GetHashCode();
hashcode = (hashcode * 397) ^ _b.GetHashCode();
hashcode = (hashcode * 397) ^ _a.GetHashCode();
return hashcode;
}
}
public override bool Equals(object obj)
{
if (obj is Color)
{
return EqualsInner(this, (Color)obj);
}
return base.Equals(obj);
}
static bool EqualsInner(Color color1, Color color2)
{
if (color1._mode == Mode.Default && color2._mode == Mode.Default)
return true;
if (color1._mode == Mode.Default || color2._mode == Mode.Default)
return false;
if (color1._mode == Mode.Hsl && color2._mode == Mode.Hsl)
return color1._hue == color2._hue && color1._saturation == color2._saturation && color1._luminosity == color2._luminosity && color1._a == color2._a;
return color1._r == color2._r && color1._g == color2._g && color1._b == color2._b && color1._a == color2._a;
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[Color: A={0}, R={1}, G={2}, B={3}, Hue={4}, Saturation={5}, Luminosity={6}]", A, R, G, B, Hue, Saturation, Luminosity);
}
public static Color FromHex(string hex)
{
hex = hex.Replace("#", "");
switch (hex.Length)
{
case 3: //#rgb => ffrrggbb
hex = string.Format("ff{0}{1}{2}{3}{4}{5}", hex[0], hex[0], hex[1], hex[1], hex[2], hex[2]);
break;
case 4: //#argb => aarrggbb
hex = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}", hex[0], hex[0], hex[1], hex[1], hex[2], hex[2], hex[3], hex[3]);
break;
case 6: //#rrggbb => ffrrggbb
hex = string.Format("ff{0}", hex);
break;
}
return FromUint(Convert.ToUInt32(hex.Replace("#", ""), 16));
}
public static Color FromUint(uint argb)
{
return FromRgba((byte)((argb & 0x00ff0000) >> 0x10), (byte)((argb & 0x0000ff00) >> 0x8), (byte)(argb & 0x000000ff), (byte)((argb & 0xff000000) >> 0x18));
}
public static Color FromRgba(int r, int g, int b, int a)
{
double red = (double)r / 255;
double green = (double)g / 255;
double blue = (double)b / 255;
double alpha = (double)a / 255;
return new Color(red, green, blue, alpha, Mode.Rgb);
}
public static Color FromRgb(int r, int g, int b)
{
return FromRgba(r, g, b, 255);
}
public static Color FromRgba(double r, double g, double b, double a)
{
return new Color(r, g, b, a);
}
public static Color FromRgb(double r, double g, double b)
{
return new Color(r, g, b, 1d, Mode.Rgb);
}
public static Color FromHsla(double h, double s, double l, double a = 1d)
{
return new Color(h, s, l, a, Mode.Hsl);
}
#region Color Definitions
public static readonly Color Transparent = FromRgba(0, 0, 0, 0);
public static readonly Color Aqua = FromRgb(0, 255, 255);
public static readonly Color Black = FromRgb(0, 0, 0);
public static readonly Color Blue = FromRgb(0, 0, 255);
public static readonly Color Fuchsia = FromRgb(255, 0, 255);
[Obsolete("Fuschia is obsolete as of version 1.3, please use the correct spelling of Fuchsia")] public static readonly Color Fuschia = FromRgb(255, 0, 255);
public static readonly Color Gray = FromRgb(128, 128, 128);
public static readonly Color Green = FromRgb(0, 128, 0);
public static readonly Color Lime = FromRgb(0, 255, 0);
public static readonly Color Maroon = FromRgb(128, 0, 0);
public static readonly Color Navy = FromRgb(0, 0, 128);
public static readonly Color Olive = FromRgb(128, 128, 0);
public static readonly Color Purple = FromRgb(128, 0, 128);
public static readonly Color Pink = FromRgb(255, 102, 255);
public static readonly Color Red = FromRgb(255, 0, 0);
public static readonly Color Silver = FromRgb(192, 192, 192);
public static readonly Color Teal = FromRgb(0, 128, 128);
public static readonly Color White = FromRgb(255, 255, 255);
public static readonly Color Yellow = FromRgb(255, 255, 0);
#endregion
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class ClusterMembersQueryDecoder
{
public const ushort BLOCK_LENGTH = 12;
public const ushort TEMPLATE_ID = 34;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private ClusterMembersQueryDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public ClusterMembersQueryDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public ClusterMembersQueryDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int CorrelationIdId()
{
return 1;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 0;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int ExtendedId()
{
return 2;
}
public static int ExtendedSinceVersion()
{
return 5;
}
public static int ExtendedEncodingOffset()
{
return 8;
}
public static int ExtendedEncodingLength()
{
return 4;
}
public static string ExtendedMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "optional";
}
return "";
}
public BooleanType Extended()
{
if (_actingVersion < 5) return BooleanType.NULL_VALUE;
return (BooleanType)_buffer.GetInt(_offset + 8, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[ClusterMembersQuery](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='extended', referencedName='null', description='null', id=2, version=5, deprecated=0, encodedLength=0, offset=8, componentTokenCount=6, encoding=Encoding{presence=OPTIONAL, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=BEGIN_ENUM, name='BooleanType', referencedName='null', description='Language independent boolean type.', id=-1, version=5, deprecated=0, encodedLength=4, offset=8, componentTokenCount=4, encoding=Encoding{presence=REQUIRED, primitiveType=INT32, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='null', timeUnit=null, semanticType='null'}}
builder.Append("Extended=");
builder.Append(Extended());
Limit(originalLimit);
return builder;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using osu.Framework.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace osu.Framework.Testing
{
public class DynamicClassCompiler<T> : IDisposable
where T : IDynamicallyCompile
{
public Action CompilationStarted;
public Action<Type> CompilationFinished;
public Action<Exception> CompilationFailed;
private readonly List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
private string lastTouchedFile;
private T checkpointObject;
public void Checkpoint(T obj)
{
checkpointObject = obj;
}
private readonly List<string> requiredFiles = new List<string>();
private List<string> requiredTypeNames = new List<string>();
private HashSet<string> assemblies;
private readonly List<string> validDirectories = new List<string>();
public void Start()
{
var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
Task.Run(() =>
{
var basePath = getSolutionPath(di);
if (!Directory.Exists(basePath))
return;
foreach (var dir in Directory.GetDirectories(basePath))
{
// only watch directories which house a csproj. this avoids submodules and directories like .git which can contain many files.
if (!Directory.GetFiles(dir, "*.csproj").Any())
continue;
validDirectories.Add(dir);
var fsw = new FileSystemWatcher(dir, @"*.cs")
{
EnableRaisingEvents = true,
IncludeSubdirectories = true,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime,
};
fsw.Changed += onChange;
fsw.Created += onChange;
watchers.Add(fsw);
}
});
string getSolutionPath(DirectoryInfo d)
{
if (d == null)
return null;
return d.GetFiles().Any(f => f.Extension == ".sln") ? d.FullName : getSolutionPath(d.Parent);
}
}
private void onChange(object sender, FileSystemEventArgs e)
{
lock (compileLock)
{
if (checkpointObject == null || isCompiling)
return;
var checkpointName = checkpointObject.GetType().Name;
var reqTypes = checkpointObject.RequiredTypes.Select(t => t.Name).ToList();
// add ourselves as a required type.
reqTypes.Add(checkpointName);
// if we are a TestCase, add the class we are testing automatically.
reqTypes.Add(checkpointName.Replace("TestCase", ""));
if (!reqTypes.Contains(Path.GetFileNameWithoutExtension(e.Name)))
return;
if (!reqTypes.SequenceEqual(requiredTypeNames))
{
requiredTypeNames = reqTypes;
requiredFiles.Clear();
foreach (var d in validDirectories)
requiredFiles.AddRange(Directory
.EnumerateFiles(d, "*.cs", SearchOption.AllDirectories)
.Where(fw => requiredTypeNames.Contains(Path.GetFileNameWithoutExtension(fw))));
}
lastTouchedFile = e.FullPath;
isCompiling = true;
Task.Run(recompile)
.ContinueWith(_ => isCompiling = false);
}
}
private int currentVersion;
private bool isCompiling;
private readonly object compileLock = new object();
private void recompile()
{
if (assemblies == null)
{
assemblies = new HashSet<string>();
foreach (var ass in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic))
assemblies.Add(ass.Location);
}
assemblies.Add(typeof(JetBrains.Annotations.NotNullAttribute).Assembly.Location);
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
// ReSharper disable once RedundantExplicitArrayCreation this doesn't compile when the array is empty
var parseOptions = new CSharpParseOptions(preprocessorSymbols: new string[] {
#if DEBUG
"DEBUG",
#endif
#if TRACE
"TRACE",
#endif
#if RELEASE
"RELEASE",
#endif
}, languageVersion: LanguageVersion.CSharp7_3);
var references = assemblies.Select(a => MetadataReference.CreateFromFile(a));
while (!checkFileReady(lastTouchedFile))
Thread.Sleep(10);
Logger.Log($@"Recompiling {Path.GetFileName(checkpointObject.GetType().Name)}...", LoggingTarget.Runtime, LogLevel.Important);
CompilationStarted?.Invoke();
// ensure we don't duplicate the dynamic suffix.
string assemblyNamespace = checkpointObject.GetType().Assembly.GetName().Name.Replace(".Dynamic", "");
string assemblyVersion = $"{++currentVersion}.0.*";
string dynamicNamespace = $"{assemblyNamespace}.Dynamic";
var compilation = CSharpCompilation.Create(
dynamicNamespace,
requiredFiles.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), parseOptions, file))
// Compile the assembly with a new version so that it replaces the existing one
.Append(CSharpSyntaxTree.ParseText($"using System.Reflection; [assembly: AssemblyVersion(\"{assemblyVersion}\")]", parseOptions))
,
references,
options
);
using (var ms = new MemoryStream())
{
var compilationResult = compilation.Emit(ms);
if (compilationResult.Success)
{
ms.Seek(0, SeekOrigin.Begin);
CompilationFinished?.Invoke(
Assembly.Load(ms.ToArray()).GetModules()[0].GetTypes().LastOrDefault(t => t.FullName == checkpointObject.GetType().FullName)
);
}
else
{
foreach (var diagnostic in compilationResult.Diagnostics)
{
if (diagnostic.Severity < DiagnosticSeverity.Error)
continue;
CompilationFailed?.Invoke(new Exception(diagnostic.ToString()));
}
}
}
}
/// <summary>
/// Check whether a file has finished being written to.
/// </summary>
private static bool checkFileReady(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
return inputStream.Length > 0;
}
catch (Exception)
{
return false;
}
}
#region IDisposable Support
private bool isDisposed;
protected virtual void Dispose(bool disposing)
{
if (!isDisposed)
{
isDisposed = true;
watchers.ForEach(w => w.Dispose());
}
}
~DynamicClassCompiler()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Eto.Forms;
using Eto.Drawing;
using Eto.OpenTK;
using System.Diagnostics;
using System.Timers;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using System.Security.Cryptography;
namespace TestEtoGl
{
/// <summary>
/// Your application's main form
/// </summary>
public class MainForm : Form
{
public class myStuff
{
public List<ObservableCollection<string>> entries { get; set; }
}
public List<ObservableCollection<string>> myList;
public OVPSettings ovpSettings, ovp2Settings, vSettings;
public System.Timers.Timer m_timer;
public PointF[] refPoly;
public PointF[] previewPoly;
TestViewport viewport, viewport2;
ProgressBar progressBar;
Label statusLine;
DropDown testComboBox;
Button testComboBox_SelEntry;
public Int32 numberOfCases;
public Int32 timer_interval;
public object drawingLock;
public Int64 timeOfLastPreviewUpdate;
public Stopwatch sw;
public double swTime;
public Stopwatch sw_Preview;
public Int32 currentProgress;
public bool runAbort;
public bool drawing;
public delegate void updateSimUIMT();
public updateSimUIMT updateSimUIMTFunc { get; set; }
public delegate void abortRun();
public abortRun abortRunFunc { get; set; }
public delegate void configureProgressBar(Int32 maxValue);
public configureProgressBar configureProgressBarFunc { get; set; }
private void updateSimUIMT_()
{
m_timer.Elapsed += new System.Timers.ElapsedEventHandler(updatePreview);
}
private void configureProgressBar_(Int32 maxValue)
{
Application.Instance.Invoke(() =>
{
progressBar.MaxValue = maxValue;
progressBar.Value = 0;
});
}
private void updatePreview(object sender, EventArgs e)
{
if (Monitor.TryEnter(drawingLock))
{
try
{
drawing = true;
//if ((sw_Preview.Elapsed.TotalMilliseconds - timeOfLastPreviewUpdate) > m_timer.Interval)
{
// try
{
Application.Instance.Invoke(new Action(() =>
{
// also sets commonVars.drawing to 'false'
previewUpdate();
}));
}
}
}
catch (Exception)
{
}
finally
{
Monitor.Exit(drawingLock);
drawing = false;
}
}
}
public void previewUpdate()
{
{
//ovpSettings.polyList.Clear();
lock (previewPoly)
{
ovpSettings.addPolygon(previewPoly.ToArray(), new Color(0, 0.5f, 0), 0.7f, false);
}
viewport.updateViewport();
double progress = (double)currentProgress / (double)numberOfCases;
statusLine.Text = (progress * 100).ToString("#.##") + "% complete";
progressBar.Value = currentProgress; // * 100.0f;
}
}
public void runCases(object sender, EventArgs e)
{
Task t2 = Task.Factory.StartNew(() =>
{
run2();
}
);
if (t2.IsCompleted || t2.IsCanceled || t2.IsFaulted)
{
t2.Dispose();
}
}
public void run2()
{
currentProgress = 0;
ovpSettings.polyList.Clear();
configureProgressBarFunc?.Invoke(numberOfCases);
previewPoly = refPoly.ToArray();
m_timer = new System.Timers.Timer();
// Set up timers for the UI refresh
m_timer.AutoReset = true;
m_timer.Interval = timer_interval;
updateSimUIMTFunc?.Invoke();
m_timer.Start();
swTime = 0.0; // reset time for the batch
timeOfLastPreviewUpdate = 0;
sw = new Stopwatch();
sw.Stop();
sw.Reset();
sw_Preview = new Stopwatch();
sw_Preview.Stop();
sw_Preview.Reset();
// Set our parallel task options based on user settings.
ParallelOptions po = new ParallelOptions();
// Attempt at parallelism.
CancellationTokenSource cancelSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancelSource.Token;
po.MaxDegreeOfParallelism = 4;
// Run a task to enable cancelling from another thread.
Task t = Task.Factory.StartNew(() =>
{
if (abortRunFunc != null)
{
abortRunFunc();
if (runAbort)
{
cancelSource.Cancel();
}
}
}
);
sw.Start();
sw_Preview.Start();
try
{
Parallel.For(0, numberOfCases, po, (i, loopState) =>
{
try
{
PointF[] newPoly = randomScale_MT();
Interlocked.Increment(ref currentProgress);
if (!drawing)
{
lock (previewPoly)
{
previewPoly = newPoly.ToArray();
}
}
if (runAbort)
{
cancelSource.Cancel();
cancellationToken.ThrowIfCancellationRequested();
}
}
catch (OperationCanceledException)
{
m_timer.Stop();
runAbort = false; // reset state to allow user to abort save of results.
sw.Stop();
loopState.Stop();
}
});
}
catch (Exception ex)
{
var err = ex.ToString();
}
t.Dispose();
sw.Stop();
sw.Reset();
sw_Preview.Stop();
sw_Preview.Reset();
m_timer.Stop();
m_timer.Dispose();
}
private PointF[] randomScale_MT()
{
double myRandom = RNG.random_gauss3()[0];
double myRandom1 = RNG.random_gauss3()[1];
PointF[] newPoly = new PointF[5];
for (int pt = 0; pt < newPoly.Length; pt++)
{
newPoly[pt] = new PointF((float)(refPoly[pt].X + (100.0f * myRandom1)), (float)(refPoly[pt].Y + (100.0f * myRandom)));
}
Thread.Sleep(10);
return newPoly;
}
public void abortTheRun(object sender, EventArgs e)
{
runAbort = true;
}
private void changeSelEntry(object sender, EventArgs e)
{
testComboBox.SelectedIndex = Math.Abs(testComboBox.SelectedIndex - 1);
}
public MainForm ()
{
myList = new List<ObservableCollection<string>>();
myList.Add(new ObservableCollection<string> { "First", "Second" });
DataContext = new myStuff
{
entries = myList
};
refPoly = new PointF[5];
refPoly[0] = new PointF(-50, 50);
refPoly[1] = new PointF(50, 50);
refPoly[2] = new PointF(50, -50);
refPoly[3] = new PointF(-50, -50);
refPoly[4] = refPoly[0];
drawingLock = new object();
MinimumSize = new Size(200, 200);
updateSimUIMTFunc = updateSimUIMT_;
configureProgressBarFunc = configureProgressBar_;
numberOfCases = 25000;
timer_interval = 10;
ovpSettings = new OVPSettings ();
ovp2Settings = new OVPSettings ();
ovp2Settings.zoomFactor = 3;
Title = "My Eto Form";
/*
Test flags.
0 : stamdard viewports in splitter test.
1 : viewports in tabs (WPF has issues here due to the deferred evaluation; still need a better fix)
3 : single viewport in panel, dropdown switches out the view settings.
*/
int mode = 0;
if (mode == 0)
{
viewport = new TestViewport(ref ovpSettings);
viewport.Size = new Size(250, 250);
viewport2 = new TestViewport(ref ovp2Settings);
viewport2.Size = new Size(200, 200);
Panel testing = new Panel();
testing.Size = new Size(viewport.Width + viewport2.Width, viewport.Height);
testing.Content = new Splitter
{
Orientation = Orientation.Horizontal,
FixedPanel = SplitterFixedPanel.None,
Panel1 = viewport,
Panel2 = viewport2
};
Panel testing2 = new Panel();
testing2.Content = new Splitter
{
Orientation = Orientation.Horizontal,
FixedPanel = SplitterFixedPanel.None,
Panel1 = statusLine,
Panel2 = progressBar
};
testComboBox_SelEntry = new Button();
testComboBox_SelEntry.Text = "Change";
testComboBox_SelEntry.Click += changeSelEntry;
testComboBox = new DropDown();
testComboBox.DataContext = DataContext;
testComboBox.BindDataContext(c => c.DataStore, (myStuff m) => m.entries[0]);
testComboBox.SelectedIndex = 0;
//testComboBox.SelectedIndexBinding.BindDataContext((myStuff m) => m.index);
Panel testing3 = new Panel();
testing3.Content = new Splitter
{
Orientation = Orientation.Horizontal,
FixedPanel = SplitterFixedPanel.None,
Panel1 = testComboBox_SelEntry,
Panel2 = testComboBox
};
Panel testing4 = new Panel();
testing4.Content = new Splitter
{
Orientation = Orientation.Vertical,
FixedPanel = SplitterFixedPanel.None,
Panel1 = testing3,
Panel2 = testing
};
Splitter mySplitter = new Splitter
{
Orientation = Orientation.Vertical,
FixedPanel = SplitterFixedPanel.None,
Panel1 = testing4,
Panel2 = testing2
};
Content = mySplitter;
}
if (mode == 1)
{
TabControl tabControl_main = new TabControl();
tabControl_main.Size = new Size(300, 300);
Content = tabControl_main;
TabPage tab_0 = new TabPage();
tab_0.Text = "0";
tabControl_main.Pages.Add(tab_0);
PixelLayout tabPage_0_content = new PixelLayout();
tabPage_0_content.Size = new Size(280, 280);
TabPage tab_1 = new TabPage();
tab_1.Text = "1";
tabControl_main.Pages.Add(tab_1);
PixelLayout tabPage_1_content = new PixelLayout();
tabPage_1_content.Size = new Size(280, 280);
tab_1.Content = tabPage_1_content;
TabPage tab_2 = new TabPage();
tab_2.Text = "2";
tabControl_main.Pages.Add(tab_2);
viewport = new TestViewport(ref ovpSettings);
viewport.Size = new Size(200, 200);
tabPage_1_content.Add(viewport, 5, 5);
viewport2 = new TestViewport(ref ovp2Settings);
viewport2.Size = new Size(200, 200);
tab_2.Content = viewport2;
}
if (mode == 2)
{
ovpSettings.addPolygon(refPoly, Color.FromArgb(0, 255, 0), 0.7f, false);
ovp2Settings.addPolygon(refPoly, Color.FromArgb(255, 0, 0), 0.7f, false);
vSettings = new OVPSettings();
viewport = new TestViewport(ref vSettings);
viewport.Size = new Size(250, 250);
Panel testing = new Panel();
testing.Size = new Size(viewport.Width, viewport.Height);
PixelLayout p = new PixelLayout();
p.Add(viewport, 0, 0);
testing.Content = p;
testComboBox_SelEntry = new Button();
testComboBox_SelEntry.Text = "Change";
testComboBox_SelEntry.Click += changeSelEntry;
testComboBox = new DropDown();
testComboBox.DataContext = DataContext;
testComboBox.BindDataContext(c => c.DataStore, (myStuff m) => m.entries[0]);
testComboBox.SelectedIndex = 0;
testComboBox.SelectedIndexChanged += adjustView_;
//testComboBox.SelectedIndexBinding.BindDataContext((myStuff m) => m.index);
var testing3 = new Splitter
{
Orientation = Orientation.Horizontal,
FixedPanel = SplitterFixedPanel.None,
Panel1 = testComboBox_SelEntry,
Panel2 = testComboBox
};
var testing4 = new Splitter
{
Orientation = Orientation.Vertical,
FixedPanel = SplitterFixedPanel.None,
Panel1 = testing3,
Panel2 = testing
};
var mySplitter = new Splitter
{
Orientation = Orientation.Vertical,
FixedPanel = SplitterFixedPanel.None,
Panel1 = testing4,
Panel2 = new Panel()
};
Content = mySplitter;
}
statusLine = new Label();
statusLine.Size = new Size(150, 11);
statusLine.Text = "Hello world";
progressBar = new ProgressBar();
progressBar.Height = 15;
progressBar.MaxValue = numberOfCases;
// create a few commands that can be used for the menu and toolbar
var clickMe = new Command { MenuText = "Run", ToolBarText = "Run" };
clickMe.Executed += runCases;
var abort = new Command { MenuText = "Abort", ToolBarText = "Abort" };
abort.Executed += abortTheRun;
var adjustList = new Command { MenuText = "Add to list", ToolBarText = "Add" };
if (mode != 3)
{
adjustList.Executed += adjustList_;
}
var quitCommand = new Command { MenuText = "Quit", Shortcut = Application.Instance.CommonModifier | Keys.Q };
quitCommand.Executed += (sender, e) => Application.Instance.Quit ();
var aboutCommand = new Command { MenuText = "About..." };
aboutCommand.Executed += (sender, e) => MessageBox.Show (this, "About my app...");
// create menu
Menu = new MenuBar {
Items = {
// File submenu
new ButtonMenuItem { Text = "&File", Items = { clickMe } },
// new ButtonMenuItem { Text = "&Edit", Items = { /* commands/items */ } },
// new ButtonMenuItem { Text = "&View", Items = { /* commands/items */ } },
},
ApplicationItems = {
// application (OS X) or file menu (others)
new ButtonMenuItem { Text = "&Preferences..." },
},
QuitItem = quitCommand,
AboutItem = aboutCommand
};
// create toolbar
ToolBar = new ToolBar { Items = { clickMe, abort, adjustList } };
//mySplitter.Panel1.SizeChanged += splitterSize;
//mySplitter.Panel2.SizeChanged += splitterSize;
}
void adjustView_(object sender, EventArgs e)
{
if (testComboBox.SelectedIndex == 0)
{
viewport.changeSettingsRef(ref ovpSettings);
}
else
{
viewport.changeSettingsRef(ref ovp2Settings);
}
}
void adjustList_(object sender, EventArgs e)
{
myList[0].Add("Entry " + myList[0].Count.ToString());
if (testComboBox.SelectedIndex == -1)
{
testComboBox.SelectedIndex = 0;
}
if (testComboBox.SelectedIndex >= myList[0].Count)
{
testComboBox.SelectedIndex = myList[0].Count - 1;
}
// testComboBox.SelectedIndex = 1;
}
/* These shouldn't be necessary
protected override void OnWindowStateChanged(EventArgs e)
{
base.OnWindowStateChanged(e);
viewport.updateViewport();
viewport.updateViewport();
if (viewport2 != null)
{
viewport2.updateViewport();
}
}
void splitterSize(object sender, EventArgs e)
{
viewport.updateViewport();
viewport.updateViewport();
if (viewport2 != null)
{
viewport2.updateViewport();
}
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
viewport.updateViewport();
if (viewport2 != null)
{
viewport2.updateViewport();
}
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
viewport.updateViewport();
viewport.updateViewport();
if (viewport2 != null)
{
viewport2.updateViewport();
}
}
*/
}
public static class RNG
{
/*
* This class is interesting. Originally, the intent was to have per-thread RNGs, but it became apparent that threads that instantiated an RNG
* would get the same random number distribution when the RNGs were initialized at the same system time.
* To avoid this, earlier systems made a common RNG and the threads would query from that RNG.
* However, this was not thread-safe, such that the calls to the RNG would start returning 0 and the application enters a spiral of death as the RNG was
* continuously, and unsuccessfully, polled for a non-zero value.
*
* Locking the RNG was one option, so that only one thread could query at a time, but this caused severe performance issues.
*
* So, to address this, I've gone back to a per-thread RNG (referenced in jobSettings()) and then use the RNGCryptoServiceProvider to provide a
* 'seed' value for a null RNG entity. This avoids some severe performance issues if the RNGCryptoServiceProvider is used for all random numbers.
*
* Ref : http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx
*/
private static RNGCryptoServiceProvider _global = new RNGCryptoServiceProvider();
[ThreadStatic]
private static Random _local;
public static double[] random_gauss3()
{
Random random = _local;
if (random == null)
{
byte[] buffer = new byte[4];
_global.GetBytes(buffer);
_local = random = new Random(BitConverter.ToInt32(buffer, 0));
}
// Box-Muller transform
// We aren't allowed 0, so we reject any values approaching zero.
double U1, U2;
U1 = random.NextDouble();
while (U1 < 1E-15)
{
U1 = random.NextDouble();
}
U2 = random.NextDouble();
while (U2 < 1E-15)
{
U2 = random.NextDouble();
}
// PAs are 3-sigma, so this needs to be divided by 3 to give single sigma value when used
double A1 = Math.Sqrt(-2 * Math.Log(U2, Math.E)) * Math.Cos(2 * Math.PI * U1) / 3;
double A2 = Math.Sqrt(-2 * Math.Log(U1, Math.E)) * Math.Sin(2 * Math.PI * U2) / 3;
double[] myReturn = { A1, A2 };
return myReturn;
}
// This is our Gaussian RNG
public static double random_gauss()
{
Random random = _local;
if (random == null)
{
byte[] buffer = new byte[4];
_global.GetBytes(buffer);
_local = random = new Random(BitConverter.ToInt32(buffer, 0));
}
// We aren't allowed 0, so we reject any values approaching zero.
double U1 = random.NextDouble();
while (U1 < 1E-15)
{
U1 = random.NextDouble();
}
double U2 = random.NextDouble();
while (U2 < 1E-15)
{
U2 = random.NextDouble();
}
// PAs are 3-sigma, so this needs to be divided by 3 to give single sigma value when used
double A1 = Math.Sqrt(-2 * Math.Log(U2, Math.E)) * Math.Cos(2 * Math.PI * U1) / 3;
double A2 = Math.Sqrt(-2 * Math.Log(U1, Math.E)) * Math.Sin(2 * Math.PI * U2) / 3;
return A1;
}
// This is a slightly different version of our Gaussian RNG
public static double random_gauss2()
{
Random random = _local;
if (random == null)
{
byte[] buffer = new byte[4];
_global.GetBytes(buffer);
_local = random = new Random(BitConverter.ToInt32(buffer, 0));
}
// We aren't allowed 0, so we reject any values approaching zero.
double U1 = random.NextDouble();
while (U1 < 1E-15)
{
U1 = random.NextDouble();
}
double U2 = random.NextDouble();
while (U2 < 1E-15)
{
U2 = random.NextDouble();
}
// PAs are 3-sigma, so this needs to be divided by 3 to give single sigma value when used
double A2 = Math.Sqrt(-2 * Math.Log(U1, Math.E)) * Math.Sin(2 * Math.PI * U2) / 3;
return A2;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace Artem.Data.Access {
/// <summary>
///
/// </summary>
public class DataAccessView<T> : BindingList<T>, IBindingListView, IRaiseItemChangedEvents {
#region Fields /////////////////////////////////////////////////////////////////
private bool m_Sorted = false;
private bool m_Filtered = false;
private string m_FilterString = null;
private ListSortDirection m_SortDirection =
ListSortDirection.Ascending;
private PropertyDescriptor m_SortProperty = null;
private ListSortDescriptionCollection m_SortDescriptions =
new ListSortDescriptionCollection();
private List<T> m_OriginalCollection = new List<T>();
#endregion
#region Construct //////////////////////////////////////////////////////////////
/// <summary>
/// Initializes a new instance of the <see cref="T:DataAccessView<T>"/> class.
/// </summary>
public DataAccessView()
: base() {
}
/// <summary>
/// Initializes a new instance of the <see cref="T:DataAccessView<T>"/> class.
/// </summary>
/// <param name="list">The list.</param>
public DataAccessView(List<T> list)
: base(list) {
}
#endregion
#region Properties /////////////////////////////////////////////////////////////
/// <summary>
/// Gets a value indicating whether the list supports sorting.
/// </summary>
/// <value></value>
/// <returns>true if the list supports sorting; otherwise, false. The default is false.</returns>
protected override bool SupportsSortingCore {
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the list is sorted.
/// </summary>
/// <value></value>
/// <returns>true if the list is sorted; otherwise, false. The default is false.</returns>
protected override bool IsSortedCore {
get { return m_Sorted; }
}
/// <summary>
/// Gets the direction the list is sorted.
/// </summary>
/// <value></value>
/// <returns>One of the <see cref="T:System.ComponentModel.ListSortDirection"></see> values. The default is <see cref="F:System.ComponentModel.ListSortDirection.Ascending"></see>. </returns>
protected override ListSortDirection SortDirectionCore {
get { return m_SortDirection; }
}
/// <summary>
/// Gets a value indicating whether the list supports searching.
/// </summary>
/// <value></value>
/// <returns>true if the list supports searching; otherwise, false. The default is false.</returns>
protected override bool SupportsSearchingCore {
get { return true; }
}
/// <summary>
/// Gets the property descriptor that is used for sorting the list if sorting is implemented in a derived class; otherwise, returns null.
/// </summary>
/// <value></value>
/// <returns>The <see cref="T:System.ComponentModel.PropertyDescriptor"></see> used for sorting the list.</returns>
protected override PropertyDescriptor SortPropertyCore {
get { return m_SortProperty; }
}
/// <summary>
/// Gets or sets the filter to be used to exclude items from the collection of items returned by the data source
/// </summary>
/// <value></value>
/// <returns>The string used to filter items out in the item collection returned by the data source. </returns>
string IBindingListView.Filter {
get {
return m_FilterString;
}
set {
m_FilterString = value;
m_Filtered = true;
UpdateFilter();
}
}
/// <summary>
/// Gets the collection of sort descriptions currently applied to the data source.
/// </summary>
/// <value></value>
/// <returns>The <see cref="T:System.ComponentModel.ListSortDescriptionCollection"></see> currently applied to the data source.</returns>
ListSortDescriptionCollection IBindingListView.SortDescriptions {
get { return m_SortDescriptions; }
}
/// <summary>
/// Gets a value indicating whether the data source supports advanced sorting.
/// </summary>
/// <value></value>
/// <returns>true if the data source supports advanced sorting; otherwise, false. </returns>
bool IBindingListView.SupportsAdvancedSorting {
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the data source supports filtering.
/// </summary>
/// <value></value>
/// <returns>true if the data source supports filtering; otherwise, false. </returns>
bool IBindingListView.SupportsFiltering {
get { return true; }
}
/// <summary>
/// Gets or sets a value indicating whether you can add items to the list using the <see cref="M:System.ComponentModel.BindingList`1.AddNew"></see> method.
/// </summary>
/// <value></value>
/// <returns>true if you can add items to the list with the <see cref="M:System.ComponentModel.BindingList`1.AddNew"></see> method; otherwise, false. The default depends on the underlying type contained in the list.</returns>
bool IBindingList.AllowNew {
get { return CheckReadOnly(); }
}
/// <summary>
/// Gets or sets a value indicating whether you can remove items from the collection.
/// </summary>
/// <value></value>
/// <returns>true if you can remove items from the list with the <see cref="M:System.ComponentModel.BindingList`1.RemoveItem(System.Int32)"></see> method otherwise, false. The default is true.</returns>
bool IBindingList.AllowRemove {
get { return CheckReadOnly(); }
}
bool IRaiseItemChangedEvents.RaisesItemChangedEvents {
get { return true; }
}
#endregion
/// <summary>
/// Finds the core.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="key">The key.</param>
/// <returns></returns>
protected override int FindCore(PropertyDescriptor property, object key) {
// Simple iteration:
for (int i = 0; i < Count; i++) {
T item = this[i];
if (property.GetValue(item).Equals(key)) {
return i;
}
}
return -1; // Not found
#region Alternative search implementation
// using List.FindIndex:
//Predicate<T> pred = delegate(T item)
//{
// if (property.GetValue(item).Equals(key))
// return true;
// else
// return false;
//};
//List<T> list = Items as List<T>;
//if (list == null)
// return -1;
//return list.FindIndex(pred);
#endregion
}
/// <summary>
/// Applies the sort core.
/// </summary>
/// <param name="property">The property.</param>
/// <param name="direction">The direction.</param>
protected override void ApplySortCore(
PropertyDescriptor property, ListSortDirection direction) {
m_SortDirection = direction;
m_SortProperty = property;
SortComparer<T> comparer =
new SortComparer<T>(property, direction);
ApplySortInternal(comparer);
}
/// <summary>
/// Applies the sort internal.
/// </summary>
/// <param name="comparer">The comparer.</param>
private void ApplySortInternal(SortComparer<T> comparer) {
if (m_OriginalCollection.Count == 0) {
m_OriginalCollection.AddRange(this);
}
List<T> listRef = this.Items as List<T>;
if (listRef == null)
return;
listRef.Sort(comparer);
m_Sorted = true;
OnListChanged(new ListChangedEventArgs(
ListChangedType.Reset, -1));
}
/// <summary>
/// Removes any sort applied with <see cref="M:System.ComponentModel.BindingList`1.ApplySortCore(System.ComponentModel.PropertyDescriptor,System.ComponentModel.ListSortDirection)"></see> if sorting is implemented in a derived class; otherwise, raises <see cref="T:System.NotSupportedException"></see>.
/// </summary>
protected override void RemoveSortCore() {
if (!m_Sorted)
return; Clear();
foreach (T item in m_OriginalCollection) {
Add(item);
}
m_OriginalCollection.Clear();
m_SortProperty = null;
m_SortDescriptions = null;
m_Sorted = false;
}
/// <summary>
/// Sorts the data source based on the given <see cref="T:System.ComponentModel.ListSortDescriptionCollection"></see>.
/// </summary>
/// <param name="sorts">The <see cref="T:System.ComponentModel.ListSortDescriptionCollection"></see> containing the sorts to apply to the data source.</param>
void IBindingListView.ApplySort(ListSortDescriptionCollection sorts) {
m_SortProperty = null;
m_SortDescriptions = sorts;
SortComparer<T> comparer = new SortComparer<T>(sorts);
ApplySortInternal(comparer);
}
/// <summary>
/// Removes the current filter applied to the data source.
/// </summary>
void IBindingListView.RemoveFilter() {
if (!m_Filtered)
return;
m_FilterString = null;
m_Filtered = false;
m_Sorted = false;
m_SortDescriptions = null;
m_SortProperty = null;
Clear();
foreach (T item in m_OriginalCollection) {
Add(item);
}
m_OriginalCollection.Clear();
}
/// <summary>
/// Updates the filter.
/// </summary>
protected virtual void UpdateFilter() {
int equalsPos = m_FilterString.IndexOf('=');
// Get property name
string propName = m_FilterString.Substring(0, equalsPos).Trim();
// Get filter criteria
string criteria = m_FilterString.Substring(equalsPos + 1,
m_FilterString.Length - equalsPos - 1).Trim();
// Strip leading and trailing quotes
criteria = criteria.Substring(1, criteria.Length - 2);
// Get a property descriptor for the filter property
PropertyDescriptor propDesc =
TypeDescriptor.GetProperties(typeof(T))[propName];
if (m_OriginalCollection.Count == 0) {
m_OriginalCollection.AddRange(this);
}
List<T> currentCollection = new List<T>(this);
Clear();
foreach (T item in currentCollection) {
object value = propDesc.GetValue(item);
if (value.ToString() == criteria) {
Add(item);
}
}
}
/// <summary>
/// Checks the read only.
/// </summary>
/// <returns></returns>
private bool CheckReadOnly() {
if (m_Sorted || m_Filtered) {
return false;
}
else {
return true;
}
}
/// <summary>
/// Inserts the specified item in the list at the specified index.
/// </summary>
/// <param name="index">The zero-based index where the item is to be inserted.</param>
/// <param name="item">The item to insert in the list.</param>
protected override void InsertItem(int index, T item) {
foreach (PropertyDescriptor propDesc in
TypeDescriptor.GetProperties(item)) {
if (propDesc.SupportsChangeEvents) {
propDesc.AddValueChanged(item, OnItemChanged);
}
}
base.InsertItem(index, item);
}
/// <summary>
/// Removes the item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to remove.</param>
protected override void RemoveItem(int index) {
T item = Items[index];
PropertyDescriptorCollection propDescs =
TypeDescriptor.GetProperties(item);
foreach (PropertyDescriptor propDesc in propDescs) {
if (propDesc.SupportsChangeEvents) {
propDesc.RemoveValueChanged(item, OnItemChanged);
}
}
base.RemoveItem(index);
}
/// <summary>
/// Called when [item changed].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
void OnItemChanged(object sender, EventArgs args) {
int index = Items.IndexOf((T)sender);
OnListChanged(new ListChangedEventArgs(
ListChangedType.ItemChanged, index));
}
}
#region SortComparer ///////////////////////////////////////////////////////////
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
class SortComparer<T> : IComparer<T> {
private ListSortDescriptionCollection m_SortCollection = null;
private PropertyDescriptor m_PropDesc = null;
private ListSortDirection m_Direction =
ListSortDirection.Ascending;
public SortComparer(PropertyDescriptor propDesc,
ListSortDirection direction) {
m_PropDesc = propDesc;
m_Direction = direction;
}
public SortComparer(ListSortDescriptionCollection sortCollection) {
m_SortCollection = sortCollection;
}
int IComparer<T>.Compare(T x, T y) {
if (m_PropDesc != null) {// Simple sort
object xValue = m_PropDesc.GetValue(x);
object yValue = m_PropDesc.GetValue(y);
return CompareValues(xValue, yValue, m_Direction);
}
else if (m_SortCollection != null &&
m_SortCollection.Count > 0) {
return RecursiveCompareInternal(x, y, 0);
}
else return 0;
}
private int CompareValues(object xValue, object yValue,
ListSortDirection direction) {
int retValue = 0;
if (xValue is IComparable) {// Can ask the x value
retValue = ((IComparable)xValue).CompareTo(yValue);
}
else if (yValue is IComparable) {//Can ask the y value
retValue = ((IComparable)yValue).CompareTo(xValue);
}
// not comparable, compare String representations
else if (!xValue.Equals(yValue)) {
retValue = xValue.ToString().CompareTo(yValue.ToString());
}
if (direction == ListSortDirection.Ascending) {
return retValue;
}
else {
return retValue * -1;
}
}
private int RecursiveCompareInternal(T x, T y, int index) {
if (index >= m_SortCollection.Count)
return 0; // termination condition
ListSortDescription listSortDesc = m_SortCollection[index];
object xValue = listSortDesc.PropertyDescriptor.GetValue(x);
object yValue = listSortDesc.PropertyDescriptor.GetValue(y);
int retValue = CompareValues(xValue,
yValue, listSortDesc.SortDirection);
if (retValue == 0) {
return RecursiveCompareInternal(x, y, ++index);
}
else {
return retValue;
}
}
}
#endregion
}
| |
namespace Microsoft.Protocols.TestSuites.MS_CPSWS
{
using System;
using System.ServiceModel;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// Adapter class of MS-CPSWS.
/// </summary>
public partial class MS_CPSWSAdapter : ManagedAdapterBase, IMS_CPSWSAdapter
{
#region Variables
/// <summary>
/// The proxy class.
/// </summary>
private ClaimProviderWebServiceClient cpswsClient;
#endregion Variables
#region Initialize TestSuite
/// <summary>
/// Overrides IAdapter's Initialize(), to set default protocol short name of the testSite.
/// </summary>
/// <param name="testSite">Transfer ITestSite into Adapter,Make adapter can use ITestSite's function.</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
// Set the protocol name of current test suite
testSite.DefaultProtocolDocShortName = "MS-CPSWS";
// Load Common configuration
this.LoadCommonConfiguration();
Common.CheckCommonProperties(this.Site, true);
// Load SHOULDMAY configuration
Common.MergeSHOULDMAYConfig(this.Site);
// Initialize the proxy.
this.cpswsClient = this.GetClaimProviderWebServiceClient();
// Set Credentials information
Common.AcceptServerCertificate();
}
#endregion
#region MS-CPSWSAdapter Members
/// <summary>
/// A method used to get the claim types.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names which are used to retrieve the claim types.</param>
/// <returns>A return value represents a list of claim types.</returns>
public ArrayOfString ClaimTypes(ArrayOfString providerNames)
{
ArrayOfString responseOfClaimTypes = new ArrayOfString();
try
{
responseOfClaimTypes = this.cpswsClient.ClaimTypes(providerNames);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [ClaimTypes] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.ValidateClaimTypesResponseData(responseOfClaimTypes);
return responseOfClaimTypes;
}
/// <summary>
/// A method used to get the claim value types.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names which are used to retrieve the claim value types.</param>
/// <returns>A return value represents a list of claim value types.</returns>
public ArrayOfString ClaimValueTypes(ArrayOfString providerNames)
{
ArrayOfString responseOfClaimValueTypes = new ArrayOfString();
try
{
responseOfClaimValueTypes = this.cpswsClient.ClaimValueTypes(providerNames);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [ClaimValueTypes] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.ValidateClaimValueTypesResponseData(responseOfClaimValueTypes);
return responseOfClaimValueTypes;
}
/// <summary>
/// A method used to get the entity types.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names which are used to retrieve the entity types.</param>
/// <returns>A return value represents a list of entity types.</returns>
public ArrayOfString EntityTypes(ArrayOfString providerNames)
{
ArrayOfString responseOfEntityTypes = new ArrayOfString();
try
{
responseOfEntityTypes = this.cpswsClient.EntityTypes(providerNames);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [EntityTypes] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.ValidateEntityTypesResponseData(responseOfEntityTypes);
return responseOfEntityTypes;
}
/// <summary>
/// A method used to retrieve a claims provider hierarchy tree from a claims provider.
/// </summary>
/// <param name="providerName">A parameter represents a provider name.</param>
/// <param name="principalType">A parameter represents which type of picker entities to be included in the output claims provider hierarchy tree.</param>
/// <param name="hierarchyNodeID">A parameter represents the identifier of the node to be used as root of the returned claims provider hierarchy tree.</param>
/// <param name="numberOfLevels">A parameter represents the maximum number of levels that can be returned by the protocol server in any of the output claims provider hierarchy tree.</param>
/// <returns>A return value represents a claims provider hierarchy tree.</returns>
public SPProviderHierarchyTree GetHierarchy(string providerName, SPPrincipalType principalType, string hierarchyNodeID, int numberOfLevels)
{
SPProviderHierarchyTree responseOfGetHierarchy = new SPProviderHierarchyTree();
try
{
responseOfGetHierarchy = this.cpswsClient.GetHierarchy(providerName, principalType, hierarchyNodeID, numberOfLevels);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [GetHierarchy] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.ValidateGetHierarchyResponseData(responseOfGetHierarchy);
return responseOfGetHierarchy;
}
/// <summary>
/// A method used to retrieve a list of claims provider hierarchy trees from a list of claims providers.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names.</param>
/// <param name="principalType">A parameter represents which type of picker entities to be included in the output claims provider hierarchy tree.</param>
/// <param name="numberOfLevels">A parameter represents the maximum number of levels that can be returned by the protocol server in any of the output claims provider hierarchy tree.</param>
/// <returns>A return value represents a list of claims provider hierarchy trees.</returns>
public SPProviderHierarchyTree[] GetHierarchyAll(ArrayOfString providerNames, SPPrincipalType principalType, int numberOfLevels)
{
SPProviderHierarchyTree[] responseOfGetHierarchyAll = new SPProviderHierarchyTree[0];
try
{
responseOfGetHierarchyAll = this.cpswsClient.GetHierarchyAll(providerNames, principalType, numberOfLevels);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [GetHierarchyAll] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.ValidateGetHierarchyAllResponseData(responseOfGetHierarchyAll);
return responseOfGetHierarchyAll;
}
/// <summary>
/// A method used to retrieve schema for the current hierarchy provider.
/// </summary>
/// <returns>A return value represents the hierarchy claims provider schema.</returns>
public SPProviderSchema HierarchyProviderSchema()
{
SPProviderSchema responseOfHierarchyProviderSchema = new SPProviderSchema();
try
{
responseOfHierarchyProviderSchema = this.cpswsClient.HierarchyProviderSchema();
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [HierarchyProviderSchema] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.VerifyHierarchyProviderSchema(responseOfHierarchyProviderSchema);
return responseOfHierarchyProviderSchema;
}
/// <summary>
/// A method used to retrieve a list of claims provider schemas from a list of claims providers.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names.</param>
/// <returns>A return value represents a list of claims provider schemas</returns>
public SPProviderSchema[] ProviderSchemas(ArrayOfString providerNames)
{
SPProviderSchema[] responseOfProviderSchemas = new SPProviderSchema[0];
try
{
responseOfProviderSchemas = this.cpswsClient.ProviderSchemas(providerNames);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [ProviderSchemas] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.VerifyProviderSchemas(responseOfProviderSchemas);
return responseOfProviderSchemas;
}
/// <summary>
/// A method used to resolve an input string to picker entities using a list of claims providers.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names.</param>
/// <param name="principalType">A parameter represents which type of picker entities to be included in the result.</param>
/// <param name="resolveInput">A parameter represents the input to be resolved.</param>
/// <returns>A return value represents a list of picker entities.</returns>
public PickerEntity[] Resolve(ArrayOfString providerNames, SPPrincipalType principalType, string resolveInput)
{
PickerEntity[] responseOfResolve = new PickerEntity[0];
try
{
responseOfResolve = this.cpswsClient.Resolve(providerNames, principalType, resolveInput);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [Resolve] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.ValidateResolveResponseData(responseOfResolve);
return responseOfResolve;
}
/// <summary>
/// A method used to resolve an input claim to picker entities using a list of claims providers.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names.</param>
/// <param name="principalType">A parameter represents which type of picker entities to be included in the result</param>
/// <param name="resolveInput">A parameter represents the SPClaim to be resolved.</param>
/// <returns>A return value represents a list of picker entities.</returns>
public PickerEntity[] ResolveClaim(ArrayOfString providerNames, SPPrincipalType principalType, SPClaim resolveInput)
{
PickerEntity[] responseOfResolveClaim = new PickerEntity[0];
try
{
responseOfResolveClaim = this.cpswsClient.ResolveClaim(providerNames, principalType, resolveInput);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [ResolveClaim] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.ValidateResolveClaimResponseData(responseOfResolveClaim);
return responseOfResolveClaim;
}
/// <summary>
/// A method used to resolve a list of strings to picker entities using a list of claims providers.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names.</param>
/// <param name="principalType">A parameter represents which type of picker entities to be included in the result.</param>
/// <param name="resolveInput">A parameter represents a list of input strings to be resolved.</param>
/// <returns>A return value represents a list of picker entities.</returns>
public PickerEntity[] ResolveMultiple(ArrayOfString providerNames, SPPrincipalType principalType, ArrayOfString resolveInput)
{
PickerEntity[] responseOfResolveMultiple = new PickerEntity[0];
try
{
responseOfResolveMultiple = this.cpswsClient.ResolveMultiple(providerNames, principalType, resolveInput);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [ResolveMultiple] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.ValidateResolveMultipleResponseData(responseOfResolveMultiple);
return responseOfResolveMultiple;
}
/// <summary>
/// A method used to resolve a list of claims to picker entities using a list of claims providers.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names.</param>
/// <param name="principalType">A parameter represents which type of picker entities to be included in the result.</param>
/// <param name="resolveInput">A parameter represents a list of claims to be resolved.</param>
/// <returns>A return value represents a list of picker entities.</returns>
public PickerEntity[] ResolveMultipleClaim(ArrayOfString providerNames, SPPrincipalType principalType, SPClaim[] resolveInput)
{
PickerEntity[] responseOfResolveMultipleClaim = new PickerEntity[0];
try
{
responseOfResolveMultipleClaim = this.cpswsClient.ResolveMultipleClaim(providerNames, principalType, resolveInput);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [ResolveMultipleClaim] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.ValidateResolveMultipleClaimResponseData(responseOfResolveMultipleClaim);
return responseOfResolveMultipleClaim;
}
/// <summary>
/// A method used to perform a search for entities on a list of claims providers.
/// </summary>
/// <param name="providerSearchArguments">A parameter represents the search arguments.</param>
/// <param name="principalType">A parameter represents which type of picker entities to be included in the output claims provider hierarchy tree.</param>
/// <param name="searchPattern">A parameter represents the search string.</param>
/// <returns>A return value represents a list of claims provider hierarchy trees.</returns>
public SPProviderHierarchyTree[] Search(SPProviderSearchArguments[] providerSearchArguments, SPPrincipalType principalType, string searchPattern)
{
SPProviderHierarchyTree[] responseOfSearch = new SPProviderHierarchyTree[0];
try
{
responseOfSearch = this.cpswsClient.Search(providerSearchArguments, principalType, searchPattern);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [Search] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.VerifySearch(responseOfSearch);
return responseOfSearch;
}
/// <summary>
/// A method used to perform a search for entities on a list of claims providers.
/// </summary>
/// <param name="providerNames">A parameter represents a list of provider names.</param>
/// <param name="principalType">A parameter represents which type of picker entities to be included in the output claims provider hierarchy tree.</param>
/// <param name="searchPattern">A parameter represents the search string.</param>
/// <param name="maxCount">A parameter represents the maximum number of matched entities to be returned in total across all the output claims provider hierarchy trees.</param>
/// <returns>A return value represents a list of claims provider hierarchy trees.</returns>
public SPProviderHierarchyTree[] SearchAll(ArrayOfString providerNames, SPPrincipalType principalType, string searchPattern, int maxCount)
{
SPProviderHierarchyTree[] responseOfSearchAll = new SPProviderHierarchyTree[0];
try
{
responseOfSearchAll = this.cpswsClient.SearchAll(providerNames, principalType, searchPattern, maxCount);
this.CaptureTransportRelatedRequirements();
}
catch (FaultException faultEX)
{
this.Site.Log.Add(
LogEntryKind.Debug,
@"There is an exception generated when calling [SearchAll] method:\r\n{0}",
faultEX.Message);
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureSOAPFaultRequirement(faultEX);
throw;
}
this.VerifySearchAll(responseOfSearchAll);
return responseOfSearchAll;
}
#endregion
#region Private helper methods
/// <summary>
/// A method used to load Common Configuration
/// </summary>
private void LoadCommonConfiguration()
{
// Get a specified property value from ptfconfig file.
string conmmonConfigFileName = Common.GetConfigurationPropertyValue("CommonConfigurationFileName", this.Site);
// Execute the merge the common configuration
Common.MergeGlobalConfig(conmmonConfigFileName, this.Site);
}
/// <summary>
/// A method used to get the claim provider web service client
/// </summary>
/// <returns>A return value represents the claim provider web service client.</returns>
private ClaimProviderWebServiceClient GetClaimProviderWebServiceClient()
{
TransportProtocol currentTransportValue = Common.GetConfigurationPropertyValue<TransportProtocol>("TransportType", this.Site);
string endpointName = string.Empty;
string targetAddressValue = string.Empty;
switch (currentTransportValue)
{
case TransportProtocol.HTTP:
{
endpointName = Common.GetConfigurationPropertyValue("HttpEndPointName", this.Site);
targetAddressValue = Common.GetConfigurationPropertyValue("TargetHTTPServiceUrl", this.Site);
break;
}
case TransportProtocol.HTTPS:
{
endpointName = Common.GetConfigurationPropertyValue("HttpsEndPointName", this.Site);
targetAddressValue = Common.GetConfigurationPropertyValue("TargetHTTPSServiceUrl", this.Site);
break;
}
}
EndpointAddress targetAddress = new EndpointAddress(targetAddressValue);
ClaimProviderWebServiceClient protocolClient = WcfClientFactory.CreateClient<ClaimProviderWebServiceClient, IClaimProviderWebService>(this.Site, endpointName, targetAddress);
// Setting credential
string userName = Common.GetConfigurationPropertyValue("UserName", this.Site);
string password = Common.GetConfigurationPropertyValue("Password", this.Site);
string domain = Common.GetConfigurationPropertyValue("Domain", this.Site);
protocolClient.ClientCredentials.Windows.ClientCredential.UserName = userName;
protocolClient.ClientCredentials.Windows.ClientCredential.Password = password;
protocolClient.ClientCredentials.Windows.ClientCredential.Domain = domain;
protocolClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
protocolClient.Open();
return protocolClient;
}
#endregion
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.Reflection;
using dnlib.Threading;
namespace dnlib.DotNet {
/// <summary>
/// <see cref="Importer"/> options
/// </summary>
[Flags]
public enum ImporterOptions {
/// <summary>
/// Use <see cref="TypeDef"/>s whenever possible if the <see cref="TypeDef"/> is located
/// in this module.
/// </summary>
TryToUseTypeDefs = 1,
/// <summary>
/// Use <see cref="MethodDef"/>s whenever possible if the <see cref="MethodDef"/> is located
/// in this module.
/// </summary>
TryToUseMethodDefs = 2,
/// <summary>
/// Use <see cref="FieldDef"/>s whenever possible if the <see cref="FieldDef"/> is located
/// in this module.
/// </summary>
TryToUseFieldDefs = 4,
/// <summary>
/// Use <see cref="TypeDef"/>s, <see cref="MethodDef"/>s and <see cref="FieldDef"/>s
/// whenever possible if the definition is located in this module.
/// </summary>
/// <seealso cref="TryToUseTypeDefs"/>
/// <seealso cref="TryToUseMethodDefs"/>
/// <seealso cref="TryToUseFieldDefs"/>
TryToUseDefs = TryToUseTypeDefs | TryToUseMethodDefs | TryToUseFieldDefs,
/// <summary>
/// Don't set this flag. For internal use only.
/// </summary>
FixSignature = int.MinValue,
}
/// <summary>
/// Imports <see cref="Type"/>s, <see cref="ConstructorInfo"/>s, <see cref="MethodInfo"/>s
/// and <see cref="FieldInfo"/>s as references
/// </summary>
public struct Importer {
readonly ModuleDef module;
readonly GenericParamContext gpContext;
RecursionCounter recursionCounter;
ImporterOptions options;
/// <summary>
/// Gets/sets the <see cref="ImporterOptions.TryToUseTypeDefs"/> bit
/// </summary>
public bool TryToUseTypeDefs {
get { return (options & ImporterOptions.TryToUseTypeDefs) != 0; }
set {
if (value)
options |= ImporterOptions.TryToUseTypeDefs;
else
options &= ~ImporterOptions.TryToUseTypeDefs;
}
}
/// <summary>
/// Gets/sets the <see cref="ImporterOptions.TryToUseMethodDefs"/> bit
/// </summary>
public bool TryToUseMethodDefs {
get { return (options & ImporterOptions.TryToUseMethodDefs) != 0; }
set {
if (value)
options |= ImporterOptions.TryToUseMethodDefs;
else
options &= ~ImporterOptions.TryToUseMethodDefs;
}
}
/// <summary>
/// Gets/sets the <see cref="ImporterOptions.TryToUseFieldDefs"/> bit
/// </summary>
public bool TryToUseFieldDefs {
get { return (options & ImporterOptions.TryToUseFieldDefs) != 0; }
set {
if (value)
options |= ImporterOptions.TryToUseFieldDefs;
else
options &= ~ImporterOptions.TryToUseFieldDefs;
}
}
/// <summary>
/// Gets/sets the <see cref="ImporterOptions.FixSignature"/> bit
/// </summary>
bool FixSignature {
get { return (options & ImporterOptions.FixSignature) != 0; }
set {
if (value)
options |= ImporterOptions.FixSignature;
else
options &= ~ImporterOptions.FixSignature;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module that will own all references</param>
public Importer(ModuleDef module)
: this(module, 0, new GenericParamContext()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module that will own all references</param>
/// <param name="gpContext">Generic parameter context</param>
public Importer(ModuleDef module, GenericParamContext gpContext)
: this(module, 0, gpContext) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module that will own all references</param>
/// <param name="options">Importer options</param>
public Importer(ModuleDef module, ImporterOptions options)
: this(module, options, new GenericParamContext()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="module">The module that will own all references</param>
/// <param name="options">Importer options</param>
/// <param name="gpContext">Generic parameter context</param>
public Importer(ModuleDef module, ImporterOptions options, GenericParamContext gpContext) {
this.module = module;
this.recursionCounter = new RecursionCounter();
this.options = options;
this.gpContext = gpContext;
}
/// <summary>
/// Imports a <see cref="Type"/> as a <see cref="ITypeDefOrRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c> if <paramref name="type"/> is invalid</returns>
public ITypeDefOrRef Import(Type type) {
return module.UpdateRowId(ImportAsTypeSig(type).ToTypeDefOrRef());
}
/// <summary>
/// Imports a <see cref="Type"/> as a <see cref="ITypeDefOrRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <param name="requiredModifiers">A list of all required modifiers or <c>null</c></param>
/// <param name="optionalModifiers">A list of all optional modifiers or <c>null</c></param>
/// <returns>The imported type or <c>null</c> if <paramref name="type"/> is invalid</returns>
public ITypeDefOrRef Import(Type type, IList<Type> requiredModifiers, IList<Type> optionalModifiers) {
return module.UpdateRowId(ImportAsTypeSig(type, requiredModifiers, optionalModifiers).ToTypeDefOrRef());
}
/// <summary>
/// Imports a <see cref="Type"/> as a <see cref="TypeSig"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c> if <paramref name="type"/> is invalid</returns>
public TypeSig ImportAsTypeSig(Type type) {
return ImportAsTypeSig(type, false);
}
TypeSig ImportAsTypeSig(Type type, bool treatAsGenericInst) {
if (type == null)
return null;
switch (treatAsGenericInst ? ElementType.GenericInst : type.GetElementType2()) {
case ElementType.Void: return module.CorLibTypes.Void;
case ElementType.Boolean: return module.CorLibTypes.Boolean;
case ElementType.Char: return module.CorLibTypes.Char;
case ElementType.I1: return module.CorLibTypes.SByte;
case ElementType.U1: return module.CorLibTypes.Byte;
case ElementType.I2: return module.CorLibTypes.Int16;
case ElementType.U2: return module.CorLibTypes.UInt16;
case ElementType.I4: return module.CorLibTypes.Int32;
case ElementType.U4: return module.CorLibTypes.UInt32;
case ElementType.I8: return module.CorLibTypes.Int64;
case ElementType.U8: return module.CorLibTypes.UInt64;
case ElementType.R4: return module.CorLibTypes.Single;
case ElementType.R8: return module.CorLibTypes.Double;
case ElementType.String: return module.CorLibTypes.String;
case ElementType.TypedByRef:return module.CorLibTypes.TypedReference;
case ElementType.U: return module.CorLibTypes.UIntPtr;
case ElementType.Object: return module.CorLibTypes.Object;
case ElementType.Ptr: return new PtrSig(ImportAsTypeSig(type.GetElementType(), treatAsGenericInst));
case ElementType.ByRef: return new ByRefSig(ImportAsTypeSig(type.GetElementType(), treatAsGenericInst));
case ElementType.SZArray: return new SZArraySig(ImportAsTypeSig(type.GetElementType(), treatAsGenericInst));
case ElementType.ValueType: return new ValueTypeSig(CreateTypeRef(type));
case ElementType.Class: return new ClassSig(CreateTypeRef(type));
case ElementType.Var: return new GenericVar((uint)type.GenericParameterPosition, gpContext.Type);
case ElementType.MVar: return new GenericMVar((uint)type.GenericParameterPosition, gpContext.Method);
case ElementType.I:
FixSignature = true; // FnPtr is mapped to System.IntPtr
return module.CorLibTypes.IntPtr;
case ElementType.Array:
FixSignature = true; // We don't know sizes and lower bounds
return new ArraySig(ImportAsTypeSig(type.GetElementType(), treatAsGenericInst), (uint)type.GetArrayRank());
case ElementType.GenericInst:
var typeGenArgs = type.GetGenericArguments();
var git = new GenericInstSig(ImportAsTypeSig(type.GetGenericTypeDefinition()) as ClassOrValueTypeSig, (uint)typeGenArgs.Length);
foreach (var ga in typeGenArgs)
git.GenericArguments.Add(ImportAsTypeSig(ga));
return git;
case ElementType.Sentinel:
case ElementType.Pinned:
case ElementType.FnPtr: // mapped to System.IntPtr
case ElementType.CModReqd:
case ElementType.CModOpt:
case ElementType.ValueArray:
case ElementType.R:
case ElementType.Internal:
case ElementType.Module:
case ElementType.End:
default:
return null;
}
}
ITypeDefOrRef TryResolve(TypeRef tr) {
if (!TryToUseTypeDefs || tr == null)
return tr;
if (!IsThisModule(tr))
return tr;
var td = tr.Resolve();
if (td == null || td.Module != module)
return tr;
return td;
}
IMethodDefOrRef TryResolveMethod(IMethodDefOrRef mdr) {
if (!TryToUseMethodDefs || mdr == null)
return mdr;
var mr = mdr as MemberRef;
if (mr == null)
return mdr;
if (!mr.IsMethodRef)
return mr;
var declType = GetDeclaringType(mr);
if (declType == null)
return mr;
if (declType.Module != module)
return mr;
return (IMethodDefOrRef)declType.ResolveMethod(mr) ?? mr;
}
IField TryResolveField(MemberRef mr) {
if (!TryToUseFieldDefs || mr == null)
return mr;
if (!mr.IsFieldRef)
return mr;
var declType = GetDeclaringType(mr);
if (declType == null)
return mr;
if (declType.Module != module)
return mr;
return (IField)declType.ResolveField(mr) ?? mr;
}
TypeDef GetDeclaringType(MemberRef mr) {
if (mr == null)
return null;
var td = mr.Class as TypeDef;
if (td != null)
return td;
td = TryResolve(mr.Class as TypeRef) as TypeDef;
if (td != null)
return td;
var modRef = mr.Class as ModuleRef;
if (IsThisModule(modRef))
return module.GlobalType;
return null;
}
bool IsThisModule(TypeRef tr) {
if (tr == null)
return false;
var scopeType = tr.ScopeType.GetNonNestedTypeRefScope() as TypeRef;
if (scopeType == null)
return false;
if (module == scopeType.ResolutionScope)
return true;
var modRef = scopeType.ResolutionScope as ModuleRef;
if (modRef != null)
return IsThisModule(modRef);
var asmRef = scopeType.ResolutionScope as AssemblyRef;
return Equals(module.Assembly, asmRef);
}
bool IsThisModule(ModuleRef modRef) {
return modRef != null &&
module.Name == modRef.Name &&
Equals(module.Assembly, modRef.DefinitionAssembly);
}
static bool Equals(IAssembly a, IAssembly b) {
if (a == b)
return true;
if (a == null || b == null)
return false;
return Utils.Equals(a.Version, b.Version) &&
PublicKeyBase.TokenEquals(a.PublicKeyOrToken, b.PublicKeyOrToken) &&
UTF8String.Equals(a.Name, b.Name) &&
UTF8String.CaseInsensitiveEquals(a.Culture, b.Culture);
}
ITypeDefOrRef CreateTypeRef(Type type) {
return TryResolve(CreateTypeRef2(type));
}
TypeRef CreateTypeRef2(Type type) {
if (!type.IsNested)
return module.UpdateRowId(new TypeRefUser(module, type.Namespace ?? string.Empty, type.Name ?? string.Empty, CreateScopeReference(type)));
return module.UpdateRowId(new TypeRefUser(module, string.Empty, type.Name ?? string.Empty, CreateTypeRef2(type.DeclaringType)));
}
IResolutionScope CreateScopeReference(Type type) {
if (type == null)
return null;
var asmName = type.Assembly.GetName();
var modAsm = module.Assembly;
if (modAsm != null) {
if (UTF8String.ToSystemStringOrEmpty(modAsm.Name).Equals(asmName.Name, StringComparison.OrdinalIgnoreCase)) {
if (UTF8String.ToSystemStringOrEmpty(module.Name).Equals(type.Module.ScopeName, StringComparison.OrdinalIgnoreCase))
return module;
return module.UpdateRowId(new ModuleRefUser(module, type.Module.ScopeName));
}
}
var pkt = asmName.GetPublicKeyToken();
if (pkt == null || pkt.Length == 0)
pkt = null;
return module.UpdateRowId(new AssemblyRefUser(asmName.Name, asmName.Version, PublicKeyBase.CreatePublicKeyToken(pkt), asmName.CultureInfo.Name));
}
/// <summary>
/// Imports a <see cref="Type"/> as a <see cref="ITypeDefOrRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <param name="requiredModifiers">A list of all required modifiers or <c>null</c></param>
/// <param name="optionalModifiers">A list of all optional modifiers or <c>null</c></param>
/// <returns>The imported type or <c>null</c> if <paramref name="type"/> is invalid</returns>
public TypeSig ImportAsTypeSig(Type type, IList<Type> requiredModifiers, IList<Type> optionalModifiers) {
return ImportAsTypeSig(type, requiredModifiers, optionalModifiers, false);
}
TypeSig ImportAsTypeSig(Type type, IList<Type> requiredModifiers, IList<Type> optionalModifiers, bool treatAsGenericInst) {
if (type == null)
return null;
if (IsEmpty(requiredModifiers) && IsEmpty(optionalModifiers))
return ImportAsTypeSig(type, treatAsGenericInst);
FixSignature = true; // Order of modifiers is unknown
var ts = ImportAsTypeSig(type, treatAsGenericInst);
// We don't know the original order of the modifiers.
// Assume all required modifiers are closer to the real type.
// Assume all modifiers should be applied in the same order as in the lists.
if (requiredModifiers != null) {
foreach (var modifier in requiredModifiers.GetSafeEnumerable())
ts = new CModReqdSig(Import(modifier), ts);
}
if (optionalModifiers != null) {
foreach (var modifier in optionalModifiers.GetSafeEnumerable())
ts = new CModOptSig(Import(modifier), ts);
}
return ts;
}
static bool IsEmpty<T>(IList<T> list) {
return list == null || list.Count == 0;
}
/// <summary>
/// Imports a <see cref="MethodBase"/> as a <see cref="IMethod"/>. This will be either
/// a <see cref="MemberRef"/> or a <see cref="MethodSpec"/>.
/// </summary>
/// <param name="methodBase">The method</param>
/// <returns>The imported method or <c>null</c> if <paramref name="methodBase"/> is invalid
/// or if we failed to import the method</returns>
public IMethod Import(MethodBase methodBase) {
return Import(methodBase, false);
}
/// <summary>
/// Imports a <see cref="MethodBase"/> as a <see cref="IMethod"/>. This will be either
/// a <see cref="MemberRef"/> or a <see cref="MethodSpec"/>.
/// </summary>
/// <param name="methodBase">The method</param>
/// <param name="forceFixSignature">Always verify method signature to make sure the
/// returned reference matches the metadata in the source assembly</param>
/// <returns>The imported method or <c>null</c> if <paramref name="methodBase"/> is invalid
/// or if we failed to import the method</returns>
public IMethod Import(MethodBase methodBase, bool forceFixSignature) {
FixSignature = false;
return ImportInternal(methodBase, forceFixSignature);
}
IMethod ImportInternal(MethodBase methodBase) {
return ImportInternal(methodBase, false);
}
IMethod ImportInternal(MethodBase methodBase, bool forceFixSignature) {
if (methodBase == null)
return null;
if (forceFixSignature) {
//TODO:
}
bool isMethodSpec = methodBase.IsGenericButNotGenericMethodDefinition();
if (isMethodSpec) {
IMethodDefOrRef method;
var origMethod = methodBase.Module.ResolveMethod(methodBase.MetadataToken);
if (methodBase.DeclaringType.GetElementType2() == ElementType.GenericInst)
method = module.UpdateRowId(new MemberRefUser(module, methodBase.Name, CreateMethodSig(origMethod), Import(methodBase.DeclaringType)));
else
method = ImportInternal(origMethod) as IMethodDefOrRef;
method = TryResolveMethod(method);
var gim = CreateGenericInstMethodSig(methodBase);
var methodSpec = module.UpdateRowId(new MethodSpecUser(method, gim));
if (FixSignature && !forceFixSignature) {
//TODO:
}
return methodSpec;
}
else {
IMemberRefParent parent;
if (methodBase.DeclaringType == null) {
// It's the global type. We can reference it with a ModuleRef token.
parent = GetModuleParent(methodBase.Module);
}
else
parent = Import(methodBase.DeclaringType);
if (parent == null)
return null;
MethodBase origMethod;
try {
// Get the original method def in case the declaring type is a generic
// type instance and the method uses at least one generic type parameter.
origMethod = methodBase.Module.ResolveMethod(methodBase.MetadataToken);
}
catch (ArgumentException) {
// Here if eg. the method was created by the runtime (eg. a multi-dimensional
// array getter/setter method). The method token is in that case 0x06000000,
// which is invalid.
origMethod = methodBase;
}
var methodSig = CreateMethodSig(origMethod);
IMethodDefOrRef methodRef = module.UpdateRowId(new MemberRefUser(module, methodBase.Name, methodSig, parent));
methodRef = TryResolveMethod(methodRef);
if (FixSignature && !forceFixSignature) {
//TODO:
}
return methodRef;
}
}
MethodSig CreateMethodSig(MethodBase mb) {
var sig = new MethodSig(GetCallingConvention(mb));
var mi = mb as MethodInfo;
if (mi != null)
sig.RetType = ImportAsTypeSig(mi.ReturnParameter, mb.DeclaringType);
else
sig.RetType = module.CorLibTypes.Void;
foreach (var p in mb.GetParameters())
sig.Params.Add(ImportAsTypeSig(p, mb.DeclaringType));
if (mb.IsGenericMethodDefinition)
sig.GenParamCount = (uint)mb.GetGenericArguments().Length;
return sig;
}
TypeSig ImportAsTypeSig(ParameterInfo p, Type declaringType) {
return ImportAsTypeSig(p.ParameterType, p.GetRequiredCustomModifiers(), p.GetOptionalCustomModifiers(), declaringType.MustTreatTypeAsGenericInstType(p.ParameterType));
}
CallingConvention GetCallingConvention(MethodBase mb) {
CallingConvention cc = 0;
var mbcc = mb.CallingConvention;
if (mb.IsGenericMethodDefinition)
cc |= CallingConvention.Generic;
if ((mbcc & CallingConventions.HasThis) != 0)
cc |= CallingConvention.HasThis;
if ((mbcc & CallingConventions.ExplicitThis) != 0)
cc |= CallingConvention.ExplicitThis;
switch (mbcc & CallingConventions.Any) {
case CallingConventions.Standard:
cc |= CallingConvention.Default;
break;
case CallingConventions.VarArgs:
cc |= CallingConvention.VarArg;
break;
case CallingConventions.Any:
default:
FixSignature = true;
cc |= CallingConvention.Default;
break;
}
return cc;
}
GenericInstMethodSig CreateGenericInstMethodSig(MethodBase mb) {
var genMethodArgs = mb.GetGenericArguments();
var gim = new GenericInstMethodSig(CallingConvention.GenericInst, (uint)genMethodArgs.Length);
foreach (var gma in genMethodArgs)
gim.GenericArguments.Add(ImportAsTypeSig(gma));
return gim;
}
IMemberRefParent GetModuleParent(Module module2) {
// If we have no assembly, assume this is a netmodule in the same assembly as module
var modAsm = module.Assembly;
bool isSameAssembly = modAsm == null ||
UTF8String.ToSystemStringOrEmpty(modAsm.Name).Equals(module2.Assembly.GetName().Name, StringComparison.OrdinalIgnoreCase);
if (!isSameAssembly)
return null;
return module.UpdateRowId(new ModuleRefUser(module, module.Name));
}
/// <summary>
/// Imports a <see cref="FieldInfo"/> as a <see cref="MemberRef"/>
/// </summary>
/// <param name="fieldInfo">The field</param>
/// <returns>The imported field or <c>null</c> if <paramref name="fieldInfo"/> is invalid
/// or if we failed to import the field</returns>
public IField Import(FieldInfo fieldInfo) {
return Import(fieldInfo, false);
}
/// <summary>
/// Imports a <see cref="FieldInfo"/> as a <see cref="MemberRef"/>
/// </summary>
/// <param name="fieldInfo">The field</param>
/// <param name="forceFixSignature">Always verify field signature to make sure the
/// returned reference matches the metadata in the source assembly</param>
/// <returns>The imported field or <c>null</c> if <paramref name="fieldInfo"/> is invalid
/// or if we failed to import the field</returns>
public IField Import(FieldInfo fieldInfo, bool forceFixSignature) {
FixSignature = false;
if (fieldInfo == null)
return null;
if (forceFixSignature) {
//TODO:
}
IMemberRefParent parent;
if (fieldInfo.DeclaringType == null) {
// It's the global type. We can reference it with a ModuleRef token.
parent = GetModuleParent(fieldInfo.Module);
}
else
parent = Import(fieldInfo.DeclaringType);
if (parent == null)
return null;
FieldInfo origField;
try {
// Get the original field def in case the declaring type is a generic
// type instance and the field uses a generic type parameter.
origField = fieldInfo.Module.ResolveField(fieldInfo.MetadataToken);
}
catch (ArgumentException) {
origField = fieldInfo;
}
MemberRef fieldRef;
if (origField.FieldType.ContainsGenericParameters) {
var origDeclType = origField.DeclaringType;
var asm = module.Context.AssemblyResolver.Resolve(origDeclType.Module.Assembly.GetName(), module);
if (asm == null || asm.FullName != origDeclType.Assembly.FullName)
throw new Exception("Couldn't resolve the correct assembly");
var mod = asm.FindModule(origDeclType.Module.Name) as ModuleDefMD;
if (mod == null)
throw new Exception("Couldn't resolve the correct module");
var fieldDef = mod.ResolveField((uint)(origField.MetadataToken & 0x00FFFFFF));
if (fieldDef == null)
throw new Exception("Couldn't resolve the correct field");
var fieldSig = new FieldSig(Import(fieldDef.FieldSig.GetFieldType()));
fieldRef = module.UpdateRowId(new MemberRefUser(module, fieldInfo.Name, fieldSig, parent));
}
else {
var fieldSig = new FieldSig(ImportAsTypeSig(fieldInfo.FieldType));
fieldRef = module.UpdateRowId(new MemberRefUser(module, fieldInfo.Name, fieldSig, parent));
}
var field = TryResolveField(fieldRef);
if (FixSignature && !forceFixSignature) {
//TODO:
}
return field;
}
/// <summary>
/// Imports a <see cref="IType"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public IType Import(IType type) {
if (type == null)
return null;
if (!recursionCounter.Increment())
return null;
IType result;
TypeDef td;
TypeRef tr;
TypeSpec ts;
TypeSig sig;
if ((td = type as TypeDef) != null)
result = Import(td);
else if ((tr = type as TypeRef) != null)
result = Import(tr);
else if ((ts = type as TypeSpec) != null)
result = Import(ts);
else if ((sig = type as TypeSig) != null)
result = Import(sig);
else
result = null;
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="TypeDef"/> as a <see cref="TypeRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public ITypeDefOrRef Import(TypeDef type) {
if (type == null)
return null;
if (TryToUseTypeDefs && type.Module == module)
return type;
return Import2(type);
}
TypeRef Import2(TypeDef type) {
if (type == null)
return null;
if (!recursionCounter.Increment())
return null;
TypeRef result;
var declType = type.DeclaringType;
if (declType != null)
result = module.UpdateRowId(new TypeRefUser(module, type.Namespace, type.Name, Import2(declType)));
else
result = module.UpdateRowId(new TypeRefUser(module, type.Namespace, type.Name, CreateScopeReference(type.DefinitionAssembly, type.Module)));
recursionCounter.Decrement();
return result;
}
IResolutionScope CreateScopeReference(IAssembly defAsm, ModuleDef defMod) {
if (defAsm == null)
return null;
var modAsm = module.Assembly;
if (defMod != null && defAsm != null && modAsm != null) {
if (UTF8String.CaseInsensitiveEquals(modAsm.Name, defAsm.Name)) {
if (UTF8String.CaseInsensitiveEquals(module.Name, defMod.Name))
return module;
return module.UpdateRowId(new ModuleRefUser(module, defMod.Name));
}
}
var pkt = PublicKeyBase.ToPublicKeyToken(defAsm.PublicKeyOrToken);
if (PublicKeyBase.IsNullOrEmpty2(pkt))
pkt = null;
return module.UpdateRowId(new AssemblyRefUser(defAsm.Name, defAsm.Version, pkt, defAsm.Culture) { Attributes = defAsm.Attributes & ~AssemblyAttributes.PublicKey });
}
/// <summary>
/// Imports a <see cref="TypeRef"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public ITypeDefOrRef Import(TypeRef type) {
return TryResolve(Import2(type));
}
TypeRef Import2(TypeRef type) {
if (type == null)
return null;
if (!recursionCounter.Increment())
return null;
TypeRef result;
var declaringType = type.DeclaringType;
if (declaringType != null)
result = module.UpdateRowId(new TypeRefUser(module, type.Namespace, type.Name, Import2(declaringType)));
else
result = module.UpdateRowId(new TypeRefUser(module, type.Namespace, type.Name, CreateScopeReference(type.DefinitionAssembly, type.Module)));
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="TypeSpec"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public TypeSpec Import(TypeSpec type) {
if (type == null)
return null;
return module.UpdateRowId(new TypeSpecUser(Import(type.TypeSig)));
}
/// <summary>
/// Imports a <see cref="TypeSig"/>
/// </summary>
/// <param name="type">The type</param>
/// <returns>The imported type or <c>null</c></returns>
public TypeSig Import(TypeSig type) {
if (type == null)
return null;
if (!recursionCounter.Increment())
return null;
TypeSig result;
switch (type.ElementType) {
case ElementType.Void: result = module.CorLibTypes.Void; break;
case ElementType.Boolean: result = module.CorLibTypes.Boolean; break;
case ElementType.Char: result = module.CorLibTypes.Char; break;
case ElementType.I1: result = module.CorLibTypes.SByte; break;
case ElementType.U1: result = module.CorLibTypes.Byte; break;
case ElementType.I2: result = module.CorLibTypes.Int16; break;
case ElementType.U2: result = module.CorLibTypes.UInt16; break;
case ElementType.I4: result = module.CorLibTypes.Int32; break;
case ElementType.U4: result = module.CorLibTypes.UInt32; break;
case ElementType.I8: result = module.CorLibTypes.Int64; break;
case ElementType.U8: result = module.CorLibTypes.UInt64; break;
case ElementType.R4: result = module.CorLibTypes.Single; break;
case ElementType.R8: result = module.CorLibTypes.Double; break;
case ElementType.String: result = module.CorLibTypes.String; break;
case ElementType.TypedByRef:result = module.CorLibTypes.TypedReference; break;
case ElementType.I: result = module.CorLibTypes.IntPtr; break;
case ElementType.U: result = module.CorLibTypes.UIntPtr; break;
case ElementType.Object: result = module.CorLibTypes.Object; break;
case ElementType.Ptr: result = new PtrSig(Import(type.Next)); break;
case ElementType.ByRef: result = new ByRefSig(Import(type.Next)); break;
case ElementType.ValueType: result = CreateClassOrValueType((type as ClassOrValueTypeSig).TypeDefOrRef, true); break;
case ElementType.Class: result = CreateClassOrValueType((type as ClassOrValueTypeSig).TypeDefOrRef, false); break;
case ElementType.Var: result = new GenericVar((type as GenericVar).Number, gpContext.Type); break;
case ElementType.ValueArray:result = new ValueArraySig(Import(type.Next), (type as ValueArraySig).Size); break;
case ElementType.FnPtr: result = new FnPtrSig(Import((type as FnPtrSig).Signature)); break;
case ElementType.SZArray: result = new SZArraySig(Import(type.Next)); break;
case ElementType.MVar: result = new GenericMVar((type as GenericMVar).Number, gpContext.Method); break;
case ElementType.CModReqd: result = new CModReqdSig(Import((type as ModifierSig).Modifier), Import(type.Next)); break;
case ElementType.CModOpt: result = new CModOptSig(Import((type as ModifierSig).Modifier), Import(type.Next)); break;
case ElementType.Module: result = new ModuleSig((type as ModuleSig).Index, Import(type.Next)); break;
case ElementType.Sentinel: result = new SentinelSig(); break;
case ElementType.Pinned: result = new PinnedSig(Import(type.Next)); break;
case ElementType.Array:
var arraySig = (ArraySig)type;
var sizes = new List<uint>(arraySig.Sizes);
var lbounds = new List<int>(arraySig.LowerBounds);
result = new ArraySig(Import(type.Next), arraySig.Rank, sizes, lbounds);
break;
case ElementType.GenericInst:
var gis = (GenericInstSig)type;
var genArgs = new List<TypeSig>(gis.GenericArguments.Count);
foreach (var ga in gis.GenericArguments.GetSafeEnumerable())
genArgs.Add(Import(ga));
result = new GenericInstSig(Import(gis.GenericType) as ClassOrValueTypeSig, genArgs);
break;
case ElementType.End:
case ElementType.R:
case ElementType.Internal:
default:
result = null;
break;
}
recursionCounter.Decrement();
return result;
}
ITypeDefOrRef Import(ITypeDefOrRef type) {
return (ITypeDefOrRef)Import((IType)type);
}
TypeSig CreateClassOrValueType(ITypeDefOrRef type, bool isValueType) {
var corLibType = module.CorLibTypes.GetCorLibTypeSig(type);
if (corLibType != null)
return corLibType;
if (isValueType)
return new ValueTypeSig(Import(type));
return new ClassSig(Import(type));
}
/// <summary>
/// Imports a <see cref="CallingConventionSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public CallingConventionSig Import(CallingConventionSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
CallingConventionSig result;
var sigType = sig.GetType();
if (sigType == typeof(MethodSig))
result = Import((MethodSig)sig);
else if (sigType == typeof(FieldSig))
result = Import((FieldSig)sig);
else if (sigType == typeof(GenericInstMethodSig))
result = Import((GenericInstMethodSig)sig);
else if (sigType == typeof(PropertySig))
result = Import((PropertySig)sig);
else if (sigType == typeof(LocalSig))
result = Import((LocalSig)sig);
else
result = null; // Should never be reached
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="FieldSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public FieldSig Import(FieldSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
var result = new FieldSig(sig.GetCallingConvention(), Import(sig.Type));
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="MethodSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public MethodSig Import(MethodSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
MethodSig result = Import(new MethodSig(sig.GetCallingConvention()), sig);
recursionCounter.Decrement();
return result;
}
T Import<T>(T sig, T old) where T : MethodBaseSig {
sig.RetType = Import(old.RetType);
foreach (var p in old.Params.GetSafeEnumerable())
sig.Params.Add(Import(p));
sig.GenParamCount = old.GenParamCount;
var paramsAfterSentinel = sig.ParamsAfterSentinel;
if (paramsAfterSentinel != null) {
foreach (var p in old.ParamsAfterSentinel.GetSafeEnumerable())
paramsAfterSentinel.Add(Import(p));
}
return sig;
}
/// <summary>
/// Imports a <see cref="PropertySig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public PropertySig Import(PropertySig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
PropertySig result = Import(new PropertySig(sig.GetCallingConvention()), sig);
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="LocalSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public LocalSig Import(LocalSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
LocalSig result = new LocalSig(sig.GetCallingConvention(), (uint)sig.Locals.Count);
foreach (var l in sig.Locals.GetSafeEnumerable())
result.Locals.Add(Import(l));
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="GenericInstMethodSig"/>
/// </summary>
/// <param name="sig">The sig</param>
/// <returns>The imported sig or <c>null</c> if input is invalid</returns>
public GenericInstMethodSig Import(GenericInstMethodSig sig) {
if (sig == null)
return null;
if (!recursionCounter.Increment())
return null;
GenericInstMethodSig result = new GenericInstMethodSig(sig.GetCallingConvention(), (uint)sig.GenericArguments.Count);
foreach (var l in sig.GenericArguments.GetSafeEnumerable())
result.GenericArguments.Add(Import(l));
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="IField"/>
/// </summary>
/// <param name="field">The field</param>
/// <returns>The imported type or <c>null</c> if <paramref name="field"/> is invalid</returns>
public IField Import(IField field) {
if (field == null)
return null;
if (!recursionCounter.Increment())
return null;
IField result;
MemberRef mr;
FieldDef fd;
if ((fd = field as FieldDef) != null)
result = Import(fd);
else if ((mr = field as MemberRef) != null)
result = Import(mr);
else
result = null;
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="IMethod"/>
/// </summary>
/// <param name="method">The method</param>
/// <returns>The imported method or <c>null</c> if <paramref name="method"/> is invalid</returns>
public IMethod Import(IMethod method) {
if (method == null)
return null;
if (!recursionCounter.Increment())
return null;
IMethod result;
MethodDef md;
MethodSpec ms;
MemberRef mr;
if ((md = method as MethodDef) != null)
result = Import(md);
else if ((ms = method as MethodSpec) != null)
result = Import(ms);
else if ((mr = method as MemberRef) != null)
result = Import(mr);
else
result = null;
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="FieldDef"/> as an <see cref="IField"/>
/// </summary>
/// <param name="field">The field</param>
/// <returns>The imported type or <c>null</c> if <paramref name="field"/> is invalid</returns>
public IField Import(FieldDef field) {
if (field == null)
return null;
if (TryToUseFieldDefs && field.Module == module)
return field;
if (!recursionCounter.Increment())
return null;
MemberRef result = module.UpdateRowId(new MemberRefUser(module, field.Name));
result.Signature = Import(field.Signature);
result.Class = ImportParent(field.DeclaringType);
recursionCounter.Decrement();
return result;
}
IMemberRefParent ImportParent(TypeDef type) {
if (type == null)
return null;
if (type.IsGlobalModuleType) {
var om = type.Module;
return module.UpdateRowId(new ModuleRefUser(module, om == null ? null : om.Name));
}
return Import(type);
}
/// <summary>
/// Imports a <see cref="MethodDef"/> as an <see cref="IMethod"/>
/// </summary>
/// <param name="method">The method</param>
/// <returns>The imported method or <c>null</c> if <paramref name="method"/> is invalid</returns>
public IMethod Import(MethodDef method) {
if (method == null)
return null;
if (TryToUseMethodDefs && method.Module == module)
return method;
if (!recursionCounter.Increment())
return null;
MemberRef result = module.UpdateRowId(new MemberRefUser(module, method.Name));
result.Signature = Import(method.Signature);
result.Class = ImportParent(method.DeclaringType);
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="MethodSpec"/>
/// </summary>
/// <param name="method">The method</param>
/// <returns>The imported method or <c>null</c> if <paramref name="method"/> is invalid</returns>
public MethodSpec Import(MethodSpec method) {
if (method == null)
return null;
if (!recursionCounter.Increment())
return null;
MethodSpec result = module.UpdateRowId(new MethodSpecUser((IMethodDefOrRef)Import(method.Method)));
result.Instantiation = Import(method.Instantiation);
recursionCounter.Decrement();
return result;
}
/// <summary>
/// Imports a <see cref="MemberRef"/>
/// </summary>
/// <param name="memberRef">The member ref</param>
/// <returns>The imported member ref or <c>null</c> if <paramref name="memberRef"/> is invalid</returns>
public MemberRef Import(MemberRef memberRef) {
if (memberRef == null)
return null;
if (!recursionCounter.Increment())
return null;
MemberRef result = module.UpdateRowId(new MemberRefUser(module, memberRef.Name));
result.Signature = Import(memberRef.Signature);
result.Class = Import(memberRef.Class);
if (result.Class == null) // Will be null if memberRef.Class is null or a MethodDef
result = null;
recursionCounter.Decrement();
return result;
}
IMemberRefParent Import(IMemberRefParent parent) {
var tdr = parent as ITypeDefOrRef;
if (tdr != null) {
var td = tdr as TypeDef;
if (td != null && td.IsGlobalModuleType) {
var om = td.Module;
return module.UpdateRowId(new ModuleRefUser(module, om == null ? null : om.Name));
}
return Import(tdr);
}
var modRef = parent as ModuleRef;
if (modRef != null)
return module.UpdateRowId(new ModuleRefUser(module, modRef.Name));
var method = parent as MethodDef;
if (method != null) {
var dt = method.DeclaringType;
return dt == null || dt.Module != module ? null : method;
}
return null;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type ProfilePhotoRequest.
/// </summary>
public partial class ProfilePhotoRequest : BaseRequest, IProfilePhotoRequest
{
/// <summary>
/// Constructs a new ProfilePhotoRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public ProfilePhotoRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified ProfilePhoto using POST.
/// </summary>
/// <param name="profilePhotoToCreate">The ProfilePhoto to create.</param>
/// <returns>The created ProfilePhoto.</returns>
public System.Threading.Tasks.Task<ProfilePhoto> CreateAsync(ProfilePhoto profilePhotoToCreate)
{
return this.CreateAsync(profilePhotoToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified ProfilePhoto using POST.
/// </summary>
/// <param name="profilePhotoToCreate">The ProfilePhoto to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ProfilePhoto.</returns>
public async System.Threading.Tasks.Task<ProfilePhoto> CreateAsync(ProfilePhoto profilePhotoToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<ProfilePhoto>(profilePhotoToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified ProfilePhoto.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified ProfilePhoto.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<ProfilePhoto>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified ProfilePhoto.
/// </summary>
/// <returns>The ProfilePhoto.</returns>
public System.Threading.Tasks.Task<ProfilePhoto> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified ProfilePhoto.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The ProfilePhoto.</returns>
public async System.Threading.Tasks.Task<ProfilePhoto> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<ProfilePhoto>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified ProfilePhoto using PATCH.
/// </summary>
/// <param name="profilePhotoToUpdate">The ProfilePhoto to update.</param>
/// <returns>The updated ProfilePhoto.</returns>
public System.Threading.Tasks.Task<ProfilePhoto> UpdateAsync(ProfilePhoto profilePhotoToUpdate)
{
return this.UpdateAsync(profilePhotoToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified ProfilePhoto using PATCH.
/// </summary>
/// <param name="profilePhotoToUpdate">The ProfilePhoto to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated ProfilePhoto.</returns>
public async System.Threading.Tasks.Task<ProfilePhoto> UpdateAsync(ProfilePhoto profilePhotoToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<ProfilePhoto>(profilePhotoToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IProfilePhotoRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IProfilePhotoRequest Expand(Expression<Func<ProfilePhoto, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IProfilePhotoRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IProfilePhotoRequest Select(Expression<Func<ProfilePhoto, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="profilePhotoToInitialize">The <see cref="ProfilePhoto"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(ProfilePhoto profilePhotoToInitialize)
{
}
}
}
| |
namespace android.database
{
[global::MonoJavaBridge.JavaClass()]
public partial class CursorWindow : android.database.sqlite.SQLiteClosable, android.os.Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected CursorWindow(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
protected override void finalize()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.CursorWindow.staticClass, "finalize", "()V", ref global::android.database.CursorWindow._m0);
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual short getShort(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::android.database.CursorWindow.staticClass, "getShort", "(II)S", ref global::android.database.CursorWindow._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual int getInt(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.CursorWindow.staticClass, "getInt", "(II)I", ref global::android.database.CursorWindow._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual long getLong(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.database.CursorWindow.staticClass, "getLong", "(II)J", ref global::android.database.CursorWindow._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual bool putLong(long arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "putLong", "(JII)Z", ref global::android.database.CursorWindow._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual float getFloat(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.database.CursorWindow.staticClass, "getFloat", "(II)F", ref global::android.database.CursorWindow._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual double getDouble(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::android.database.CursorWindow.staticClass, "getDouble", "(II)D", ref global::android.database.CursorWindow._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual bool putDouble(double arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "putDouble", "(DII)Z", ref global::android.database.CursorWindow._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void clear()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.CursorWindow.staticClass, "clear", "()V", ref global::android.database.CursorWindow._m8);
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void close()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.CursorWindow.staticClass, "close", "()V", ref global::android.database.CursorWindow._m9);
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual global::java.lang.String getString(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.database.CursorWindow.staticClass, "getString", "(II)Ljava/lang/String;", ref global::android.database.CursorWindow._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual bool putNull(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "putNull", "(II)Z", ref global::android.database.CursorWindow._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.CursorWindow.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.database.CursorWindow._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual int describeContents()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.CursorWindow.staticClass, "describeContents", "()I", ref global::android.database.CursorWindow._m13);
}
private static global::MonoJavaBridge.MethodId _m14;
protected override void onAllReferencesReleased()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.CursorWindow.staticClass, "onAllReferencesReleased", "()V", ref global::android.database.CursorWindow._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual bool putString(java.lang.String arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "putString", "(Ljava/lang/String;II)Z", ref global::android.database.CursorWindow._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual byte[] getBlob(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.database.CursorWindow.staticClass, "getBlob", "(II)[B", ref global::android.database.CursorWindow._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as byte[];
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void copyStringToBuffer(int arg0, int arg1, android.database.CharArrayBuffer arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.CursorWindow.staticClass, "copyStringToBuffer", "(IILandroid/database/CharArrayBuffer;)V", ref global::android.database.CursorWindow._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual bool isNull(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "isNull", "(II)Z", ref global::android.database.CursorWindow._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new int StartPosition
{
get
{
return getStartPosition();
}
set
{
setStartPosition(value);
}
}
private static global::MonoJavaBridge.MethodId _m19;
public virtual int getStartPosition()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.CursorWindow.staticClass, "getStartPosition", "()I", ref global::android.database.CursorWindow._m19);
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual void setStartPosition(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.CursorWindow.staticClass, "setStartPosition", "(I)V", ref global::android.database.CursorWindow._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int NumRows
{
get
{
return getNumRows();
}
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual int getNumRows()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.database.CursorWindow.staticClass, "getNumRows", "()I", ref global::android.database.CursorWindow._m21);
}
public new int NumColumns
{
set
{
setNumColumns(value);
}
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual bool setNumColumns(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "setNumColumns", "(I)Z", ref global::android.database.CursorWindow._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual bool allocRow()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "allocRow", "()Z", ref global::android.database.CursorWindow._m23);
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual void freeLastRow()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.database.CursorWindow.staticClass, "freeLastRow", "()V", ref global::android.database.CursorWindow._m24);
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual bool putBlob(byte[] arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "putBlob", "([BII)Z", ref global::android.database.CursorWindow._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual bool isBlob(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "isBlob", "(II)Z", ref global::android.database.CursorWindow._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual bool isLong(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "isLong", "(II)Z", ref global::android.database.CursorWindow._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual bool isFloat(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "isFloat", "(II)Z", ref global::android.database.CursorWindow._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual bool isString(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.database.CursorWindow.staticClass, "isString", "(II)Z", ref global::android.database.CursorWindow._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m30;
public static global::android.database.CursorWindow newFromParcel(android.os.Parcel arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.database.CursorWindow._m30.native == global::System.IntPtr.Zero)
global::android.database.CursorWindow._m30 = @__env.GetStaticMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "newFromParcel", "(Landroid/os/Parcel;)Landroid/database/CursorWindow;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.database.CursorWindow.staticClass, global::android.database.CursorWindow._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.CursorWindow;
}
private static global::MonoJavaBridge.MethodId _m31;
public CursorWindow(bool arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.database.CursorWindow._m31.native == global::System.IntPtr.Zero)
global::android.database.CursorWindow._m31 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "<init>", "(Z)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.database.CursorWindow.staticClass, global::android.database.CursorWindow._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _CREATOR2199;
public static global::android.os.Parcelable_Creator CREATOR
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.database.CursorWindow.staticClass, _CREATOR2199)) as android.os.Parcelable_Creator;
}
}
static CursorWindow()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.database.CursorWindow.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/CursorWindow"));
global::android.database.CursorWindow._CREATOR2199 = @__env.GetStaticFieldIDNoThrow(global::android.database.CursorWindow.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;");
}
}
}
| |
/*
Copyright (c) 2012-2015, Coherent Labs AD
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 Coherent UI nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Coherent.UI.Mobile;
using Coherent.UI.Mobile.Binding;
namespace Coherent.UI.Binding
{
internal delegate void ManagedCallback(IntPtr data, double id);
class Invoker
{
internal Invoker(Binder binder, System.Delegate callback)
{
Binder = binder;
Callback = callback;
var parameters = callback.Method.GetParameters();
DelegateIsMethodStub = parameters.Length > 1 && parameters[0].ParameterType == typeof(MethodBinding);
var skipParameters = (DelegateIsMethodStub) ? 1 : 0;
Arguments = new object[parameters.Length - skipParameters];
ArgumentGetters = (from parameter in parameters.Skip(skipParameters)
select Importer.CreateArgumentGetter(parameter.ParameterType))
.ToArray<Importer.ReadDelegate>();
}
internal void Invoke(IntPtr data, double id)
{
var importer = Binder.GetImporter(data);
bool executeHandler = true;
var arguments = importer.BeginArgumentList();
var argumentsCount = Arguments.Length;
if (arguments < argumentsCount)
{
for (var i = arguments; i < argumentsCount; ++i)
{
Binder.InvalidArgument(ScriptCallErrorType.SCE_ArgumentType, String.Format("Missing argument {0}", i));
}
executeHandler = false;
}
if (executeHandler)
{
var argumentsOffest = (!DelegateIsMethodStub) ? 0 : 1;
for (var i = 0; i < argumentsCount; ++i)
{
try
{
Arguments[i] = ArgumentGetters[i](importer);
}
catch (BindingException e)
{
Binder.InvalidArgument(
e.Error, String.Format(e.Message, i));
executeHandler = false;
}
}
}
ExecuteAndSendResult(Binder, Callback, Arguments, id, executeHandler, DelegateIsMethodStub);
}
static internal void ExecuteAndSendResult(Binder binder, System.Delegate callback, object[] arguments, double id, bool execute, bool isDynamic)
{
object result = null;
if (execute)
{
if (!isDynamic)
{
foreach (var invocation in callback.GetInvocationList())
{
result = invocation.Method.Invoke(invocation.Target, arguments);
}
}
else
{
result = callback.DynamicInvoke(arguments);
}
if (result != null && id != 0)
{
binder.Return(id, result);
}
}
else
{
binder.SendError();
}
}
private object[] Arguments;
#if COHERENT_PLATFORM_IOS || COHERENT_PLATFORM_ANDROID
private Importer.ReadDelegate[] ArgumentGetters;
#else
private Importer.ReadDelegate<object>[] ArgumentGetters;
#endif
private System.Delegate Callback;
private Binder Binder;
private bool DelegateIsMethodStub;
}
internal class GenericInvoker
{
internal GenericInvoker(Binder binder, System.Delegate callback)
{
Binder = binder;
Callback = callback;
Arguments = new object[2];
if (GenericSignature == null)
{
GenericSignature = new System.Type[] { typeof(string), typeof(Value[]) };
}
var parameterTypes = from parameter in Callback.Method.GetParameters() select parameter.ParameterType;
if (!parameterTypes.SequenceEqual(GenericSignature))
{
throw new UnsupportedCallbackException("Generic callback must have signature (string, Coherent.UI.Binding.Value[])");
}
}
internal void Invoke(IntPtr data, double id)
{
var importer = Binder.GetImporter(data);
bool executeHandler = true;
var argumentsCount = importer.BeginArgumentList();
try {
Arguments[0] = importer.Read<string>();
}
catch (BindingException e)
{
Binder.InvalidArgument(e.Error, String.Format(e.Message, "1"));
executeHandler = false;
}
Value[] arguments = new Value[argumentsCount - 1];
var ReadValue = (System.Func<Value>)importer.Read<Value>;
for (var i = 1; i < argumentsCount; ++i)
{
try {
arguments[i - 1] = ReadValue();
}
catch (BindingException e)
{
Binder.InvalidArgument(e.Error, String.Format(e.Message, i));
executeHandler = false;
}
}
Arguments[1] = arguments;
Invoker.ExecuteAndSendResult(Binder, Callback, Arguments, id, executeHandler, false);
}
private System.Delegate Callback;
private Binder Binder;
private object[] Arguments;
private static System.Type[] GenericSignature;
}
internal partial class Binder: IDisposable
{
internal Binder()
{
RawBinder = View.GetBinder();
PlatformInitialize();
}
internal Binder(View view)
{
View = view;
RawBinder = View.GetBinder();
PlatformInitialize();
}
private ManagedCallback CreateGenericCallback(System.Delegate callback)
{
var invoker = new GenericInvoker(this, callback);
return invoker.Invoke;
}
private ManagedCallback CreateCallback(System.Delegate callback)
{
var invoker = new Invoker(this, callback);
return invoker.Invoke;
}
internal Importer GetImporter(IntPtr data)
{
Importer.SetData(data);
return Importer;
}
internal Exporter GetExporter()
{
Exporter.ResetData();
return Exporter;
}
internal void SendError()
{
RawBinder.RawResult(0, null);
}
internal void Return(double id, object result)
{
var exporter = GetExporter();
exporter.Export(result);
RawBinder.RawResult(exporter.GetBytesCount(), exporter.GetBytes());
}
internal void InvalidArgument(ScriptCallErrorType error, string message)
{
View.SetScriptError(error, message);
}
private Importer Importer = new Importer(new BlobReader());
private Exporter Exporter = new Exporter(new BlobWriter());
private View View;
internal DotNetBinder RawBinder;
private DotNetBinder.BindingsCallback BindingsReleased;
private DotNetBinder.BindingsCallback BindingsReadyDelegate;
private MethodBinding m_MethodBinding = new MethodBinding();
}
}
| |
/*
* Copyright 2013 Olivier Caron-Lizotte
* olivierlizotte@gmail.com
* Licensed under the MIT license: <http://www.opensource.org/licenses/mit-license.php>
*/
using System.Collections.Generic;
using System;
namespace PeptidAce
{
public class stPeptide
{
public string Sequence;
public List<string> Proteins;
}
/// <summary>
/// Peptide class, mostly as its defined in Morpheus, with a few twists
/// </summary>
public class Peptide : AminoAcidPolymer
{
public Protein Parent { get; set; }
public int StartResidueNumber { get; set; }
public int EndResidueNumber { get; set; }
public int MissedCleavages { get; set; }
public char PreviousAminoAcid { get; set; }
public char NextAminoAcid { get; set; }
public bool Decoy{get; set;}
/*{
get { return Parent.Decoy; }
private set { }
}//*/
public bool Target
{
get { return !Decoy; }
private set { Decoy = !value; }
}
public string ExtendedSequence()
{
return PreviousAminoAcid.ToString() + '.' + Sequence + '.' + NextAminoAcid.ToString();
}
public string ExtendedLeucineSequence()
{
return ExtendedSequence().Replace('I', 'L');
}
public string ModificationString()
{
string cumul = "";
foreach (int key in VariableModifications.Keys)
cumul += key + "[" + VariableModifications[key].Description + "]";
return cumul;
}
public bool IsSamePeptide(Peptide peptide, bool checkMods)
{
if (BaseSequence.Equals(peptide.BaseSequence))
{
if (checkMods)
{
if (VariableModifications != null && peptide.VariableModifications != null)
foreach (int key in VariableModifications.Keys)
if (!peptide.VariableModifications.ContainsKey(key) || VariableModifications[key] != peptide.VariableModifications[key])
return false;
}
return true;
}
else
return false;
}
public Peptide()
{
}
public static string GetSequence(string protSequence, int start, int stop)
{
if(start < stop)
return protSequence.Substring(start, stop - start + 1);
else
{
char[] sequence_array = protSequence.Substring(stop, start - stop + 1).ToCharArray();
Array.Reverse(sequence_array);
return new string(sequence_array);
}
}
public Peptide Reverse()
{
return new Peptide(Parent, EndResidueNumber-1, StartResidueNumber-1, MissedCleavages);
}
public Peptide(string sequence, bool decoy)
: base(sequence, true)
{
StartResidueNumber = 1;
EndResidueNumber = Length;
MissedCleavages = 0;
this.Decoy = decoy;
NextAminoAcid = '-';
PreviousAminoAcid = '-';
}
public Peptide(string sequence)
: base(sequence, true)
{
StartResidueNumber = 1;
EndResidueNumber = Length;
MissedCleavages = 0;
this.Decoy = false;
NextAminoAcid = '-';
PreviousAminoAcid = '-';
}
public Peptide(string sequence, Dictionary<int, Modification> mods)
: base(sequence, true)
{
StartResidueNumber = 1;
EndResidueNumber = Length;
MissedCleavages = 0;
this.Decoy = false;
NextAminoAcid = '-';
PreviousAminoAcid = '-';
SetVariableModifications(mods);
}
public Peptide(Protein parent, int startResidueNumber, int endResidueNumber, int missedCleavages)
: base(GetSequence(parent.BaseSequence, startResidueNumber, endResidueNumber), true)
{
Parent = parent;
Decoy = parent.Decoy;
StartResidueNumber = startResidueNumber + 1;
EndResidueNumber = endResidueNumber + 1;
MissedCleavages = missedCleavages;
if (startResidueNumber < endResidueNumber)
{
if (startResidueNumber - 1 >= 0)
PreviousAminoAcid = parent[startResidueNumber - 1];
else
PreviousAminoAcid = '-';
if (endResidueNumber + 1 < parent.Length)
NextAminoAcid = parent[endResidueNumber + 1];
else
NextAminoAcid = '-';
}
else
{
//Reverse sequences are decoy
Decoy = true;
if (endResidueNumber - 1 >= 0)
PreviousAminoAcid = parent[endResidueNumber - 1];
else
PreviousAminoAcid = '-';
if (startResidueNumber + 1 < parent.Length)
NextAminoAcid = parent[startResidueNumber + 1];
else
NextAminoAcid = '-';
}
}
public double[] GetMasses()
{
double cumul = Utilities.Constants.WATER_MONOISOTOPIC_MASS;
double[] array = new double[BaseSequence.Length];
for (int r = 1; r <= BaseSequence.Length; r++)
{
double tmp = 0;
if (FixedModifications != null && FixedModifications.ContainsKey(r + 1))
foreach (Modification mod in FixedModifications[r + 1])
tmp += mod.MonoisotopicMassShift;
if (VariableModifications != null && VariableModifications.ContainsKey(r + 1))
tmp += VariableModifications[r + 1].MonoisotopicMassShift;
array[r - 1] = AminoAcidMasses.GetMonoisotopicMass(BaseSequence[r - 1]) + tmp;
cumul += array[r - 1];
}
return array;
}
private Peptide(Peptide peptide)
: base()
{
StartResidueNumber = peptide.StartResidueNumber;
EndResidueNumber = peptide.EndResidueNumber;
MissedCleavages = peptide.MissedCleavages;
this.Decoy = peptide.Decoy;
NextAminoAcid = peptide.NextAminoAcid;
PreviousAminoAcid = peptide.PreviousAminoAcid;
Parent = peptide.Parent;
BaseSequence = peptide.BaseSequence;
_preCompSeq = peptide._preCompSeq;
fixedModifications = peptide.fixedModifications;
}
public IEnumerable<Peptide> GetVariablyModifiedPeptides(IEnumerable<Modification> variableModifications, int maximumVariableModificationIsoforms)
{
Dictionary<int, List<Modification>> possible_modifications = new Dictionary<int, List<Modification>>(Length + 4);
foreach(Modification variable_modification in variableModifications)
{
if(variable_modification.Type == ModificationType.ProteinNTerminus && (StartResidueNumber == 1 || (StartResidueNumber == 2 && Parent[0] == 'M')))
{
List<Modification> prot_n_term_variable_mods;
if(!possible_modifications.TryGetValue(0, out prot_n_term_variable_mods))
{
prot_n_term_variable_mods = new List<Modification>();
prot_n_term_variable_mods.Add(variable_modification);
possible_modifications.Add(0, prot_n_term_variable_mods);
}
else
{
prot_n_term_variable_mods.Add(variable_modification);
}
}
if(variable_modification.Type == ModificationType.PeptideNTerminus)
{
List<Modification> pep_n_term_variable_mods;
if(!possible_modifications.TryGetValue(1, out pep_n_term_variable_mods))
{
pep_n_term_variable_mods = new List<Modification>();
pep_n_term_variable_mods.Add(variable_modification);
possible_modifications.Add(1, pep_n_term_variable_mods);
}
else
{
pep_n_term_variable_mods.Add(variable_modification);
}
}
for(int r = 0; r < Length; r++)
{
if(variable_modification.Type == ModificationType.AminoAcidResidue && this[r] == variable_modification.AminoAcid)
{
List<Modification> residue_variable_mods;
if(!possible_modifications.TryGetValue(r + 2, out residue_variable_mods))
{
residue_variable_mods = new List<Modification>();
residue_variable_mods.Add(variable_modification);
possible_modifications.Add(r + 2, residue_variable_mods);
}
else
{
residue_variable_mods.Add(variable_modification);
}
}
}
if(variable_modification.Type == ModificationType.PeptideCTerminus)
{
List<Modification> pep_c_term_variable_mods;
if(!possible_modifications.TryGetValue(Length + 2, out pep_c_term_variable_mods))
{
pep_c_term_variable_mods = new List<Modification>();
pep_c_term_variable_mods.Add(variable_modification);
possible_modifications.Add(Length + 2, pep_c_term_variable_mods);
}
else
{
pep_c_term_variable_mods.Add(variable_modification);
}
}
if(variable_modification.Type == ModificationType.ProteinCTerminus && (EndResidueNumber == Parent.Length - 1))
{
List<Modification> prot_c_term_variable_mods;
if(!possible_modifications.TryGetValue(Length + 3, out prot_c_term_variable_mods))
{
prot_c_term_variable_mods = new List<Modification>();
prot_c_term_variable_mods.Add(variable_modification);
possible_modifications.Add(Length + 3, prot_c_term_variable_mods);
}
else
{
prot_c_term_variable_mods.Add(variable_modification);
}
}
}
//int variable_modification_isoforms = 0;
foreach (Dictionary<int, Modification> kvp in GetVariableModificationPatterns(possible_modifications, maximumVariableModificationIsoforms))
{
Peptide peptide = new Peptide(this);
//peptide.SetFixedModifications(FixedModifications);
peptide.SetVariableModifications(kvp);
yield return peptide;
//variable_modification_isoforms++;
//if(variable_modification_isoforms >= maximumVariableModificationIsoforms)
//{
// yield break;
//}
}
}
public IEnumerable<Peptide> GetSNPsdPeptides()
{
string strCumul = "";
for (int i = 0; i < BaseSequence.Length; i++)
{
foreach (char letter in AminoAcidMasses.AMINO_ACIDS)
{
if (BaseSequence[i] != letter)
{
Peptide newPeptide = new Peptide(this);
if (i + 1 < BaseSequence.Length)
newPeptide.BaseSequence = strCumul + letter + BaseSequence.Substring(i + 1);
else
newPeptide.BaseSequence = strCumul + letter;
yield return newPeptide;
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Reflection.Metadata
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
public unsafe struct BlobReader
{
/// <summary>An array containing the '\0' character.</summary>
private static readonly char[] s_nullCharArray = new char[1] { '\0' };
internal const int InvalidCompressedInteger = int.MaxValue;
private readonly MemoryBlock _block;
// Points right behind the last byte of the block.
private readonly byte* _endPointer;
private byte* _currentPointer;
/// <summary>
/// Creates a reader of the specified memory block.
/// </summary>
/// <param name="buffer">Pointer to the start of the memory block.</param>
/// <param name="length">Length in bytes of the memory block.</param>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is null and <paramref name="length"/> is greater than zero.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is negative.</exception>
/// <exception cref="PlatformNotSupportedException">The current platform is not little-endian.</exception>
public BlobReader(byte* buffer, int length)
: this(MemoryBlock.CreateChecked(buffer, length))
{
}
internal BlobReader(MemoryBlock block)
{
Debug.Assert(block.Length >= 0 && (block.Pointer != null || block.Length == 0));
_block = block;
_currentPointer = block.Pointer;
_endPointer = block.Pointer + block.Length;
}
internal string GetDebuggerDisplay()
{
if (_block.Pointer == null)
{
return "<null>";
}
int displayedBytes;
string display = _block.GetDebuggerDisplay(out displayedBytes);
if (this.Offset < displayedBytes)
{
display = display.Insert(this.Offset * 3, "*");
}
else if (displayedBytes == _block.Length)
{
display += "*";
}
else
{
display += "*...";
}
return display;
}
#region Offset, Skipping, Marking, Alignment, Bounds Checking
/// <summary>
/// Pointer to the byte at the start of the underlying memory block.
/// </summary>
public byte* StartPointer => _block.Pointer;
/// <summary>
/// Pointer to the byte at the current position of the reader.
/// </summary>
public byte* CurrentPointer => _currentPointer;
/// <summary>
/// The total length of the underlying memory block.
/// </summary>
public int Length => _block.Length;
/// <summary>
/// Gets or sets the offset from start of the blob to the current position.
/// </summary>
/// <exception cref="BadImageFormatException">Offset is set outside the bounds of underlying reader.</exception>
public int Offset
{
get
{
return (int)(_currentPointer - _block.Pointer);
}
set
{
if (unchecked((uint)value) > (uint)_block.Length)
{
Throw.OutOfBounds();
}
_currentPointer = _block.Pointer + value;
}
}
/// <summary>
/// Bytes remaining from current position to end of underlying memory block.
/// </summary>
public int RemainingBytes => (int)(_endPointer - _currentPointer);
/// <summary>
/// Repositions the reader to the start of the underluing memory block.
/// </summary>
public void Reset()
{
_currentPointer = _block.Pointer;
}
/// <summary>
/// Repositions the reader forward by the number of bytes required to satisfy the given alignment.
/// </summary>
public void Align(byte alignment)
{
if (!TryAlign(alignment))
{
Throw.OutOfBounds();
}
}
internal bool TryAlign(byte alignment)
{
int remainder = this.Offset & (alignment - 1);
Debug.Assert((alignment & (alignment - 1)) == 0, "Alignment must be a power of two.");
Debug.Assert(remainder >= 0 && remainder < alignment);
if (remainder != 0)
{
int bytesToSkip = alignment - remainder;
if (bytesToSkip > RemainingBytes)
{
return false;
}
_currentPointer += bytesToSkip;
}
return true;
}
internal MemoryBlock GetMemoryBlockAt(int offset, int length)
{
CheckBounds(offset, length);
return new MemoryBlock(_currentPointer + offset, length);
}
#endregion
#region Bounds Checking
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int offset, int byteCount)
{
if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)(_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void CheckBounds(int byteCount)
{
if (unchecked((uint)byteCount) > (_endPointer - _currentPointer))
{
Throw.OutOfBounds();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance(int length)
{
byte* p = _currentPointer;
if (unchecked((uint)length) > (uint)(_endPointer - p))
{
Throw.OutOfBounds();
}
_currentPointer = p + length;
return p;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private byte* GetCurrentPointerAndAdvance1()
{
byte* p = _currentPointer;
if (p == _endPointer)
{
Throw.OutOfBounds();
}
_currentPointer = p + 1;
return p;
}
#endregion
#region Read Methods
public bool ReadBoolean()
{
// It's not clear from the ECMA spec what exactly is the encoding of Boolean.
// Some metadata writers encode "true" as 0xff, others as 1. So we treat all non-zero values as "true".
//
// We propose to clarify and relax the current wording in the spec as follows:
//
// Chapter II.16.2 "Field init metadata"
// ... bool '(' true | false ')' Boolean value stored in a single byte, 0 represents false, any non-zero value represents true ...
//
// Chapter 23.3 "Custom attributes"
// ... A bool is a single byte with value 0 representing false and any non-zero value representing true ...
return ReadByte() != 0;
}
public sbyte ReadSByte()
{
return *(sbyte*)GetCurrentPointerAndAdvance1();
}
public byte ReadByte()
{
return *(byte*)GetCurrentPointerAndAdvance1();
}
public char ReadChar()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(char));
return (char)(ptr[0] + (ptr[1] << 8));
}
}
public short ReadInt16()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(short));
return (short)(ptr[0] + (ptr[1] << 8));
}
}
public ushort ReadUInt16()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(ushort));
return (ushort)(ptr[0] + (ptr[1] << 8));
}
}
public int ReadInt32()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(int));
return (int)(ptr[0] + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24));
}
}
public uint ReadUInt32()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(uint));
return (uint)(ptr[0] + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24));
}
}
public long ReadInt64()
{
unchecked
{
byte* ptr = GetCurrentPointerAndAdvance(sizeof(long));
uint lo = (uint)(ptr[0] + (ptr[1] << 8) + (ptr[2] << 16) + (ptr[3] << 24));
uint hi = (uint)(ptr[4] + (ptr[5] << 8) + (ptr[6] << 16) + (ptr[7] << 24));
return (long)(lo + ((ulong)hi << 32));
}
}
public ulong ReadUInt64()
{
return unchecked((ulong)ReadInt64());
}
public float ReadSingle()
{
int val = ReadInt32();
return *(float*)&val;
}
public double ReadDouble()
{
long val = ReadInt64();
return *(double*)&val;
}
public Guid ReadGuid()
{
const int size = 16;
byte * ptr = GetCurrentPointerAndAdvance(size);
if (BitConverter.IsLittleEndian)
{
return *(Guid*)ptr;
}
else
{
unchecked
{
return new Guid(
(int)(ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24)),
(short)(ptr[4] | (ptr[5] << 8)),
(short)(ptr[6] | (ptr[7] << 8)),
ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]);
}
}
}
/// <summary>
/// Reads <see cref="decimal"/> number.
/// </summary>
/// <remarks>
/// Decimal number is encoded in 13 bytes as follows:
/// - byte 0: highest bit indicates sign (1 for negative, 0 for non-negative); the remaining 7 bits encode scale
/// - bytes 1..12: 96-bit unsigned integer in little endian encoding.
/// </remarks>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid <see cref="decimal"/> number.</exception>
public decimal ReadDecimal()
{
byte* ptr = GetCurrentPointerAndAdvance(13);
byte scale = (byte)(*ptr & 0x7f);
if (scale > 28)
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
unchecked
{
return new decimal(
(int)(ptr[1] | (ptr[2] << 8) | (ptr[3] << 16) | (ptr[4] << 24)),
(int)(ptr[5] | (ptr[6] << 8) | (ptr[7] << 16) | (ptr[8] << 24)),
(int)(ptr[9] | (ptr[10] << 8) | (ptr[11] << 16) | (ptr[12] << 24)),
isNegative: (*ptr & 0x80) != 0,
scale: scale);
}
}
public DateTime ReadDateTime()
{
return new DateTime(ReadInt64());
}
public SignatureHeader ReadSignatureHeader()
{
return new SignatureHeader(ReadByte());
}
/// <summary>
/// Finds specified byte in the blob following the current position.
/// </summary>
/// <returns>
/// Index relative to the current position, or -1 if the byte is not found in the blob following the current position.
/// </returns>
/// <remarks>
/// Doesn't change the current position.
/// </remarks>
public int IndexOf(byte value)
{
int start = Offset;
int absoluteIndex = _block.IndexOfUnchecked(value, start);
return (absoluteIndex >= 0) ? absoluteIndex - start : -1;
}
/// <summary>
/// Reads UTF8 encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF8(int byteCount)
{
string s = _block.PeekUtf8(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads UTF16 (little-endian) encoded string starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The string.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public string ReadUTF16(int byteCount)
{
string s = _block.PeekUtf16(this.Offset, byteCount);
_currentPointer += byteCount;
return s;
}
/// <summary>
/// Reads bytes starting at the current position.
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <returns>The byte array.</returns>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public byte[] ReadBytes(int byteCount)
{
byte[] bytes = _block.PeekBytes(this.Offset, byteCount);
_currentPointer += byteCount;
return bytes;
}
/// <summary>
/// Reads bytes starting at the current position in to the given buffer at the given offset;
/// </summary>
/// <param name="byteCount">The number of bytes to read.</param>
/// <param name="buffer">The destination buffer the bytes read will be written.</param>
/// <param name="bufferOffset">The offset in the destination buffer where the bytes read will be written.</param>
/// <exception cref="BadImageFormatException"><paramref name="byteCount"/> bytes not available.</exception>
public void ReadBytes(int byteCount, byte[] buffer, int bufferOffset)
{
Marshal.Copy((IntPtr)GetCurrentPointerAndAdvance(byteCount), buffer, bufferOffset, byteCount);
}
internal string ReadUtf8NullTerminated()
{
int bytesRead;
string value = _block.PeekUtf8NullTerminated(this.Offset, null, MetadataStringDecoder.DefaultUTF8, out bytesRead, '\0');
_currentPointer += bytesRead;
return value;
}
private int ReadCompressedIntegerOrInvalid()
{
int bytesRead;
int value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
_currentPointer += bytesRead;
return value;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedInteger(out int value)
{
value = ReadCompressedIntegerOrInvalid();
return value != InvalidCompressedInteger;
}
/// <summary>
/// Reads an unsigned compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedInteger()
{
int value;
if (!TryReadCompressedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <param name="value">The value of the compressed integer that was read.</param>
/// <returns>true if the value was read successfully. false if the data at the current position was not a valid compressed integer.</returns>
public bool TryReadCompressedSignedInteger(out int value)
{
int bytesRead;
value = _block.PeekCompressedInteger(this.Offset, out bytesRead);
if (value == InvalidCompressedInteger)
{
return false;
}
bool signExtend = (value & 0x1) != 0;
value >>= 1;
if (signExtend)
{
switch (bytesRead)
{
case 1:
value |= unchecked((int)0xffffffc0);
break;
case 2:
value |= unchecked((int)0xffffe000);
break;
default:
Debug.Assert(bytesRead == 4);
value |= unchecked((int)0xf0000000);
break;
}
}
_currentPointer += bytesRead;
return true;
}
/// <summary>
/// Reads a signed compressed integer value.
/// See Metadata Specification section II.23.2: Blobs and signatures.
/// </summary>
/// <returns>The value of the compressed integer that was read.</returns>
/// <exception cref="BadImageFormatException">The data at the current position was not a valid compressed integer.</exception>
public int ReadCompressedSignedInteger()
{
int value;
if (!TryReadCompressedSignedInteger(out value))
{
Throw.InvalidCompressedInteger();
}
return value;
}
/// <summary>
/// Reads type code encoded in a serialized custom attribute value.
/// </summary>
/// <returns><see cref="SerializationTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SerializationTypeCode ReadSerializationTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
if (value > byte.MaxValue)
{
return SerializationTypeCode.Invalid;
}
return unchecked((SerializationTypeCode)value);
}
/// <summary>
/// Reads type code encoded in a signature.
/// </summary>
/// <returns><see cref="SignatureTypeCode.Invalid"/> if the encoding is invalid.</returns>
public SignatureTypeCode ReadSignatureTypeCode()
{
int value = ReadCompressedIntegerOrInvalid();
switch (value)
{
case (int)CorElementType.ELEMENT_TYPE_CLASS:
case (int)CorElementType.ELEMENT_TYPE_VALUETYPE:
return SignatureTypeCode.TypeHandle;
default:
if (value > byte.MaxValue)
{
return SignatureTypeCode.Invalid;
}
return unchecked((SignatureTypeCode)value);
}
}
/// <summary>
/// Reads a string encoded as a compressed integer containing its length followed by
/// its contents in UTF8. Null strings are encoded as a single 0xFF byte.
/// </summary>
/// <remarks>Defined as a 'SerString' in the ECMA CLI specification.</remarks>
/// <returns>String value or null.</returns>
/// <exception cref="BadImageFormatException">If the encoding is invalid.</exception>
public string ReadSerializedString()
{
int length;
if (TryReadCompressedInteger(out length))
{
// Removal of trailing '\0' is a departure from the spec, but required
// for compatibility with legacy compilers.
return ReadUTF8(length).TrimEnd(s_nullCharArray);
}
if (ReadByte() != 0xFF)
{
Throw.InvalidSerializedString();
}
return null;
}
/// <summary>
/// Reads a type handle encoded in a signature as TypeDefOrRefOrSpecEncoded (see ECMA-335 II.23.2.8).
/// </summary>
/// <returns>The handle or nil if the encoding is invalid.</returns>
public EntityHandle ReadTypeHandle()
{
uint value = (uint)ReadCompressedIntegerOrInvalid();
uint tokenType = s_corEncodeTokenArray[value & 0x3];
if (value == InvalidCompressedInteger || tokenType == 0)
{
return default(EntityHandle);
}
return new EntityHandle(tokenType | (value >> 2));
}
private static readonly uint[] s_corEncodeTokenArray = new uint[] { TokenTypeIds.TypeDef, TokenTypeIds.TypeRef, TokenTypeIds.TypeSpec, 0 };
/// <summary>
/// Reads a #Blob heap handle encoded as a compressed integer.
/// </summary>
/// <remarks>
/// Blobs that contain references to other blobs are used in Portable PDB format, for example <see cref="Document.Name"/>.
/// </remarks>
public BlobHandle ReadBlobHandle()
{
return BlobHandle.FromOffset(ReadCompressedInteger());
}
/// <summary>
/// Reads a constant value (see ECMA-335 Partition II section 22.9) from the current position.
/// </summary>
/// <exception cref="BadImageFormatException">Error while reading from the blob.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="typeCode"/> is not a valid <see cref="ConstantTypeCode"/>.</exception>
/// <returns>
/// Boxed constant value. To avoid allocating the object use Read* methods directly.
/// Constants of type <see cref="ConstantTypeCode.String"/> are encoded as UTF16 strings, use <see cref="ReadUTF16(int)"/> to read them.
/// </returns>
public object ReadConstant(ConstantTypeCode typeCode)
{
// Partition II section 22.9:
//
// Type shall be exactly one of: ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1,
// ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, ELEMENT_TYPE_U4,
// ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, or ELEMENT_TYPE_STRING;
// or ELEMENT_TYPE_CLASS with a Value of zero (23.1.16)
switch (typeCode)
{
case ConstantTypeCode.Boolean:
return ReadBoolean();
case ConstantTypeCode.Char:
return ReadChar();
case ConstantTypeCode.SByte:
return ReadSByte();
case ConstantTypeCode.Int16:
return ReadInt16();
case ConstantTypeCode.Int32:
return ReadInt32();
case ConstantTypeCode.Int64:
return ReadInt64();
case ConstantTypeCode.Byte:
return ReadByte();
case ConstantTypeCode.UInt16:
return ReadUInt16();
case ConstantTypeCode.UInt32:
return ReadUInt32();
case ConstantTypeCode.UInt64:
return ReadUInt64();
case ConstantTypeCode.Single:
return ReadSingle();
case ConstantTypeCode.Double:
return ReadDouble();
case ConstantTypeCode.String:
return ReadUTF16(RemainingBytes);
case ConstantTypeCode.NullReference:
// Partition II section 22.9:
// The encoding of Type for the nullref value is ELEMENT_TYPE_CLASS with a Value of a 4-byte zero.
// Unlike uses of ELEMENT_TYPE_CLASS in signatures, this one is not followed by a type token.
if (ReadUInt32() != 0)
{
throw new BadImageFormatException(SR.InvalidConstantValue);
}
return null;
default:
throw new ArgumentOutOfRangeException(nameof(typeCode));
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using Svg.Pathing;
namespace Svg
{
public static class PointFExtensions
{
public static string ToSvgString(this PointF p)
{
return p.X.ToString() + " " + p.Y.ToString();
}
}
public class SvgPathBuilder : TypeConverter
{
/// <summary>
/// Parses the specified string into a collection of path segments.
/// </summary>
/// <param name="path">A <see cref="string"/> containing path data.</param>
public static SvgPathSegmentList Parse(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
var segments = new SvgPathSegmentList();
try
{
char command;
bool isRelative;
foreach (var commandSet in SplitCommands(path.TrimEnd(null)))
{
command = commandSet[0];
isRelative = char.IsLower(command);
// http://www.w3.org/TR/SVG11/paths.html#PathDataGeneralInformation
CreatePathSegment(command, segments, new CoordinateParser(commandSet.Trim()), isRelative);
}
}
catch (Exception exc)
{
Trace.TraceError("Error parsing path \"{0}\": {1}", path, exc.Message);
}
return segments;
}
private static void CreatePathSegment(char command, SvgPathSegmentList segments, CoordinateParser parser, bool isRelative)
{
var coords = new float[6];
switch (command)
{
case 'm': // relative moveto
case 'M': // moveto
if (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]))
{
segments.Add(new SvgMoveToSegment(ToAbsolute(coords[0], coords[1], segments, isRelative)));
}
while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]))
{
segments.Add(new SvgLineSegment(segments.Last.End,
ToAbsolute(coords[0], coords[1], segments, isRelative)));
}
break;
case 'a':
case 'A':
bool size;
bool sweep;
while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]) &&
parser.TryGetFloat(out coords[2]) && parser.TryGetBool(out size) &&
parser.TryGetBool(out sweep) && parser.TryGetFloat(out coords[3]) &&
parser.TryGetFloat(out coords[4]))
{
// A|a rx ry x-axis-rotation large-arc-flag sweep-flag x y
segments.Add(new SvgArcSegment(segments.Last.End, coords[0], coords[1], coords[2],
(size ? SvgArcSize.Large : SvgArcSize.Small),
(sweep ? SvgArcSweep.Positive : SvgArcSweep.Negative),
ToAbsolute(coords[3], coords[4], segments, isRelative)));
}
break;
case 'l': // relative lineto
case 'L': // lineto
while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]))
{
segments.Add(new SvgLineSegment(segments.Last.End,
ToAbsolute(coords[0], coords[1], segments, isRelative)));
}
break;
case 'H': // horizontal lineto
case 'h': // relative horizontal lineto
while (parser.TryGetFloat(out coords[0]))
{
segments.Add(new SvgLineSegment(segments.Last.End,
ToAbsolute(coords[0], segments.Last.End.Y, segments, isRelative, false)));
}
break;
case 'V': // vertical lineto
case 'v': // relative vertical lineto
while (parser.TryGetFloat(out coords[0]))
{
segments.Add(new SvgLineSegment(segments.Last.End,
ToAbsolute(segments.Last.End.X, coords[0], segments, false, isRelative)));
}
break;
case 'Q': // curveto
case 'q': // relative curveto
while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]) &&
parser.TryGetFloat(out coords[2]) && parser.TryGetFloat(out coords[3]))
{
segments.Add(new SvgQuadraticCurveSegment(segments.Last.End,
ToAbsolute(coords[0], coords[1], segments, isRelative),
ToAbsolute(coords[2], coords[3], segments, isRelative)));
}
break;
case 'T': // shorthand/smooth curveto
case 't': // relative shorthand/smooth curveto
while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]))
{
var lastQuadCurve = segments.Last as SvgQuadraticCurveSegment;
var controlPoint = lastQuadCurve != null
? Reflect(lastQuadCurve.ControlPoint, segments.Last.End)
: segments.Last.End;
segments.Add(new SvgQuadraticCurveSegment(segments.Last.End, controlPoint,
ToAbsolute(coords[0], coords[1], segments, isRelative)));
}
break;
case 'C': // curveto
case 'c': // relative curveto
while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]) &&
parser.TryGetFloat(out coords[2]) && parser.TryGetFloat(out coords[3]) &&
parser.TryGetFloat(out coords[4]) && parser.TryGetFloat(out coords[5]))
{
segments.Add(new SvgCubicCurveSegment(segments.Last.End,
ToAbsolute(coords[0], coords[1], segments, isRelative),
ToAbsolute(coords[2], coords[3], segments, isRelative),
ToAbsolute(coords[4], coords[5], segments, isRelative)));
}
break;
case 'S': // shorthand/smooth curveto
case 's': // relative shorthand/smooth curveto
while (parser.TryGetFloat(out coords[0]) && parser.TryGetFloat(out coords[1]) &&
parser.TryGetFloat(out coords[2]) && parser.TryGetFloat(out coords[3]))
{
var lastCubicCurve = segments.Last as SvgCubicCurveSegment;
var controlPoint = lastCubicCurve != null
? Reflect(lastCubicCurve.SecondControlPoint, segments.Last.End)
: segments.Last.End;
segments.Add(new SvgCubicCurveSegment(segments.Last.End, controlPoint,
ToAbsolute(coords[0], coords[1], segments, isRelative),
ToAbsolute(coords[2], coords[3], segments, isRelative)));
}
break;
case 'Z': // closepath
case 'z': // relative closepath
segments.Add(new SvgClosePathSegment());
break;
}
}
private static PointF Reflect(PointF point, PointF mirror)
{
float x, y, dx, dy;
dx = Math.Abs(mirror.X - point.X);
dy = Math.Abs(mirror.Y - point.Y);
if (mirror.X >= point.X)
{
x = mirror.X + dx;
}
else
{
x = mirror.X - dx;
}
if (mirror.Y >= point.Y)
{
y = mirror.Y + dy;
}
else
{
y = mirror.Y - dy;
}
return new PointF(x, y);
}
/// <summary>
/// Creates point with absolute coorindates.
/// </summary>
/// <param name="x">Raw X-coordinate value.</param>
/// <param name="y">Raw Y-coordinate value.</param>
/// <param name="segments">Current path segments.</param>
/// <param name="isRelativeBoth"><b>true</b> if <paramref name="x"/> and <paramref name="y"/> contains relative coordinate values, otherwise <b>false</b>.</param>
/// <returns><see cref="PointF"/> that contains absolute coordinates.</returns>
private static PointF ToAbsolute(float x, float y, SvgPathSegmentList segments, bool isRelativeBoth)
{
return ToAbsolute(x, y, segments, isRelativeBoth, isRelativeBoth);
}
/// <summary>
/// Creates point with absolute coorindates.
/// </summary>
/// <param name="x">Raw X-coordinate value.</param>
/// <param name="y">Raw Y-coordinate value.</param>
/// <param name="segments">Current path segments.</param>
/// <param name="isRelativeX"><b>true</b> if <paramref name="x"/> contains relative coordinate value, otherwise <b>false</b>.</param>
/// <param name="isRelativeY"><b>true</b> if <paramref name="y"/> contains relative coordinate value, otherwise <b>false</b>.</param>
/// <returns><see cref="PointF"/> that contains absolute coordinates.</returns>
private static PointF ToAbsolute(float x, float y, SvgPathSegmentList segments, bool isRelativeX, bool isRelativeY)
{
var point = new PointF(x, y);
if ((isRelativeX || isRelativeY) && segments.Count > 0)
{
var lastSegment = segments.Last;
// if the last element is a SvgClosePathSegment the position of the previous element should be used because the position of SvgClosePathSegment is 0,0
if (lastSegment is SvgClosePathSegment) lastSegment = segments.Reverse().OfType<SvgMoveToSegment>().First();
if (isRelativeX)
{
point.X += lastSegment.End.X;
}
if (isRelativeY)
{
point.Y += lastSegment.End.Y;
}
}
return point;
}
private static IEnumerable<string> SplitCommands(string path)
{
var commandStart = 0;
for (var i = 0; i < path.Length; i++)
{
string command;
if (char.IsLetter(path[i]) && path[i] != 'e' && path[i] != 'E') //e is used in scientific notiation. but not svg path
{
command = path.Substring(commandStart, i - commandStart).Trim();
commandStart = i;
if (!string.IsNullOrEmpty(command))
{
yield return command;
}
if (path.Length == i + 1)
{
yield return path[i].ToString();
}
}
else if (path.Length == i + 1)
{
command = path.Substring(commandStart, i - commandStart + 1).Trim();
if (!string.IsNullOrEmpty(command))
{
yield return command;
}
}
}
}
//private static IEnumerable<float> ParseCoordinates(string coords)
//{
// if (string.IsNullOrEmpty(coords) || coords.Length < 2) yield break;
// var pos = 0;
// var currState = NumState.separator;
// var newState = NumState.separator;
// for (int i = 1; i < coords.Length; i++)
// {
// switch (currState)
// {
// case NumState.separator:
// if (char.IsNumber(coords[i]))
// {
// newState = NumState.integer;
// }
// else if (IsCoordSeparator(coords[i]))
// {
// newState = NumState.separator;
// }
// else
// {
// switch (coords[i])
// {
// case '.':
// newState = NumState.decPlace;
// break;
// case '+':
// case '-':
// newState = NumState.prefix;
// break;
// default:
// newState = NumState.invalid;
// break;
// }
// }
// break;
// case NumState.prefix:
// if (char.IsNumber(coords[i]))
// {
// newState = NumState.integer;
// }
// else if (coords[i] == '.')
// {
// newState = NumState.decPlace;
// }
// else
// {
// newState = NumState.invalid;
// }
// break;
// case NumState.integer:
// if (char.IsNumber(coords[i]))
// {
// newState = NumState.integer;
// }
// else if (IsCoordSeparator(coords[i]))
// {
// newState = NumState.separator;
// }
// else
// {
// switch (coords[i])
// {
// case '.':
// newState = NumState.decPlace;
// break;
// case 'e':
// newState = NumState.exponent;
// break;
// case '+':
// case '-':
// newState = NumState.prefix;
// break;
// default:
// newState = NumState.invalid;
// break;
// }
// }
// break;
// case NumState.decPlace:
// if (char.IsNumber(coords[i]))
// {
// newState = NumState.fraction;
// }
// else if (IsCoordSeparator(coords[i]))
// {
// newState = NumState.separator;
// }
// else
// {
// switch (coords[i])
// {
// case 'e':
// newState = NumState.exponent;
// break;
// case '+':
// case '-':
// newState = NumState.prefix;
// break;
// default:
// newState = NumState.invalid;
// break;
// }
// }
// break;
// case NumState.fraction:
// if (char.IsNumber(coords[i]))
// {
// newState = NumState.fraction;
// }
// else if (IsCoordSeparator(coords[i]))
// {
// newState = NumState.separator;
// }
// else
// {
// switch (coords[i])
// {
// case '.':
// newState = NumState.decPlace;
// break;
// case 'e':
// newState = NumState.exponent;
// break;
// case '+':
// case '-':
// newState = NumState.prefix;
// break;
// default:
// newState = NumState.invalid;
// break;
// }
// }
// break;
// case NumState.exponent:
// if (char.IsNumber(coords[i]))
// {
// newState = NumState.expValue;
// }
// else if (IsCoordSeparator(coords[i]))
// {
// newState = NumState.invalid;
// }
// else
// {
// switch (coords[i])
// {
// case '+':
// case '-':
// newState = NumState.expPrefix;
// break;
// default:
// newState = NumState.invalid;
// break;
// }
// }
// break;
// case NumState.expPrefix:
// if (char.IsNumber(coords[i]))
// {
// newState = NumState.expValue;
// }
// else
// {
// newState = NumState.invalid;
// }
// break;
// case NumState.expValue:
// if (char.IsNumber(coords[i]))
// {
// newState = NumState.expValue;
// }
// else if (IsCoordSeparator(coords[i]))
// {
// newState = NumState.separator;
// }
// else
// {
// switch (coords[i])
// {
// case '.':
// newState = NumState.decPlace;
// break;
// case '+':
// case '-':
// newState = NumState.prefix;
// break;
// default:
// newState = NumState.invalid;
// break;
// }
// }
// break;
// }
// if (newState < currState)
// {
// yield return float.Parse(coords.Substring(pos, i - pos), NumberStyles.Float, CultureInfo.InvariantCulture);
// pos = i;
// }
// else if (newState != currState && currState == NumState.separator)
// {
// pos = i;
// }
// if (newState == NumState.invalid) yield break;
// currState = newState;
// }
// if (currState != NumState.separator)
// {
// yield return float.Parse(coords.Substring(pos, coords.Length - pos), NumberStyles.Float, CultureInfo.InvariantCulture);
// }
//}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
return Parse((string)value);
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
var paths = value as SvgPathSegmentList;
if (paths != null)
{
var curretCulture = CultureInfo.CurrentCulture;
try {
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var s = string.Join(" ", paths.Select(p => p.ToString()).ToArray());
return s;
}
finally
{
// Make sure to set back the old culture even an error occurred.
Thread.CurrentThread.CurrentCulture = curretCulture;
}
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
}
}
| |
// 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 representation of a 32 bit 2's complement
** integer.
**
**
===========================================================*/
using System;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
namespace System
{
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Int32 : IComparable, IFormattable, IConvertible
, IComparable<Int32>, IEquatable<Int32>
{
private int m_value; // Do not rename (binary serialization)
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
// 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 Int32, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Int32)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
int i = (int)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeInt32);
}
public int CompareTo(int value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj)
{
if (!(obj is Int32))
{
return false;
}
return m_value == ((Int32)obj).m_value;
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(Int32 obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return m_value;
}
[Pure]
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
[Pure]
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public static int Parse(String s)
{
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static int Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo);
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[Pure]
public static int Parse(String s, IFormatProvider provider)
{
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[Pure]
public static int Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String. Returns false rather
// than throwing exceptin if input is invalid
//
[Pure]
public static bool TryParse(String s, out Int32 result)
{
return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
// Parses an integer from a String in the given style. Returns false rather
// than throwing exceptin if input is invalid
//
[Pure]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
[Pure]
public TypeCode GetTypeCode()
{
return TypeCode.Int32;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
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 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 Convert.ToSingle(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, "Int32", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Reflection;
using Subtext.Framework.Data;
namespace Subtext.Framework.Infrastructure.Installation
{
public class SqlInstaller : IInstaller
{
private readonly string _connectionString;
public SqlInstaller(string connectionString)
{
_connectionString = connectionString;
}
public string DBUser { get; set; }
public void Install(Version assemblyVersion)
{
using(var connection = new SqlConnection(_connectionString))
{
connection.Open();
using(SqlTransaction transaction = connection.BeginTransaction())
{
try
{
ReadOnlyCollection<string> scripts = ListInstallationScripts(GetCurrentInstallationVersion(),
VersionInfo.CurrentAssemblyVersion);
foreach(string scriptName in scripts)
{
ScriptHelper.ExecuteScript(scriptName, transaction, DBUser);
}
ScriptHelper.ExecuteScript("StoredProcedures.sql", transaction, DBUser);
UpdateInstallationVersionNumber(assemblyVersion, transaction);
transaction.Commit();
}
catch(Exception)
{
transaction.Rollback();
throw;
}
}
}
}
/// <summary>
/// Upgrades this instance. Returns true if it was successful.
/// </summary>
/// <returns></returns>
public void Upgrade(Version currentAssemblyVersion)
{
using(var connection = new SqlConnection(_connectionString))
{
connection.Open();
using(SqlTransaction transaction = connection.BeginTransaction())
{
try
{
Version installationVersion = GetCurrentInstallationVersion() ?? new Version(1, 0, 0, 0);
ReadOnlyCollection<string> scripts = ListInstallationScripts(installationVersion, currentAssemblyVersion);
foreach(string scriptName in scripts)
{
ScriptHelper.ExecuteScript(scriptName, transaction, DBUser);
}
ScriptHelper.ExecuteScript("StoredProcedures.sql", transaction, DBUser);
UpdateInstallationVersionNumber(currentAssemblyVersion, transaction);
transaction.Commit();
}
catch(Exception)
{
transaction.Rollback();
throw;
}
}
}
}
/// <summary>
/// Returns a collection of installation script names with a version
/// less than or equal to the max version.
/// </summary>
/// <param name="minVersionExclusive">The min verison exclusive.</param>
/// <param name="maxVersionInclusive">The max version inclusive.</param>
/// <returns></returns>
public static ReadOnlyCollection<string> ListInstallationScripts(Version minVersionExclusive,
Version maxVersionInclusive)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string[] resourceNames = assembly.GetManifestResourceNames();
var collection = new List<string>();
foreach(string resourceName in resourceNames)
{
InstallationScriptInfo scriptInfo = InstallationScriptInfo.Parse(resourceName);
if(scriptInfo == null)
{
continue;
}
if((minVersionExclusive == null || scriptInfo.Version > minVersionExclusive)
&& (maxVersionInclusive == null || scriptInfo.Version <= maxVersionInclusive))
{
collection.Add(scriptInfo.ScriptName);
}
}
var scripts = new string[collection.Count];
collection.CopyTo(scripts, 0);
Array.Sort(scripts);
return new ReadOnlyCollection<string>(new List<string>(scripts));
}
/// <summary>
/// Updates the value of the current installed version within the subtext_Version table.
/// </summary>
/// <param name="newVersion">New version.</param>
/// <param name="transaction">The transaction to perform this action within.</param>
public static void UpdateInstallationVersionNumber(Version newVersion, SqlTransaction transaction)
{
var procedures = new StoredProcedures(transaction);
procedures.VersionAdd(newVersion.Major, newVersion.Minor, newVersion.Build, DateTime.Now);
}
/// <summary>
/// Gets the <see cref="Version"/> of the current Subtext data store (ie. SQL Server).
/// This is the value stored in the database. If it does not match the actual
/// assembly version, we may need to run an upgrade.
/// </summary>
/// <returns></returns>
public Version GetCurrentInstallationVersion()
{
var procedures = new StoredProcedures(_connectionString);
try
{
using(var reader = procedures.VersionGetCurrent())
{
if(reader.Read())
{
var version = new Version((int)reader["Major"], (int)reader["Minor"], (int)reader["Build"]);
reader.Close();
return version;
}
}
}
catch(SqlException exception)
{
if(exception.Number != (int)SqlErrorMessage.CouldNotFindStoredProcedure)
{
throw;
}
}
return null;
}
/// <summary>
/// Gets a value indicating whether the subtext installation needs an upgrade
/// to occur.
/// </summary>
/// <value>
/// <c>true</c> if [needs upgrade]; otherwise, <c>false</c>.
/// </value>
public bool NeedsUpgrade(Version installationVersion, Version currentAssemblyVersion)
{
if(installationVersion >= currentAssemblyVersion)
{
return false;
}
if(installationVersion == null)
{
//This is the base version. We need to hardcode this
//because Subtext 1.0 didn't write the assembly version
//into the database.
installationVersion = new Version(1, 0, 0, 0);
}
ReadOnlyCollection<string> scripts = ListInstallationScripts(installationVersion, currentAssemblyVersion);
return scripts.Count > 0;
}
}
}
| |
#region License
//
// Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using FluentMigrator.Builders;
using FluentMigrator.Builders.Create.Column;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
using FluentMigrator.Oracle;
using FluentMigrator.Postgres;
using FluentMigrator.SqlServer;
using Moq;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Builders.Create
{
[TestFixture]
public class CreateColumnExpressionBuilderTests
{
[Test]
public void CallingOnTableSetsTableName()
{
var expressionMock = new Mock<CreateColumnExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.OnTable("Bacon");
expressionMock.VerifySet(x => x.TableName = "Bacon");
}
[Test]
public void CallingAsAnsiStringSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString());
}
[Test]
public void CallingAsAnsiStringWithSizeSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString(42));
}
[Test]
public void CallingAsAnsiStringWithSizeSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(42, b => b.AsAnsiString(42));
}
[Test]
public void CallingAsBinarySetsColumnDbTypeToBinary()
{
VerifyColumnDbType(DbType.Binary, b => b.AsBinary());
}
[Test]
public void CallingAsBinaryWithSizeSetsColumnDbTypeToBinary()
{
VerifyColumnDbType(DbType.Binary, b => b.AsBinary(42));
}
[Test]
public void CallingAsBinaryWithSizeSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(42, b => b.AsBinary(42));
}
[Test]
public void CallingAsBooleanSetsColumnDbTypeToBoolean()
{
VerifyColumnDbType(DbType.Boolean, b => b.AsBoolean());
}
[Test]
public void CallingAsByteSetsColumnDbTypeToByte()
{
VerifyColumnDbType(DbType.Byte, b => b.AsByte());
}
[Test]
public void CallingAsCurrencySetsColumnDbTypeToCurrency()
{
VerifyColumnDbType(DbType.Currency, b => b.AsCurrency());
}
[Test]
public void CallingAsDateSetsColumnDbTypeToDate()
{
VerifyColumnDbType(DbType.Date, b => b.AsDate());
}
[Test]
public void CallingAsDateTimeSetsColumnDbTypeToDateTime()
{
VerifyColumnDbType(DbType.DateTime, b => b.AsDateTime());
}
[Test]
public void CallingAsDateTime2SetsColumnDbTypeToDateTime2()
{
VerifyColumnDbType(DbType.DateTime2, b => b.AsDateTime2());
}
[Test]
public void CallingAsDateTimeOffsetSetsColumnDbTypeToDateTimeOffset()
{
VerifyColumnDbType(DbType.DateTimeOffset, b => b.AsDateTimeOffset());
}
[Test]
public void CallingAsDecimalSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal());
}
[Test]
public void CallingAsDecimalWithSizeAndPrecisionSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(1, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnPrecisionToSpecifiedValue()
{
VerifyColumnPrecision(2, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDoubleSetsColumnDbTypeToDouble()
{
VerifyColumnDbType(DbType.Double, b => b.AsDouble());
}
[Test]
public void CallingAsGuidSetsColumnDbTypeToGuid()
{
VerifyColumnDbType(DbType.Guid, b => b.AsGuid());
}
[Test]
public void CallingAsFixedLengthStringSetsColumnDbTypeToStringFixedLength()
{
VerifyColumnDbType(DbType.StringFixedLength, e => e.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnDbTypeToAnsiStringFixedLength()
{
VerifyColumnDbType(DbType.AnsiStringFixedLength, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFloatSetsColumnDbTypeToSingle()
{
VerifyColumnDbType(DbType.Single, b => b.AsFloat());
}
[Test]
public void CallingAsInt16SetsColumnDbTypeToInt16()
{
VerifyColumnDbType(DbType.Int16, b => b.AsInt16());
}
[Test]
public void CallingAsInt32SetsColumnDbTypeToInt32()
{
VerifyColumnDbType(DbType.Int32, b => b.AsInt32());
}
[Test]
public void CallingAsInt64SetsColumnDbTypeToInt64()
{
VerifyColumnDbType(DbType.Int64, b => b.AsInt64());
}
[Test]
public void CallingAsStringSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString());
}
[Test]
public void CallingAsStringWithLengthSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString(255));
}
[Test]
public void CallingAsStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsAnsiStringWithCollation()
{
VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsAnsiString(Generators.GeneratorTestHelper.TestColumnCollationName));
}
[Test]
public void CallingAsFixedLengthAnsiStringWithCollation()
{
VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsFixedLengthAnsiString(255, Generators.GeneratorTestHelper.TestColumnCollationName));
}
[Test]
public void CallingAsFixedLengthStringWithCollation()
{
VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsFixedLengthString(255, Generators.GeneratorTestHelper.TestColumnCollationName));
}
[Test]
public void CallingAsStringWithCollation()
{
VerifyColumnCollation(Generators.GeneratorTestHelper.TestColumnCollationName, b => b.AsString(Generators.GeneratorTestHelper.TestColumnCollationName));
}
[Test]
public void CallingAsTimeSetsColumnDbTypeToTime()
{
VerifyColumnDbType(DbType.Time, b => b.AsTime());
}
[Test]
public void CallingAsXmlSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml());
}
[Test]
public void CallingAsXmlWithSizeSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml(255));
}
[Test]
public void CallingAsXmlSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsXml(255));
}
[Test]
public void CallingAsCustomSetsTypeToNullAndSetsCustomType()
{
VerifyColumnProperty(c => c.Type = null, b => b.AsCustom("Test"));
VerifyColumnProperty(c => c.CustomType = "Test", b => b.AsCustom("Test"));
}
[Test]
public void CallingWithDefaultValueSetsDefaultValue()
{
const int value = 42;
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.WithDefaultValue(value);
columnMock.VerifySet(c => c.DefaultValue = value);
}
[Test]
public void CallingWithDefaultSetsDefaultValue()
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.WithDefault(SystemMethods.NewGuid);
columnMock.VerifySet(c => c.DefaultValue = SystemMethods.NewGuid);
}
[Test]
public void CallingForeignKeySetsIsForeignKeyToTrue()
{
VerifyColumnProperty(c => c.IsForeignKey = true, b => b.ForeignKey());
}
[Test]
public void CallingIdentitySetsIsIdentityToTrue()
{
VerifyColumnProperty(c => c.IsIdentity = true, b => b.Identity());
}
[Test]
public void CallingSeededIdentitySetsAdditionalProperties()
{
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Identity(23, 44);
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(SqlServerExtensions.IdentitySeed, 23));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(SqlServerExtensions.IdentityIncrement, 44));
}
[Test]
public void CallingSeededLongIdentitySetsAdditionalProperties()
{
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Identity(long.MaxValue, 44);
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(SqlServerExtensions.IdentitySeed, long.MaxValue));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(SqlServerExtensions.IdentityIncrement, 44));
}
[Test]
public void CallingGeneratedIdentitySetsAdditionalProperties()
{
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Identity(OracleGenerationType.Always, startWith: 0, incrementBy: 1);
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityGeneration, OracleGenerationType.Always));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityStartWith, 0L));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityIncrementBy, 1));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityMinValue, null));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityMaxValue, null));
}
[Test]
public void CallingGeneratedLongIdentitySetsAdditionalProperties()
{
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Identity(OracleGenerationType.Always, startWith: 0L, incrementBy: 1);
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityGeneration, OracleGenerationType.Always));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityStartWith, 0L));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityIncrementBy, 1));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityMinValue, null));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityMaxValue, null));
}
[Test]
public void CallingGeneratedIdentityMinMaxSetsAdditionalProperties()
{
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Identity(OracleGenerationType.Always, startWith: 0, incrementBy: 1, minValue: 0, long.MaxValue);
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityGeneration, OracleGenerationType.Always));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityStartWith, 0L));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityIncrementBy, 1));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityMinValue, 0L));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(OracleExtensions.IdentityMaxValue, long.MaxValue));
}
[Test]
public void CallingIndexedCallsHelperWithNullIndexName()
{
VerifyColumnHelperCall(c => c.Indexed(), h => h.Indexed(null));
}
[Test]
public void CallingIndexedNamedCallsHelperWithName()
{
VerifyColumnHelperCall(c => c.Indexed("MyIndexName"), h => h.Indexed("MyIndexName"));
}
[Test]
public void CallingPrimaryKeySetsIsPrimaryKeyToTrue()
{
VerifyColumnProperty(c => c.IsPrimaryKey = true, b => b.PrimaryKey());
}
[Test]
public void CallingReferencesAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ReferencedBy("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.ForeignTable == "FooTable" &&
fk.ForeignKey.ForeignColumns.Contains("BarColumn") &&
fk.ForeignKey.ForeignColumns.Count == 1 &&
fk.ForeignKey.PrimaryTable == "Bacon" &&
fk.ForeignKey.PrimaryColumns.Contains("BaconId") &&
fk.ForeignKey.PrimaryColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingReferencedByAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ReferencedBy("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.ForeignTable == "FooTable" &&
fk.ForeignKey.ForeignColumns.Contains("BarColumn") &&
fk.ForeignKey.ForeignColumns.Count == 1 &&
fk.ForeignKey.PrimaryTable == "Bacon" &&
fk.ForeignKey.PrimaryColumns.Contains("BaconId") &&
fk.ForeignKey.PrimaryColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingForeignKeyAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ForeignKey("fk_foo", "FooTable", "BarColumn");
contextMock.VerifyGet(x => x.Expressions);
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.PrimaryTable == "FooTable" &&
fk.ForeignKey.PrimaryColumns.Contains("BarColumn") &&
fk.ForeignKey.PrimaryColumns.Count == 1 &&
fk.ForeignKey.ForeignTable == "Bacon" &&
fk.ForeignKey.ForeignColumns.Contains("BaconId") &&
fk.ForeignKey.ForeignColumns.Count == 1
)));
}
[Test]
public void CallingForeignKeyWithCustomSchemaAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.SchemaName).Returns("FooSchema");
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ForeignKey("fk_foo", "BarSchema", "BarTable", "BarColumn");
contextMock.VerifyGet(x => x.Expressions);
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.PrimaryTableSchema == "BarSchema" &&
fk.ForeignKey.PrimaryTable == "BarTable" &&
fk.ForeignKey.PrimaryColumns.Contains("BarColumn") &&
fk.ForeignKey.PrimaryColumns.Count == 1 &&
fk.ForeignKey.ForeignTableSchema == "FooSchema" &&
fk.ForeignKey.ForeignTable == "Bacon" &&
fk.ForeignKey.ForeignColumns.Contains("BaconId") &&
fk.ForeignKey.ForeignColumns.Count == 1
)));
}
[TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)]
public void CallingOnUpdateSetsOnUpdateOnForeignKeyExpression(Rule rule)
{
var builder = new CreateColumnExpressionBuilder(null, null) {CurrentForeignKey = new ForeignKeyDefinition()};
builder.OnUpdate(rule);
Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule));
Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(Rule.None));
}
[TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)]
public void CallingOnDeleteSetsOnDeleteOnForeignKeyExpression(Rule rule)
{
var builder = new CreateColumnExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() };
builder.OnDelete(rule);
Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(Rule.None));
Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule));
}
[TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)]
public void CallingOnDeleteOrUpdateSetsOnUpdateAndOnDeleteOnForeignKeyExpression(Rule rule)
{
var builder = new CreateColumnExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() };
builder.OnDeleteOrUpdate(rule);
Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule));
Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule));
}
[Test]
public void CallingPostgresGeneratedIdentitySetsAdditionalProperties()
{
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupGet(x => x.Column).Returns(columnMock.Object);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.Identity(PostgresGenerationType.Always);
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(PostgresExtensions.IdentityGeneration, PostgresGenerationType.Always));
}
[Test]
public void ColumnHelperSetOnCreation()
{
var expressionMock = new Mock<CreateColumnExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
Assert.IsNotNull(builder.ColumnHelper);
}
[Test]
public void ColumnExpressionBuilderUsesExpressionColumnSchemaAndTableName()
{
var expressionMock = new Mock<CreateColumnExpression>();
var contextMock = new Mock<IMigrationContext>();
expressionMock.SetupGet(n => n.SchemaName).Returns("Fred");
expressionMock.SetupGet(n => n.TableName).Returns("Flinstone");
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
var builderAsInterface = (IColumnExpressionBuilder)builder;
Assert.AreEqual("Fred", builderAsInterface.SchemaName);
Assert.AreEqual("Flinstone", builderAsInterface.TableName);
}
[Test]
public void ColumnExpressionBuilderUsesExpressionColumn()
{
var expressionMock = new Mock<CreateColumnExpression>();
var contextMock = new Mock<IMigrationContext>();
var curColumn = new Mock<ColumnDefinition>().Object;
expressionMock.SetupGet(n => n.Column).Returns(curColumn);
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
var builderAsInterface = (IColumnExpressionBuilder)builder;
Assert.AreSame(curColumn, builderAsInterface.Column);
}
[Test]
public void NullableUsesHelper()
{
VerifyColumnHelperCall(c => c.Nullable(), h => h.SetNullable(true));
}
[Test]
public void NotNullableUsesHelper()
{
VerifyColumnHelperCall(c => c.NotNullable(), h => h.SetNullable(false));
}
[Test]
public void UniqueUsesHelper()
{
VerifyColumnHelperCall(c => c.Unique(), h => h.Unique(null));
}
[Test]
public void NamedUniqueUsesHelper()
{
VerifyColumnHelperCall(c => c.Unique("asdf"), h => h.Unique("asdf"));
}
[Test]
public void SetExistingRowsUsesHelper()
{
VerifyColumnHelperCall(c => c.SetExistingRowsTo("test"), h => h.SetExistingRowsTo("test"));
}
private void VerifyColumnHelperCall(Action<CreateColumnExpressionBuilder> callToTest, System.Linq.Expressions.Expression<Action<ColumnExpressionBuilderHelper>> expectedHelperAction)
{
var expressionMock = new Mock<CreateColumnExpression>();
var contextMock = new Mock<IMigrationContext>();
var helperMock = new Mock<ColumnExpressionBuilderHelper>();
var builder = new CreateColumnExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ColumnHelper = helperMock.Object;
callToTest(builder);
helperMock.Verify(expectedHelperAction);
}
private void VerifyColumnProperty(Action<ColumnDefinition> columnExpression, Action<CreateColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
contextMock.SetupGet(mc => mc.Expressions).Returns(new Collection<IMigrationExpression>());
callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(columnExpression);
}
private void VerifyColumnDbType(DbType expected, Action<CreateColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.Type = expected);
}
private void VerifyColumnSize(int expected, Action<CreateColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.Size = expected);
}
private void VerifyColumnPrecision(int expected, Action<CreateColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.Precision = expected);
}
private void VerifyColumnCollation(string expected, Action<CreateColumnExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<CreateColumnExpression>();
expressionMock.SetupProperty(e => e.Column);
var expression = expressionMock.Object;
expression.Column = columnMock.Object;
var contextMock = new Mock<IMigrationContext>();
callToTest(new CreateColumnExpressionBuilder(expression, contextMock.Object));
columnMock.VerifySet(c => c.CollationName = expected);
}
}
}
| |
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using BTCPayServer.Client;
using BTCPayServer.Client.Models;
using BTCPayServer.Data;
using BTCPayServer.Security.Greenfield;
using BTCPayServer.Views.Manage;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using Xunit;
using Xunit.Abstractions;
using StoreData = BTCPayServer.Data.StoreData;
namespace BTCPayServer.Tests
{
public class ApiKeysTests : UnitTestBase
{
public const int TestTimeout = TestUtils.TestTimeout;
public const string TestApiPath = "api/test/apikey";
public ApiKeysTests(ITestOutputHelper helper) : base(helper)
{
}
[Fact(Timeout = TestTimeout)]
[Trait("Selenium", "Selenium")]
public async Task CanCreateApiKeys()
{
//there are 2 ways to create api keys:
//as a user through your profile
//as an external application requesting an api key from a user
using var s = CreateSeleniumTester();
await s.StartAsync();
var tester = s.Server;
var user = tester.NewAccount();
await user.GrantAccessAsync();
await user.MakeAdmin(false);
s.GoToLogin();
s.LogIn(user.RegisterDetails.Email, user.RegisterDetails.Password);
s.GoToProfile(ManageNavPages.APIKeys);
s.Driver.FindElement(By.Id("AddApiKey")).Click();
TestLogs.LogInformation("Checking admin permissions");
//not an admin, so this permission should not show
Assert.DoesNotContain("btcpay.server.canmodifyserversettings", s.Driver.PageSource);
await user.MakeAdmin();
s.Logout();
s.GoToLogin();
s.LogIn(user.RegisterDetails.Email, user.RegisterDetails.Password);
s.GoToProfile(ManageNavPages.APIKeys);
s.Driver.FindElement(By.Id("AddApiKey")).Click();
Assert.Contains("btcpay.server.canmodifyserversettings", s.Driver.PageSource);
//server management should show now
s.Driver.SetCheckbox(By.Id("btcpay.server.canmodifyserversettings"), true);
s.Driver.SetCheckbox(By.Id("btcpay.store.canmodifystoresettings"), true);
s.Driver.SetCheckbox(By.Id("btcpay.user.canviewprofile"), true);
s.Driver.FindElement(By.Id("Generate")).Click();
var superApiKey = s.FindAlertMessage().FindElement(By.TagName("code")).Text;
TestLogs.LogInformation("Checking super admin key");
//this api key has access to everything
await TestApiAgainstAccessToken(superApiKey, tester, user, Policies.CanModifyServerSettings, Policies.CanModifyStoreSettings, Policies.CanViewProfile);
s.Driver.FindElement(By.Id("AddApiKey")).Click();
s.Driver.SetCheckbox(By.Id("btcpay.server.canmodifyserversettings"), true);
s.Driver.FindElement(By.Id("Generate")).Click();
var serverOnlyApiKey = s.FindAlertMessage().FindElement(By.TagName("code")).Text;
TestLogs.LogInformation("Checking CanModifyServerSettings permissions");
await TestApiAgainstAccessToken(serverOnlyApiKey, tester, user,
Policies.CanModifyServerSettings);
s.Driver.FindElement(By.Id("AddApiKey")).Click();
s.Driver.SetCheckbox(By.Id("btcpay.store.canmodifystoresettings"), true);
s.Driver.FindElement(By.Id("Generate")).Click();
var allStoreOnlyApiKey = s.FindAlertMessage().FindElement(By.TagName("code")).Text;
TestLogs.LogInformation("Checking CanModifyStoreSettings permissions");
await TestApiAgainstAccessToken(allStoreOnlyApiKey, tester, user,
Policies.CanModifyStoreSettings);
s.Driver.FindElement(By.Id("AddApiKey")).Click();
s.Driver.FindElement(By.CssSelector("button[value='btcpay.store.canmodifystoresettings:change-store-mode']")).Click();
//there should be a store already by default in the dropdown
var getPermissionValueIndex =
s.Driver.FindElement(By.CssSelector("input[value='btcpay.store.canmodifystoresettings']"))
.GetAttribute("name")
.Replace(".Permission", ".SpecificStores[0]");
var dropdown = s.Driver.FindElement(By.Name(getPermissionValueIndex));
var option = dropdown.FindElement(By.TagName("option"));
var storeId = option.GetAttribute("value");
option.Click();
s.Driver.FindElement(By.Id("Generate")).Click();
var selectiveStoreApiKey = s.FindAlertMessage().FindElement(By.TagName("code")).Text;
TestLogs.LogInformation("Checking CanModifyStoreSettings with StoreId permissions");
await TestApiAgainstAccessToken(selectiveStoreApiKey, tester, user,
Permission.Create(Policies.CanModifyStoreSettings, storeId).ToString());
s.Driver.FindElement(By.Id("AddApiKey")).Click();
s.Driver.FindElement(By.Id("Generate")).Click();
var noPermissionsApiKey = s.FindAlertMessage().FindElement(By.TagName("code")).Text;
TestLogs.LogInformation("Checking no permissions");
await TestApiAgainstAccessToken(noPermissionsApiKey, tester, user);
await Assert.ThrowsAnyAsync<HttpRequestException>(async () =>
{
await TestApiAgainstAccessToken<bool>("incorrect key", $"{TestApiPath}/me/id",
tester.PayTester.HttpClient);
});
TestLogs.LogInformation("Checking authorize screen");
//let's test the authorized screen now
//options for authorize are:
//applicationName
//redirect
//permissions
//strict
//selectiveStores
//redirect
//appidentifier
var appidentifier = "testapp";
var callbackUrl = s.ServerUri + "postredirect-callback-test";
var authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri,
new[] { Policies.CanModifyStoreSettings, Policies.CanModifyServerSettings }, applicationDetails: (appidentifier, new Uri(callbackUrl))).ToString();
s.Driver.Navigate().GoToUrl(authUrl);
Assert.Contains(appidentifier, s.Driver.PageSource);
Assert.Equal("hidden", s.Driver.FindElement(By.Id("btcpay.store.canmodifystoresettings")).GetAttribute("type").ToLowerInvariant());
Assert.Equal("true", s.Driver.FindElement(By.Id("btcpay.store.canmodifystoresettings")).GetAttribute("value").ToLowerInvariant());
Assert.Equal("hidden", s.Driver.FindElement(By.Id("btcpay.server.canmodifyserversettings")).GetAttribute("type").ToLowerInvariant());
Assert.Equal("true", s.Driver.FindElement(By.Id("btcpay.server.canmodifyserversettings")).GetAttribute("value").ToLowerInvariant());
Assert.DoesNotContain("change-store-mode", s.Driver.PageSource);
s.Driver.FindElement(By.Id("consent-yes")).Click();
Assert.Equal(callbackUrl, s.Driver.Url);
var apiKeyRepo = s.Server.PayTester.GetService<APIKeyRepository>();
var accessToken = GetAccessTokenFromCallbackResult(s.Driver);
await TestApiAgainstAccessToken(accessToken, tester, user,
(await apiKeyRepo.GetKey(accessToken)).GetBlob().Permissions);
authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri,
new[] { Policies.CanModifyStoreSettings, Policies.CanModifyServerSettings }, false, true, applicationDetails: (null, new Uri(callbackUrl))).ToString();
s.Driver.Navigate().GoToUrl(authUrl);
Assert.DoesNotContain("kukksappname", s.Driver.PageSource);
Assert.Equal("checkbox", s.Driver.FindElement(By.Id("btcpay.store.canmodifystoresettings")).GetAttribute("type").ToLowerInvariant());
Assert.Equal("true", s.Driver.FindElement(By.Id("btcpay.store.canmodifystoresettings")).GetAttribute("value").ToLowerInvariant());
Assert.Equal("checkbox", s.Driver.FindElement(By.Id("btcpay.server.canmodifyserversettings")).GetAttribute("type").ToLowerInvariant());
Assert.Equal("true", s.Driver.FindElement(By.Id("btcpay.server.canmodifyserversettings")).GetAttribute("value").ToLowerInvariant());
s.Driver.SetCheckbox(By.Id("btcpay.server.canmodifyserversettings"), false);
Assert.Contains("change-store-mode", s.Driver.PageSource);
s.Driver.FindElement(By.Id("consent-yes")).Click();
Assert.Equal(callbackUrl, s.Driver.Url);
accessToken = GetAccessTokenFromCallbackResult(s.Driver);
TestLogs.LogInformation("Checking authorized permissions");
await TestApiAgainstAccessToken(accessToken, tester, user,
(await apiKeyRepo.GetKey(accessToken)).GetBlob().Permissions);
//let's test the app identifier system
authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri,
new[] { Policies.CanModifyStoreSettings, Policies.CanModifyServerSettings }, false, true, (appidentifier, new Uri(callbackUrl))).ToString();
//if it's the same, go to the confirm page
s.Driver.Navigate().GoToUrl(authUrl);
s.Driver.FindElement(By.Id("continue")).Click();
Assert.Equal(callbackUrl, s.Driver.Url);
//same app but different redirect = nono
authUrl = BTCPayServerClient.GenerateAuthorizeUri(s.ServerUri,
new[] { Policies.CanModifyStoreSettings, Policies.CanModifyServerSettings }, false, true, (appidentifier, new Uri("https://international.local/callback"))).ToString();
s.Driver.Navigate().GoToUrl(authUrl);
Assert.False(s.Driver.Url.StartsWith("https://international.com/callback"));
// Make sure we can check all permissions when not an admin
await user.MakeAdmin(false);
s.Logout();
s.GoToLogin();
s.LogIn(user.RegisterDetails.Email, user.RegisterDetails.Password);
s.GoToProfile(ManageNavPages.APIKeys);
s.Driver.FindElement(By.Id("AddApiKey")).Click();
int checkedPermissionCount = 0;
foreach (var checkbox in s.Driver.FindElements(By.ClassName("form-check-input")))
{
checkedPermissionCount++;
s.Driver.ScrollTo(checkbox);
checkbox.Click();
}
var generate = s.Driver.FindElement(By.Id("Generate"));
s.Driver.ScrollTo(generate);
generate.Click();
var allAPIKey = s.FindAlertMessage().FindElement(By.TagName("code")).Text;
TestLogs.LogInformation("Checking API key permissions");
var apikeydata = await TestApiAgainstAccessToken<ApiKeyData>(allAPIKey, "api/v1/api-keys/current", tester.PayTester.HttpClient);
Assert.Equal(checkedPermissionCount, apikeydata.Permissions.Length);
}
async Task TestApiAgainstAccessToken(string accessToken, ServerTester tester, TestAccount testAccount,
params string[] expectedPermissionsArr)
{
var expectedPermissions = Permission.ToPermissions(expectedPermissionsArr).ToArray();
expectedPermissions ??= new Permission[0];
var apikeydata = await TestApiAgainstAccessToken<ApiKeyData>(accessToken, $"api/v1/api-keys/current", tester.PayTester.HttpClient);
var permissions = apikeydata.Permissions;
Assert.Equal(expectedPermissions.Length, permissions.Length);
foreach (var expectPermission in expectedPermissions)
{
Assert.True(permissions.Any(p => p == expectPermission), $"Missing expected permission {expectPermission}");
}
if (permissions.Contains(Permission.Create(Policies.CanViewProfile)))
{
var resultUser = await TestApiAgainstAccessToken<string>(accessToken, $"{TestApiPath}/me/id", tester.PayTester.HttpClient);
Assert.Equal(testAccount.UserId, resultUser);
}
else
{
await Assert.ThrowsAnyAsync<HttpRequestException>(async () =>
{
await TestApiAgainstAccessToken<string>(accessToken, $"{TestApiPath}/me/id", tester.PayTester.HttpClient);
});
}
//create a second user to see if any of its data gets messed upin our results.
var secondUser = tester.NewAccount();
secondUser.GrantAccess();
var canModifyAllStores = Permission.Create(Policies.CanModifyStoreSettings, null);
var canModifyServer = Permission.Create(Policies.CanModifyServerSettings, null);
var unrestricted = Permission.Create(Policies.Unrestricted, null);
var selectiveStorePermissions = permissions.Where(p => p.Scope != null && p.Policy == Policies.CanModifyStoreSettings);
if (permissions.Contains(canModifyAllStores) || selectiveStorePermissions.Any())
{
var resultStores =
await TestApiAgainstAccessToken<StoreData[]>(accessToken, $"{TestApiPath}/me/stores",
tester.PayTester.HttpClient);
foreach (var selectiveStorePermission in selectiveStorePermissions)
{
Assert.True(await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/stores/{selectiveStorePermission.Scope}/can-edit",
tester.PayTester.HttpClient));
Assert.Contains(resultStores,
data => data.Id.Equals(selectiveStorePermission.Scope, StringComparison.InvariantCultureIgnoreCase));
}
bool shouldBeAuthorized = false;
if (permissions.Contains(canModifyAllStores) || selectiveStorePermissions.Contains(Permission.Create(Policies.CanViewStoreSettings, testAccount.StoreId)))
{
Assert.True(await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/stores/{testAccount.StoreId}/can-view",
tester.PayTester.HttpClient));
Assert.Contains(resultStores,
data => data.Id.Equals(testAccount.StoreId, StringComparison.InvariantCultureIgnoreCase));
shouldBeAuthorized = true;
}
if (permissions.Contains(canModifyAllStores) || selectiveStorePermissions.Contains(Permission.Create(Policies.CanModifyStoreSettings, testAccount.StoreId)))
{
Assert.True(await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/stores/{testAccount.StoreId}/can-view",
tester.PayTester.HttpClient));
Assert.True(await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/stores/{testAccount.StoreId}/can-edit",
tester.PayTester.HttpClient));
Assert.Contains(resultStores,
data => data.Id.Equals(testAccount.StoreId, StringComparison.InvariantCultureIgnoreCase));
shouldBeAuthorized = true;
}
if (!shouldBeAuthorized)
{
await Assert.ThrowsAnyAsync<HttpRequestException>(async () =>
{
await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/stores/{testAccount.StoreId}/can-edit",
tester.PayTester.HttpClient);
});
await Assert.ThrowsAnyAsync<HttpRequestException>(async () =>
{
await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/stores/{testAccount.StoreId}/can-view",
tester.PayTester.HttpClient);
});
Assert.DoesNotContain(resultStores,
data => data.Id.Equals(testAccount.StoreId, StringComparison.InvariantCultureIgnoreCase));
}
}
else if (!permissions.Contains(unrestricted))
{
await Assert.ThrowsAnyAsync<HttpRequestException>(async () =>
{
await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/stores/{testAccount.StoreId}/can-edit",
tester.PayTester.HttpClient);
});
}
else
{
await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/stores/{testAccount.StoreId}/can-edit",
tester.PayTester.HttpClient);
}
if (!permissions.Contains(unrestricted))
{
await Assert.ThrowsAnyAsync<HttpRequestException>(async () =>
{
await TestApiAgainstAccessToken<bool>(accessToken, $"{TestApiPath}/me/stores/{secondUser.StoreId}/can-edit",
tester.PayTester.HttpClient);
});
}
else
{
await TestApiAgainstAccessToken<bool>(accessToken, $"{TestApiPath}/me/stores/{secondUser.StoreId}/can-edit",
tester.PayTester.HttpClient);
}
if (permissions.Contains(canModifyServer))
{
Assert.True(await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/is-admin",
tester.PayTester.HttpClient));
}
else
{
await Assert.ThrowsAnyAsync<HttpRequestException>(async () =>
{
await TestApiAgainstAccessToken<bool>(accessToken,
$"{TestApiPath}/me/is-admin",
tester.PayTester.HttpClient);
});
}
}
public async Task<T> TestApiAgainstAccessToken<T>(string apikey, string url, HttpClient client)
{
var httpRequest = new HttpRequestMessage(HttpMethod.Get,
new Uri(client.BaseAddress, url));
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("token", apikey);
var result = await client.SendAsync(httpRequest);
result.EnsureSuccessStatusCode();
var rawJson = await result.Content.ReadAsStringAsync();
if (typeof(T).IsPrimitive || typeof(T) == typeof(string))
{
return (T)Convert.ChangeType(rawJson, typeof(T));
}
return JsonConvert.DeserializeObject<T>(rawJson);
}
private string GetAccessTokenFromCallbackResult(IWebDriver driver)
{
var source = driver.FindElement(By.TagName("body")).Text;
var json = JObject.Parse(source);
return json.GetValue("apiKey")!.Value<string>();
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using TestExtensions;
using UnitTests.GrainInterfaces;
using Xunit;
namespace DefaultCluster.Tests.ActivationsLifeCycleTests
{
public class GrainActivateDeactivateTests : HostedTestClusterEnsureDefaultStarted, IDisposable
{
private IActivateDeactivateWatcherGrain watcher;
public GrainActivateDeactivateTests(DefaultClusterFixture fixture) : base(fixture)
{
watcher = this.GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(0);
watcher.Clear().Wait();
}
public virtual void Dispose()
{
watcher.Clear().Wait();
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")]
public async Task WatcherGrain_GetGrain()
{
IActivateDeactivateWatcherGrain grain = this.GrainFactory.GetGrain<IActivateDeactivateWatcherGrain>(1);
await grain.Clear();
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task Activate_Simple()
{
int id = random.Next();
ISimpleActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ISimpleActivateDeactivateTestGrain>(id);
string activation = await grain.DoSomething();
await CheckNumActivateDeactivateCalls(1, 0, activation, "After activation");
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task Deactivate_Simple()
{
int id = random.Next();
ISimpleActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ISimpleActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task Reactivate_Simple()
{
int id = random.Next();
ISimpleActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ISimpleActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
// Reactivate
string activation2 = await grain.DoSomething();
Assert.NotEqual(activation, activation2); // New activation created after re-activate
await CheckNumActivateDeactivateCalls(2, 1, new[] { activation, activation2 }, "After reactivation");
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task Activate_TailCall()
{
int id = random.Next();
ITailCallActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ITailCallActivateDeactivateTestGrain>(id);
string activation = await grain.DoSomething();
await CheckNumActivateDeactivateCalls(1, 0, activation, "After activation");
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task Deactivate_TailCall()
{
int id = random.Next();
ITailCallActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ITailCallActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task Reactivate_TailCall()
{
int id = random.Next();
ITailCallActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ITailCallActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
// Reactivate
string activation2 = await grain.DoSomething();
Assert.NotEqual(activation, activation2); // New activation created after re-activate
await CheckNumActivateDeactivateCalls(2, 1, new[] { activation, activation2 }, "After reactivation");
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate"), TestCategory("Reentrancy")]
public async Task LongRunning_Deactivate()
{
int id = random.Next();
ILongRunningActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ILongRunningActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
await CheckNumActivateDeactivateCalls(1, 0, activation, "Before deactivation");
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation, "After deactivation");
// Reactivate
string activation2 = await grain.DoSomething();
Assert.NotEqual(activation, activation2); // New activation created after re-activate;
await CheckNumActivateDeactivateCalls(2, 1, new[] { activation, activation2 }, "After reactivation");
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task BadActivate_Await()
{
try
{
int id = random.Next();
IBadActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<IBadActivateDeactivateTestGrain>(id);
await grain.ThrowSomething();
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain");
}
catch (ApplicationException exc)
{
Assert.Contains("Application-OnActivateAsync", exc.Message);
}
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task BadActivate_GetValue()
{
try
{
int id = random.Next();
IBadActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<IBadActivateDeactivateTestGrain>(id);
long key = await grain.GetKey();
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain, but returned " + key);
}
catch (ApplicationException exc)
{
Assert.Contains("Application-OnActivateAsync", exc.Message);
}
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task BadActivate_Await_ViaOtherGrain()
{
try
{
int id = random.Next();
ICreateGrainReferenceTestGrain grain = this.GrainFactory.GetGrain<ICreateGrainReferenceTestGrain>(id);
await grain.ForwardCall(this.GrainFactory.GetGrain<IBadActivateDeactivateTestGrain>(id));
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain");
}
catch (ApplicationException exc)
{
Assert.Contains("Application-OnActivateAsync", exc.Message);
}
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task Constructor_Bad_Await()
{
try
{
int id = random.Next();
IBadConstructorTestGrain grain = this.GrainFactory.GetGrain<IBadConstructorTestGrain>(id);
await grain.DoSomething();
Assert.True(false, "Expected ThrowSomething call to fail as unable to Activate grain");
}
catch (TimeoutException te)
{
Console.WriteLine("Received timeout: " + te);
throw; // Fail test
}
catch (Exception exc)
{
AssertIsNotInvalidOperationException(exc, "Constructor");
}
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task Constructor_CreateGrainReference()
{
int id = random.Next();
ICreateGrainReferenceTestGrain grain = this.GrainFactory.GetGrain<ICreateGrainReferenceTestGrain>(id);
string activation = await grain.DoSomething();
Assert.NotNull(activation);
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task TaskAction_Deactivate()
{
int id = random.Next();
ITaskActionActivateDeactivateTestGrain grain = this.GrainFactory.GetGrain<ITaskActionActivateDeactivateTestGrain>(id);
// Activate
string activation = await grain.DoSomething();
// Deactivate
await grain.DoDeactivate();
Thread.Sleep(TimeSpan.FromSeconds(2)); // Allow some time for deactivate to happen
await CheckNumActivateDeactivateCalls(1, 1, activation.ToString());
}
[Fact, TestCategory("BVT"), TestCategory("ActivateDeactivate")]
public async Task DeactivateOnIdleWhileActivate()
{
int id = random.Next();
IDeactivatingWhileActivatingTestGrain grain = this.GrainFactory.GetGrain<IDeactivatingWhileActivatingTestGrain>(id);
try
{
string activation = await grain.DoSomething();
Assert.True(false, "Should have thrown.");
}
catch(InvalidOperationException exc)
{
this.Logger.Info("Thrown as expected:", exc);
Assert.True(
exc.Message.Contains("DeactivateOnIdle from within OnActivateAsync"),
"Did not get expected exception message returned: " + exc.Message);
}
}
private async Task CheckNumActivateDeactivateCalls(
int expectedActivateCalls,
int expectedDeactivateCalls,
string forActivation,
string when = null)
{
await CheckNumActivateDeactivateCalls(
expectedActivateCalls,
expectedDeactivateCalls,
new string[] { forActivation },
when )
;
}
private async Task CheckNumActivateDeactivateCalls(
int expectedActivateCalls,
int expectedDeactivateCalls,
string[] forActivations,
string when = null)
{
string[] activateCalls = await watcher.GetActivateCalls();
Assert.Equal(expectedActivateCalls, activateCalls.Length);
string[] deactivateCalls = await watcher.GetDeactivateCalls();
Assert.Equal(expectedDeactivateCalls, deactivateCalls.Length);
for (int i = 0; i < expectedActivateCalls; i++)
{
Assert.Equal(forActivations[i], activateCalls[i]);
}
for (int i = 0; i < expectedDeactivateCalls; i++)
{
Assert.Equal(forActivations[i], deactivateCalls[i]);
}
}
private static void AssertIsNotInvalidOperationException(Exception thrownException, string expectedMessageSubstring)
{
Console.WriteLine("Received exception: " + thrownException);
Exception e = thrownException.GetBaseException();
Console.WriteLine("Nested exception type: " + e.GetType().FullName);
Console.WriteLine("Nested exception message: " + e.Message);
Assert.IsAssignableFrom<Exception>(e);
Assert.False(e is InvalidOperationException);
Assert.True(e.Message.Contains(expectedMessageSubstring), "Did not get expected exception message returned: " + e.Message);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
namespace OpenSim.ApplicationPlugins.Rest.Inventory
{
/// <remarks>
/// The class signature reveals the roles that RestHandler plays.
///
/// [1] It is a sub-class of RestPlugin. It inherits and extends
/// the functionality of this class, constraining it to the
/// specific needs of this REST implementation. This relates
/// to the plug-in mechanism supported by OpenSim, the specifics
/// of which are mostly hidden by RestPlugin.
/// [2] IRestHandler describes the interface that this class
/// exports to service implementations. This is the services
/// management interface.
/// [3] IHttpAgentHandler describes the interface that is exported
/// to the BaseHttpServer in support of this particular HTTP
/// processing model. This is the request interface of the
/// handler.
/// </remarks>
public class RestHandler : RestPlugin, IRestHandler, IHttpAgentHandler
{
// Handler tables: both stream and REST are supported. The path handlers and their
// respective allocators are stored in separate tables.
internal Dictionary<string,RestMethodHandler> pathHandlers = new Dictionary<string,RestMethodHandler>();
internal Dictionary<string,RestMethodAllocator> pathAllocators = new Dictionary<string,RestMethodAllocator>();
internal Dictionary<string,RestStreamHandler> streamHandlers = new Dictionary<string,RestStreamHandler>();
#region local static state
private static bool handlersLoaded = false;
private static List<Type> classes = new List<Type>();
private static List<IRest> handlers = new List<IRest>();
private static Type[] parms = new Type[0];
private static Object[] args = new Object[0];
/// <summary>
/// This static initializer scans the ASSEMBLY for classes that
/// export the IRest interface and builds a list of them. These
/// are later activated by the handler. To add a new handler it
/// is only necessary to create a new services class that implements
/// the IRest interface, and recompile the handler. This gives
/// all of the build-time flexibility of a modular approach
/// while not introducing yet-another module loader. Note that
/// multiple assembles can still be built, each with its own set
/// of handlers. Examples of services classes are RestInventoryServices
/// and RestSkeleton.
/// </summary>
static RestHandler()
{
Module[] mods = Assembly.GetExecutingAssembly().GetModules();
foreach (Module m in mods)
{
Type[] types = m.GetTypes();
foreach (Type t in types)
{
try
{
if (t.GetInterface("IRest") != null)
{
classes.Add(t);
}
}
catch (Exception)
{
Rest.Log.WarnFormat("[STATIC-HANDLER]: #0 Error scanning {1}", t);
Rest.Log.InfoFormat("[STATIC-HANDLER]: #0 {1} is not included", t);
}
}
}
}
#endregion local static state
#region local instance state
/// <summary>
/// This routine loads all of the handlers discovered during
/// instance initialization.
/// A table of all loaded and successfully constructed handlers
/// is built, and this table is then used by the constructor to
/// initialize each of the handlers in turn.
/// NOTE: The loading process does not automatically imply that
/// the handler has registered any kind of an interface, that
/// may be (optionally) done by the handler either during
/// construction, or during initialization.
///
/// I was not able to make this code work within a constructor
/// so it is isolated within this method.
/// </summary>
private void LoadHandlers()
{
lock (handlers)
{
if (!handlersLoaded)
{
ConstructorInfo ci;
Object ht;
foreach (Type t in classes)
{
try
{
ci = t.GetConstructor(parms);
ht = ci.Invoke(args);
handlers.Add((IRest)ht);
}
catch (Exception e)
{
Rest.Log.WarnFormat("{0} Unable to load {1} : {2}", MsgId, t, e.Message);
}
}
handlersLoaded = true;
}
}
}
#endregion local instance state
#region overriding properties
// These properties override definitions
// in the base class.
// Name is used to differentiate the message header.
public override string Name
{
get { return "HANDLER"; }
}
// Used to partition the .ini configuration space.
public override string ConfigName
{
get { return "RestHandler"; }
}
// We have to rename these because we want
// to be able to share the values with other
// classes in our assembly and the base
// names are protected.
public string MsgId
{
get { return base.MsgID; }
}
public string RequestId
{
get { return base.RequestID; }
}
#endregion overriding properties
#region overriding methods
/// <summary>
/// This method is called by OpenSimMain immediately after loading the
/// plugin and after basic server setup, but before running any server commands.
/// </summary>
/// <remarks>
/// Note that entries MUST be added to the active configuration files before
/// the plugin can be enabled.
/// </remarks>
public override void Initialise(OpenSimBase openSim)
{
try
{
// This plugin will only be enabled if the broader
// REST plugin mechanism is enabled.
Rest.Log.InfoFormat("{0} Plugin is initializing", MsgId);
base.Initialise(openSim);
// IsEnabled is implemented by the base class and
// reflects an overall RestPlugin status
if (!IsEnabled)
{
Rest.Log.WarnFormat("{0} Plugins are disabled", MsgId);
return;
}
Rest.Log.InfoFormat("{0} Rest <{1}> plugin will be enabled", MsgId, Name);
Rest.Log.InfoFormat("{0} Configuration parameters read from <{1}>", MsgId, ConfigName);
// These are stored in static variables to make
// them easy to reach from anywhere in the assembly.
Rest.main = openSim;
if (Rest.main == null)
throw new Exception("OpenSim base pointer is null");
Rest.Plugin = this;
Rest.Config = Config;
Rest.Prefix = Prefix;
Rest.GodKey = GodKey;
Rest.Authenticate = Rest.Config.GetBoolean("authenticate", Rest.Authenticate);
Rest.Scheme = Rest.Config.GetString("auth-scheme", Rest.Scheme);
Rest.Secure = Rest.Config.GetBoolean("secured", Rest.Secure);
Rest.ExtendedEscape = Rest.Config.GetBoolean("extended-escape", Rest.ExtendedEscape);
Rest.Realm = Rest.Config.GetString("realm", Rest.Realm);
Rest.DumpAsset = Rest.Config.GetBoolean("dump-asset", Rest.DumpAsset);
Rest.Fill = Rest.Config.GetBoolean("path-fill", Rest.Fill);
Rest.DumpLineSize = Rest.Config.GetInt("dump-line-size", Rest.DumpLineSize);
Rest.FlushEnabled = Rest.Config.GetBoolean("flush-on-error", Rest.FlushEnabled);
// Note: Odd spacing is required in the following strings
Rest.Log.InfoFormat("{0} Authentication is {1}required", MsgId,
(Rest.Authenticate ? "" : "not "));
Rest.Log.InfoFormat("{0} Security is {1}enabled", MsgId,
(Rest.Secure ? "" : "not "));
Rest.Log.InfoFormat("{0} Extended URI escape processing is {1}enabled", MsgId,
(Rest.ExtendedEscape ? "" : "not "));
Rest.Log.InfoFormat("{0} Dumping of asset data is {1}enabled", MsgId,
(Rest.DumpAsset ? "" : "not "));
// The supplied prefix MUST be absolute
if (Rest.Prefix.Substring(0,1) != Rest.UrlPathSeparator)
{
Rest.Log.WarnFormat("{0} Prefix <{1}> is not absolute and must be", MsgId, Rest.Prefix);
Rest.Log.InfoFormat("{0} Prefix changed to </{1}>", MsgId, Rest.Prefix);
Rest.Prefix = String.Format("{0}{1}", Rest.UrlPathSeparator, Rest.Prefix);
}
// If data dumping is requested, report on the chosen line
// length.
if (Rest.DumpAsset)
{
Rest.Log.InfoFormat("{0} Dump {1} bytes per line", MsgId, Rest.DumpLineSize);
}
// Load all of the handlers present in the
// assembly
// In principle, as we're an application plug-in,
// most of what needs to be done could be done using
// static resources, however the Open Sim plug-in
// model makes this an instance, so that's what we
// need to be.
// There is only one Communications manager per
// server, and by inference, only one each of the
// user, asset, and inventory servers. So we can cache
// those using a static initializer.
// We move all of this processing off to another
// services class to minimize overlap between function
// and infrastructure.
LoadHandlers();
// The intention of a post construction initializer
// is to allow for setup that is dependent upon other
// activities outside of the agency.
foreach (IRest handler in handlers)
{
try
{
handler.Initialize();
}
catch (Exception e)
{
Rest.Log.ErrorFormat("{0} initialization error: {1}", MsgId, e.Message);
}
}
// Now that everything is setup we can proceed to
// add THIS agent to the HTTP server's handler list
if (!AddAgentHandler(Rest.Name,this))
{
Rest.Log.ErrorFormat("{0} Unable to activate handler interface", MsgId);
foreach (IRest handler in handlers)
{
handler.Close();
}
}
}
catch (Exception e)
{
Rest.Log.ErrorFormat("{0} Plugin initialization has failed: {1}", MsgId, e.Message);
}
}
/// <summary>
/// In the interests of efficiency, and because we cannot determine whether
/// or not this instance will actually be harvested, we clobber the only
/// anchoring reference to the working state for this plug-in. What the
/// call to close does is irrelevant to this class beyond knowing that it
/// can nullify the reference when it returns.
/// To make sure everything is copacetic we make sure the primary interface
/// is disabled by deleting the handler from the HTTP server tables.
/// </summary>
public override void Close()
{
Rest.Log.InfoFormat("{0} Plugin is terminating", MsgId);
try
{
RemoveAgentHandler(Rest.Name, this);
}
catch (KeyNotFoundException){}
foreach (IRest handler in handlers)
{
handler.Close();
}
}
#endregion overriding methods
#region interface methods
/// <summary>
/// This method is called by the HTTP server to match an incoming
/// request. It scans all of the strings registered by the
/// underlying handlers and looks for the best match. It returns
/// true if a match is found.
/// The matching process could be made arbitrarily complex.
/// Note: The match is case-insensitive.
/// </summary>
public bool Match(OSHttpRequest request, OSHttpResponse response)
{
string path = request.RawUrl.ToLower();
// Rest.Log.DebugFormat("{0} Match ENTRY", MsgId);
try
{
foreach (string key in pathHandlers.Keys)
{
// Rest.Log.DebugFormat("{0} Match testing {1} against agent prefix <{2}>", MsgId, path, key);
// Note that Match will not necessarily find the handler that will
// actually be used - it does no test for the "closest" fit. It
// simply reflects that at least one possible handler exists.
if (path.StartsWith(key))
{
// Rest.Log.DebugFormat("{0} Matched prefix <{1}>", MsgId, key);
// This apparently odd evaluation is needed to prevent a match
// on anything other than a URI token boundary. Otherwise we
// may match on URL's that were not intended for this handler.
return (path.Length == key.Length ||
path.Substring(key.Length, 1) == Rest.UrlPathSeparator);
}
}
path = String.Format("{0}{1}{2}", request.HttpMethod, Rest.UrlMethodSeparator, path);
foreach (string key in streamHandlers.Keys)
{
// Rest.Log.DebugFormat("{0} Match testing {1} against stream prefix <{2}>", MsgId, path, key);
// Note that Match will not necessarily find the handler that will
// actually be used - it does no test for the "closest" fit. It
// simply reflects that at least one possible handler exists.
if (path.StartsWith(key))
{
// Rest.Log.DebugFormat("{0} Matched prefix <{1}>", MsgId, key);
// This apparently odd evaluation is needed to prevent a match
// on anything other than a URI token boundary. Otherwise we
// may match on URL's that were not intended for this handler.
return (path.Length == key.Length ||
path.Substring(key.Length, 1) == Rest.UrlPathSeparator);
}
}
}
catch (Exception e)
{
Rest.Log.ErrorFormat("{0} matching exception for path <{1}> : {2}", MsgId, path, e.Message);
}
return false;
}
/// <summary>
/// This is called by the HTTP server once the handler has indicated
/// that it is able to handle the request.
/// Preconditions:
/// [1] request != null and is a valid request object
/// [2] response != null and is a valid response object
/// Behavior is undefined if preconditions are not satisfied.
/// </summary>
public bool Handle(OSHttpRequest request, OSHttpResponse response)
{
bool handled;
base.MsgID = base.RequestID;
// Debug only
if (Rest.DEBUG)
{
Rest.Log.DebugFormat("{0} ENTRY", MsgId);
Rest.Log.DebugFormat("{0} Agent: {1}", MsgId, request.UserAgent);
Rest.Log.DebugFormat("{0} Method: {1}", MsgId, request.HttpMethod);
for (int i = 0; i < request.Headers.Count; i++)
{
Rest.Log.DebugFormat("{0} Header [{1}] : <{2}> = <{3}>",
MsgId, i, request.Headers.GetKey(i), request.Headers.Get(i));
}
Rest.Log.DebugFormat("{0} URI: {1}", MsgId, request.RawUrl);
}
// If a path handler worked we're done, otherwise try any
// available stream handlers too.
try
{
handled = (FindPathHandler(request, response) ||
FindStreamHandler(request, response));
}
catch (Exception e)
{
// A raw exception indicates that something we weren't expecting has
// happened. This should always reflect a shortcoming in the plugin,
// or a failure to satisfy the preconditions. It should not reflect
// an error in the request itself. Under such circumstances the state
// of the request cannot be determined and we are obliged to mark it
// as 'handled'.
Rest.Log.ErrorFormat("{0} Plugin error: {1}", MsgId, e.Message);
handled = true;
}
Rest.Log.DebugFormat("{0} EXIT", MsgId);
return handled;
}
#endregion interface methods
/// <summary>
/// If there is a stream handler registered that can handle the
/// request, then fine. If the request is not matched, do
/// nothing.
/// Note: The selection is case-insensitive
/// </summary>
private bool FindStreamHandler(OSHttpRequest request, OSHttpResponse response)
{
RequestData rdata = new RequestData(request, response, String.Empty);
string bestMatch = String.Empty;
string path = String.Format("{0}:{1}", rdata.method, rdata.path).ToLower();
Rest.Log.DebugFormat("{0} Checking for stream handler for <{1}>", MsgId, path);
if (!IsEnabled)
{
return false;
}
foreach (string pattern in streamHandlers.Keys)
{
if (path.StartsWith(pattern))
{
if (pattern.Length > bestMatch.Length)
{
bestMatch = pattern;
}
}
}
// Handle using the best match available
if (bestMatch.Length > 0)
{
Rest.Log.DebugFormat("{0} Stream-based handler matched with <{1}>", MsgId, bestMatch);
RestStreamHandler handler = streamHandlers[bestMatch];
rdata.buffer = handler.Handle(rdata.path, rdata.request.InputStream, rdata.request, rdata.response);
rdata.AddHeader(rdata.response.ContentType,handler.ContentType);
rdata.Respond("FindStreamHandler Completion");
}
return rdata.handled;
}
/// <summary>
/// Add a stream handler for the designated HTTP method and path prefix.
/// If the handler is not enabled, the request is ignored. If the path
/// does not start with the REST prefix, it is added. If method-qualified
/// path has not already been registered, the method is added to the active
/// handler table.
/// </summary>
public void AddStreamHandler(string httpMethod, string path, RestMethod method)
{
if (!IsEnabled)
{
return;
}
if (!path.StartsWith(Rest.Prefix))
{
path = String.Format("{0}{1}", Rest.Prefix, path);
}
path = String.Format("{0}{1}{2}", httpMethod, Rest.UrlMethodSeparator, path);
// Conditionally add to the list
if (!streamHandlers.ContainsKey(path))
{
streamHandlers.Add(path, new RestStreamHandler(httpMethod, path, method));
Rest.Log.DebugFormat("{0} Added handler for {1}", MsgId, path);
}
else
{
Rest.Log.WarnFormat("{0} Ignoring duplicate handler for {1}", MsgId, path);
}
}
/// <summary>
/// Given the supplied request/response, if the handler is enabled, the inbound
/// information is used to match an entry in the active path handler tables, using
/// the method-qualified path information. If a match is found, then the handler is
/// invoked. The result is the boolean result of the handler, or false if no
/// handler was located. The boolean indicates whether or not the request has been
/// handled, not whether or not the request was successful - that information is in
/// the response.
/// Note: The selection process is case-insensitive
/// </summary>
internal bool FindPathHandler(OSHttpRequest request, OSHttpResponse response)
{
RequestData rdata = null;
string bestMatch = null;
if (!IsEnabled)
{
return false;
}
// Conditionally add to the list
Rest.Log.DebugFormat("{0} Checking for path handler for <{1}>", MsgId, request.RawUrl);
foreach (string pattern in pathHandlers.Keys)
{
if (request.RawUrl.ToLower().StartsWith(pattern))
{
if (String.IsNullOrEmpty(bestMatch) || pattern.Length > bestMatch.Length)
{
bestMatch = pattern;
}
}
}
if (!String.IsNullOrEmpty(bestMatch))
{
rdata = pathAllocators[bestMatch](request, response, bestMatch);
Rest.Log.DebugFormat("{0} Path based REST handler matched with <{1}>", MsgId, bestMatch);
try
{
pathHandlers[bestMatch](rdata);
}
// A plugin generated error indicates a request-related error
// that has been handled by the plugin.
catch (RestException r)
{
Rest.Log.WarnFormat("{0} Request failed: {1}", MsgId, r.Message);
}
}
return (rdata == null) ? false : rdata.handled;
}
/// <summary>
/// A method handler and a request allocator are stored using the designated
/// path as a key. If an entry already exists, it is replaced by the new one.
/// </summary>
public void AddPathHandler(RestMethodHandler mh, string path, RestMethodAllocator ra)
{
if (!IsEnabled)
{
return;
}
if (pathHandlers.ContainsKey(path))
{
Rest.Log.DebugFormat("{0} Replacing handler for <${1}>", MsgId, path);
pathHandlers.Remove(path);
}
if (pathAllocators.ContainsKey(path))
{
Rest.Log.DebugFormat("{0} Replacing allocator for <${1}>", MsgId, path);
pathAllocators.Remove(path);
}
Rest.Log.DebugFormat("{0} Adding path handler for {1}", MsgId, path);
pathHandlers.Add(path, mh);
pathAllocators.Add(path, ra);
}
}
}
| |
// 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.Numerics;
using Xunit;
namespace ComplexTestSupport
{
public static class Support
{
private static Random s_random;
static Support()
{
s_random = new Random(-55);
}
public static Random Random
{
get { return s_random; }
}
// Valid values in double type
public static Double[] doubleValidValues = new Double[] {
double.MinValue,
-1,
0,
double.Epsilon,
1,
double.MaxValue,
};
// Invalid values in double type
public static Double[] doubleInvalidValues = new Double[] {
double.NegativeInfinity,
double.PositiveInfinity,
double.NaN
};
// Typical phase values in double type
public static Double[] phaseTypicalValues = new Double[] {
-Math.PI/2,
0,
Math.PI/2
};
public static String[] supportedStdNumericFormats = new String[] { "C", "E", "F", "G", "N", "P", "R" };
private static double GetRandomValue(double mult, bool fIsNegative)
{
double randomDouble = (mult * s_random.NextDouble());
randomDouble %= (Double)(mult);
return fIsNegative ? -randomDouble : randomDouble;
}
public static double GetRandomDoubleValue(bool fIsNegative)
{
return GetRandomValue(double.MaxValue, fIsNegative);
}
public static double GetSmallRandomDoubleValue(bool fIsNegative)
{
return GetRandomValue(1.0, fIsNegative);
}
public static Int16 GetRandomInt16Value(bool fIsNegative)
{
if (fIsNegative)
{
return ((Int16)s_random.Next(Int16.MinValue, 0));
}
else
{
return ((Int16)s_random.Next(1, Int16.MaxValue));
}
}
public static Int32 GetRandomInt32Value(bool fIsNegative)
{
return ((Int32)GetRandomValue(Int32.MaxValue, fIsNegative));
}
public static Int64 GetRandomInt64Value(bool fIsNegative)
{
return ((Int64)GetRandomValue(Int64.MaxValue, fIsNegative));
}
public static Byte GetRandomByteValue()
{
return ((Byte)s_random.Next(1, Byte.MaxValue));
}
#if CLS_Compliant
public static SByte GetRandomSByteValue(bool fIsNegative)
{
if (fIsNegative)
{
return ((SByte) random.Next(SByte.MinValue, 0));
}
else
{
return ((SByte) random.Next(1, SByte.MaxValue));
}
}
public static UInt16 GetRandomUInt16Value()
{
return ((UInt16)random.Next(1, UInt16.MaxValue));
}
public static UInt32 GetRandomUInt32Value()
{
return ((UInt32)GetRandomValue(UInt32.MaxValue, false));
}
public static UInt64 GetRandomUInt64Value()
{
return ((UInt64)GetRandomValue(UInt64.MaxValue, false));
}
#endif
public static Single GetRandomSingleValue(bool fIsNegative)
{
return ((Single)GetRandomValue(Single.MaxValue, fIsNegative));
}
public static BigInteger GetRandomBigIntegerValue(bool fIsNegative)
{
return ((BigInteger)GetRandomValue(double.MaxValue, fIsNegative));
}
public static Decimal GetRandomDecimalValue(bool fIsNegative)
{
if (fIsNegative)
{
return ((Decimal)new Decimal(
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
true,
(byte)s_random.Next(0, 29)));
}
else
{
return ((Decimal)new Decimal(
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
false,
(byte)s_random.Next(0, 29)));
}
}
public static double GetRandomPhaseValue(bool fIsNegative)
{
return GetRandomValue((Math.PI / 2), fIsNegative);
}
public static bool IsDiffTolerable(double d1, double d2)
{
if (double.IsInfinity(d1))
{
return AreSameInfinity(d1, d2 * 10);
}
else if (double.IsInfinity(d2))
{
return AreSameInfinity(d1 * 10, d2);
}
else
{
double diffRatio = (d1 - d2) / d1;
diffRatio *= Math.Pow(10, 6);
diffRatio = Math.Abs(diffRatio);
return (diffRatio < 1);
}
}
private static bool AreSameInfinity(double d1, double d2)
{
return
double.IsNegativeInfinity(d1) == double.IsNegativeInfinity(d2) &&
double.IsPositiveInfinity(d1) == double.IsPositiveInfinity(d2);
}
public static void VerifyRealImaginaryProperties(Complex complex, double real, double imaginary, string message)
{
Assert.True(real.Equals((Double)complex.Real) || IsDiffTolerable(complex.Real, real), message);
Assert.True(imaginary.Equals((Double)complex.Imaginary) || IsDiffTolerable(complex.Imaginary, imaginary), message);
}
public static void VerifyMagnitudePhaseProperties(Complex complex, double magnitude, double phase, string message)
{
// The magnitude (m) of a complex number (z = x + yi) is the absolute value - |z| = sqrt(x^2 + y^2)
// Verification is done using the square of the magnitude since m^2 = x^2 + y^2
double expectedMagnitudeSqr = magnitude * magnitude;
double actualMagnitudeSqr = complex.Magnitude * complex.Magnitude;
Assert.True(expectedMagnitudeSqr.Equals((Double)(actualMagnitudeSqr)) || IsDiffTolerable(actualMagnitudeSqr, expectedMagnitudeSqr), message);
if (double.IsNaN(magnitude))
{
phase = double.NaN;
}
else if (magnitude == 0)
{
phase = 0;
}
else if (magnitude < 0)
{
phase += (phase < 0) ? Math.PI : -Math.PI;
}
Assert.True(phase.Equals((Double)complex.Phase) || IsDiffTolerable(complex.Phase, phase), message);
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using NUnit.Framework;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Pkcs.Tests
{
/**
* Exercise the various key stores, making sure we at least get back what we put in!
* <p>This tests both the PKCS12 key store.</p>
*/
[TestFixture]
public class Pkcs12StoreTest
: SimpleTest
{
private static readonly char[] passwd = "hello world".ToCharArray();
//
// pkcs-12 pfx-pdu
//
private static readonly byte[] pkcs12 = Base64.Decode(
"MIACAQMwgAYJKoZIhvcNAQcBoIAkgAQBMAQBgAQBMAQBgAQBBgQBCQQJKoZI"
+ "hvcNAQcBBAGgBAGABAEkBAGABAEEBAEBBAEwBAEEBAEDBAOCAzQEAQQEAQEE"
+ "ATAEAQQEAQMEA4IDMAQBBAQBAQQBBgQBBAQBAQQBCwQBBAQBCwQLKoZIhvcN"
+ "AQwKAQIEAQQEAQEEAaAEAQQEAQMEA4ICpQQBBAQBAQQBMAQBBAQBAwQDggKh"
+ "BAEEBAEBBAEwBAEEBAEBBAEbBAEEBAEBBAEGBAEEBAEBBAEKBAEEBAEKBAoq"
+ "hkiG9w0BDAEDBAEEBAEPBA8wDQQIoagiwNZPJR4CAQEEAQQEAQEEAQQEAQQE"
+ "AQMEA4ICgAQBBAQDggKABIICgEPG0XlhMFyrs4ZWDrvEzl51ICfXd6K2ql2l"
+ "nnxhszUbigtSj6x49VEx4PfOB9fQFeidc5L5An+nKp646NBMIY0UwXGs8BLQ"
+ "au59jtOs987+l7QYIvl6fdGUIuLPhVSnZZDyqD+HQjU/0/ccKFHRif4tlEQq"
+ "aErvZbFeH0pg4ijf1HfgX6gBJGRKdO+msa4qKGnZdHCSLZehyyxvxAmURetg"
+ "yhtEl7RmedTB+4TDs7atekqxkNlD9tfwDUX6sb0IH6qbEA6P/DlVMdaD54Cl"
+ "QDxRzOfIIjklZhv5OMFWtPK0aYPcqyxzLpw1qRAyoTVXpidkj/hpIpgCVBP/"
+ "k5s2+WdGbLgA/4/zSrF6feRCE5llzM2IGxiHVq4oPzzngl3R+Fi5VCPDMcuW"
+ "NRuIOzJA+RNV2NPOE/P3knThDnwiImq+rfxmvZ1u6T06s20RmWK6cxp7fTEw"
+ "lQ9BOsv+mmyV8dr6cYJq4IlRzHdFOyEUBDwfHThyribNKKobO50xh2f93xYj"
+ "Rn5UMOQBJIe3b7OKZt5HOIMrJSZO02IZgvImi9yQWi96PnWa419D1cAsLWvM"
+ "xiN0HqZMbDFfxVM2BZmsxiexLhkHWKwLqfQDzRjJfmVww8fnXpWZhFXKyut9"
+ "gMGEyCNoba4RU3QI/wHKWYaK74qtJpsucuLWBH6UcsHsCry6VZkwRxWwC0lb"
+ "/F3Bm5UKHax5n9JHJ2amQm9zW3WJ0S5stpPObfmg5ArhbPY+pVOsTqBRlop1"
+ "bYJLD/X8Qbs468Bwzej0FhoEU59ZxFrbjLSBsMUYrVrwD83JE9kEazMLVchc"
+ "uCB9WT1g0hxYb7VA0BhOrWhL8F5ZH72RMCYLPI0EAQQEAQEEATEEAQQEAQEE"
+ "AXgEAQQEAQEEATAEAQQEAQEEAVEEAQQEAQEEAQYEAQQEAQEEAQkEAQQEAQkE"
+ "CSqGSIb3DQEJFAQBBAQBAQQBMQQBBAQBAQQBRAQBBAQBAQQBHgQBBAQBAQQB"
+ "QgQBBAQBQgRCAEQAYQB2AGkAZAAgAEcALgAgAEgAbwBvAGsAJwBzACAAVgBl"
+ "AHIAaQBTAGkAZwBuACwAIABJAG4AYwAuACAASQBEBAEEBAEBBAEwBAEEBAEB"
+ "BAEjBAEEBAEBBAEGBAEEBAEBBAEJBAEEBAEJBAkqhkiG9w0BCRUEAQQEAQEE"
+ "ATEEAQQEAQEEARYEAQQEAQEEAQQEAQQEAQEEARQEAQQEARQEFKEcMJ798oZL"
+ "FkH0OnpbUBnrTLgWBAIAAAQCAAAEAgAABAEwBAGABAEGBAEJBAkqhkiG9w0B"
+ "BwYEAaAEAYAEATAEAYAEAQIEAQEEAQAEATAEAYAEAQYEAQkECSqGSIb3DQEH"
+ "AQQBMAQBGwQBBgQBCgQKKoZIhvcNAQwBBgQPMA0ECEE7euvmxxwYAgEBBAGg"
+ "BAGABAEEBAEIBAgQIWDGlBWxnwQBBAQBCAQI2WsMhavhSCcEAQQEAQgECPol"
+ "uHJy9bm/BAEEBAEQBBCiRxtllKXkJS2anKD2q3FHBAEEBAEIBAjKy6BRFysf"
+ "7gQBBAQDggMwBIIDMJWRGu2ZLZild3oz7UBdpBDUVMOA6eSoWiRIfVTo4++l"
+ "RUBm8TpmmGrVkV32PEoLkoV+reqlyWCvqqSjRzi3epQiVwPQ6PV+ccLqxDhV"
+ "pGWDRQ5UttDBC2+u4fUQVZi2Z1i1g2tsk6SzB3MKUCrjoWKvaDUUwXo5k9Vz"
+ "qSLWCLTZCjs3RaY+jg3NbLZYtfMDdYovhCU2jMYV9adJ8MxxmJRz+zPWAJph"
+ "LH8hhfkKG+wJOSszqk9BqGZUa/mnZyzeQSMTEFga1ZB/kt2e8SZFWrTZEBgJ"
+ "oszsL5MObbwMDowNurnZsnS+Mf7xi01LeG0VT1fjd6rn9BzVwuMwhoqyoCNo"
+ "ziUqSUyLEwnGTYYpvXLxzhNiYzW8546KdoEKDkEjhfYsc4XqSjm9NYy/BW/M"
+ "qR+aL92j8hqnkrWkrWyvocUe3mWaiqt7/oOzNZiMTcV2dgjjh9HfnjSHjFGe"
+ "CVhnEWzV7dQIVyc/qvNzOuND8X5IyJ28xb6a/i1vScwGuo/UDgPAaMjGw28f"
+ "siOZBShzde0Kj82y8NilfYLHHeIGRW+N/grUFWhW25mAcBReXDd5JwOqM/eF"
+ "y+4+zBzlO84ws88T1pkSifwtMldglN0APwr4hvUH0swfiqQOWtwyeM4t+bHd"
+ "5buAlXOkSeF5rrLzZ2/Lx+JJmI2pJ/CQx3ej3bxPlx/BmarUGAxaI4le5go4"
+ "KNfs4GV8U+dbEHQz+yDYL+ksYNs1eb+DjI2khbl28jhoeAFKBtu2gGOL5M9M"
+ "CIP/JDOCHimu1YZRuOTAf6WISnG/0Ri3pYZsgQ0i4cXj+WfYwYVjhKX5AcDj"
+ "UKnc4/Cxp+TbbgZqEKRcYVb2q0kOAxkeaNo3WCm+qvUYrwAmKp4nVB+/24rK"
+ "khHiyYJQsETxtOEyvJkVxAS01djY4amuJ4jL0sYnXIhW3Ag93eavbzksGT7W"
+ "Fg1ywpr1x1xpXWIIuVt1k4e+g9fy7Yx7rx0IK1qCSjNwU3QPWbaef1rp0Q/X"
+ "P9IVXYkqo1g/T3SyXqrbZLO+sDjiG4IT3z3fJJqt81sRSVT0QN1ND8l93BG4"
+ "QKzghYw8sZ4FwKPtLky1dDcVTgQBBAQBCAQIK/85VMKWDWYEAQQEAQgECGsO"
+ "Q85CcFwPBAEEBAEIBAhaup6ot9XnQAQBBAQCgaAEgaCeCMadSm5fkLfhErYQ"
+ "DgePZl/rrjP9FQ3VJZ13XrjTSjTRknAbXi0DEu2tvAbmCf0sdoVNuZIZ92W0"
+ "iyaa2/A3RHA2RLPNQz5meTi1RE2N361yR0q181dC3ztkkJ8PLyd74nCtgPUX"
+ "0JlsvLRrdSjPBpBQ14GiM8VjqeIY7EVFy3vte6IbPzodxaviuSc70iXM4Yko"
+ "fQq6oaSjNBFRqkHrBAEEBAEIBAjlIvOf8SnfugQBBAQBCAQIutCF3Jovvl0E"
+ "AQQEAQgECO7jxbucdp/3BAEEBAEIBAidxK3XDLj+BwQBBAQBCAQI3m/HMbd3"
+ "TwwEAQQEA4ICOASCAjgtoCiMfTkjpCRuMhF5gNLRBiNv+xjg6GvZftR12qiJ"
+ "dLeCERI5bvXbh9GD6U+DjTUfhEab/37TbiI7VOFzsI/R137sYy9Tbnu7qkSx"
+ "u0bTvyXSSmio6sMRiWIcakmDbv+TDWR/xgtj7+7C6p+1jfUGXn/RjB3vlyjL"
+ "Q9lFe5F84qkZjnADo66p9gor2a48fgGm/nkABIUeyzFWCiTp9v6FEzuBfeuP"
+ "T9qoKSnCitaXRCru5qekF6L5LJHLNXLtIMSrbO0bS3hZK58FZAUVMaqawesJ"
+ "e/sVfQip9x/aFQ6U3KlSpJkmZK4TAqp9jIfxBC8CclbuwmoXPMomiCH57ykr"
+ "vkFHOGcxRcCxax5HySCwSyPDr8I4+6Kocty61i/1Xr4xJjb+3oyFStIpB24x"
+ "+ALb0Mz6mUa1ls76o+iQv0VM2YFwnx+TC8KC1+O4cNOE/gKeh0ircenVX83h"
+ "GNez8C5Ltg81g6p9HqZPc2pkwsneX2sJ4jMsjDhewV7TyyS3x3Uy3vTpZPek"
+ "VdjYeVIcgAz8VLJOpsIjyHMB57AyT7Yj87hVVy//VODnE1T88tRXZb+D+fCg"
+ "lj2weQ/bZtFzDX0ReiEQP6+yklGah59omeklIy9wctGV1o9GNZnGBSLvQ5NI"
+ "61e9zmQTJD2iDjihvQA/6+edKswCjGRX6rMjRWXT5Jv436l75DVoUj09tgR9"
+ "ytXSathCjQUL9MNXzUMtr7mgEUPETjM/kYBR7CNrsc+gWTWHYaSWuqKVBAEE"
+ "BAEIBAh6slfZ6iqkqwQBBAQBCAQI9McJKl5a+UwEAQQEATgEOBelrmiYMay3"
+ "q0OW2x2a8QQodYqdUs1TCUU4JhfFGFRy+g3yU1cP/9ZSI8gcI4skdPc31cFG"
+ "grP7BAEEBAEIBAhzv/wSV+RBJQQBBAQBCAQI837ImVqqlr4EAQQEAQgECGeU"
+ "gjULLnylBAEEBAEIBAjD3P4hlSBCvQQBBAQBCAQISP/qivIzf50EAQQEAQgE"
+ "CKIDMX9PKxICBAEEBAOCBOgEggTocP5VVT1vWvpAV6koZupKN1btJ3C01dR6"
+ "16g1zJ5FK5xL1PTdA0r6iAwVtgYdxQYnU8tht3bkNXdPJC1BdsC9oTkBg9Nr"
+ "dqlF5cCzXWIezcR3ObjGLpXu49SAHvChH4emT5rytv81MYxZ7bGmlQfp8BNa"
+ "0cMZz05A56LXw//WWDEzZcbKSk4tCsfMXBdGk/ngs7aILZ4FGM620PBPtD92"
+ "pz2Ui/tUZqtQ0WKdLzwga1E/rl02a/x78/OdlVRNeaIYWJWLmLavX98w0PhY"
+ "ha3Tbj/fqq+H3ua6Vv2Ff4VeXazkXpp4tTiqUxhc6aAGiRYckwZaP7OPSbos"
+ "RKFlRLVofSGu1IVSKO+7faxV4IrVaAAzqRwLGkpJZLV7NkzkU1BwgvsAZAI4"
+ "WClPDF228ygbhLwrSN2NK0s+5bKhTCNAR/LCUf3k7uip3ZSe18IwEkUMWiaZ"
+ "ayktcTYn2ZjmfIfV7wIxHgWPkP1DeB+RMS7VZe9zEgJKOA16L+9SNBwJSSs9"
+ "5Sb1+nmhquZmnAltsXMgwOrR12JLIgdfyyqGcNq997U0/KuHybqBVDVu0Fyr"
+ "6O+q5oRmQZq6rju7h+Hb/ZUqRxRoTTSPjGD4Cu9vUqkoNVgwYOT+88FIMYun"
+ "g9eChhio2kwPYwU/9BNGGzh+hAvAKcUpO016mGLImYin+FpQxodJXfpNCFpG"
+ "4v4HhIwKh71OOfL6ocM/518dYwuU4Ds2/JrDhYYFsn+KprLftjrnTBnSsfYS"
+ "t68b+Xr16qv9r6sseEkXbsaNbrGiZAhfHEVBOxQ4lchHrMp4zpduxG4crmpc"
+ "+Jy4SadvS0uaJvADgI03DpsDYffUdriECUqAfOg/Hr7HHyr6Q9XMo1GfIarz"
+ "eUHBgi1Ny0nDTWkdb7I3bIajG+Unr3KfK6dZz5Lb3g5NeclU5zintB1045Jr"
+ "j9fvGGk0/2lG0n17QViBiOzGs2poTlhn7YxmiskwlkRKVafxPZNPxKILpN9s"
+ "YaWGz93qER/pGMJarGJxu8sFi3+yt6FZ4pVPkvKE8JZMEPBBrmH41batS3sw"
+ "sfnJ5CicAkwd8bluQpoc6qQd81HdNpS6u7djaRSDwPtYnZWu/8Hhj4DXisje"
+ "FJBAjQdn2nK4MV7WKVwr+mNcVgOdc5IuOZbRLOfc3Sff6kYVuQFfcCGgAFpd"
+ "nbprF/FnYXR/rghWE7fT1gfzSMNv+z5UjZ5Rtg1S/IQfUM/P7t0UqQ01/w58"
+ "bTlMGihTxHiJ4Qf3o5GUzNmAyryLvID+nOFqxpr5es6kqSN4GPRHsmUIpB9t"
+ "f9Nw952vhsXI9uVkhQap3JvmdAKJaIyDz6Qi7JBZvhxpghVIDh73BQTaAFP9"
+ "5GUcPbYOYJzKaU5MeYEsorGoanSqPDeKDeZxjxJD4xFsqJCoutyssqIxnXUN"
+ "Y3Uojbz26IJOhqIBLaUn6QVFX79buWYjJ5ZkDS7D8kq6DZeqZclt5711AO5U"
+ "uz/eDSrx3d4iVHR+kSeopxFKsrK+KCH3CbBUMIFGX/GE9WPhDWCtjjNKEe8W"
+ "PinQtxvv8MlqGXtv3v7ObJ2BmfIfLD0rh3EB5WuRNKL7Ssxaq14KZGEBvc7G"
+ "Fx7jXLOW6ZV3SH+C3deJGlKM2kVhDdIVjjODvQzD8qw8a/ZKqDO5hGGKUTGD"
+ "Psdd7O/k/Wfn+XdE+YuKIhcEAQQEAQgECJJCZNJdIshRBAEEBAEIBAiGGrlG"
+ "HlKwrAQBBAQBCAQIkdvKinJYjJcEAQQEAUAEQBGiIgN/s1bvPQr+p1aQNh/X"
+ "UQFmay6Vm5HIvPhoNrX86gmMjr6/sg28/WCRtSfyuYjwQkK91n7MwFLOBaU3"
+ "RrsEAQQEAQgECLRqESFR50+zBAEEBAEIBAguqbAEWMTiPwQBBAQBGAQYKzUv"
+ "EetQEAe3cXEGlSsY4a/MNTbzu1WbBAEEBAEIBAiVpOv1dOWZ1AQCAAAEAgAA"
+ "BAIAAAQCAAAEAgAABAIAAAAAAAAAADA1MCEwCQYFKw4DAhoFAAQUvMkeVqe6"
+ "D4UmMHGEQwcb8O7ZwhgEEGiX9DeqtRwQnVi+iY/6Re8AAA==");
private static readonly byte[] certUTF = Base64.Decode(
"MIIGVQIBAzCCBg8GCSqGSIb3DQEHAaCCBgAEggX8MIIF+DCCAsUGCSqGSIb3"
+ "DQEHAaCCArYEggKyMIICrjCCAqoGCyqGSIb3DQEMCgEDoIIChTCCAoEGCiqG"
+ "SIb3DQEJFgGgggJxBIICbTCCAmkwggHSoAMCAQICAQcwDQYJKoZIhvcNAQEF"
+ "BQAwOTEPMA0GA1UEBxMGTGV1dmVuMRkwFwYDVQQKExBVdGltYWNvIFN1YiBD"
+ "QSAyMQswCQYDVQQGEwJCRTAeFw05OTEyMzEyMzAwMDBaFw0xOTEyMzEyMzAw"
+ "MDBaMFcxCzAJBgNVBAYTAkJFMQ8wDQYDVQQHEwZIYWFjaHQxEDAOBgNVBAoT"
+ "B1V0aW1hY28xDDAKBgNVBAsMA1ImRDEXMBUGA1UEAxMOR2VlcnQgRGUgUHJp"
+ "bnMwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANYGIyhTn/p0IA41ElLD"
+ "fZ44PS88AAcDCiOd2DIMLck56ea+5nhI0JLyz1XgPHecc8SLFdl7vSIBA0eb"
+ "tm/A7WIqIp0lcvgoyQ0qsak/dvzs+xw6r2xLCVogku4+/To6UebtfRsukXNI"
+ "ckP5lWV/Ui4l+XvGdmENlEE9/BvOZIvLAgMBAAGjYzBhMBEGA1UdIwQKMAiA"
+ "BlN1YkNBMjAQBgNVHQ4ECQQHVXNlcklEMjAOBgNVHQ8BAf8EBAMCBLAwGQYD"
+ "VR0RBBIwEIEOVXNlcklEMkB1dGkuYmUwDwYDVR0TAQH/BAUwAwEBADANBgkq"
+ "hkiG9w0BAQUFAAOBgQACS7iLLgMV4O5gFdriI7dqX55l7Qn6HiRNxlSH2kCX"
+ "41X82gae4MHFc41qqsC4qm6KZWi1yvTN9XgSBCXTaw1SXGTK7SuNdoYh6ufC"
+ "KuAwy5lsaetyARDksRiOIrNV9j+MRIjJMjPNg+S+ysIHTWZo2NTUuVuZ01D2"
+ "jDtYPhcDFDESMBAGCSqGSIb3DQEJFTEDBAE3MIIDKwYJKoZIhvcNAQcGoIID"
+ "HDCCAxgCAQAwggMRBgkqhkiG9w0BBwEwKAYKKoZIhvcNAQwBAzAaBBS5KxQC"
+ "BMuZ1To+yed2j/TT45td6gICCACAggLYxQS+fu7W2sLQTkslI0EoNxLoH/WO"
+ "L8NgiIgZ5temV3mgC2q0MxjVVq+SCvG89ZSTfptxOaSmYV772irFdzlrtotZ"
+ "wmYk1axuFDYQ1gH0M6i9FWuhOnbk7qHclmOroXqrrbP6g3IsjwztH0+iwBCg"
+ "39f63V0rr8DHiu7zZ2hBkU4/RHEsXLjaCBVNTUSssWhVLisLh2sqBJccPC2E"
+ "1lw4c4WrshGQ+syLGG38ttFgXT1c+xYNpUKqJiJTLVouOH9kK3nH1hPRHKMN"
+ "9CucBdUzibvkcRk1L53F3MfvjhCSNeWEmd9PKN+FtUtzRWQG3L84VGTM37Ws"
+ "YcxaDwDFGcw3u1W8WFsCCkjpZecKN8P2Kp/ai/iugcXY77bYwAwpETDvQFvD"
+ "nnL9oGi03HYdfeiXglC7x7dlojvnpkXDbE0nJiFwhe8Mxpx8GVlGHtP+siXg"
+ "tklubg1eTCSoG9m1rsBJM717ZHXUGf32HNun2dn4vOWGocgBmokZ46KKMb9v"
+ "reT39JTxi8Jlp+2cYb6Qr/oBzudR+D4iAiiVhhhEbJKPNHa61YyxF810fNI2"
+ "GWlNIyN3KcI8XU6WJutm/0H3X8Y+iCSWrJ2exUktj8GiqNQ6Yx0YgEk9HI7W"
+ "t9UVTIsPCgCqrV4SWCOPf6so1JqnpvlPvvNyNxSsAJ7DaJx1+oD2QQfhowk/"
+ "bygkKnRo5Y15ThrTsIyQKsJHTIVy+6K5uFZnlT1DGV3DcNpuk3AY26hrAzWO"
+ "TuWXsULZe7M6h6U2hTT/eplZ/mwHlXdF1VErIuusaCdkSI0doY4/Q223H40L"
+ "BNU3pTezl41PLceSll00WGVr2MunlNeXKnXDJW06lnfs9BmnpV2+Lkfmf30W"
+ "Pn4RKJQc+3D3SV4fCoQLIGrKiZLFfEdGJcMlySr+dJYcEtoZPuo6i/hb5xot"
+ "le63h65ihNtXlEDrNpYSQqnfhjOzk5/+ZvYEcOtDObEwPTAhMAkGBSsOAwIa"
+ "BQAEFMIeDI9l2Da24mtA1fbQIPc6+4dUBBQ8a4lD7j1CA1vRLhdEgPM+5hpD"
+ "RgICCAA=");
private static readonly byte[] pkcs12noFriendly = Base64.Decode(
"MIACAQMwgAYJKoZIhvcNAQcBoIAkgASCBAAwgDCABgkqhkiG9w0BBwGggCSA"
+ "BIICvjCCArowggK2BgsqhkiG9w0BDAoBAqCCAqUwggKhMBsGCiqGSIb3DQEM"
+ "AQMwDQQIyJDupEHvySECAQEEggKAupvM7RuZL3G4qNeJM3afElt03TVfynRT"
+ "xUxAZOfx+zekHJTlnEuHJ+a16cOV6dQUgYfyMw1xcq4E+l59rVeMX9V3Zr0K"
+ "tsMN9VYB/9zn62Kw6LQnY0rMlWYf4bt9Ut5ysq0hE5t9FL+NZ5FbFdWBOKsj"
+ "/3oC6eNXOkOFyrY2haPJtD1hVHUosrlC0ffecV0YxPDsReeyx0R4CiYZpAUy"
+ "ZD7rkxL+mSX7zTsShRiga2Q/NEhC1KZpbhO/qbyOgvH0r7CRumSMvijzDgaV"
+ "IGqtrIZ2E2k5kscjcuFTW0x3OZTLAW/UnAh4JXJzC6isbdiWuswbAEBHifUC"
+ "rk2f+bDJKe2gkH67J2K0yDQ3YSSibpjDX/bVfbtfmOoggK9MKQwqEeE0nbYE"
+ "jzInH2OK5jPtmwppjmVA7i3Uk25w2+z7b/suUbft9hPCNjxFvzdbyCcXK4Vv"
+ "xAgEbVWnIkvOQNbyaQi+DEF/4P26GwgJgXuJpMBn0zzsSZSIDLNl8eJHoKp2"
+ "ZXknTi0SZkLaYlBxZlNhFoyXLfvQd6TI2aR5aCVqg1aZMBXyOWfz5t0JTVX8"
+ "HTIcdXKis91iEsLB7vjcxIOASTAjKARr5tRp6OvaVterAyDOn2awYQJLLic5"
+ "pQfditRAlsLkTxlDdu0/QBMXSPptO8g3R+dS7ntvCjXgZZyxpOeKkssS2l5v"
+ "/B2EsfKmYA9hU4aBdW1S9o/PcF1wpVqABd8664TGJ77tCAkbdHe0VJ3Bop2X"
+ "lNxlWeEeD0v0QUZLqkJoMEwi5SUE6HAWjbqGhRuHyey9E+UsdCVnQ8AxXQzL"
+ "2UKOmIrXc6R25GsLPCysXuXPRFBB2Tul0V3re3hPcAAAAAAAADCABgkqhkiG"
+ "9w0BBwaggDCAAgEAMIAGCSqGSIb3DQEHATAbBgoqhkiG9w0BDAEGMA0ECDXn"
+ "UZu6xckzAgEBoIAEggTYQMbzAoGnRVJMbCaJJUYgaARJ4zMfxt2e12H4pX/e"
+ "vnZrR1eKAMck5c2vJoEasr0i2VUcAcK12AntVIEnBwuRBcA2WrZnC28WR+O7"
+ "rLdu9ymG2V3zmk66aTizaB6rcHAzs2lD74n+/zJhZNaDMBfu9LzAdWb/u6Rb"
+ "AThmbw764Zyv9802pET6xrB8ureffgyvQAdlcGHM+yxaOV3ZEtS0cp7i+pb/"
+ "NTiET4jAFoO1tbBrWGJSRrMKvx4ZREppMhG3e/pYglfMFl+1ejbDsOvEUKSt"
+ "H+MVrgDgAv4NsUtNmBu+BIIEAIOCjrBSK3brtV0NZOWsa6hZSSGBhflbEY8s"
+ "U1bDsgZIW4ZaJJvSYEXLmiWSBOgq9VxojMfjowY+zj6ePJJMyI3E7AcFa+on"
+ "zZjeKxkKypER+TtpBeraqUfgf01b6olH8L2i4+1yotCQ0PS+15qRYPK6D+d3"
+ "S+R4veOA6wEsNRijVcB3oQsBCi0FVdf+6MVDvjNzBCZXj0heVi+x0EE106Sz"
+ "B3HaDbB/KNHMPZvvs3J3z2lWLj5w7YZ9eVmrVJKsgG2HRKxtt2IQquRj4BkS"
+ "upFnMTBVgWxXgwXycauC9bgYZurs+DbijqhHfWpUrttDfavsP8aX6+i3gabK"
+ "DH4LQRL7xrTcKkcUHxOTcPHLgDPhi+RevkV+BX9tdajbk4tqw1d+0wOkf1pW"
+ "aTG8fUp0lUpra7EJ0lGy8t/MB3NEk/5tLk9qA2nsKKdNoEdZWiEBE0fMrH1o"
+ "tWJDew3VhspT+Lkor2dLN5ydjcr3wkb76OETPeMxS91onNj5mrAMUBt66vb6"
+ "Gx4CL8FTRNZ/l8Kzngzdv9PmmKPTIXbhYbn3XRGg3od2tC/oVfsqYlGAMgFO"
+ "STt+BZ1BR9Phyi4jsiy8R0seCEDRWYQLbwgwVj0V8Rx9VptqRoCnB4XhGJoJ"
+ "TdAz/MT7KOSxIh2F2FymTJpyImcV6X4Kcj9iY0AZQ4zj712g4yMR6xKGzRu6"
+ "oIBDkFW2bdA3Lb9ePpo5GFtNyA7IbggIko6VOeeOKxaq9nALS2gsZc1yaYtp"
+ "aKL8kB+dVTCXiLgQniO6eMzgonsuwFnG+42XM1vhEpAvFzeJRC0CYzebEK9n"
+ "nGXKCPoqPFuw3gcPMn57NCZJ8MjT/p0wANIEm6AsgqrdFKwTRVJ1ytB/X9Ri"
+ "ysmjMBs9zbFKjU9jVDg1vGBNtb7YnYg9IrYHa3e4yTu2wUJKGP2XWHVgjDR7"
+ "6RtzlO4ljw0kkSMMEDle2ZbGZ6lVXbFwV0wPNPmGA6+XGJRxcddTnrM6R/41"
+ "zqksFLgoNL2BdofMXwv7SzxGyvFhHdRRdBZ5dKj2K9OfXakEcm/asZGu87u8"
+ "y9m7Cckw8ilSNPMdvYiFRoThICx9NiwYl1IIKGcWlb9p6RAx6XNSkY6ZZ6pE"
+ "Vla1E26rbd7is1ssSeqxLXXV9anuG5HDwMIt+CIbD8fZmNTcWMzZRiaFajvR"
+ "gXdyTu/UhVdhiQPF+lrxp4odgF0cXrpcGaKvOtPq04F4ad3O5EkSGucI210Q"
+ "pR/jQs07Yp5xDPzsXAb8naHb84FvK1iONAEjWbfhDxqtH7KGrBbW4KEzJrv3"
+ "B8GLDp+wOAFjGEdGDPkOx3y2L2HuI1XiS9LwL+psCily/A96OiUyRU8yEz4A"
+ "AAAAAAAAAAAEAwAAAAAAAAAAADAtMCEwCQYFKw4DAhoFAAQU1NQjgVRH6Vg3"
+ "tTy3wnQisALy9aYECKiM2gZrLi+fAAA=");
private static readonly char[] noFriendlyPassword = "sschette12".ToCharArray();
private static readonly byte[] pkcs12StorageIssue = Base64.Decode(
"MIIO8QIBAzCCDrEGCSqGSIb3DQEHAaCCDqIEgg6eMIIOmjCCBBMGCSqGSIb3"
+ "DQEHAaCCBAQEggQAMIID/DCCA/gGCyqGSIb3DQEMCgECoIICtjCCArIwHAYK"
+ "KoZIhvcNAQwBAzAOBAgURJ+/5hA2pgICB9AEggKQYZ4POE8clgH9Bjd1XO8m"
+ "sr6NiRBiA08CllHSOn2RzyAgHTa+cKaWrEVVJ9mCd9XveSUCoBF9E1C3jSl0"
+ "XIqLNgYd6mWK9BpeMRImM/5crjy///K4ab9kymzkc5qc0pIpdCQCZ04YmtFP"
+ "B80VCgyaoh2xoxqgjBCIgdSg5XdepdA5nXkG9EsQ1oVUyCykv20lKgKKRseG"
+ "Jo23AX8YUYR7ANqP2gz9lvlX6RBczuoZ62ujopUexiQgt5SZx97sgo3o/b/C"
+ "px17A2L4wLdeAYCMCsZhC2UeaqnZCHSsvnPZfRGiuSEGbV5gHLmXszLDaEdQ"
+ "Bo873GTpKTTzBfRFzNCtYtZRqh2AUsInWZWQUcCeX6Ogwa0wTonkp18/tqsh"
+ "Fj1fVpnsRmjJTTXFxkPtUw5GPJnDAM0t1xqV7kOjN76XnZrMyk2azQ1Mf3Hn"
+ "sGpF+VRGH6JtxbM0Jm5zD9uHcmkSfNR3tP/+vHOB1mkIR9tD2cHvBg7pAlPD"
+ "RfDVWynhS+UBNlQ0SEM/pgR7PytRSUoKc/hhe3N8VerF7VL3BwWfBLlZFYZH"
+ "FvPQg4coxF7+We7nrSQfXvdVBP9Zf0PTdf3pbZelGCPVjOzbzY/o/cB23IwC"
+ "ONxlY8SC1nJDXrPZ5sY51cg/qUqor056YqipRlI6I+FoTMmMDKPAiV1V5ibo"
+ "DNQJkyv/CAbTX4+oFlxgddTwYcPZgd/GoGjiP9yBHHdRISatHwMcM06CzXJS"
+ "s3MhzXWD4aNxvvSpXAngDLdlB7cm4ja2klmMzL7IuxzLXFQFFvYf7IF5I1pC"
+ "YZOmTlJgp0efL9bHjuHFnh0S0lPtlGDOjJ/4YpWvSKDplcPiXhaFVjsUtclE"
+ "oxCC5xppRm8QWS8xggEtMA0GCSsGAQQBgjcRAjEAMBMGCSqGSIb3DQEJFTEG"
+ "BAQBAAAAMGkGCSsGAQQBgjcRATFcHloATQBpAGMAcgBvAHMAbwBmAHQAIABS"
+ "AFMAQQAgAFMAQwBoAGEAbgBuAGUAbAAgAEMAcgB5AHAAdABvAGcAcgBhAHAA"
+ "aABpAGMAIABQAHIAbwB2AGkAZABlAHIwgZsGCSqGSIb3DQEJFDGBjR6BigA3"
+ "AGQAZQBmADUAYgA0ADMANgBjAGEAYgBkADAAMAAyAGQAZAAyADkAMAAzAGIA"
+ "MQA2ADgANgBjADcAOQA0ADgAXwA0ADYAZgAyADYAZgBkADQALQA4ADEAMgBk"
+ "AC0ANABlAGYAYgAtADgAMAA4ADgALQA0ADUAYQBiADkAMQA5ADEAMAA3AGMA"
+ "YzCCCn8GCSqGSIb3DQEHBqCCCnAwggpsAgEAMIIKZQYJKoZIhvcNAQcBMBwG"
+ "CiqGSIb3DQEMAQYwDgQIbr2xdnQ9inMCAgfQgIIKOHg9VKz+jlM+3abi3cp6"
+ "/XMathxDSEJLrxJs6j5DAVX17S4sw1Q/1pptjdMdd8QtTfUB6JpfgJ5Kpn+h"
+ "gZMf6M8wWue0U/RZN0D9w7o+2n+X3ItdEXu80eJVDOm7I2p8qiXtijbMbXRL"
+ "Cup1lgfPM5uv2D63/hmWRXLeG8eySrJnKENngpM559V8TI2JcTUBy1ZP3kcH"
+ "KbcJ/tVPnIIe4qguxfsTmDtAQviGvWUohbt+RGFmtqfgntK7o6b+S8uRSwEs"
+ "fOU/pnVE9M1ugtNJZI/xeGJq6umZWXA/OrAcK7feWUwqRvfivDGQJEoggByd"
+ "4/g92PhK1JGkwlCb1HdfhOOKKChowQ4zVvSOm+uBxARGhk2i5uW9I20I0vSJ"
+ "px42O2VFVJweOchfp+wBtSHBKYP1ZXyXWMvOtULClosSeesbYMAwvyBfpYEz"
+ "3rQt/1iZkqDmEisXk8X1aEKG1KSWaSPyb/+6glWikDm+YdQw3Khu7IZt1l/H"
+ "qWGecccel+R9mT4YjRzHlahUYk4U+RNVasVpH1Kxz2j3CZqL+b3jQOwSAPd/"
+ "hKI+S/pjIpBPfiC4WxORAzGZzY2j+a79B70h1DO1D9jGur3vJDbdmGBNgs6d"
+ "nonE1B527SICcGeXY1MtnZCLOPvySih0AvOekbN9x2CJg+Hp9e7A3Fxni53/"
+ "oMLr9wGRRDki72eXCXW98mU8VJofoWYS1/VBLXGf/f+tJ9J02PpzxleqPH9T"
+ "4mE+YHnZId6cqjCXmwvMr2cMw2clDVfvkbAJRE3eZHzL7IWSO8+giXzzrTsl"
+ "VbMuXVkT4oniTN7TSRsBCT3zVVmCy1QL2hPBD6KsVc+bvLgAHRov84FPrI3f"
+ "kY/oJufT36VE34Eu+QjzULlvVsLE3lhjutOerVIGSP//FM4LE99hp214P0JF"
+ "DgBK+3J+ihmFdW8hUXOt6BU8/MBeiroiJMWo1/f/XcduekG2ZsdGv+GNPzXI"
+ "PyHRpCgAgmck1+qoUPXxHRJuNqv223OZ5MN14X7iLl5OZ+f8IWfxUnZeZ9gj"
+ "HNeceElwZ+YOup1CAi3haD9jxRWhZG4NDfB4IYi4Bc/TAkXE3jCPkYEvIbj9"
+ "ExaU1Ts0+lqOOcwRmBoYjVrz0xbtfR/OWlopyrDHbeL5iQcQCW/loYRapWCZ"
+ "E4ekHknpX9yoAwT355vtTkl0VKXeSZHE8jREhN95aY9zCoLYwbTQDTw7qUR5"
+ "UamabLew0oS0XALtuOrfX4OUOZZUstUsGBle/Pw1TE3Bhe1clhrikp0F+Xgb"
+ "Xx90KqxZX/36RMnCMAD7/q+57rV7WXp2Y5tT0AUgyUMjy1F1X/b1olUfqO1u"
+ "rlWIUTl2znmQ3D9uO3W4ytfgGd5DpKcl2w84MBAT9qGwKuQg/UYKbP4K/+4L"
+ "Y1DWCy3utmohQ28IJtlIUkPL1G7lHX1tfq/VA+bRNTJIhMrNn06ZJpuEJHDs"
+ "/ferdlMFt/d6MrwVivmPVYkb8mSbHSiI8jZOFE44sA974depsDyXafFaSsl0"
+ "bVzqOAu0C/n9dIednU0xxxgDF/djdZ/QhbaDIg2VJf11wx0nw9n76B0+eeyu"
+ "QLaapzxCpQNDVOAM9doBb5F1I5pXQHFQqzTNtLmqDC4x0g8IH7asyk5LCglT"
+ "b1pwMqPJOL2vGWKRLhPzT+9OfSpCmYGKytf593hmGmwIgEO13hQrw31F5TYt"
+ "btkbDr+Q5XilOKEczhEM+Ug7YHU7bxkckOAbxu0YeRp/57GdGLokeLJ0dRlQ"
+ "+V2CfQvWJoVC6PS4PUQtjwgK2p/LU10QsEFwM/S621fGq9zGrv7+FPBATRDb"
+ "k4E9D/WaRylnW11ZTrOlTchQkoHcOh0xztlFxU8jzuIuDrPQQWkoqdl6B+yf"
+ "lykRNJKKxwzFiPl40nLC3nEdIzCEvR4r/9QHiWQxAVSc/wQX+an5vakUmSXS"
+ "oLFjgVdY1jmvdsx2r5BQPuOR8ONGmw/muvVSMaHV85brA4uk0lxn00HD9/a0"
+ "A1LCeFkabNLn9wJT8RaJeOSNmFFllLR70OHaoPSb3GyzHpvd1e6aeaimdyVH"
+ "BQWJ6Ufx+HjbOGuOiN46WyE6Q27dnWxx8qF89dKB4T/J0mEXqueiUjAUnnnR"
+ "Cs4zPaX53hmNBdrZGaLs+xNG8xy+iyBUJIWWfQAQjCjfHYlT9nygiUWIbVQq"
+ "RHkGkAN62jsSNLgHvWVzQPNNsYq0U8TPhyyci/vc8MJytujjptcz8FPqUjg2"
+ "TPv34ef9buErsm4vsdEv/8Z+9aDaNex+O3Lo3N0Aw7M5NcntFBHjFY/nBFNZ"
+ "whH5YA4gQ8PLZ5qshlGvb0DFXHV/9zxnsdPkLwH47ERm5IlEAuoaWtZFxg27"
+ "BjLfwU1Opk+ybDSb5WZVZrs7ljsU85p3Vaf3a//yoyr9ITYj15tTXxSPoct0"
+ "fDUy1I6LjJH/+eZXKA1WSda9mDQlRocvJ0IIIlI4weJpTdm8aHIJ8OngCqOF"
+ "TufcSLDM41+nxEK1LqXeAScVy74kVvvqngj6mIrbylrINZOHheEgTXrUWEc0"
+ "uXS8l1YqY6K6Ru5km2jVyWi/ujrDGb6QGShC09oiDYUuUGy4gwJ3XLVX/dR3"
+ "pmMExohTGiVefFP400wVZaxB9g1BQmjSEZxIaW1U1K6fk8Yni8yWB3/L/PuD"
+ "0+OV+98i1sQGaPe35crIpEc7R2XJdngL0Ol1ZuvCIBfy5DQwGIawTtBnjPdi"
+ "hy//QTt/isdu7C5pGaJDkZFMrfxMibr6c3xXr7wwR75sTzPNmS8mquEdLsmG"
+ "h8gTUnB8/K6V11JtUExMqTimTbUw+j8PggpeBelG36breWJIz1O+dmCTGuLM"
+ "x/sK/i8eiUeRvWjqYpq5DYt4URWg2WlcpcKiUxQp07/NMx0svDC+mlQGwMnJ"
+ "8KOJMW1qr3TGEJ/VVKKVn6sXn/RxA+VPofYzhwZByRX87XmNdPeQKC2DHQsW"
+ "6v83dua5gcnv0cv/smXt7Yr/c12i0fbIaQvj3qjtUCDucjARoBey3eCyG5H6"
+ "5VHSsFnPZ2HCTum+jRSw/ENsu/77XU4BIM2fjAfswp7iIr2Xi4OZWKIj6o6q"
+ "+fNgnOJjemDYHAFK+hWxClrG8b+9Eaf21o4zcHkhCfBlYv4d+xcZOIDsDPwI"
+ "sf+4V+CfoBLALsa2K0pXlPplGom/a8h7CjlyaICbWpEDItqwu7NQwdMRCa7i"
+ "yAyM1sVjXUdcZByS1bjOFSeBe7ygAvEl78vApLxqt8Cw11XSsOtmwssecUN/"
+ "pb7iHE4OMyOgsYx9u7rZ2hMyl42n3c29IwDYMumiNqk9cwCBpQTJAQEv4VzO"
+ "QE5xYDBY9SEozni+4f7B7e2Wj/LOGb3vfNVYGNpDczBFxvr2FXTQla0lNYD/"
+ "aePuC++QW4KvwiGL1Zx4Jo0eoDKWYlYj0qiNlQbWfVw+raaaFnlrq+je0W6P"
+ "+BrKZCncho145y+CFKRLZrN5yl/cDxwsePMVhAIMr1DzVhgBXzA3MB8wBwYF"
+ "Kw4DAhoEFN4Cwj9AtArnRbOIAsRhaaoZlTNJBBTIVPqCrloqLns145CWXjb0"
+ "g141BQ==");
private static readonly char[] storagePassword = "pass".ToCharArray();
private static readonly byte[] pkcs12nopass = Base64.Decode(
"MIIMvgIBAzCCDIQGCSqGSIb3DQEHAaCCDHUEggxxMIIMbTCCCS8GCSqGSIb3"
+ "DQEHBqCCCSAwggkcAgEAMIIJFQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYw"
+ "DgQIfnlhuZRR6/YCAggAgIII6DYgeRwq5n9kzvohZ3JuK+fB+9jZ7Or6EGBA"
+ "GDxtBfHmSNUBWJEV/I8wV1zrKKoW/CaoZfA61pyrVZRd/roaqBx/koTFoh/g"
+ "woyyWTRV9gYTXSVqPQgCH+e2dISAa6UGO+/YOWOOwG2X3t8tS+3FduFQFLt5"
+ "cvUP98zENdm57Aef5pKpBSZDLIAoTASfmqwszWABRh2p/wKOHcCQ9Aj2e2vs"
+ "pls/ntIv81MqPuxHttwX8e+3dKWGFrJRztLpCD2aua8VkSsHFsPxEHkezX4O"
+ "6/VCjMCRFGophTS4dgKKtQIhZ9i/ESlr6sGKgIpyG99ALFpNEhtTKe+T3boE"
+ "sEkhGDquSpu4PGz2m0W5sej1DyFkKX4zIbeMDAb1y3O7aP0F+Llo9QSeGsOA"
+ "aCwND3NUAKBMOHzwdyNQcuCGCqY8j5rrSt99A5FMs3UVW3XU6hRCx7JlzO05"
+ "PNCkcPRSnKSNzBhIR5W0qj4PAZnQTfX+wbtUaDLIqsObX4Muh2l3gl+JmdpO"
+ "53U7ILqN8PAPly1eT+fIrUmlMmFhvo6LbTB7B2K728wsA/5wROlud/mOQz4s"
+ "quS288YsnVc9ExSZKodWa3Pqcdb/cgKNJYDxrR6/eBHOj+0RLK/1yTK9ghj7"
+ "IPYHoEqQbw768WK92RjM+RFGlXASkQhR9y4weWj/388uAWMIbQ+R2Zi4nb31"
+ "knjqRPFThysG1bsRL04/9PgysaasfS9KYOeAlLqp+Ar4gJrof5fytBuY+6wm"
+ "/J8eEdNw7VPV1cz/4rhrd2sfJQwDEN/iZoy8rTwe7wozpwZI0lwH11BBbav+"
+ "1AMfI79jjxhqOeo7uxE2NzUmSd05JYI7a94tcRzGQyGEKpGxYCRamzFW23qb"
+ "vG5Hcqi7Tdd7eTxw4c60l/vQLSo38g6ST5yZrK3URLiAtpioPyjrq2jnVfie"
+ "QLsiAHhpHF01+t+OcKv3UjwdEyBmQ34h9klwiG7iwBFXZaPXFCF2Np1TqFVG"
+ "jjBzmB+hRddEiYwN+XGCKB2Cvgc5ZMQ8LG9jQmEKLmOjuumz1ciAVY2qtl1s"
+ "HYSvfNsIAV/gGzHshOVF19JmGtcQt3pMtupoRh+sh8jY2/x5eIKrj2Jx6HPd"
+ "p/6IPUr54j0xSd6j7gWuXMj/eKp/utMNuBzAhkydnhXYedvTDYIj7SyPPIHa"
+ "qtam8rxTDWn2AOxp7OXTgPmo1GU2zW1OLL1D3MFlS+oaRMfhgNrhW+QP5ay6"
+ "ge4QLijpnSM+p0CbFAOClwzgdJV56bBVV09sDqSBXnG9MeEv5nDaH3I+GpPA"
+ "UgDkaI4zT61kaGgk0uNMf3czy2ycoQzTx0iHDTXSdSqvUC1yFza8UG4AYaKz"
+ "14gtSL7StvZtK0Y8oI084BINI1LgrWyrOLj7vkds4WrKhXm21BtM1GbN/pFh"
+ "XI41h+XoD8KnEPqJ36rAgBo1uHqTNJCC7YikDE/dEvq6MkOx+Nug1YZRHEyi"
+ "3AHry5u1HJHtxT34HXBwRXvnstuFhvU6cjc1WY1dJhu1p82TGnx7OBo/QbcM"
+ "8MRrWmWuU5eW4jWbriGNGYfvZy+tHnGwy0bIeqrsHOG6/JwvfmYYXe64sryH"
+ "5Qo96SZtcTJZaNFwuBY+bFUuOWm8YrT1L7Gl2Muf3pEVtNHLeYARBo1jEAym"
+ "Cb4jw0oodZqbPKdyyzUZu69fdTJiQkMUcKDfHJEGK0Li9SvtdqJLiiJs57Tb"
+ "YfOvn+TIuC40ssJFtmtlGCVH/0vtKLWYeW1NYAMzgI/nlhQ7W6Aroh8sZnqv"
+ "SwxeQmRJaVLxiV6YveTKuVlCbqNVLeEtKYAujgnJtPemGCPbwZpwlBw6V+Dz"
+ "oXveOBcUqATztWJeNv7RbU0Mk7k057+DNxXBIU+eHRGquyHQSBXxBbA+OFuu"
+ "4SPfEAyoYed0HEaoKN9lIsBW1xTROI30MZvaJXvPdLsa8izXGPLnTGmoI+fv"
+ "tJ644HtBCCCr3Reu82ZsTSDMxspZ9aa4ro9Oza+R5eULXDhVXedbhJBYiPPo"
+ "J37El5lRqOgu2SEilhhVQq3ZCugsinCaY9P/RtWG4CFnH1IcIT5+/mivB48I"
+ "2XfH6Xq6ziJdj2/r86mhEnz9sKunNvYPBDGlOvI7xucEf9AiEQoTR1xyFDbW"
+ "ljL4BsJqgsHN02LyUzLwqMstwv+/JH1wUuXSK40Kik/N7+jEFW2C+/N8tN7l"
+ "RPKSLaTjxVuTfdv/BH1dkV4iGFgpQrdWkWgkb+VZP9xE2mLz715eIAg13x6+"
+ "n97tc9Hh375xZJqwr3QyYTXWpsK/vx04RThv8p0qMdqKvf3jVQWwnCnoeBv2"
+ "L4h/uisOLY18qka/Y48ttympG+6DpmzXTwD1LycoG2SOWckCMmJhZK40+zr3"
+ "NVmWf6iJtbLGMxI/kzTqbTaOfXc2MroertyM1rILRSpgnJFxJfai5Enspr9b"
+ "SCwlP718jG2lQsnYlw8CuxoZAiaNy4MmC5Y3qNl3hlcggcHeLodyGkSyRsBg"
+ "cEiKSL7JNvqr0X/nUeW28zVxkmQsWlp3KmST8agf+r+sQvw52fXNLdYznGZV"
+ "rJrwgNOoRj0Z70MwTns3s/tCqDEsy5Sv/5dZW2uQEe7/wvmsP2WLu73Rwplg"
+ "1dwi/Uo9lO9dkEzmoIK5wMPCDINxL1K+0Y79q0tIAEMDgaIxmtRpEh8/TEsA"
+ "UwyEErkDsQqgGviH+ePmawJ/yehYHTRfYUgdUflwApJxRx65pDeSYkiYboMU"
+ "8WSAQY2nh/p9hLlS4zbz9dCK2tzVyRkJgqNy/c4IpiHEx2l1iipW9vENglqx"
+ "dYP4uqD8e3OOLjDQKizWx2t1u7GRwoEVQ3d3QzzOvsRcv7h+6vNsmYqE6phe"
+ "wKFZLctpSn21zkyut444ij4sSr1OG68dEXLY0t0mATfTmXXy5GJBsdK/lLfk"
+ "YTIPYYeDMle9aEicDqaKqkZUuYPnVchGp8UFMJ3M0n48OMDdDvpzBLTxxZeW"
+ "cK5v/m3OEo3jgxy9wXfZdz//J3zXXqvX8LpMy1K9X0uCBTz6ERlawviMQhg1"
+ "1okD5zCCAzYGCSqGSIb3DQEHAaCCAycEggMjMIIDHzCCAxsGCyqGSIb3DQEM"
+ "CgECoIICpjCCAqIwHAYKKoZIhvcNAQwBAzAOBAj3QoojTSbZqgICCAAEggKA"
+ "YOSp5XGdnG1pdm9CfvlAaUSHRCOyNLndoUTqteTZjHTEM9bGwNXAx4/R5H2Q"
+ "PnPm5HB/ynVSXX0uKdW6YlbqUyAdV3eqE4X3Nl+K7ZoXmgAFnMr0tveBhT1b"
+ "7rTi0TN4twjJzBTkKcxT8XKjvpVizUxGo+Ss5Wk8FrWLHAiC5dZvgRemtGcM"
+ "w5S09Pwj+qXpjUhX1pB5/63qWPrjVf+Bfmlz4bWcqogGk0i7eg+OdTeWMrW0"
+ "KR9nD1+/uNEyc4FdGtdIPnM+ax0E+vcco0ExQpTXe0xoX4JW7O71d550Wp89"
+ "hAVPNrJA5eUbSWNsuz+38gjUJ+4XaAEhcA7HZIp6ZyxtzSJUoh7oqpRktoxu"
+ "3cSVqVxIqAEqlNn6j0vbKfW91Od5DI5L+BIxY4xqXS7fdwipj9r6qWA8t9QU"
+ "C2r1A+xXpZ4jEh6inHW9qlfACBBrYf8pSDakSR6yTbaA07LExw0IXz5oiQYt"
+ "s7yx231CZlOH88bBmruLOIZsJjeg/lf63zI7Gg4F85QG3RqEJnY2pinLUTP7"
+ "R62VErFZPc2a85r2dbFH1mSQIj/rT1IKe32zIW8xoHC4VwrPkT3bcLFAu2TH"
+ "5k5zSI/gZUKjPDxb2dwLM4pvsj3gJ9vcFZp6BCuLkZc5rd7CyD8HK9PrBLKd"
+ "H3Yngy4A08W4U3XUtIux95WE+5O/UEmSF7fr2vT//DwZArGUpBPq4Bikb8cv"
+ "0wpOwUv8r0DXveeaPsxdipXlt29Ayywcs6KIidLtCaCX6/0u/XtMsGNFS+ah"
+ "OlumTGBFpbLnagvIf0GKNhbg2lTjflACnxIj8d+QWsnrIU1uC1JRRKCnhpi2"
+ "veeWd1m8GUb3aTFiMCMGCSqGSIb3DQEJFTEWBBS9g+Xmq/8B462FWFfaLWd/"
+ "rlFxOTA7BgkqhkiG9w0BCRQxLh4sAEMAZQByAHQAeQBmAGkAawBhAHQAIAB1"
+ "AHoAeQB0AGsAbwB3AG4AaQBrAGEwMTAhMAkGBSsOAwIaBQAEFKJpUOIj0OtI"
+ "j2CPp38YIFBEqvjsBAi8G+yhJe3A/wICCAA=");
/**
* we generate a self signed certificate for the sake of testing - RSA
*/
public X509CertificateEntry CreateCert(
AsymmetricKeyParameter pubKey,
AsymmetricKeyParameter privKey,
string issuerEmail,
string subjectEmail)
{
//
// distinguished name table.
//
IDictionary issuerAttrs = new Hashtable();
issuerAttrs.Add(X509Name.C, "AU");
issuerAttrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
issuerAttrs.Add(X509Name.L, "Melbourne");
issuerAttrs.Add(X509Name.ST, "Victoria");
issuerAttrs.Add(X509Name.EmailAddress, issuerEmail);
IDictionary subjectAttrs = new Hashtable();
subjectAttrs.Add(X509Name.C, "AU");
subjectAttrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
subjectAttrs.Add(X509Name.L, "Melbourne");
subjectAttrs.Add(X509Name.ST, "Victoria");
subjectAttrs.Add(X509Name.EmailAddress, subjectEmail);
IList order = new ArrayList();
order.Add(X509Name.C);
order.Add(X509Name.O);
order.Add(X509Name.L);
order.Add(X509Name.ST);
order.Add(X509Name.EmailAddress);
//
// extensions
//
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.SetSerialNumber(BigInteger.One);
certGen.SetIssuerDN(new X509Name(order, issuerAttrs));
certGen.SetNotBefore(DateTime.UtcNow.AddDays(-30));
certGen.SetNotAfter(DateTime.UtcNow.AddDays(30));
certGen.SetSubjectDN(new X509Name(order, subjectAttrs));
certGen.SetPublicKey(pubKey);
certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");
return new X509CertificateEntry(certGen.Generate(privKey));
}
public void doTestPkcs12Store()
{
BigInteger mod = new BigInteger("bb1be8074e4787a8d77967f1575ef72dd7582f9b3347724413c021beafad8f32dba5168e280cbf284df722283dad2fd4abc750e3d6487c2942064e2d8d80641aa5866d1f6f1f83eec26b9b46fecb3b1c9856a303148a5cc899c642fb16f3d9d72f52526c751dc81622c420c82e2cfda70fe8d13f16cc7d6a613a5b2a2b5894d1", 16);
MemoryStream stream = new MemoryStream(pkcs12, false);
Pkcs12Store store = new Pkcs12StoreBuilder().Build();
store.Load(stream, passwd);
string pName = null;
foreach (string n in store.Aliases)
{
if (store.IsKeyEntry(n))
{
pName = n;
//break;
}
}
AsymmetricKeyEntry key = store.GetKey(pName);
if (!((RsaKeyParameters) key.Key).Modulus.Equals(mod))
{
Fail("Modulus doesn't match.");
}
X509CertificateEntry[] ch = store.GetCertificateChain(pName);
if (ch.Length != 3)
{
Fail("chain was wrong length");
}
if (!ch[0].Certificate.SerialNumber.Equals(new BigInteger("96153094170511488342715101755496684211")))
{
Fail("chain[0] wrong certificate.");
}
if (!ch[1].Certificate.SerialNumber.Equals(new BigInteger("279751514312356623147411505294772931957")))
{
Fail("chain[1] wrong certificate.");
}
if (!ch[2].Certificate.SerialNumber.Equals(new BigInteger("11341398017")))
{
Fail("chain[2] wrong certificate.");
}
//
// save test
//
MemoryStream bOut = new MemoryStream();
store.Save(bOut, passwd, new SecureRandom());
stream = new MemoryStream(bOut.ToArray(), false);
store.Load(stream, passwd);
key = store.GetKey(pName);
if (!((RsaKeyParameters)key.Key).Modulus.Equals(mod))
{
Fail("Modulus doesn't match.");
}
store.DeleteEntry(pName);
if (store.GetKey(pName) != null)
{
Fail("Failed deletion test.");
}
//
// cert chain test
//
store.SetCertificateEntry("testCert", ch[2]);
if (store.GetCertificateChain("testCert") != null)
{
Fail("Failed null chain test.");
}
//
// UTF 8 single cert test
//
stream = new MemoryStream(certUTF, false);
store.Load(stream, "user".ToCharArray());
if (store.GetCertificate("37") == null)
{
Fail("Failed to find UTF cert.");
}
//
// try for a self generated certificate
//
RsaKeyParameters pubKey = new RsaKeyParameters(
false,
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16));
RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16),
new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
X509CertificateEntry[] chain = new X509CertificateEntry[] {
CreateCert(pubKey, privKey, "issuer@bouncycastle.org", "subject@bouncycastle.org")
};
store = new Pkcs12StoreBuilder().Build();
store.SetKeyEntry("privateKey", new AsymmetricKeyEntry(privKey), chain);
if (!store.ContainsAlias("privateKey") || !store.ContainsAlias("PRIVATEKEY"))
{
Fail("couldn't find alias privateKey");
}
if (store.IsCertificateEntry("privateKey"))
{
Fail("key identified as certificate entry");
}
if (!store.IsKeyEntry("privateKey") || !store.IsKeyEntry("PRIVATEKEY"))
{
Fail("key not identified as key entry");
}
if (!"privateKey".Equals(store.GetCertificateAlias(chain[0].Certificate)))
{
Fail("Did not return alias for key certificate privateKey");
}
MemoryStream store1Stream = new MemoryStream();
store.Save(store1Stream, passwd, new SecureRandom());
testNoExtraLocalKeyID(store1Stream.ToArray());
//
// no friendly name test
//
stream = new MemoryStream(pkcs12noFriendly, false);
store.Load(stream, noFriendlyPassword);
pName = null;
foreach (string n in store.Aliases)
{
if (store.IsKeyEntry(n))
{
pName = n;
//break;
}
}
ch = store.GetCertificateChain(pName);
//for (int i = 0; i != ch.Length; i++)
//{
// Console.WriteLine(ch[i]);
//}
if (ch.Length != 1)
{
Fail("no cert found in pkcs12noFriendly");
}
//
// failure tests
//
ch = store.GetCertificateChain("dummy");
store.GetCertificateChain("DUMMY");
store.GetCertificate("dummy");
store.GetCertificate("DUMMY");
//
// storage test
//
stream = new MemoryStream(pkcs12StorageIssue, false);
store.Load(stream, storagePassword);
pName = null;
foreach (string n in store.Aliases)
{
if (store.IsKeyEntry(n))
{
pName = n;
//break;
}
}
ch = store.GetCertificateChain(pName);
if (ch.Length != 2)
{
Fail("Certificate chain wrong length");
}
store.Save(new MemoryStream(), storagePassword, new SecureRandom());
//
// basic certificate check
//
store.SetCertificateEntry("cert", ch[1]);
if (!store.ContainsAlias("cert") || !store.ContainsAlias("CERT"))
{
Fail("couldn't find alias cert");
}
if (!store.IsCertificateEntry("cert") || !store.IsCertificateEntry("CERT"))
{
Fail("cert not identified as certificate entry");
}
if (store.IsKeyEntry("cert") || store.IsKeyEntry("CERT"))
{
Fail("cert identified as key entry");
}
if (!store.IsEntryOfType("cert", typeof(X509CertificateEntry)))
{
Fail("cert not identified as X509CertificateEntry");
}
if (!store.IsEntryOfType("CERT", typeof(X509CertificateEntry)))
{
Fail("CERT not identified as X509CertificateEntry");
}
if (store.IsEntryOfType("cert", typeof(AsymmetricKeyEntry)))
{
Fail("cert identified as key entry via AsymmetricKeyEntry");
}
if (!"cert".Equals(store.GetCertificateAlias(ch[1].Certificate)))
{
Fail("Did not return alias for certificate entry");
}
//
// test restoring of a certificate with private key originally as a ca certificate
//
store = new Pkcs12StoreBuilder().Build();
store.SetCertificateEntry("cert", ch[0]);
if (!store.ContainsAlias("cert") || !store.ContainsAlias("CERT"))
{
Fail("restore: couldn't find alias cert");
}
if (!store.IsCertificateEntry("cert") || !store.IsCertificateEntry("CERT"))
{
Fail("restore: cert not identified as certificate entry");
}
if (store.IsKeyEntry("cert") || store.IsKeyEntry("CERT"))
{
Fail("restore: cert identified as key entry");
}
if (store.IsEntryOfType("cert", typeof(AsymmetricKeyEntry)))
{
Fail("restore: cert identified as key entry via AsymmetricKeyEntry");
}
if (store.IsEntryOfType("CERT", typeof(AsymmetricKeyEntry)))
{
Fail("restore: cert identified as key entry via AsymmetricKeyEntry");
}
if (!store.IsEntryOfType("cert", typeof(X509CertificateEntry)))
{
Fail("restore: cert not identified as X509CertificateEntry");
}
//
// test of reading incorrect zero-length encoding
//
stream = new MemoryStream(pkcs12nopass, false);
store.Load(stream, "".ToCharArray());
}
private void testSupportedTypes(AsymmetricKeyEntry privKey, X509CertificateEntry[] chain)
{
basicStoreTest(privKey, chain,
PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc,
PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc );
basicStoreTest(privKey, chain,
PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc,
PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc );
}
private void basicStoreTest(AsymmetricKeyEntry privKey, X509CertificateEntry[] chain,
DerObjectIdentifier keyAlgorithm, DerObjectIdentifier certAlgorithm)
{
Pkcs12Store store = new Pkcs12StoreBuilder()
.SetKeyAlgorithm(keyAlgorithm)
.SetCertAlgorithm(certAlgorithm)
.Build();
store.SetKeyEntry("key", privKey, chain);
MemoryStream bOut = new MemoryStream();
store.Save(bOut, passwd, new SecureRandom());
store.Load(new MemoryStream(bOut.ToArray(), false), passwd);
AsymmetricKeyEntry k = store.GetKey("key");
if (!k.Equals(privKey))
{
Fail("private key didn't match");
}
X509CertificateEntry[] c = store.GetCertificateChain("key");
if (c.Length != chain.Length || !c[0].Equals(chain[0]))
{
Fail("certificates didn't match");
}
// check attributes
Pkcs12Entry b1 = k;
Pkcs12Entry b2 = chain[0];
if (b1[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] != null)
{
DerBmpString name = (DerBmpString)b1[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
if (!name.Equals(new DerBmpString("key")))
{
Fail("friendly name wrong");
}
}
else
{
Fail("no friendly name found on key");
}
if (b1[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] != null)
{
Asn1OctetString id = (Asn1OctetString)b1[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID];
if (!id.Equals(b2[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID]))
{
Fail("local key id mismatch");
}
}
else
{
Fail("no local key id found");
}
//
// check algorithm types.
//
Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());
Pfx pfx = new Pfx((Asn1Sequence)aIn.ReadObject());
ContentInfo cInfo = pfx.AuthSafe;
Asn1OctetString auth = (Asn1OctetString)cInfo.Content;
aIn = new Asn1InputStream(auth.GetOctets());
Asn1Sequence s1 = (Asn1Sequence)aIn.ReadObject();
ContentInfo c1 = ContentInfo.GetInstance(s1[0]);
ContentInfo c2 = ContentInfo.GetInstance(s1[1]);
aIn = new Asn1InputStream(((Asn1OctetString)c1.Content).GetOctets());
SafeBag sb = new SafeBag((Asn1Sequence)(((Asn1Sequence)aIn.ReadObject())[0]));
EncryptedPrivateKeyInfo encInfo = EncryptedPrivateKeyInfo.GetInstance(sb.BagValue);
// check the key encryption
if (!encInfo.EncryptionAlgorithm.ObjectID.Equals(keyAlgorithm))
{
Fail("key encryption algorithm wrong");
}
// check the certificate encryption
EncryptedData cb = EncryptedData.GetInstance(c2.Content);
if (!cb.EncryptionAlgorithm.ObjectID.Equals(certAlgorithm))
{
Fail("cert encryption algorithm wrong");
}
}
private void testNoExtraLocalKeyID(byte[] store1data)
{
IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
kpg.Init(new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25));
AsymmetricCipherKeyPair newPair = kpg.GenerateKeyPair();
Pkcs12Store store1 = new Pkcs12StoreBuilder().Build();
store1.Load(new MemoryStream(store1data, false), passwd);
Pkcs12Store store2 = new Pkcs12StoreBuilder().Build();
AsymmetricKeyEntry k1 = store1.GetKey("privatekey");
X509CertificateEntry[] chain1 = store1.GetCertificateChain("privatekey");
X509CertificateEntry[] chain2 = new X509CertificateEntry[chain1.Length + 1];
Array.Copy(chain1, 0, chain2, 1, chain1.Length);
chain2[0] = CreateCert(newPair.Public, k1.Key, "subject@bouncycastle.org", "extra@bouncycaste.org");
if (chain1[0][PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
{
Fail("localKeyID not found initially");
}
store2.SetKeyEntry("new", new AsymmetricKeyEntry(newPair.Private), chain2);
MemoryStream bOut = new MemoryStream();
store2.Save(bOut, passwd, new SecureRandom());
store2.Load(new MemoryStream(bOut.ToArray(), false), passwd);
chain2 = store2.GetCertificateChain("new");
if (chain2[1][PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] != null)
{
Fail("localKeyID found after save");
}
}
public override string Name
{
get { return "PKCS12Store"; }
}
public override void PerformTest()
{
doTestPkcs12Store();
}
public static void Main(
string[] args)
{
RunTest(new Pkcs12StoreTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System.Linq;
using System;
using System.Collections.Generic;
public enum RuleResult { Done, Working }
namespace Casanova.Prelude
{
public class Tuple<T,E> {
public T Item1 { get; set;}
public E Item2 { get; set;}
public Tuple(T item1, E item2)
{
Item1 = item1;
Item2 = item2;
}
}
public static class MyExtensions
{
//public T this[List<T> list]
//{
// get { return list.ElementAt(0); }
//}
public static bool CompareStruct<T>(this List<T> list1, List<T> list2)
{
if (list1.Count != list2.Count) return false;
for (int i = 0; i < list1.Count; i++)
{
if (!list1[i].Equals(list2[i])) return false;
}
return true;
}
public static T Head<T>(this List<T> list) { return list.ElementAt(0); }
public static T Head<T>(this IEnumerable<T> list) { return list.ElementAt(0); }
public static int Length<T>(this List<T> list) { return list.Count; }
public static int Length<T>(this IEnumerable<T> list) { return list.ToList<T>().Count; }
}
public class Cons<T> : IEnumerable<T>
{
public class Enumerator : IEnumerator<T>
{
public Enumerator(Cons<T> parent)
{
firstEnumerated = 0;
this.parent = parent;
tailEnumerator = parent.tail.GetEnumerator();
}
byte firstEnumerated;
Cons<T> parent;
IEnumerator<T> tailEnumerator;
public T Current
{
get
{
if (firstEnumerated == 0) return default(T);
if (firstEnumerated == 1) return parent.head;
else return tailEnumerator.Current;
}
}
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext()
{
if (firstEnumerated == 0)
{
if (parent.head == null) return false;
firstEnumerated++;
return true;
}
if (firstEnumerated == 1) firstEnumerated++;
return tailEnumerator.MoveNext();
}
public void Reset() { firstEnumerated = 0; tailEnumerator.Reset(); }
public void Dispose() { }
}
T head;
IEnumerable<T> tail;
public Cons(T head, IEnumerable<T> tail)
{
this.head = head;
this.tail = tail;
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
}
public class Empty<T> : IEnumerable<T>
{
public Empty() { }
public class Enumerator : IEnumerator<T>
{
public T Current { get { throw new Exception("Empty sequence has no elements"); } }
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext() { return false; }
public void Reset() { }
public void Dispose() { }
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator();
}
}
public abstract class Option<T> : IComparable, IEquatable<Option<T>>
{
public bool IsSome;
public bool IsNone { get { return !IsSome; } }
protected abstract Just<T> Some { get; }
public U Match<U>(Func<T,U> f, Func<U> g) {
if (this.IsSome)
return f(this.Some.Value);
else
return g();
}
public bool Equals(Option<T> b)
{
return this.Match(
x => b.Match(
y => x.Equals(y),
() => false),
() => b.Match(
y => false,
() => true));
}
public override bool Equals(System.Object other)
{
if (other == null) return false;
if (other is Option<T>)
{
var other1 = other as Option<T>;
return this.Equals(other1);
}
return false;
}
public override int GetHashCode() { return this.GetHashCode(); }
public static bool operator ==(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return a.Equals(b);
}
public static bool operator !=(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return !(a.Equals(b));
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
if (obj is Option<T>)
{
var obj1 = obj as Option<T>;
if (this.Equals(obj1)) return 0;
}
return -1;
}
abstract public T Value { get; }
public override string ToString()
{
return "Option<" + typeof(T).ToString() + ">";
}
}
public class Just<T> : Option<T>
{
T elem;
public Just(T elem) { this.elem = elem; this.IsSome = true; }
protected override Just<T> Some { get { return this; } }
public override T Value { get { return elem; } }
}
public class Nothing<T> : Option<T>
{
public Nothing() { this.IsSome = false; }
protected override Just<T> Some { get { return null; } }
public override T Value { get { throw new Exception("Cant get a value from a None object"); } }
}
public class Utils
{
public static T IfThenElse<T>(Func<bool> c, Func<T> t, Func<T> e)
{
if (c())
return t();
else
return e();
}
}
}
public class FastStack
{
public int[] Elements;
public int Top;
public FastStack(int elems)
{
Top = 0;
Elements = new int[elems];
}
public void Clear() { Top = 0; }
public void Push(int x) { Elements[Top++] = x; }
}
public class RuleTable
{
public RuleTable(int elems)
{
ActiveIndices = new FastStack(elems);
SupportStack = new FastStack(elems);
ActiveSlots = new bool[elems];
}
public FastStack ActiveIndices;
public FastStack SupportStack;
public bool[] ActiveSlots;
public void Add(int i)
{
if (!ActiveSlots[i])
{
ActiveSlots[i] = true;
ActiveIndices.Push(i);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
namespace System.Security.Cryptography.Xml
{
/// <summary>
/// Trace support for debugging issues signing and verifying XML signatures.
/// </summary>
internal static class SignedXmlDebugLog
{
//
// In order to enable XML digital signature debug loggging, applications should setup their config
// file to be similar to the following:
//
// <configuration>
// <system.diagnostics>
// <sources>
// <source name="System.Security.Cryptography.Xml.SignedXml"
// switchName="XmlDsigLogSwitch">
// <listeners>
// <add name="logFile" />
// </listeners>
// </source>
// </sources>
// <switches>
// <add name="XmlDsigLogSwitch" value="Verbose" />
// </switches>
// <sharedListeners>
// <add name="logFile"
// type="System.Diagnostics.TextWriterTraceListener"
// initializeData="XmlDsigLog.txt"/>
// </sharedListeners>
// <trace autoflush="true">
// <listeners>
// <add name="logFile" />
// </listeners>
// </trace>
// </system.diagnostics>
// </configuration>
//
private const string NullString = "(null)";
private static TraceSource s_traceSource = new TraceSource("System.Security.Cryptography.Xml.SignedXml");
private static volatile bool s_haveVerboseLogging;
private static volatile bool s_verboseLogging;
private static volatile bool s_haveInformationLogging;
private static volatile bool s_informationLogging;
/// <summary>
/// Types of events that are logged to the debug log
/// </summary>
internal enum SignedXmlDebugEvent
{
/// <summary>
/// Canonicalization of input XML has begun
/// </summary>
BeginCanonicalization,
/// <summary>
/// Verification of the signature format itself is beginning
/// </summary>
BeginCheckSignatureFormat,
/// <summary>
/// Verification of a signed info is beginning
/// </summary>
BeginCheckSignedInfo,
/// <summary>
/// Signing is beginning
/// </summary>
BeginSignatureComputation,
/// <summary>
/// Signature verification is beginning
/// </summary>
BeginSignatureVerification,
/// <summary>
/// Input data has been transformed to its canonicalized form
/// </summary>
CanonicalizedData,
/// <summary>
/// The result of signature format validation
/// </summary>
FormatValidationResult,
/// <summary>
/// Namespaces are being propigated into the signature
/// </summary>
NamespacePropagation,
/// <summary>
/// Output from a Reference
/// </summary>
ReferenceData,
/// <summary>
/// The result of a signature verification
/// </summary>
SignatureVerificationResult,
/// <summary>
/// Calculating the final signature
/// </summary>
Signing,
/// <summary>
/// A reference is being hashed
/// </summary>
SigningReference,
/// <summary>
/// A signature has failed to verify
/// </summary>
VerificationFailure,
/// <summary>
/// Verify that a reference has the correct hash value
/// </summary>
VerifyReference,
/// <summary>
/// Verification is processing the SignedInfo section of the signature
/// </summary>
VerifySignedInfo,
/// <summary>
/// Verification status on the x.509 certificate in use
/// </summary>
X509Verification,
/// <summary>
/// The signature is being rejected by the signature format verifier due to having
/// a canonicalization algorithm which is not on the known valid list.
/// </summary>
UnsafeCanonicalizationMethod,
/// <summary>
/// The signature is being rejected by the signature verifier due to having
/// a transform algorithm which is not on the known valid list.
/// </summary>
UnsafeTransformMethod,
}
/// <summary>
/// Check to see if logging should be done in this process
/// </summary>
private static bool InformationLoggingEnabled
{
get
{
if (!s_haveInformationLogging)
{
s_informationLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Information);
s_haveInformationLogging = true;
}
return s_informationLogging;
}
}
/// <summary>
/// Check to see if verbose log messages should be generated
/// </summary>
private static bool VerboseLoggingEnabled
{
get
{
if (!s_haveVerboseLogging)
{
s_verboseLogging = s_traceSource.Switch.ShouldTrace(TraceEventType.Verbose);
s_haveVerboseLogging = true;
}
return s_verboseLogging;
}
}
/// <summary>
/// Convert the byte array into a hex string
/// </summary>
private static string FormatBytes(byte[] bytes)
{
if (bytes == null)
return NullString;
StringBuilder builder = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
{
builder.Append(b.ToString("x2", CultureInfo.InvariantCulture));
}
return builder.ToString();
}
/// <summary>
/// Map a key to a string describing the key
/// </summary>
private static string GetKeyName(object key)
{
Debug.Assert(key != null, "key != null");
ICspAsymmetricAlgorithm cspKey = key as ICspAsymmetricAlgorithm;
X509Certificate certificate = key as X509Certificate;
X509Certificate2 certificate2 = key as X509Certificate2;
//
// Use the following sources for key names, if available:
//
// * CAPI key -> key container name
// * X509Certificate2 -> subject simple name
// * X509Certificate -> subject name
// * All others -> hash code
//
string keyName = null;
if (cspKey != null && cspKey.CspKeyContainerInfo.KeyContainerName != null)
{
keyName = string.Format(CultureInfo.InvariantCulture,
"\"{0}\"",
cspKey.CspKeyContainerInfo.KeyContainerName);
}
else if (certificate2 != null)
{
keyName = string.Format(CultureInfo.InvariantCulture,
"\"{0}\"",
certificate2.GetNameInfo(X509NameType.SimpleName, false));
}
else if (certificate != null)
{
keyName = string.Format(CultureInfo.InvariantCulture,
"\"{0}\"",
certificate.Subject);
}
else
{
keyName = key.GetHashCode().ToString("x8", CultureInfo.InvariantCulture);
}
return string.Format(CultureInfo.InvariantCulture, "{0}#{1}", key.GetType().Name, keyName);
}
/// <summary>
/// Map an object to a string describing the object
/// </summary>
private static string GetObjectId(object o)
{
Debug.Assert(o != null, "o != null");
return string.Format(CultureInfo.InvariantCulture,
"{0}#{1}", o.GetType().Name,
o.GetHashCode().ToString("x8", CultureInfo.InvariantCulture));
}
/// <summary>
/// Map an OID to the friendliest name possible
/// </summary>
private static string GetOidName(Oid oid)
{
Debug.Assert(oid != null, "oid != null");
string friendlyName = oid.FriendlyName;
if (string.IsNullOrEmpty(friendlyName))
friendlyName = oid.Value;
return friendlyName;
}
/// <summary>
/// Log that canonicalization has begun on input data
/// </summary>
/// <param name="signedXml">SignedXml object doing the signing or verification</param>
/// <param name="canonicalizationTransform">transform canonicalizing the input</param>
internal static void LogBeginCanonicalization(SignedXml signedXml, Transform canonicalizationTransform)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null");
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_BeginCanonicalization,
canonicalizationTransform.Algorithm,
canonicalizationTransform.GetType().Name);
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.BeginCanonicalization,
logMessage);
}
if (VerboseLoggingEnabled)
{
string canonicalizationSettings = string.Format(CultureInfo.InvariantCulture,
SR.Log_CanonicalizationSettings,
canonicalizationTransform.Resolver.GetType(),
canonicalizationTransform.BaseURI);
WriteLine(signedXml,
TraceEventType.Verbose,
SignedXmlDebugEvent.BeginCanonicalization,
canonicalizationSettings);
}
}
/// <summary>
/// Log that we're going to be validating the signature format itself
/// </summary>
/// <param name="signedXml">SignedXml object doing the verification</param>
/// <param name="formatValidator">Callback delegate which is being used for format verification</param>
internal static void LogBeginCheckSignatureFormat(SignedXml signedXml, Func<SignedXml, bool> formatValidator)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(formatValidator != null, "formatValidator != null");
if (InformationLoggingEnabled)
{
MethodInfo validationMethod = formatValidator.Method;
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_CheckSignatureFormat,
validationMethod.Module.Assembly.FullName,
validationMethod.DeclaringType.FullName,
validationMethod.Name);
WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignatureFormat, logMessage);
}
}
/// <summary>
/// Log that checking SignedInfo is beginning
/// </summary>
/// <param name="signedXml">SignedXml object doing the verification</param>
/// <param name="signedInfo">SignedInfo object being verified</param>
internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo signedInfo)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(signedInfo != null, " signedInfo != null");
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_CheckSignedInfo,
signedInfo.Id != null ? signedInfo.Id : NullString);
WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, logMessage);
}
}
/// <summary>
/// Log that signature computation is beginning
/// </summary>
/// <param name="signedXml">SignedXml object doing the signing</param>
/// <param name="context">Context of the signature</param>
internal static void LogBeginSignatureComputation(SignedXml signedXml, XmlElement context)
{
Debug.Assert(signedXml != null, "signedXml != null");
if (InformationLoggingEnabled)
{
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.BeginSignatureComputation,
SR.Log_BeginSignatureComputation);
}
if (VerboseLoggingEnabled)
{
string contextData = string.Format(CultureInfo.InvariantCulture,
SR.Log_XmlContext,
context != null ? context.OuterXml : NullString);
WriteLine(signedXml,
TraceEventType.Verbose,
SignedXmlDebugEvent.BeginSignatureComputation,
contextData);
}
}
/// <summary>
/// Log that signature verification is beginning
/// </summary>
/// <param name="signedXml">SignedXml object doing the verification</param>
/// <param name="context">Context of the verification</param>
internal static void LogBeginSignatureVerification(SignedXml signedXml, XmlElement context)
{
Debug.Assert(signedXml != null, "signedXml != null");
if (InformationLoggingEnabled)
{
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.BeginSignatureVerification,
SR.Log_BeginSignatureVerification);
}
if (VerboseLoggingEnabled)
{
string contextData = string.Format(CultureInfo.InvariantCulture,
SR.Log_XmlContext,
context != null ? context.OuterXml : NullString);
WriteLine(signedXml,
TraceEventType.Verbose,
SignedXmlDebugEvent.BeginSignatureVerification,
contextData);
}
}
/// <summary>
/// Log the canonicalized data
/// </summary>
/// <param name="signedXml">SignedXml object doing the signing or verification</param>
/// <param name="canonicalizationTransform">transform canonicalizing the input</param>
internal static void LogCanonicalizedOutput(SignedXml signedXml, Transform canonicalizationTransform)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(canonicalizationTransform != null, "canonicalizationTransform != null");
if (VerboseLoggingEnabled)
{
using (StreamReader reader = new StreamReader(canonicalizationTransform.GetOutput(typeof(Stream)) as Stream))
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_CanonicalizedOutput,
reader.ReadToEnd());
WriteLine(signedXml,
TraceEventType.Verbose,
SignedXmlDebugEvent.CanonicalizedData,
logMessage);
}
}
}
/// <summary>
/// Log that the signature format callback has rejected the signature
/// </summary>
/// <param name="signedXml">SignedXml object doing the signature verification</param>
/// <param name="result">result of the signature format verification</param>
internal static void LogFormatValidationResult(SignedXml signedXml, bool result)
{
Debug.Assert(signedXml != null, "signedXml != null");
if (InformationLoggingEnabled)
{
string logMessage = result ? SR.Log_FormatValidationSuccessful :
SR.Log_FormatValidationNotSuccessful;
WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.FormatValidationResult, logMessage);
}
}
/// <summary>
/// Log that a signature is being rejected as having an invalid format due to its canonicalization
/// algorithm not being on the valid list.
/// </summary>
/// <param name="signedXml">SignedXml object doing the signature verification</param>
/// <param name="result">result of the signature format verification</param>
internal static void LogUnsafeCanonicalizationMethod(SignedXml signedXml, string algorithm, IEnumerable<string> validAlgorithms)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(validAlgorithms != null, "validAlgorithms != null");
if (InformationLoggingEnabled)
{
StringBuilder validAlgorithmBuilder = new StringBuilder();
foreach (string validAlgorithm in validAlgorithms)
{
if (validAlgorithmBuilder.Length != 0)
{
validAlgorithmBuilder.Append(", ");
}
validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm);
}
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_UnsafeCanonicalizationMethod,
algorithm,
validAlgorithmBuilder.ToString());
WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.UnsafeCanonicalizationMethod, logMessage);
}
}
/// <summary>
/// Log that a signature is being rejected as having an invalid signature due to a transform
/// algorithm not being on the valid list.
/// </summary>
/// <param name="signedXml">SignedXml object doing the signature verification</param>
/// <param name="algorithm">Transform algorithm that was not allowed</param>
/// <param name="validC14nAlgorithms">The valid C14N algorithms</param>
/// <param name="validTransformAlgorithms">The valid C14N algorithms</param>
internal static void LogUnsafeTransformMethod(
SignedXml signedXml,
string algorithm,
IEnumerable<string> validC14nAlgorithms,
IEnumerable<string> validTransformAlgorithms)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(validC14nAlgorithms != null, "validC14nAlgorithms != null");
Debug.Assert(validTransformAlgorithms != null, "validTransformAlgorithms != null");
if (InformationLoggingEnabled)
{
StringBuilder validAlgorithmBuilder = new StringBuilder();
foreach (string validAlgorithm in validC14nAlgorithms)
{
if (validAlgorithmBuilder.Length != 0)
{
validAlgorithmBuilder.Append(", ");
}
validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm);
}
foreach (string validAlgorithm in validTransformAlgorithms)
{
if (validAlgorithmBuilder.Length != 0)
{
validAlgorithmBuilder.Append(", ");
}
validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm);
}
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_UnsafeTransformMethod,
algorithm,
validAlgorithmBuilder.ToString());
WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.UnsafeTransformMethod, logMessage);
}
}
/// <summary>
/// Log namespaces which are being propagated into the signature
/// </summary>
/// <param name="signedXml">SignedXml doing the signing or verification</param>
/// <param name="namespaces">namespaces being propagated</param>
internal static void LogNamespacePropagation(SignedXml signedXml, XmlNodeList namespaces)
{
Debug.Assert(signedXml != null, "signedXml != null");
if (InformationLoggingEnabled)
{
if (namespaces != null)
{
foreach (XmlAttribute propagatedNamespace in namespaces)
{
string propagationMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_PropagatingNamespace,
propagatedNamespace.Name,
propagatedNamespace.Value);
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.NamespacePropagation,
propagationMessage);
}
}
else
{
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.NamespacePropagation,
SR.Log_NoNamespacesPropagated);
}
}
}
/// <summary>
/// Log the output of a reference
/// </summary>
/// <param name="reference">The reference being processed</param>
/// <param name="data">Stream containing the output of the reference</param>
/// <returns>Stream containing the output of the reference</returns>
internal static Stream LogReferenceData(Reference reference, Stream data)
{
if (VerboseLoggingEnabled)
{
//
// Since the input data stream could be from the network or another source that does not
// support rewinding, we will read the stream into a temporary MemoryStream that can be used
// to stringify the output and also return to the reference so that it can produce the hash
// value.
//
MemoryStream ms = new MemoryStream();
// First read the input stream into our temporary stream
byte[] buffer = new byte[4096];
int readBytes = 0;
do
{
readBytes = data.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, readBytes);
} while (readBytes == buffer.Length);
// Log out information about it
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_TransformedReferenceContents,
Encoding.UTF8.GetString(ms.ToArray()));
WriteLine(reference,
TraceEventType.Verbose,
SignedXmlDebugEvent.ReferenceData,
logMessage);
// Rewind to the beginning, so that the entire input stream is hashed
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
else
{
return data;
}
}
/// <summary>
/// Log the computation of a signature value when signing with an asymmetric algorithm
/// </summary>
/// <param name="signedXml">SignedXml object calculating the signature</param>
/// <param name="key">key used for signing</param>
/// <param name="signatureDescription">signature description being used to create the signature</param>
/// <param name="hash">hash algorithm used to digest the output</param>
/// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param>
internal static void LogSigning(SignedXml signedXml,
object key,
SignatureDescription signatureDescription,
HashAlgorithm hash,
AsymmetricSignatureFormatter asymmetricSignatureFormatter)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(signatureDescription != null, "signatureDescription != null");
Debug.Assert(hash != null, "hash != null");
Debug.Assert(asymmetricSignatureFormatter != null, "asymmetricSignatureFormatter != null");
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_SigningAsymmetric,
GetKeyName(key),
signatureDescription.GetType().Name,
hash.GetType().Name,
asymmetricSignatureFormatter.GetType().Name);
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.Signing,
logMessage);
}
}
/// <summary>
/// Log the computation of a signature value when signing with a keyed hash algorithm
/// </summary>
/// <param name="signedXml">SignedXml object calculating the signature</param>
/// <param name="key">key the signature is created with</param>
/// <param name="hash">hash algorithm used to digest the output</param>
/// <param name="asymmetricSignatureFormatter">signature formatter used to do the signing</param>
internal static void LogSigning(SignedXml signedXml, KeyedHashAlgorithm key)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(key != null, "key != null");
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_SigningHmac,
key.GetType().Name);
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.Signing,
logMessage);
}
}
/// <summary>
/// Log the calculation of a hash value of a reference
/// </summary>
/// <param name="signedXml">SignedXml object driving the signature</param>
/// <param name="reference">Reference being hashed</param>
internal static void LogSigningReference(SignedXml signedXml, Reference reference)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(reference != null, "reference != null");
if (VerboseLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_SigningReference,
GetObjectId(reference),
reference.Uri,
reference.Id,
reference.Type,
reference.DigestMethod,
CryptoHelpers.CreateFromName(reference.DigestMethod).GetType().Name);
WriteLine(signedXml,
TraceEventType.Verbose,
SignedXmlDebugEvent.SigningReference,
logMessage);
}
}
/// <summary>
/// Log the specific point where a signature is determined to not be verifiable
/// </summary>
/// <param name="signedXml">SignedXml object doing the verification</param>
/// <param name="failureLocation">location that the signature was determined to be invalid</param>
internal static void LogVerificationFailure(SignedXml signedXml, string failureLocation)
{
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_VerificationFailed,
failureLocation);
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.VerificationFailure,
logMessage);
}
}
/// <summary>
/// Log the success or failure of a signature verification operation
/// </summary>
/// <param name="signedXml">SignedXml object doing the verification</param>
/// <param name="key">public key used to verify the signature</param>
/// <param name="verified">true if the signature verified, false otherwise</param>
internal static void LogVerificationResult(SignedXml signedXml, object key, bool verified)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(key != null, "key != null");
if (InformationLoggingEnabled)
{
string resource = verified ? SR.Log_VerificationWithKeySuccessful :
SR.Log_VerificationWithKeyNotSuccessful;
string logMessage = string.Format(CultureInfo.InvariantCulture,
resource,
GetKeyName(key));
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.SignatureVerificationResult,
logMessage);
}
}
/// <summary>
/// Log the check for appropriate X509 key usage
/// </summary>
/// <param name="signedXml">SignedXml doing the signature verification</param>
/// <param name="certificate">certificate having its key usages checked</param>
/// <param name="keyUsages">key usages being examined</param>
internal static void LogVerifyKeyUsage(SignedXml signedXml, X509Certificate certificate, X509KeyUsageExtension keyUsages)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(certificate != null, "certificate != null");
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_KeyUsages,
keyUsages.KeyUsages,
GetOidName(keyUsages.Oid),
GetKeyName(certificate));
WriteLine(signedXml,
TraceEventType.Verbose,
SignedXmlDebugEvent.X509Verification,
logMessage);
}
}
/// <summary>
/// Log that we are verifying a reference
/// </summary>
/// <param name="signedXml">SignedXMl object doing the verification</param>
/// <param name="reference">reference being verified</param>
internal static void LogVerifyReference(SignedXml signedXml, Reference reference)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(reference != null, "reference != null");
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_VerifyReference,
GetObjectId(reference),
reference.Uri,
reference.Id,
reference.Type);
WriteLine(signedXml,
TraceEventType.Verbose,
SignedXmlDebugEvent.VerifyReference,
logMessage);
}
}
/// <summary>
/// Log the hash comparison when verifying a reference
/// </summary>
/// <param name="signedXml">SignedXml object verifying the signature</param>
/// <param name="reference">reference being verified</param>
/// <param name="actualHash">actual hash value of the reference</param>
/// <param name="expectedHash">hash value the signature expected the reference to have</param>
internal static void LogVerifyReferenceHash(SignedXml signedXml,
Reference reference,
byte[] actualHash,
byte[] expectedHash)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(reference != null, "reference != null");
Debug.Assert(actualHash != null, "actualHash != null");
Debug.Assert(expectedHash != null, "expectedHash != null");
if (VerboseLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_ReferenceHash,
GetObjectId(reference),
reference.DigestMethod,
CryptoHelpers.CreateFromName(reference.DigestMethod).GetType().Name,
FormatBytes(actualHash),
FormatBytes(expectedHash));
WriteLine(signedXml,
TraceEventType.Verbose,
SignedXmlDebugEvent.VerifyReference,
logMessage);
}
}
/// <summary>
/// Log the verification parameters when verifying the SignedInfo section of a signature using an
/// asymmetric key
/// </summary>
/// <param name="signedXml">SignedXml object doing the verification</param>
/// <param name="key">key being used to verify the signed info</param>
/// <param name="signatureDescription">type of signature description class used</param>
/// <param name="hashAlgorithm">type of hash algorithm used</param>
/// <param name="asymmetricSignatureDeformatter">type of signature deformatter used</param>
/// <param name="actualHashValue">hash value of the signed info</param>
/// <param name="signatureValue">raw signature value</param>
internal static void LogVerifySignedInfo(SignedXml signedXml,
AsymmetricAlgorithm key,
SignatureDescription signatureDescription,
HashAlgorithm hashAlgorithm,
AsymmetricSignatureDeformatter asymmetricSignatureDeformatter,
byte[] actualHashValue,
byte[] signatureValue)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(signatureDescription != null, "signatureDescription != null");
Debug.Assert(hashAlgorithm != null, "hashAlgorithm != null");
Debug.Assert(asymmetricSignatureDeformatter != null, "asymmetricSignatureDeformatter != null");
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_VerifySignedInfoAsymmetric,
GetKeyName(key),
signatureDescription.GetType().Name,
hashAlgorithm.GetType().Name,
asymmetricSignatureDeformatter.GetType().Name);
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.VerifySignedInfo,
logMessage);
}
if (VerboseLoggingEnabled)
{
string hashLog = string.Format(CultureInfo.InvariantCulture,
SR.Log_ActualHashValue,
FormatBytes(actualHashValue));
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog);
string signatureLog = string.Format(CultureInfo.InvariantCulture,
SR.Log_RawSignatureValue,
FormatBytes(signatureValue));
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog);
}
}
/// <summary>
/// Log the verification parameters when verifying the SignedInfo section of a signature using a
/// keyed hash algorithm
/// </summary>
/// <param name="signedXml">SignedXml object doing the verification</param>
/// <param name="mac">hash algorithm doing the verification</param>
/// <param name="actualHashValue">hash value of the signed info</param>
/// <param name="signatureValue">raw signature value</param>
internal static void LogVerifySignedInfo(SignedXml signedXml,
KeyedHashAlgorithm mac,
byte[] actualHashValue,
byte[] signatureValue)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(mac != null, "mac != null");
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_VerifySignedInfoHmac,
mac.GetType().Name);
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.VerifySignedInfo,
logMessage);
}
if (VerboseLoggingEnabled)
{
string hashLog = string.Format(CultureInfo.InvariantCulture,
SR.Log_ActualHashValue,
FormatBytes(actualHashValue));
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog);
string signatureLog = string.Format(CultureInfo.InvariantCulture,
SR.Log_RawSignatureValue,
FormatBytes(signatureValue));
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog);
}
}
/// <summary>
/// Log that an X509 chain is being built for a certificate
/// </summary>
/// <param name="signedXml">SignedXml object building the chain</param>
/// <param name="chain">chain built for the certificate</param>
/// <param name="certificate">certificate having the chain built for it</param>
internal static void LogVerifyX509Chain(SignedXml signedXml, X509Chain chain, X509Certificate certificate)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(certificate != null, "certificate != null");
Debug.Assert(chain != null, "chain != null");
if (InformationLoggingEnabled)
{
string buildMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_BuildX509Chain,
GetKeyName(certificate));
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.X509Verification,
buildMessage);
}
if (VerboseLoggingEnabled)
{
// Dump out the flags and other miscelanious information used for building
string revocationMode = string.Format(CultureInfo.InvariantCulture,
SR.Log_RevocationMode,
chain.ChainPolicy.RevocationFlag);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationMode);
string revocationFlag = string.Format(CultureInfo.InvariantCulture,
SR.Log_RevocationFlag,
chain.ChainPolicy.RevocationFlag);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationFlag);
string verificationFlags = string.Format(CultureInfo.InvariantCulture,
SR.Log_VerificationFlag,
chain.ChainPolicy.VerificationFlags);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationFlags);
string verificationTime = string.Format(CultureInfo.InvariantCulture,
SR.Log_VerificationTime,
chain.ChainPolicy.VerificationTime);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationTime);
string urlTimeout = string.Format(CultureInfo.InvariantCulture,
SR.Log_UrlTimeout,
chain.ChainPolicy.UrlRetrievalTimeout);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, urlTimeout);
}
// If there were any errors in the chain, make sure to dump those out
if (InformationLoggingEnabled)
{
foreach (X509ChainStatus status in chain.ChainStatus)
{
if (status.Status != X509ChainStatusFlags.NoError)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_X509ChainError,
status.Status,
status.StatusInformation);
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.X509Verification,
logMessage);
}
}
}
// Finally, dump out the chain itself
if (VerboseLoggingEnabled)
{
StringBuilder chainElements = new StringBuilder();
chainElements.Append(SR.Log_CertificateChain);
foreach (X509ChainElement element in chain.ChainElements)
{
chainElements.AppendFormat(CultureInfo.InvariantCulture, " {0}", GetKeyName(element.Certificate));
}
WriteLine(signedXml,
TraceEventType.Verbose,
SignedXmlDebugEvent.X509Verification,
chainElements.ToString());
}
}
/// <summary>
/// Write information when user hits the Signed XML recursion depth limit issue.
/// This is helpful in debugging this kind of issues.
/// </summary>
/// <param name="signedXml">SignedXml object verifying the signature</param>
/// <param name="reference">reference being verified</param>
internal static void LogSignedXmlRecursionLimit(SignedXml signedXml,
Reference reference)
{
Debug.Assert(signedXml != null, "signedXml != null");
Debug.Assert(reference != null, "reference != null");
if (InformationLoggingEnabled)
{
string logMessage = string.Format(CultureInfo.InvariantCulture,
SR.Log_SignedXmlRecursionLimit,
GetObjectId(reference),
reference.DigestMethod,
CryptoHelpers.CreateFromName(reference.DigestMethod).GetType().Name);
WriteLine(signedXml,
TraceEventType.Information,
SignedXmlDebugEvent.VerifySignedInfo,
logMessage);
}
}
/// <summary>
/// Write data to the log
/// </summary>
/// <param name="source">object doing the trace</param>
/// <param name="eventType">severity of the debug event</param>
/// <param name="data">data being written</param>
/// <param name="eventId">type of event being traced</param>
private static void WriteLine(object source, TraceEventType eventType, SignedXmlDebugEvent eventId, string data)
{
Debug.Assert(source != null, "source != null");
Debug.Assert(!string.IsNullOrEmpty(data), "!string.IsNullOrEmpty(data)");
Debug.Assert(InformationLoggingEnabled, "InformationLoggingEnabled");
s_traceSource.TraceEvent(eventType,
(int)eventId,
"[{0}, {1}] {2}",
GetObjectId(source),
eventId,
data);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Config
{
public enum EnumArea
{
None,
Area_China,
Area_Taiwan,
Area_Europe,
Area_JSK,
Area_SoutheastAsia
}
public class LanguageType
{
public static string LT_ChineseS = "china";
public static string LT_ChineseT = "chinaT";
public static string LT_English = "english";
public static string LT_Thai = "thai";
public static string LT_Vietnamese = "vietnamese";
public static string LT_French = "french";
public static string LT_German = "german";
public static string LT_Polish = "polish";
public static string LT_Italian = "italian";
public static string LT_Turkish = "turkish";
public static string LT_Russian = "russian";
public static string LT_Korean = "korean";
public static string LT_Japanese = "japanese";
public static string LT_Portuguese = "portuguese";
public static string LT_Spanish = "spanish";
}
public class GameAddress
{
public string strID = string.Empty;
public string strName = string.Empty;
public string strDomainAddress = string.Empty;
public string strIPAddress = string.Empty;
}
public class PushServerInfo
{
public string strServerID = string.Empty;
public string strServerName = string.Empty;
public string strServerIP = string.Empty;
public string strServerPort = string.Empty;
public string strApiKey = string.Empty;
}
public class CustomInfo
{
public string strCustomInfoID = string.Empty;
public string strCustomInfoVaule = string.Empty;
}
public class NoticeInfo
{
public string strText;
public int iIndex;
}
public enum LoadStatus
{
LS_INIT,
LS_FAILED,
LS_SUCCUSED,
LS_MAX
}
public const string ANYSDK = "ANYSDK";
public const string USER_ACCOUNT = "useraccount";
public const string ACCOUNT_ID = "accountid";
public const string USER_NAME = "user_name";
public const string SERVERID = "serverid";
public const string GAME_ID = "game_id";
public const string APPSTORE_URL = "appstore_url";
private static UIFont snailFont = null;
private static UIFont nGuiFont = null;
public static bool bANYSDK = false;
public static string LaunchName = "Launch";
public static string MessageName = "MessageName";
public static string LanguagePath = "Language/";
public static string Language = Config.LanguageType.LT_ChineseS;
public static bool bAppStore = false;
public static bool bGameInitFailed = false;
public static bool bisOpenCommentValue = true;
public static string Appstore = "appstore";
public static string Snail = string.Empty;
public static string DefaultBundleIdentifier = "com.snailgames.chosen.snail";
public static string DefaulBundleIdMac = "com.snailgames.chosen.mac";
public static string serverName = string.Empty;
public static string gameId = string.Empty;
public static string accessId = string.Empty;
public static string accessPassword = string.Empty;
public static string accessType = string.Empty;
public static string seed = string.Empty;
public static string serverId = string.Empty;
public static string pushPhoneTypeName = string.Empty;
public static string dataCollectionUrl = string.Empty;
public static bool isPickGuildReward = false;
public static string errorLogUrl = string.Empty;
public static string errorLogUrlId = string.Empty;
public static string NativeErrorUrl = string.Empty;
public static string appid = string.Empty;
public static string appkey = string.Empty;
public static string registerServerUrl = string.Empty;
public static bool isFirstLogin = false;
public static bool mbEnableCatcher = false;
public static bool ErrorLogPhoneOpen = false;
public static string FrameAddress = string.Empty;
public static bool debug = false;
public string versionUpdateUrl = string.Empty;
public static string channelId = string.Empty;
public static bool IsInstallWechat = false;
public static string channelName = string.Empty;
public static string cid = string.Empty;
public static string idfa = string.Empty;
public static string LifeCycleStr = string.Empty;
public static string WeChatShareImgUrl = string.Empty;
public static string strChannelUniqueName = string.Empty;
public static string strAdressId = string.Empty;
public static string BundleIdentifier = string.Empty;
public static Dictionary<string, List<string>> accInfo = new Dictionary<string, List<string>>();
public static string strShowAppAdUrl = "http;//10.203.11.48/ad/ad.json";
public static string appStoreURL = string.Empty;
public static string ClientInstallUrl = string.Empty;
public static string phoneType = string.Empty;
public static string version = string.Empty;
public static string wxAndroidId = string.Empty;
public static string wxiOSId = string.Empty;
public static string pushServiceIP = string.Empty;
public static string pushServicePOST = string.Empty;
public static string channelAppSecret = string.Empty;
public static string Weixin_Link_Url = string.Empty;
public static string act_Url = string.Empty;
public static string curreRoleName = string.Empty;
public static string payCallBackURL = string.Empty;
public static string strAppStoreID = string.Empty;
public static string strNoticeName = string.Empty;
public static string strChannelName = string.Empty;
private static bool mbUseCacheWWW = false;
public static int iCacheVersion = 0;
public static string isOpenFPS = string.Empty;
public static string IsGMOpen = string.Empty;
public static bool bNeedDataCollect = false;
public static bool bNeedWechatShare = false;
public static int mQueueWaitTime = 5;
public static string accountName = string.Empty;
public static bool mbDynamicRes = true;
public static bool mbMd5 = false;
public static Dictionary<string, Config.GameAddress> mUpdaterAddress = new Dictionary<string, Config.GameAddress>();
public static Dictionary<string, Dictionary<string, string>> mDictUpdaterGuide = new Dictionary<string, Dictionary<string, string>>();
public static List<Dictionary<string, string>> mDictServerList = new List<Dictionary<string, string>>();
public static List<Dictionary<string, string>> mDictAllServerList = new List<Dictionary<string, string>>();
public static Dictionary<string, string> mWordsDict = new Dictionary<string, string>();
public static string mstrShopData = string.Empty;
public static string mstrServerNotice = string.Empty;
public static Dictionary<string, Config.CustomInfo> mDictCustomInfoList = new Dictionary<string, Config.CustomInfo>();
public static List<Config.PushServerInfo> mDictPushServerList = new List<Config.PushServerInfo>();
public static string mstrPreSuffix = "File://";
public static string mstrStreamSuffix = "File://";
public static string mstrAssetBundleRootPath = string.Empty;
public static string mstrSourceResRootPath = string.Empty;
public static string mstrStreamResRootPath = string.Empty;
public static string mstrMacAddress = string.Empty;
public static string mstrVersionUseage = string.Empty;
public static string mstrInstallationVersion = string.Empty;
public static string mstrLocalVersion = string.Empty;
public static int miLocalNumberVersion = 1;
public static UIFont SnailFont
{
get
{
return Config.snailFont;
}
set
{
Config.snailFont = value;
}
}
public static UIFont NGUIFont
{
get
{
return Config.nGuiFont;
}
set
{
Config.nGuiFont = value;
}
}
public static bool bEditor
{
get
{
return false;
}
}
public static bool bAndroid
{
get
{
return true;
}
}
public static bool bIPhone
{
get
{
return false;
}
}
public static bool bWin
{
get
{
return false;
}
}
public static bool bMac
{
get
{
return false;
}
}
public static Config.EnumArea GameArea
{
get;
private set;
}
public static string ScreenResolution
{
get
{
return ResolutionConstrain.Instance.width + "*" + ResolutionConstrain.Instance.height;
}
}
public static bool mbVerifyVersion
{
get
{
if (string.IsNullOrEmpty(Config.mstrLocalVersion))
{
return false;
}
string updaterConfig = Config.GetUpdaterConfig("VerifyVerison", "Value");
return !string.IsNullOrEmpty(updaterConfig) && Config.mstrLocalVersion == updaterConfig;
}
}
public static UIFont LoadUIFont(string strFontName)
{
if (Application.isPlaying)
{
string path = "Local/Fonts/" + strFontName;
UnityEngine.Object @object = Resources.Load(path);
if (@object != null)
{
GameObject gameObject = @object as GameObject;
UIFont component = gameObject.GetComponent<UIFont>();
if (component != null)
{
return component;
}
}
}
return null;
}
public static void SetUseCacheWWW(bool bUseCache)
{
Config.mbUseCacheWWW = bUseCache;
}
public static bool GetUseCacheWWW()
{
return Config.mbUseCacheWWW;
}
public static void SetCacheVersion(string strCacheVersion)
{
string @string = PlayerPrefs.GetString("CacheVersion", string.Empty);
if (string.IsNullOrEmpty(@string) || strCacheVersion != @string)
{
PlayerPrefs.SetString("CacheVersion", strCacheVersion);
Caching.CleanCache();
}
Config.iCacheVersion = 0;
if (string.IsNullOrEmpty(strCacheVersion))
{
LogSystem.LogWarning(new object[]
{
"Version Error ",
strCacheVersion
});
return;
}
string text = strCacheVersion.Replace(".", string.Empty);
if (string.IsNullOrEmpty(text))
{
LogSystem.LogWarning(new object[]
{
"Version Error ",
text
});
return;
}
Config.iCacheVersion = int.Parse(text);
}
public static int GetQueueWaitTime()
{
return Config.mQueueWaitTime;
}
public static void SetLanguage(string sType)
{
if (string.IsNullOrEmpty(sType))
{
sType = Config.LanguageType.LT_ChineseS;
}
Config.LanguagePath = Config.LanguagePath + sType + "/";
}
public static string GetMacAddress()
{
return Config.mstrMacAddress;
}
public static void SetMacAddress(string strMacAddress)
{
Config.mstrMacAddress = strMacAddress;
}
public static string GetPreSuffix()
{
return Config.mstrPreSuffix;
}
public static void SetPreSuffix(string strSuffix)
{
Config.mstrPreSuffix = strSuffix;
}
public static string GetStreamSuffix()
{
return Config.mstrStreamSuffix;
}
public static void SetStreamSuffix(string strSuffix)
{
Config.mstrStreamSuffix = strSuffix;
}
public static Config.GameAddress GetUpdaterAddress()
{
if (Config.mUpdaterAddress.Count == 0)
{
return null;
}
string key;
if (string.IsNullOrEmpty(Config.strAdressId))
{
key = "QaAddr";
}
else
{
key = Config.strAdressId;
}
if (Config.mUpdaterAddress.ContainsKey(key))
{
return Config.mUpdaterAddress[key];
}
return null;
}
public static string GetUpdaterConfig(string strKey, string strName)
{
if (Config.mDictUpdaterGuide.ContainsKey(strKey) && Config.mDictUpdaterGuide[strKey].ContainsKey(strName))
{
return Config.mDictUpdaterGuide[strKey][strName];
}
return string.Empty;
}
public static string GetAssetBundleRootPath()
{
return Config.mstrAssetBundleRootPath;
}
public static void SetAssetBundleRootPath(string strRootPath)
{
Config.mstrAssetBundleRootPath = strRootPath;
}
public static string GetVersionUseage()
{
return Config.mstrVersionUseage;
}
public static void SetVersionUseage(string strValue)
{
Config.mstrVersionUseage = strValue;
}
public static string GetInstallationVersion()
{
return Config.mstrInstallationVersion;
}
public static void SetInstallationVersion(string strValue)
{
Config.mstrInstallationVersion = strValue;
}
public static string GetLocalVersion()
{
return Config.mstrLocalVersion;
}
public static void SetLocalVersion(string strLocalVersion)
{
Config.mstrLocalVersion = strLocalVersion;
}
public static int GetLocalNumberVersion()
{
return Config.miLocalNumberVersion;
}
public static void SetLocalNumberVersion(string strLocalNumberVersion)
{
if (string.IsNullOrEmpty(strLocalNumberVersion))
{
Config.miLocalNumberVersion = 0;
}
else
{
try
{
Config.miLocalNumberVersion = int.Parse(strLocalNumberVersion);
}
catch (Exception ex)
{
Config.miLocalNumberVersion = 0;
LogSystem.LogError(new object[]
{
ex.ToString()
});
}
}
}
public static string GetSourceRootPath()
{
return Config.mstrSourceResRootPath;
}
public static void SetSourceRootPath(string strRootPath)
{
Config.mstrSourceResRootPath = strRootPath;
}
public static string GetStreamRootPath()
{
return Config.mstrStreamResRootPath;
}
public static void SetStreamRootPath(string strRootPath)
{
Config.mstrStreamResRootPath = strRootPath;
}
public static void SetUpdaterAddress(TextAsset text)
{
if (text == null)
{
return;
}
XMLParser xMLParser = new XMLParser();
XMLNode xMLNode = xMLParser.Parse(text.text);
XMLNodeList nodeList = xMLNode.GetNodeList("Addresses>0>Address");
if (nodeList != null)
{
foreach (XMLNode xMLNode2 in nodeList)
{
Config.GameAddress gameAddress = new Config.GameAddress();
gameAddress.strID = xMLNode2.GetValue("@ID");
gameAddress.strName = xMLNode2.GetValue("@Name");
gameAddress.strDomainAddress = xMLNode2.GetValue("@DomainAddr") + "/" + Config.GetInstallationVersion();
gameAddress.strIPAddress = xMLNode2.GetValue("@IPAddr") + "/" + Config.GetInstallationVersion();
if (!Config.mUpdaterAddress.ContainsKey(gameAddress.strID))
{
Config.mUpdaterAddress.Add(gameAddress.strID, gameAddress);
}
}
}
}
public static void SetUpdateGuideInfo(string xmlString)
{
if (string.IsNullOrEmpty(xmlString))
{
return;
}
int startIndex = xmlString.IndexOf('<');
xmlString = xmlString.Substring(startIndex);
xmlString.Trim();
XMLParser xMLParser = new XMLParser();
XMLNode xMLNode = xMLParser.Parse(xmlString);
XMLNodeList xMLNodeList = (XMLNodeList)xMLNode["Resources"];
if (xMLNodeList == null)
{
return;
}
for (int i = 0; i < xMLNodeList.Count; i++)
{
XMLNode xMLNode2 = xMLNodeList[i] as XMLNode;
XMLNodeList nodeList = xMLNode2.GetNodeList("Resource");
if (nodeList != null)
{
for (int j = 0; j < nodeList.Count; j++)
{
XMLNode xMLNode3 = nodeList[j] as XMLNode;
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string key = string.Empty;
foreach (DictionaryEntry dictionaryEntry in xMLNode3)
{
if (dictionaryEntry.Value != null)
{
string text = dictionaryEntry.Key as string;
if (text[0] == '@')
{
text = text.Substring(1);
if (text == "ID")
{
key = (string)dictionaryEntry.Value;
}
else if (dictionary.ContainsKey(text))
{
dictionary[text] = (string)dictionaryEntry.Value;
}
else
{
dictionary.Add(text, (string)dictionaryEntry.Value);
}
}
}
}
if (Config.mDictUpdaterGuide.ContainsKey(key))
{
Config.mDictUpdaterGuide[key] = dictionary;
}
else
{
Config.mDictUpdaterGuide.Add(key, dictionary);
}
}
}
}
}
public static void SetServerNotice(string xmlString)
{
Config.mstrServerNotice = xmlString;
}
public static int Compare_Index(Config.NoticeInfo aInfo, Config.NoticeInfo bInfo)
{
if (aInfo.iIndex > bInfo.iIndex)
{
return 1;
}
if (aInfo.iIndex < bInfo.iIndex)
{
return -1;
}
return 0;
}
public static void SetCustomInfoList(string xmlString)
{
int startIndex = xmlString.IndexOf('<');
xmlString = xmlString.Substring(startIndex);
xmlString.Trim();
XMLParser xMLParser = new XMLParser();
XMLNode xMLNode = xMLParser.Parse(xmlString);
Config.bAppStore = (Config.channelName == Config.Appstore);
Config.SetCustomInfo((XMLNodeList)xMLNode["Resources"]);
Config.InitResouceInfo();
Config.SetChannelInfo(xMLNode);
Config.SetWechatInfo(xMLNode);
Config.SetAccInfo(xMLNode);
}
private static void SetWechatInfo(XMLNode rootnode)
{
if (rootnode == null)
{
return;
}
XMLNodeList nodeList = rootnode.GetNodeList("Resources>0>Wechat>0>Property");
foreach (XMLNode xMLNode in nodeList)
{
string value = xMLNode.GetValue("@ID");
if (value == Config.BundleIdentifier)
{
Config.bNeedWechatShare = "1".Equals(xMLNode.GetValue("@WechatShare"));
Config.wxAndroidId = xMLNode.GetValue("@wxAndroidId");
Config.WeChatShareImgUrl = xMLNode.GetValue("@WeChatShareImgUrl");
LogSystem.LogWarning(new object[]
{
"------1----wxAndroidId--------" + Config.wxAndroidId
});
LogSystem.LogWarning(new object[]
{
"------1-----bNeedWechatShare-------" + Config.bNeedWechatShare
});
LogSystem.LogWarning(new object[]
{
"------1-----WeChatShareImgUrl-------" + Config.WeChatShareImgUrl
});
return;
}
}
LogSystem.LogWarning(new object[]
{
"------2----wxAndroidId--------" + Config.wxAndroidId
});
LogSystem.LogWarning(new object[]
{
"------2-----bNeedWechatShare-------" + Config.bNeedWechatShare
});
LogSystem.LogWarning(new object[]
{
"------2-----WeChatShareImgUrl-------" + Config.WeChatShareImgUrl
});
}
private static void SetChannelInfo(XMLNode rootnode)
{
if (rootnode == null)
{
return;
}
XMLNodeList nodeList = rootnode.GetNodeList("Resources>0>Channel>0>Property");
Config.GameArea = Config.EnumArea.None;
LogSystem.LogWarning(new object[]
{
"----------strChannelUniqueName--------" + Config.strChannelUniqueName
});
if (string.IsNullOrEmpty(Config.strChannelUniqueName))
{
Config.strChannelUniqueName = "android_snail";
}
foreach (XMLNode xMLNode in nodeList)
{
string value = xMLNode.GetValue("@ID");
if (value == Config.strChannelUniqueName)
{
Config.payCallBackURL = xMLNode.GetValue("@PayCallBackUrl");
Config.ClientInstallUrl = xMLNode.GetValue("@ClientInstallUrl");
Config.strNoticeName = xMLNode.GetValue("@NoticeName");
Config.strChannelName = xMLNode.GetValue("@ChannelName");
Config.bNeedDataCollect = "1".Equals(xMLNode.GetValue("@DataCollect"));
LogSystem.LogWarning(new object[]
{
"------2----bNeedDataCollect--------" + Config.bNeedDataCollect
});
LogSystem.LogWarning(new object[]
{
"------2-----strID-------" + value
});
string value2 = xMLNode.GetValue("@Area");
int gameArea;
if (!string.IsNullOrEmpty(value2) && int.TryParse(value2, out gameArea))
{
Config.GameArea = (Config.EnumArea)gameArea;
}
return;
}
}
LogSystem.LogWarning(new object[]
{
"channelName not have info ",
Config.strChannelUniqueName
});
LogSystem.LogWarning(new object[]
{
"----1--------bNeedDataCollect------" + Config.bNeedDataCollect
});
}
private static void SetAccInfo(XMLNode rootnode)
{
if (rootnode == null)
{
LogSystem.LogWarning(new object[]
{
"SetAccInfo is null"
});
return;
}
XMLNodeList nodeList = rootnode.GetNodeList("Resources>0>Acc>0>Property");
if (nodeList == null)
{
LogSystem.LogWarning(new object[]
{
"SetAccInfo is null"
});
return;
}
foreach (XMLNode xMLNode in nodeList)
{
string value = xMLNode.GetValue("@No");
if (Config.accInfo.ContainsKey(value))
{
Config.accInfo[value].Add(xMLNode.GetValue("@Name"));
}
else
{
List<string> list = new List<string>();
list.Add(xMLNode.GetValue("@Name"));
Config.accInfo.Add(value, list);
}
}
}
private static void SetCustomInfo(XMLNodeList xmlNodeList)
{
if (xmlNodeList == null)
{
LogSystem.LogWarning(new object[]
{
"SetCustomInfo is null"
});
return;
}
for (int i = 0; i < xmlNodeList.Count; i++)
{
XMLNode xMLNode = xmlNodeList[i] as XMLNode;
XMLNodeList nodeList = xMLNode.GetNodeList("Resource");
if (nodeList != null)
{
for (int j = 0; j < nodeList.Count; j++)
{
XMLNode xMLNode2 = nodeList[j] as XMLNode;
Config.CustomInfo customInfo = new Config.CustomInfo();
foreach (DictionaryEntry dictionaryEntry in xMLNode2)
{
if (dictionaryEntry.Value != null)
{
string text = dictionaryEntry.Key as string;
if (text[0] == '@')
{
text = text.Substring(1);
if (text == "ID")
{
customInfo.strCustomInfoID = (dictionaryEntry.Value as string);
}
else if (text == "Value")
{
customInfo.strCustomInfoVaule = (dictionaryEntry.Value as string);
}
}
}
}
if (Config.mDictCustomInfoList.ContainsKey(customInfo.strCustomInfoID))
{
Config.mDictCustomInfoList[customInfo.strCustomInfoID] = customInfo;
}
else
{
Config.mDictCustomInfoList.Add(customInfo.strCustomInfoID, customInfo);
}
}
}
}
}
public static string GetCustomValue(string strKey)
{
Config.CustomInfo customInfo;
if (Config.mDictCustomInfoList.TryGetValue(strKey, out customInfo))
{
return customInfo.strCustomInfoVaule;
}
return string.Empty;
}
public static void InitResouceInfo()
{
if (Config.mDictCustomInfoList.ContainsKey("accessID"))
{
Config.accessId = Config.mDictCustomInfoList["accessID"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("accessPwd"))
{
Config.accessPassword = Config.mDictCustomInfoList["accessPwd"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("seed"))
{
Config.seed = Config.mDictCustomInfoList["seed"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("errorLogUrl"))
{
Config.errorLogUrl = Config.mDictCustomInfoList["errorLogUrl"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("errorLogUrlID"))
{
Config.errorLogUrlId = Config.mDictCustomInfoList["errorLogUrlID"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("NativeErrorUrl"))
{
Config.NativeErrorUrl = Config.mDictCustomInfoList["NativeErrorUrl"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("appid"))
{
Config.appid = Config.mDictCustomInfoList["appid"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("Weixin_Link_Url"))
{
Config.Weixin_Link_Url = Config.mDictCustomInfoList["Weixin_Link_Url"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("ACT_Url"))
{
Config.act_Url = Config.mDictCustomInfoList["ACT_Url"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("appkey"))
{
Config.appkey = Config.mDictCustomInfoList["appkey"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("wxiOSId"))
{
Config.wxiOSId = Config.mDictCustomInfoList["wxiOSId"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("dataCollectionUrl"))
{
Config.dataCollectionUrl = Config.mDictCustomInfoList["dataCollectionUrl"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("ErrorLogPhoneOpen"))
{
string strCustomInfoVaule = Config.mDictCustomInfoList["ErrorLogPhoneOpen"].strCustomInfoVaule;
if (strCustomInfoVaule == "true")
{
Config.ErrorLogPhoneOpen = true;
}
else
{
Config.ErrorLogPhoneOpen = false;
}
}
if (Config.mDictCustomInfoList.ContainsKey("regUrl"))
{
Config.registerServerUrl = Config.mDictCustomInfoList["regUrl"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("FrameAddress"))
{
Config.FrameAddress = Config.mDictCustomInfoList["FrameAddress"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("accessType"))
{
Config.accessType = Config.mDictCustomInfoList["accessType"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("gameID"))
{
Config.gameId = Config.mDictCustomInfoList["gameID"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("FPSOpen"))
{
Config.isOpenFPS = Config.mDictCustomInfoList["FPSOpen"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("GMOpen"))
{
Config.IsGMOpen = Config.mDictCustomInfoList["GMOpen"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("channeltype"))
{
Config.channelId = Config.mDictCustomInfoList["channeltype"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("PushAndroidName"))
{
Config.pushPhoneTypeName = Config.mDictCustomInfoList["PushAndroidName"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("version"))
{
Config.version = Config.mDictCustomInfoList["version"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("pushServiceIP"))
{
Config.pushServiceIP = Config.mDictCustomInfoList["pushServiceIP"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("pushServicePOST"))
{
Config.pushServicePOST = Config.mDictCustomInfoList["pushServicePOST"].strCustomInfoVaule;
}
if (Config.mDictCustomInfoList.ContainsKey("channelAppSecret"))
{
Config.channelAppSecret = Config.mDictCustomInfoList["channelAppSecret"].strCustomInfoVaule;
}
}
public static void SetServerList(string xmlString)
{
int startIndex = xmlString.IndexOf('<');
xmlString = xmlString.Substring(startIndex);
xmlString.Trim();
XMLParser xMLParser = new XMLParser();
XMLNode xMLNode = xMLParser.Parse(xmlString);
XMLNodeList xMLNodeList = (XMLNodeList)xMLNode["Servers"];
if (xMLNodeList == null)
{
return;
}
for (int i = 0; i < xMLNodeList.Count; i++)
{
XMLNode xMLNode2 = xMLNodeList[i] as XMLNode;
XMLNodeList nodeList = xMLNode2.GetNodeList("Server");
if (nodeList != null)
{
for (int j = 0; j < nodeList.Count; j++)
{
XMLNode xMLNode3 = nodeList[j] as XMLNode;
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (DictionaryEntry dictionaryEntry in xMLNode3)
{
if (dictionaryEntry.Value != null)
{
string text = dictionaryEntry.Key as string;
if (text[0] == '@')
{
text = text.Substring(1);
if (!dictionary.ContainsKey(text))
{
dictionary.Add(text, (string)dictionaryEntry.Value);
}
else
{
dictionary[text] = (string)dictionaryEntry.Value;
}
}
}
}
Config.mDictServerList.Add(dictionary);
}
}
}
}
public static void SetAllServerList(string xmlString)
{
int startIndex = xmlString.IndexOf('<');
xmlString = xmlString.Substring(startIndex);
xmlString.Trim();
XMLParser xMLParser = new XMLParser();
XMLNode xMLNode = xMLParser.Parse(xmlString);
XMLNodeList xMLNodeList = (XMLNodeList)xMLNode["Servers"];
if (xMLNodeList == null)
{
return;
}
for (int i = 0; i < xMLNodeList.Count; i++)
{
XMLNode xMLNode2 = xMLNodeList[i] as XMLNode;
XMLNodeList nodeList = xMLNode2.GetNodeList("Server");
if (nodeList != null)
{
for (int j = 0; j < nodeList.Count; j++)
{
XMLNode xMLNode3 = nodeList[j] as XMLNode;
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (DictionaryEntry dictionaryEntry in xMLNode3)
{
if (dictionaryEntry.Value != null)
{
string text = dictionaryEntry.Key as string;
if (text[0] == '@')
{
text = text.Substring(1);
if (!dictionary.ContainsKey(text))
{
dictionary.Add(text, (string)dictionaryEntry.Value);
}
else
{
dictionary[text] = (string)dictionaryEntry.Value;
}
}
}
}
Config.mDictAllServerList.Add(dictionary);
}
}
}
}
public static void SetShopList(string xmlString)
{
Config.mstrShopData = xmlString;
}
public static void SetPushServerList(string xmlString)
{
int startIndex = xmlString.IndexOf('<');
xmlString = xmlString.Substring(startIndex);
xmlString.Trim();
XMLParser xMLParser = new XMLParser();
XMLNode xMLNode = xMLParser.Parse(xmlString);
XMLNodeList xMLNodeList = (XMLNodeList)xMLNode["PushServers"];
if (xMLNodeList == null)
{
return;
}
for (int i = 0; i < xMLNodeList.Count; i++)
{
XMLNode xMLNode2 = xMLNodeList[i] as XMLNode;
XMLNodeList nodeList = xMLNode2.GetNodeList("Server");
if (nodeList != null)
{
for (int j = 0; j < nodeList.Count; j++)
{
XMLNode xMLNode3 = nodeList[j] as XMLNode;
Config.PushServerInfo pushServerInfo = new Config.PushServerInfo();
foreach (DictionaryEntry dictionaryEntry in xMLNode3)
{
if (dictionaryEntry.Value != null)
{
string text = dictionaryEntry.Key as string;
if (text[0] == '@')
{
text = text.Substring(1);
if (text == "ID")
{
pushServerInfo.strServerID = (dictionaryEntry.Value as string);
}
else if (text == "Name")
{
pushServerInfo.strServerName = (dictionaryEntry.Value as string);
}
else if (text == "IP")
{
pushServerInfo.strServerIP = (dictionaryEntry.Value as string);
}
else if (text == "Port")
{
pushServerInfo.strServerPort = (dictionaryEntry.Value as string);
}
else if (text == "ApiKey")
{
pushServerInfo.strApiKey = (dictionaryEntry.Value as string);
}
}
}
}
Config.mDictPushServerList.Add(pushServerInfo);
}
}
}
}
public static Config.PushServerInfo GetPushServer()
{
if (Config.mDictPushServerList.Count == 0)
{
return null;
}
int index = UnityEngine.Random.Range(0, Config.mDictPushServerList.Count);
return Config.mDictPushServerList[index];
}
public static void SetWordsInfo(string strWords)
{
if (string.IsNullOrEmpty(strWords))
{
return;
}
string[] array = strWords.Split(new string[]
{
"\r\n"
}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < array.Length; i++)
{
string[] array2 = array[i].Split(new string[]
{
"="
}, 2, StringSplitOptions.RemoveEmptyEntries);
if (array2.Length == 2)
{
if (Config.mWordsDict.ContainsKey(array2[0]))
{
LogSystem.Log(new object[]
{
"the key is echo in local file!!! please check the key = ",
array2[0]
});
}
else
{
array2[1] = array2[1].Replace("[n]", "\n");
Config.mWordsDict[array2[0]] = array2[1];
}
}
}
}
public static string GetUdpateLangage(string strKey)
{
if (Config.mWordsDict.ContainsKey(strKey))
{
return Config.mWordsDict[strKey];
}
return strKey;
}
public static void SavePlayerPrefs(string useraccount, string username, string serverid, string gameid, string appstoreUrl, string accountid)
{
PlayerPrefs.SetString("useraccount", useraccount);
string value = WWW.EscapeURL(username);
PlayerPrefs.SetString("user_name", value);
PlayerPrefs.SetString("serverid", serverid);
PlayerPrefs.SetString("game_id", gameid);
PlayerPrefs.SetString("appstore_url", appstoreUrl);
PlayerPrefs.SetString("accountid", accountid);
}
public static void GetPlayerPrefs(ref string useraccount, ref string username, ref string serverid, ref string gameid, ref string appstoreUrl, ref string accountid)
{
useraccount = PlayerPrefs.GetString("useraccount", string.Empty);
string @string = PlayerPrefs.GetString("user_name", string.Empty);
username = WWW.UnEscapeURL(@string);
serverid = PlayerPrefs.GetString("serverid", string.Empty);
gameid = PlayerPrefs.GetString("game_id", string.Empty);
appstoreUrl = PlayerPrefs.GetString("appstore_url", string.Empty);
accountid = PlayerPrefs.GetString("accountid", string.Empty);
}
public static string GetNetErrorPromp(string strKeywords)
{
string strKey = "CustomInfoError";
if (strKeywords.Contains("connect to host"))
{
strKey = "CantConnectToHost";
}
else if (strKeywords.Contains("404"))
{
strKey = "HTTPError_404";
}
else if (strKeywords.Contains("403"))
{
strKey = "HTTPError_403";
}
else if (strKeywords.Contains("405"))
{
strKey = "HTTPError_405";
}
else if (strKeywords.Contains("406"))
{
strKey = "HTTPError_406";
}
else if (strKeywords.Contains("407"))
{
strKey = "HTTPError_407";
}
else if (strKeywords.Contains("410"))
{
strKey = "HTTPError_410";
}
else if (strKeywords.Contains("412"))
{
strKey = "HTTPError_412";
}
else if (strKeywords.Contains("414"))
{
strKey = "HTTPError_414";
}
else if (strKeywords.Contains("500"))
{
strKey = "HTTPError_500";
}
else if (strKeywords.Contains("501"))
{
strKey = "HTTPError_501";
}
else if (strKeywords.Contains("502"))
{
strKey = "HTTPError_502";
}
return Config.GetUdpateLangage(strKey);
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using DjvuNet.Graphics;
namespace DjvuNet.JB2
{
public class JB2Image : JB2Dictionary
{
#region Private Variables
#endregion Private Variables
#region Public Properties
#region Height
private int _height;
/// <summary>
/// Gets or sets the height of the image
/// </summary>
public int Height
{
get { return _height; }
set
{
if (Height != value)
{
_height = value;
}
}
}
#endregion Height
#region Width
private int _width;
/// <summary>
/// Gets or sets the width of the image
/// </summary>
public int Width
{
get { return _width; }
set
{
if (Width != value)
{
_width = value;
}
}
}
#endregion Width
#region Blits
private readonly List<JB2Blit> _blits = new List<JB2Blit>();
/// <summary>
/// Gets the blits for the image
/// </summary>
public List<JB2Blit> Blits
{
get { return _blits; }
}
#endregion Blits
#endregion Public Properties
#region Constructors
#endregion Constructors
#region Public Methods
public Bitmap GetBitmap()
{
return GetBitmap(1);
}
public Bitmap GetBitmap(int subsample)
{
return GetBitmap(subsample, 1);
}
public Bitmap GetBitmap(int subsample, int align)
{
if ((Width == 0) || (Height == 0))
{
throw new SystemException("Image can not create bitmap");
}
int swidth = ((Width + subsample) - 1) / subsample;
int sheight = ((Height + subsample) - 1) / subsample;
int border = (((swidth + align) - 1) & ~(align - 1)) - swidth;
Bitmap bm = new Bitmap();
bm.Init(sheight, swidth, border);
bm.Grays = (1 + (subsample * subsample));
//for (int blitno = 0; blitno < Blits.Count; blitno++)
Parallel.For(
0,
Blits.Count,
blitno =>
{
JB2Blit pblit = GetBlit(blitno);
JB2Shape pshape = GetShape(pblit.ShapeNumber);
if (pshape.Bitmap != null)
{
bm.Blit(pshape.Bitmap, pblit.Left, pblit.Bottom, subsample);
}
});
return bm;
}
public Bitmap GetBitmap(Rectangle rect)
{
return GetBitmap(rect, 1);
}
public Bitmap GetBitmap(Rectangle rect, int subsample)
{
return GetBitmap(rect, subsample, 1);
}
public Bitmap GetBitmap(Rectangle rect, int subsample, int align)
{
return GetBitmap(rect, subsample, align, 0);
}
public Bitmap GetBitmap(Rectangle rect, int subsample, int align, int dispy)
{
if ((Width == 0) || (Height == 0))
{
throw new SystemException("Image can not create bitmap");
}
int rxmin = rect.Right * subsample;
int rymin = rect.Bottom * subsample;
int swidth = rect.Width;
int sheight = rect.Height;
int border = (((swidth + align) - 1) & ~(align - 1)) - swidth;
Bitmap bm = new Bitmap();
bm.Init(sheight, swidth, border);
bm.Grays = (1 + (subsample * subsample));
for (int blitno = 0; blitno < Blits.Count; )
{
JB2Blit pblit = GetBlit(blitno++);
JB2Shape pshape = GetShape(pblit.ShapeNumber);
if (pshape.Bitmap != null)
{
bm.Blit(pshape.Bitmap, pblit.Left - rxmin, (dispy + pblit.Bottom) - rymin, subsample);
}
}
return bm;
}
public Bitmap GetBitmap(Rectangle rect, int subsample, int align, int dispy, List<int> components)
{
if (components == null)
{
return GetBitmap(rect, subsample, align, dispy);
}
if ((Width == 0) || (Height == 0))
{
throw new SystemException("Image can not create bitmap");
}
int rxmin = rect.Right * subsample;
int rymin = rect.Bottom * subsample;
int swidth = rect.Width;
int sheight = rect.Height;
int border = (((swidth + align) - 1) & ~(align - 1)) - swidth;
Bitmap bm = new Bitmap();
bm.Init(sheight, swidth, border);
bm.Grays = (1 + (subsample * subsample));
for (int blitno = 0; blitno < Blits.Count; )
{
JB2Blit pblit = GetBlit(blitno++);
JB2Shape pshape = GetShape(pblit.ShapeNumber);
if (pshape.Bitmap != null)
{
if (bm.Blit(pshape.Bitmap, pblit.Left - rxmin, (dispy + pblit.Bottom) - rymin, subsample))
{
components.Add((blitno - 1));
}
}
}
return bm;
}
public JB2Blit GetBlit(int blitno)
{
return (JB2Blit)_blits[blitno];
}
public virtual int AddBlit(JB2Blit jb2Blit)
{
if (jb2Blit.ShapeNumber >= ShapeCount)
{
throw new ArgumentException("Image bad shape");
}
int retval = _blits.Count;
_blits.Add(jb2Blit);
return retval;
}
public override void Decode(BinaryReader gbs, JB2Dictionary zdict)
{
Init();
JB2Decoder codec = new JB2Decoder();
codec.Init(gbs, zdict);
codec.Code(this);
}
public override void Init()
{
Width = Height = 0;
_blits.Clear();
base.Init();
}
#endregion Public Methods
}
}
| |
// 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;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
namespace System.Net
{
internal enum WebHeaderCollectionType : ushort
{
Unknown,
WebRequest,
WebResponse,
HttpWebRequest,
HttpWebResponse,
HttpListenerRequest,
HttpListenerResponse,
FtpWebRequest,
FtpWebResponse,
FileWebRequest,
FileWebResponse,
}
/// <devdoc>
/// <para>
/// Contains protocol headers associated with a
/// request or response.
/// </para>
/// </devdoc>
public class WebHeaderCollection : NameValueCollection, IEnumerable
{
// Data and Constants
private const int ApproxAveHeaderLineSize = 30;
private const int ApproxHighAvgNumHeaders = 16;
private int _numCommonHeaders;
// Grouped by first character, so lookup is faster. The table s_commonHeaderHints maps first letters to indexes in this array.
// After first character, sort by decreasing length. It's ok if two headers have the same first character and length.
private static readonly string[] s_commonHeaderNames = {
HttpKnownHeaderNames.AcceptRanges, // "Accept-Ranges" 13
HttpKnownHeaderNames.ContentLength, // "Content-Length" 14
HttpKnownHeaderNames.CacheControl, // "Cache-Control" 13
HttpKnownHeaderNames.ContentType, // "Content-Type" 12
HttpKnownHeaderNames.Date, // "Date" 4
HttpKnownHeaderNames.Expires, // "Expires" 7
HttpKnownHeaderNames.ETag, // "ETag" 4
HttpKnownHeaderNames.LastModified, // "Last-Modified" 13
HttpKnownHeaderNames.Location, // "Location" 8
HttpKnownHeaderNames.ProxyAuthenticate, // "Proxy-Authenticate" 18
HttpKnownHeaderNames.P3P, // "P3P" 3
HttpKnownHeaderNames.SetCookie2, // "Set-Cookie2" 11
HttpKnownHeaderNames.SetCookie, // "Set-Cookie" 10
HttpKnownHeaderNames.Server, // "Server" 6
HttpKnownHeaderNames.Via, // "Via" 3
HttpKnownHeaderNames.WWWAuthenticate, // "WWW-Authenticate" 16
HttpKnownHeaderNames.XAspNetVersion, // "X-AspNet-Version" 16
HttpKnownHeaderNames.XPoweredBy, // "X-Powered-By" 12
"[" // This sentinel will never match. (This character isn't in the hint table.)
};
// Mask off all but the bottom five bits, and look up in this array.
private static readonly sbyte[] s_commonHeaderHints = new sbyte[] {
-1, 0, -1, 1, 4, 5, -1, -1, // - a b c d e f g
-1, -1, -1, -1, 7, -1, -1, -1, // h i j k l m n o
9, -1, -1, 11, -1, -1, 14, 15, // p q r s t u v w
16, -1, -1, -1, -1, -1, -1, -1 }; // x y z [ - - - -
// To ensure C++ and IL callers can't pollute the underlying collection by calling overridden base members directly, we
// will use a member collection instead.
private NameValueCollection _innerCollection;
private NameValueCollection InnerCollection
{
get
{
if (_innerCollection == null)
{
_innerCollection = new NameValueCollection(ApproxHighAvgNumHeaders, StringComparer.OrdinalIgnoreCase);
}
return _innerCollection;
}
}
// This is the object that created the header collection.
private WebHeaderCollectionType _type;
private bool AllowHttpRequestHeader
{
get
{
if (_type == WebHeaderCollectionType.Unknown)
{
_type = WebHeaderCollectionType.WebRequest;
}
return _type == WebHeaderCollectionType.WebRequest || _type == WebHeaderCollectionType.HttpWebRequest || _type == WebHeaderCollectionType.HttpListenerRequest;
}
}
internal bool AllowHttpResponseHeader
{
get
{
if (_type == WebHeaderCollectionType.Unknown)
{
_type = WebHeaderCollectionType.WebResponse;
}
return _type == WebHeaderCollectionType.WebResponse || _type == WebHeaderCollectionType.HttpWebResponse || _type == WebHeaderCollectionType.HttpListenerResponse;
}
}
public string this[HttpRequestHeader header]
{
get
{
if (!AllowHttpRequestHeader)
{
throw new InvalidOperationException(SR.net_headers_req);
}
return this[header.GetName()];
}
set
{
if (!AllowHttpRequestHeader)
{
throw new InvalidOperationException(SR.net_headers_req);
}
this[header.GetName()] = value;
}
}
public string this[HttpResponseHeader header]
{
get
{
if (!AllowHttpResponseHeader)
{
throw new InvalidOperationException(SR.net_headers_rsp);
}
return this[header.GetName()];
}
set
{
if (!AllowHttpResponseHeader)
{
throw new InvalidOperationException(SR.net_headers_rsp);
}
if (_type == WebHeaderCollectionType.HttpListenerResponse)
{
if (value != null && value.Length > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_headers_toolong, ushort.MaxValue));
}
}
this[header.GetName()] = value;
}
}
private static readonly char[] s_httpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };
private static readonly char[] s_invalidParamChars = new char[] { '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '\'', '/', '[', ']', '?', '=', '{', '}', ' ', '\t', '\r', '\n' };
// CheckBadChars - throws on invalid chars to be not found in header name/value
internal static string CheckBadChars(string name, bool isHeaderValue)
{
if (name == null || name.Length == 0)
{
// empty name is invalid
if (!isHeaderValue)
{
throw name == null ? new ArgumentNullException(nameof(name)) :
new ArgumentException(SR.Format(SR.net_emptystringcall, "name"), nameof(name));
}
// empty value is OK
return string.Empty;
}
if (isHeaderValue)
{
// VALUE check
// Trim spaces from both ends
name = name.Trim(s_httpTrimCharacters);
// First, check for correctly formed multi-line value
// Second, check for absence of CTL characters
int crlf = 0;
for (int i = 0; i < name.Length; ++i)
{
char c = (char)(0x000000ff & (uint)name[i]);
switch (crlf)
{
case 0:
if (c == '\r')
{
crlf = 1;
}
else if (c == '\n')
{
// Technically this is bad HTTP, but we want to be permissive in what we accept.
// It is important to note that it would be a breaking change to reject this.
crlf = 2;
}
else if (c == 127 || (c < ' ' && c != '\t'))
{
throw new ArgumentException(SR.Format(SR.net_WebHeaderInvalidControlChars, "value"));
}
break;
case 1:
if (c == '\n')
{
crlf = 2;
break;
}
throw new ArgumentException(SR.Format(SR.net_WebHeaderInvalidCRLFChars, "value"));
case 2:
if (c == ' ' || c == '\t')
{
crlf = 0;
break;
}
throw new ArgumentException(SR.Format(SR.net_WebHeaderInvalidCRLFChars, "value"));
}
}
if (crlf != 0)
{
throw new ArgumentException(SR.Format(SR.net_WebHeaderInvalidCRLFChars, "value"));
}
}
else
{
// NAME check
// First, check for absence of separators and spaces
if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(name))
{
throw new ArgumentException(SR.Format(SR.net_WebHeaderInvalidHeaderChars, "name"));
}
// Second, check for non CTL ASCII-7 characters (32-126)
if (ContainsNonAsciiChars(name))
{
throw new ArgumentException(SR.Format(SR.net_WebHeaderInvalidNonAsciiChars, "name"));
}
}
return name;
}
internal static bool ContainsNonAsciiChars(string token)
{
for (int i = 0; i < token.Length; ++i)
{
if ((token[i] < 0x20) || (token[i] > 0x7e))
{
return true;
}
}
return false;
}
// ThrowOnRestrictedHeader - generates an error if the user,
// passed in a reserved string as the header name
internal void ThrowOnRestrictedHeader(string headerName)
{
if (_type == WebHeaderCollectionType.HttpWebRequest)
{
if (HeaderInfoTable.GetKnownHeaderInfo(headerName).IsRequestRestricted)
{
throw new ArgumentException(SR.Format(SR.net_headerrestrict, headerName), "name");
}
}
else if (_type == WebHeaderCollectionType.HttpListenerResponse)
{
if (HeaderInfoTable.GetKnownHeaderInfo(headerName).IsResponseRestricted)
{
throw new ArgumentException(SR.Format(SR.net_headerrestrict, headerName), "name");
}
}
}
// Our public METHOD set, most are inherited from NameValueCollection,
// not all methods from NameValueCollection are listed, even though usable -
//
// This includes:
// - Add(name, value)
// - Add(header)
// - this[name] {set, get}
// - Remove(name), returns bool
// - Remove(name), returns void
// - Set(name, value)
// - ToString()
// Add -
// Routine Description:
// Adds headers with validation to see if they are "proper" headers.
// Will cause header to be concatenated to existing if already found.
// If the header is a special header, listed in RestrictedHeaders object,
// then this call will cause an exception indicating as such.
// Arguments:
// name - header-name to add
// value - header-value to add; if a header already exists, this value will be concatenated
// Return Value:
// None
/// <devdoc>
/// <para>
/// Adds a new header with the indicated name and value.
/// </para>
/// </devdoc>
public override void Add(string name, string value)
{
name = CheckBadChars(name, false);
ThrowOnRestrictedHeader(name);
value = CheckBadChars(value, true);
if (_type == WebHeaderCollectionType.HttpListenerResponse)
{
if (value != null && value.Length > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_headers_toolong, ushort.MaxValue));
}
}
InvalidateCachedArrays();
InnerCollection.Add(name, value);
}
// Set -
// Routine Description:
// Sets headers with validation to see if they are "proper" headers.
// If the header is a special header, listed in RestrictedHeaders object,
// then this call will cause an exception indicating as such.
// Arguments:
// name - header-name to set
// value - header-value to set
// Return Value:
// None
/// <devdoc>
/// <para>
/// Sets the specified header to the specified value.
/// </para>
/// </devdoc>
public override void Set(string name, string value)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
name = CheckBadChars(name, false);
ThrowOnRestrictedHeader(name);
value = CheckBadChars(value, true);
if (_type == WebHeaderCollectionType.HttpListenerResponse)
{
if (value != null && value.Length > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_headers_toolong, ushort.MaxValue));
}
}
InvalidateCachedArrays();
InnerCollection.Set(name, value);
}
// Remove -
// Routine Description:
// Removes give header with validation to see if they are "proper" headers.
// If the header is a speical header, listed in RestrictedHeaders object,
// then this call will cause an exception indicating as such.
// Arguments:
// name - header-name to remove
// Return Value:
// None
/// <devdoc>
/// <para>Removes the specified header.</para>
/// </devdoc>
public override void Remove(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException(nameof(name));
}
ThrowOnRestrictedHeader(name);
name = CheckBadChars(name, false);
if (_innerCollection != null)
{
InvalidateCachedArrays();
_innerCollection.Remove(name);
}
}
// GetValues
// Routine Description:
// This method takes a header name and returns a string array representing
// the individual values for that headers. For example, if the headers
// contained the line Accept: text/plain, text/html then
// GetValues("Accept") would return an array of two strings: "text/plain"
// and "text/html".
// Arguments:
// header - Name of the header.
// Return Value:
// string[] - array of parsed string objects
/// <devdoc>
/// <para>
/// Gets an array of header values stored in a
/// header.
/// </para>
/// </devdoc>
public override string[] GetValues(string header)
{
// First get the information about the header and the values for
// the header.
HeaderInfo info = HeaderInfoTable.GetKnownHeaderInfo(header);
string[] values = InnerCollection.GetValues(header);
// If we have no information about the header or it doesn't allow
// multiple values, just return the values.
if (info == null || values == null || !info.AllowMultiValues)
{
return values;
}
// Here we have a multi value header. We need to go through
// each entry in the multi values array, and if an entry itself
// has multiple values we'll need to combine those in.
//
// We do some optimazation here, where we try not to copy the
// values unless there really is one that have multiple values.
string[] tempValues;
List<string> valueList = null;
for (int i = 0; i < values.Length; i++)
{
// Parse this value header.
tempValues = info.Parser(values[i]);
// If we don't have an array list yet, see if this
// value has multiple values.
if (valueList == null)
{
// See if it has multiple values.
if (tempValues.Length > 1)
{
// It does, so we need to create an array list that
// represents the Values, then trim out this one and
// the ones after it that haven't been parsed yet.
valueList = new List<string>(values);
valueList.RemoveRange(i, values.Length - i);
valueList.AddRange(tempValues);
}
}
else
{
// We already have an List, so just add the values.
valueList.AddRange(tempValues);
}
}
// See if we have an List. If we don't, just return the values.
// Otherwise convert the List to a string array and return that.
if (valueList != null)
{
return valueList.ToArray();
}
return values;
}
// ToString() -
// Routine Description:
// Generates a string representation of the headers, that is ready to be sent except for it being in string format:
// the format looks like:
//
// Header-Name: Header-Value\r\n
// Header-Name2: Header-Value2\r\n
// ...
// Header-NameN: Header-ValueN\r\n
// \r\n
//
// Uses the string builder class to Append the elements together.
// Arguments:
// None.
// Return Value:
// string
/// <internalonly/>
/// <devdoc>
/// <para>
/// Obsolete.
/// </para>
/// </devdoc>
public override string ToString()
{
string result = GetAsString(this);
return result;
}
internal static string GetAsString(NameValueCollection cc)
{
if (cc == null || cc.Count == 0)
{
return "\r\n";
}
StringBuilder sb = new StringBuilder(ApproxAveHeaderLineSize * cc.Count);
string statusLine;
statusLine = cc[string.Empty];
if (statusLine != null)
{
sb.Append(statusLine).Append("\r\n");
}
for (int i = 0; i < cc.Count; i++)
{
string key = cc.GetKey(i) as string;
string val = cc.Get(i) as string;
if (string.IsNullOrEmpty(key))
{
continue;
}
sb.Append(key)
.Append(": ")
.Append(val)
.Append("\r\n");
}
sb.Append("\r\n");
return sb.ToString();
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.WebHeaderCollection'/>
/// class.
/// </para>
/// </devdoc>
public WebHeaderCollection() : base()
{
}
// Override Get() to check the common headers.
public override string Get(string name)
{
// Fall back to normal lookup.
if (_innerCollection == null)
{
return null;
}
return _innerCollection.Get(name);
}
public override int Count
{
get
{
return (_innerCollection == null ? 0 : _innerCollection.Count) + _numCommonHeaders;
}
}
public override KeysCollection Keys
{
get
{
return InnerCollection.Keys;
}
}
public override string Get(int index)
{
return InnerCollection.Get(index);
}
public override string[] GetValues(int index)
{
return InnerCollection.GetValues(index);
}
public override string GetKey(int index)
{
return InnerCollection.GetKey(index);
}
public override string[] AllKeys
{
get
{
return InnerCollection.AllKeys;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public override IEnumerator GetEnumerator()
{
return InnerCollection.Keys.GetEnumerator();
}
public override void Clear()
{
_numCommonHeaders = 0;
InvalidateCachedArrays();
if (_innerCollection != null)
{
_innerCollection.Clear();
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="CombinedGeometry.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
sealed partial class CombinedGeometry : Geometry
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new CombinedGeometry Clone()
{
return (CombinedGeometry)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new CombinedGeometry CloneCurrentValue()
{
return (CombinedGeometry)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void GeometryCombineModePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CombinedGeometry target = ((CombinedGeometry) d);
target.PropertyChanged(GeometryCombineModeProperty);
}
private static void Geometry1PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
CombinedGeometry target = ((CombinedGeometry) d);
Geometry oldV = (Geometry) e.OldValue;
Geometry newV = (Geometry) e.NewValue;
System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher;
if (dispatcher != null)
{
DUCE.IResource targetResource = (DUCE.IResource)target;
using (CompositionEngineLock.Acquire())
{
int channelCount = targetResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = targetResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!targetResource.GetHandle(channel).IsNull);
target.ReleaseResource(oldV,channel);
target.AddRefResource(newV,channel);
}
}
}
target.PropertyChanged(Geometry1Property);
}
private static void Geometry2PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
CombinedGeometry target = ((CombinedGeometry) d);
Geometry oldV = (Geometry) e.OldValue;
Geometry newV = (Geometry) e.NewValue;
System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher;
if (dispatcher != null)
{
DUCE.IResource targetResource = (DUCE.IResource)target;
using (CompositionEngineLock.Acquire())
{
int channelCount = targetResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = targetResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!targetResource.GetHandle(channel).IsNull);
target.ReleaseResource(oldV,channel);
target.AddRefResource(newV,channel);
}
}
}
target.PropertyChanged(Geometry2Property);
}
#region Public Properties
/// <summary>
/// GeometryCombineMode - GeometryCombineMode. Default value is GeometryCombineMode.Union.
/// </summary>
public GeometryCombineMode GeometryCombineMode
{
get
{
return (GeometryCombineMode) GetValue(GeometryCombineModeProperty);
}
set
{
SetValueInternal(GeometryCombineModeProperty, value);
}
}
/// <summary>
/// Geometry1 - Geometry. Default value is Geometry.Empty.
/// </summary>
public Geometry Geometry1
{
get
{
return (Geometry) GetValue(Geometry1Property);
}
set
{
SetValueInternal(Geometry1Property, value);
}
}
/// <summary>
/// Geometry2 - Geometry. Default value is Geometry.Empty.
/// </summary>
public Geometry Geometry2
{
get
{
return (Geometry) GetValue(Geometry2Property);
}
set
{
SetValueInternal(Geometry2Property, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new CombinedGeometry();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data.It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
// If we're told we can skip the channel check, then we must be on channel
Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));
if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
{
base.UpdateResource(channel, skipOnChannelCheck);
// Read values of properties into local variables
Transform vTransform = Transform;
Geometry vGeometry1 = Geometry1;
Geometry vGeometry2 = Geometry2;
// Obtain handles for properties that implement DUCE.IResource
DUCE.ResourceHandle hTransform;
if (vTransform == null ||
Object.ReferenceEquals(vTransform, Transform.Identity)
)
{
hTransform = DUCE.ResourceHandle.Null;
}
else
{
hTransform = ((DUCE.IResource)vTransform).GetHandle(channel);
}
DUCE.ResourceHandle hGeometry1 = vGeometry1 != null ? ((DUCE.IResource)vGeometry1).GetHandle(channel) : DUCE.ResourceHandle.Null;
DUCE.ResourceHandle hGeometry2 = vGeometry2 != null ? ((DUCE.IResource)vGeometry2).GetHandle(channel) : DUCE.ResourceHandle.Null;
// Pack & send command packet
DUCE.MILCMD_COMBINEDGEOMETRY data;
unsafe
{
data.Type = MILCMD.MilCmdCombinedGeometry;
data.Handle = _duceResource.GetHandle(channel);
data.hTransform = hTransform;
data.GeometryCombineMode = GeometryCombineMode;
data.hGeometry1 = hGeometry1;
data.hGeometry2 = hGeometry2;
// Send packed command structure
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_COMBINEDGEOMETRY));
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_COMBINEDGEOMETRY))
{
Transform vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel);
Geometry vGeometry1 = Geometry1;
if (vGeometry1 != null) ((DUCE.IResource)vGeometry1).AddRefOnChannel(channel);
Geometry vGeometry2 = Geometry2;
if (vGeometry2 != null) ((DUCE.IResource)vGeometry2).AddRefOnChannel(channel);
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
Transform vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel);
Geometry vGeometry1 = Geometry1;
if (vGeometry1 != null) ((DUCE.IResource)vGeometry1).ReleaseOnChannel(channel);
Geometry vGeometry2 = Geometry2;
if (vGeometry2 != null) ((DUCE.IResource)vGeometry2).ReleaseOnChannel(channel);
ReleaseOnChannelAnimations(channel);
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
//
// This property finds the correct initial size for the _effectiveValues store on the
// current DependencyObject as a performance optimization
//
// This includes:
// GeometryCombineMode
// Geometry1
// Geometry2
//
internal override int EffectiveValuesInitialSize
{
get
{
return 3;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the CombinedGeometry.GeometryCombineMode property.
/// </summary>
public static readonly DependencyProperty GeometryCombineModeProperty;
/// <summary>
/// The DependencyProperty for the CombinedGeometry.Geometry1 property.
/// </summary>
public static readonly DependencyProperty Geometry1Property;
/// <summary>
/// The DependencyProperty for the CombinedGeometry.Geometry2 property.
/// </summary>
public static readonly DependencyProperty Geometry2Property;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
internal const GeometryCombineMode c_GeometryCombineMode = GeometryCombineMode.Union;
internal static Geometry s_Geometry1 = Geometry.Empty;
internal static Geometry s_Geometry2 = Geometry.Empty;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static CombinedGeometry()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
Debug.Assert(s_Geometry1 == null || s_Geometry1.IsFrozen,
"Detected context bound default value CombinedGeometry.s_Geometry1 (See OS Bug #947272).");
Debug.Assert(s_Geometry2 == null || s_Geometry2.IsFrozen,
"Detected context bound default value CombinedGeometry.s_Geometry2 (See OS Bug #947272).");
// Initializations
Type typeofThis = typeof(CombinedGeometry);
GeometryCombineModeProperty =
RegisterProperty("GeometryCombineMode",
typeof(GeometryCombineMode),
typeofThis,
GeometryCombineMode.Union,
new PropertyChangedCallback(GeometryCombineModePropertyChanged),
new ValidateValueCallback(System.Windows.Media.ValidateEnums.IsGeometryCombineModeValid),
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
Geometry1Property =
RegisterProperty("Geometry1",
typeof(Geometry),
typeofThis,
Geometry.Empty,
new PropertyChangedCallback(Geometry1PropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
Geometry2Property =
RegisterProperty("Geometry2",
typeof(Geometry),
typeofThis,
Geometry.Empty,
new PropertyChangedCallback(Geometry2PropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
// 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;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string>
{
private static readonly CultureAwareComparer s_invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, false);
private static readonly CultureAwareComparer s_invariantCultureIgnoreCase = new CultureAwareComparer(CultureInfo.InvariantCulture, true);
private static readonly OrdinalCaseSensitiveComparer s_ordinal = new OrdinalCaseSensitiveComparer();
private static readonly OrdinalIgnoreCaseComparer s_ordinalIgnoreCase = new OrdinalIgnoreCaseComparer();
public static StringComparer InvariantCulture
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_invariantCulture;
}
}
public static StringComparer InvariantCultureIgnoreCase
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_invariantCultureIgnoreCase;
}
}
public static StringComparer CurrentCulture
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return new CultureAwareComparer(CultureInfo.CurrentCulture, false);
}
}
public static StringComparer CurrentCultureIgnoreCase
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return new CultureAwareComparer(CultureInfo.CurrentCulture, true);
}
}
public static StringComparer Ordinal
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_ordinal;
}
}
public static StringComparer OrdinalIgnoreCase
{
get
{
Contract.Ensures(Contract.Result<StringComparer>() != null);
return s_ordinalIgnoreCase;
}
}
// Convert a StringComparison to a StringComparer
public static StringComparer FromComparison(StringComparison comparisonType)
{
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CurrentCulture;
case StringComparison.CurrentCultureIgnoreCase:
return CurrentCultureIgnoreCase;
case StringComparison.InvariantCulture:
return InvariantCulture;
case StringComparison.InvariantCultureIgnoreCase:
return InvariantCultureIgnoreCase;
case StringComparison.Ordinal:
return Ordinal;
case StringComparison.OrdinalIgnoreCase:
return OrdinalIgnoreCase;
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
public static StringComparer Create(CultureInfo culture, bool ignoreCase)
{
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
}
Contract.Ensures(Contract.Result<StringComparer>() != null);
Contract.EndContractBlock();
return new CultureAwareComparer(culture, ignoreCase);
}
public int Compare(object x, object y)
{
if (x == y) return 0;
if (x == null) return -1;
if (y == null) return 1;
String sa = x as String;
if (sa != null)
{
String sb = y as String;
if (sb != null)
{
return Compare(sa, sb);
}
}
IComparable ia = x as IComparable;
if (ia != null)
{
return ia.CompareTo(y);
}
throw new ArgumentException(SR.Argument_ImplementIComparable);
}
public new bool Equals(Object x, Object y)
{
if (x == y) return true;
if (x == null || y == null) return false;
String sa = x as String;
if (sa != null)
{
String sb = y as String;
if (sb != null)
{
return Equals(sa, sb);
}
}
return x.Equals(y);
}
public int GetHashCode(object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
string s = obj as string;
if (s != null)
{
return GetHashCode(s);
}
return obj.GetHashCode();
}
public abstract int Compare(String x, String y);
public abstract bool Equals(String x, String y);
public abstract int GetHashCode(string obj);
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class CultureAwareComparer : StringComparer
{
private readonly CompareInfo _compareInfo; // Do not rename (binary serialization)
private readonly bool _ignoreCase; // Do not rename (binary serialization)
internal CultureAwareComparer(CultureInfo culture, bool ignoreCase)
{
_compareInfo = culture.CompareInfo;
_ignoreCase = ignoreCase;
}
private CompareOptions Options => _ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None;
public override int Compare(string x, string y)
{
if (object.ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
if (y == null) return 1;
return _compareInfo.Compare(x, y, Options);
}
public override bool Equals(string x, string y)
{
if (object.ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
return _compareInfo.Compare(x, y, Options) == 0;
}
public override int GetHashCode(string obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
return _compareInfo.GetHashCodeOfString(obj, Options);
}
// Equals method for the comparer itself.
public override bool Equals(object obj)
{
CultureAwareComparer comparer = obj as CultureAwareComparer;
return
comparer != null &&
_ignoreCase == comparer._ignoreCase &&
_compareInfo.Equals(comparer._compareInfo);
}
public override int GetHashCode()
{
int hashCode = _compareInfo.GetHashCode();
return _ignoreCase ? ~hashCode : hashCode;
}
}
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class OrdinalComparer : StringComparer
{
private readonly bool _ignoreCase; // Do not rename (binary serialization)
internal OrdinalComparer(bool ignoreCase)
{
_ignoreCase = ignoreCase;
}
public override int Compare(string x, string y)
{
if (ReferenceEquals(x, y))
return 0;
if (x == null)
return -1;
if (y == null)
return 1;
if (_ignoreCase)
{
return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
return string.CompareOrdinal(x, y);
}
public override bool Equals(string x, string y)
{
if (ReferenceEquals(x, y))
return true;
if (x == null || y == null)
return false;
if (_ignoreCase)
{
if (x.Length != y.Length)
{
return false;
}
return (string.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0);
}
return x.Equals(y);
}
public override int GetHashCode(string obj)
{
if (obj == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
}
Contract.EndContractBlock();
if (_ignoreCase)
{
return TextInfo.GetHashCodeOrdinalIgnoreCase(obj);
}
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public override bool Equals(object obj)
{
OrdinalComparer comparer = obj as OrdinalComparer;
if (comparer == null)
{
return false;
}
return (this._ignoreCase == comparer._ignoreCase);
}
public override int GetHashCode()
{
int hashCode = nameof(OrdinalComparer).GetHashCode();
return _ignoreCase ? (~hashCode) : hashCode;
}
}
[Serializable]
internal sealed class OrdinalCaseSensitiveComparer : OrdinalComparer, ISerializable
{
public OrdinalCaseSensitiveComparer() : base(false)
{
}
public override int Compare(string x, string y) => string.CompareOrdinal(x, y);
public override bool Equals(string x, string y) => string.Equals(x, y);
public override int GetHashCode(string obj)
{
if (obj == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
}
return obj.GetHashCode();
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(OrdinalComparer));
info.AddValue("_ignoreCase", false);
}
}
[Serializable]
internal sealed class OrdinalIgnoreCaseComparer : OrdinalComparer, ISerializable
{
public OrdinalIgnoreCaseComparer() : base(true)
{
}
public override int Compare(string x, string y) => string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
public override bool Equals(string x, string y) => string.Equals(x, y, StringComparison.OrdinalIgnoreCase);
public override int GetHashCode(string obj)
{
if (obj == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
}
return TextInfo.GetHashCodeOrdinalIgnoreCase(obj);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(OrdinalComparer));
info.AddValue("_ignoreCase", true);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
namespace System.Text
{
// ASCIIEncoding
//
// Note that ASCIIEncoding is optomized with no best fit and ? for fallback.
// It doesn't come in other flavors.
//
// Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit).
//
// Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd
// use fallbacks, and we cannot guarantee that fallbacks are normalized.
//
[Serializable]
public class ASCIIEncoding : Encoding
{
// Used by Encoding.ASCII for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly ASCIIEncoding s_default = new ASCIIEncoding();
public ASCIIEncoding() : base(Encoding.CodePageASCII)
{
}
internal override void SetDefaultFallbacks()
{
// For ASCIIEncoding we just use default replacement fallback
this.encoderFallback = EncoderFallback.ReplacementFallback;
this.decoderFallback = DecoderFallback.ReplacementFallback;
}
// WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...)
// WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted,
// WARNING: or it'll break VB's way of calling these.
// NOTE: Many methods in this class forward to EncodingForwarder for
// validating arguments/wrapping the unsafe methods in this class
// which do the actual work. That class contains
// shared logic for doing this which is used by
// ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
// UTF7Encoding, and UTF8Encoding.
// The reason the code is separated out into a static class, rather
// than a base class which overrides all of these methods for us
// (which is what EncodingNLS is for internal Encodings) is because
// that's really more of an implementation detail so it's internal.
// At the same time, C# doesn't allow a public class subclassing an
// internal/private one, so we end up having to re-override these
// methods in all of the public Encodings + EncodingNLS.
// Returns the number of bytes required to encode a range of characters in
// a character array.
public override int GetByteCount(char[] chars, int index, int count)
{
return EncodingForwarder.GetByteCount(this, chars, index, count);
}
public override int GetByteCount(String chars)
{
return EncodingForwarder.GetByteCount(this, chars);
}
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
return EncodingForwarder.GetByteCount(this, chars, count);
}
public override int GetBytes(String chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
}
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
public override int GetCharCount(byte[] bytes, int index, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, index, count);
}
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
return EncodingForwarder.GetCharCount(this, bytes, count);
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
}
[CLSCompliant(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
public override String GetString(byte[] bytes, int byteIndex, int byteCount)
{
return EncodingForwarder.GetString(this, bytes, byteIndex, byteCount);
}
// End of overridden methods which use EncodingForwarder
// GetByteCount
// Note: We start by assuming that the output will be the same as count. Having
// an encoder or fallback may change that assumption
internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
char charLeftOver = (char)0;
EncoderReplacementFallback fallback = null;
// Start by assuming default count, then +/- for fallback characters
char* charEnd = chars + charCount;
// For fallback we may need a fallback buffer, we know we aren't default fallback.
EncoderFallbackBuffer fallbackBuffer = null;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
fallback = encoder.Fallback as EncoderReplacementFallback;
// We mustn't have left over fallback data when counting
if (encoder.InternalHasFallbackBuffer)
{
// We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
fallbackBuffer = encoder.FallbackBuffer;
if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty,
this.EncodingName, encoder.Fallback.GetType()));
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
}
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer");
}
else
{
fallback = this.EncoderFallback as EncoderReplacementFallback;
}
// If we have an encoder AND we aren't using default fallback,
// then we may have a complicated count.
if (fallback != null && fallback.MaxCharCount == 1)
{
// Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always
// same as input size.
// Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy.
// We could however have 1 extra byte if the last call had an encoder and a funky fallback and
// if we don't use the funky fallback this time.
// Do we have an extra char left over from last time?
if (charLeftOver > 0)
charCount++;
return (charCount);
}
// Count is more complicated if you have a funky fallback
// For fallback we may need a fallback buffer, we know we're not default fallback
int byteCount = 0;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
// This will fallback a pair if *chars is a low surrogate
fallbackBuffer.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Check for fallback, this'll catch surrogate pairs too.
// no chars >= 0x80 are allowed.
if (ch > 0x7f)
{
if (fallbackBuffer == null)
{
// Initialize the buffer
if (encoder == null)
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, false);
}
// Get Fallback
fallbackBuffer.InternalFallback(ch, ref chars);
continue;
}
// We'll use this one
byteCount++;
}
Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer");
return byteCount;
}
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS encoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
// Assert because we shouldn't be able to have a null encoder.
Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
// Get any left over characters
char charLeftOver = (char)0;
EncoderReplacementFallback fallback = null;
// For fallback we may need a fallback buffer, we know we aren't default fallback.
EncoderFallbackBuffer fallbackBuffer = null;
// prepare our end
char* charEnd = chars + charCount;
byte* byteStart = bytes;
char* charStart = chars;
if (encoder != null)
{
charLeftOver = encoder.charLeftOver;
fallback = encoder.Fallback as EncoderReplacementFallback;
// We mustn't have left over fallback data when counting
if (encoder.InternalHasFallbackBuffer)
{
// We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
fallbackBuffer = encoder.FallbackBuffer;
if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty,
this.EncodingName, encoder.Fallback.GetType()));
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
}
Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
"[ASCIIEncoding.GetBytes]leftover character should be high surrogate");
// Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
encoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer");
}
else
{
fallback = this.EncoderFallback as EncoderReplacementFallback;
}
// See if we do the fast default or slightly slower fallback
if (fallback != null && fallback.MaxCharCount == 1)
{
// Fast version
char cReplacement = fallback.DefaultString[0];
// Check for replacements in range, otherwise fall back to slow version.
if (cReplacement <= (char)0x7f)
{
// We should have exactly as many output bytes as input bytes, unless there's a left
// over character, in which case we may need one more.
// If we had a left over character will have to add a ? (This happens if they had a funky
// fallback last time, but not this time.) (We can't spit any out though
// because with fallback encoder each surrogate is treated as a seperate code point)
if (charLeftOver > 0)
{
// Have to have room
// Throw even if doing no throw version because this is just 1 char,
// so buffer will never be big enough
if (byteCount == 0)
ThrowBytesOverflow(encoder, true);
// This'll make sure we still have more room and also make sure our return value is correct.
*(bytes++) = (byte)cReplacement;
byteCount--; // We used one of the ones we were counting.
}
// This keeps us from overrunning our output buffer
if (byteCount < charCount)
{
// Throw or make buffer smaller?
ThrowBytesOverflow(encoder, byteCount < 1);
// Just use what we can
charEnd = chars + byteCount;
}
// We just do a quick copy
while (chars < charEnd)
{
char ch2 = *(chars++);
if (ch2 >= 0x0080) *(bytes++) = (byte)cReplacement;
else *(bytes++) = unchecked((byte)(ch2));
}
// Clear encoder
if (encoder != null)
{
encoder.charLeftOver = (char)0;
encoder.m_charsUsed = (int)(chars - charStart);
}
return (int)(bytes - byteStart);
}
}
// Slower version, have to do real fallback.
// prepare our end
byte* byteEnd = bytes + byteCount;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
{
// Initialize the buffer
Debug.Assert(encoder != null,
"[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over");
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
// This will fallback a pair if *chars is a low surrogate
fallbackBuffer.InternalFallback(charLeftOver, ref chars);
}
// Now we may have fallback char[] already from the encoder
// Go ahead and do it, including the fallback.
char ch;
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, just get next char
ch = *chars;
chars++;
}
// Check for fallback, this'll catch surrogate pairs too.
// All characters >= 0x80 must fall back.
if (ch > 0x7f)
{
// Initialize the buffer
if (fallbackBuffer == null)
{
if (encoder == null)
fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = encoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
}
// Get Fallback
fallbackBuffer.InternalFallback(ch, ref chars);
// Go ahead & continue (& do the fallback)
continue;
}
// We'll use this one
// Bounds check
if (bytes >= byteEnd)
{
// didn't use this char, we'll throw or use buffer
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
Debug.Assert(chars > charStart || bytes == byteStart,
"[ASCIIEncoding.GetBytes]Expected chars to have advanced already.");
chars--; // don't use last char
}
else
fallbackBuffer.MovePrevious();
// Are we throwing or using buffer?
ThrowBytesOverflow(encoder, bytes == byteStart); // throw?
break; // don't throw, stop
}
// Go ahead and add it
*bytes = unchecked((byte)ch);
bytes++;
}
// Need to do encoder stuff
if (encoder != null)
{
// Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder)
// Clear it in case of MustFlush
encoder.charLeftOver = (char)0;
// Set our chars used count
encoder.m_charsUsed = (int)(chars - charStart);
}
Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
(encoder != null && !encoder.m_throwOnOverflow),
"[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end");
return (int)(bytes - byteStart);
}
// This is internal and called by something else,
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
{
// Just assert, we're called internally so these should be safe, checked already
Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
// ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
DecoderReplacementFallback fallback = null;
if (decoder == null)
fallback = this.DecoderFallback as DecoderReplacementFallback;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer");
}
if (fallback != null && fallback.MaxCharCount == 1)
{
// Just return length, SBCS stay the same length because they don't map to surrogate
// pairs and we don't have a decoder fallback.
return count;
}
// Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII
DecoderFallbackBuffer fallbackBuffer = null;
// Have to do it the hard way.
// Assume charCount will be == count
int charCount = count;
byte[] byteBuffer = new byte[1];
// Do it our fast way
byte* byteEnd = bytes + count;
// Quick loop
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
byte b = *bytes;
bytes++;
// If unknown we have to do fallback count
if (b >= 0x80)
{
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - count, null);
}
// Use fallback buffer
byteBuffer[0] = b;
charCount--; // Have to unreserve the one we already allocated for b
charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
}
}
// Fallback buffer must be empty
Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer");
// Converted sequence is same length as input
return charCount;
}
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS decoder)
{
// Just need to ASSERT, this is called by something else internal that checked parameters already
Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
// Do it fast way if using ? replacement fallback
byte* byteEnd = bytes + byteCount;
byte* byteStart = bytes;
char* charStart = chars;
// Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f
// Only need decoder fallback buffer if not using ? fallback.
// ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
DecoderReplacementFallback fallback = null;
if (decoder == null)
fallback = this.DecoderFallback as DecoderReplacementFallback;
else
{
fallback = decoder.Fallback as DecoderReplacementFallback;
Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
decoder.FallbackBuffer.Remaining == 0,
"[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer");
}
if (fallback != null && fallback.MaxCharCount == 1)
{
// Try it the fast way
char replacementChar = fallback.DefaultString[0];
// Need byteCount chars, otherwise too small buffer
if (charCount < byteCount)
{
// Need at least 1 output byte, throw if must throw
ThrowCharsOverflow(decoder, charCount < 1);
// Not throwing, use what we can
byteEnd = bytes + charCount;
}
// Quick loop, just do '?' replacement because we don't have fallbacks for decodings.
while (bytes < byteEnd)
{
byte b = *(bytes++);
if (b >= 0x80)
// This is an invalid byte in the ASCII encoding.
*(chars++) = replacementChar;
else
*(chars++) = unchecked((char)b);
}
// bytes & chars used are the same
if (decoder != null)
decoder.m_bytesUsed = (int)(bytes - byteStart);
return (int)(chars - charStart);
}
// Slower way's going to need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
byte[] byteBuffer = new byte[1];
char* charEnd = chars + charCount;
// Not quite so fast loop
while (bytes < byteEnd)
{
// Faster if don't use *bytes++;
byte b = *(bytes);
bytes++;
if (b >= 0x80)
{
// This is an invalid byte in the ASCII encoding.
if (fallbackBuffer == null)
{
if (decoder == null)
fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
else
fallbackBuffer = decoder.FallbackBuffer;
fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
}
// Use fallback buffer
byteBuffer[0] = b;
// Note that chars won't get updated unless this succeeds
if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
{
// May or may not throw, but we didn't get this byte
Debug.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)");
bytes--; // unused byte
fallbackBuffer.InternalReset(); // Didn't fall this back
ThrowCharsOverflow(decoder, chars == charStart); // throw?
break; // don't throw, but stop loop
}
}
else
{
// Make sure we have buffer space
if (chars >= charEnd)
{
Debug.Assert(bytes > byteStart || chars == charStart,
"[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)");
bytes--; // unused byte
ThrowCharsOverflow(decoder, chars == charStart); // throw?
break; // don't throw, but stop loop
}
*(chars) = unchecked((char)b);
chars++;
}
}
// Might have had decoder fallback stuff.
if (decoder != null)
decoder.m_bytesUsed = (int)(bytes - byteStart);
// Expect Empty fallback buffer for GetChars
Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
"[ASCIIEncoding.GetChars]Expected Empty fallback buffer");
return (int)(chars - charStart);
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
long byteCount = (long)charCount + 1;
if (EncoderFallback.MaxCharCount > 1)
byteCount *= EncoderFallback.MaxCharCount;
// 1 to 1 for most characters. Only surrogates with fallbacks have less.
if (byteCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(byteCount),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Just return length, SBCS stay the same length because they don't map to surrogate
long charCount = (long)byteCount;
// 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
if (DecoderFallback.MaxCharCount > 1)
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
// True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc)
public override bool IsSingleByte
{
get
{
return true;
}
}
public override Decoder GetDecoder()
{
return new DecoderNLS(this);
}
public override Encoder GetEncoder()
{
return new EncoderNLS(this);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using DiscUtils.Streams;
namespace DiscUtils.Vmdk
{
internal class DescriptorFile
{
private const string HeaderVersion = "version";
private const string HeaderContentId = "CID";
private const string HeaderParentContentId = "parentCID";
private const string HeaderCreateType = "createType";
private const string HeaderParentFileNameHint = "parentFileNameHint";
private const string DiskDbAdapterType = "ddb.adapterType";
private const string DiskDbSectors = "ddb.geometry.sectors";
private const string DiskDbHeads = "ddb.geometry.heads";
private const string DiskDbCylinders = "ddb.geometry.cylinders";
private const string DiskDbBiosSectors = "ddb.geometry.biosSectors";
private const string DiskDbBiosHeads = "ddb.geometry.biosHeads";
private const string DiskDbBiosCylinders = "ddb.geometry.biosCylinders";
private const string DiskDbHardwareVersion = "ddb.virtualHWVersion";
private const string DiskDbUuid = "ddb.uuid";
private const long MaxSize = 20 * Sizes.OneKiB;
private readonly List<DescriptorFileEntry> _diskDataBase;
private readonly List<DescriptorFileEntry> _header;
public DescriptorFile()
{
_header = new List<DescriptorFileEntry>();
Extents = new List<ExtentDescriptor>();
_diskDataBase = new List<DescriptorFileEntry>();
_header.Add(new DescriptorFileEntry(HeaderVersion, "1", DescriptorFileEntryType.Plain));
_header.Add(new DescriptorFileEntry(HeaderContentId, "ffffffff", DescriptorFileEntryType.Plain));
_header.Add(new DescriptorFileEntry(HeaderParentContentId, "ffffffff", DescriptorFileEntryType.Plain));
_header.Add(new DescriptorFileEntry(HeaderCreateType, string.Empty, DescriptorFileEntryType.Quoted));
}
public DescriptorFile(Stream source)
{
_header = new List<DescriptorFileEntry>();
Extents = new List<ExtentDescriptor>();
_diskDataBase = new List<DescriptorFileEntry>();
Load(source);
}
public DiskAdapterType AdapterType
{
get { return ParseAdapterType(GetDiskDatabase(DiskDbAdapterType)); }
set { SetDiskDatabase(DiskDbAdapterType, FormatAdapterType(value)); }
}
public Geometry BiosGeometry
{
get
{
string cylStr = GetDiskDatabase(DiskDbBiosCylinders);
string headsStr = GetDiskDatabase(DiskDbBiosHeads);
string sectorsStr = GetDiskDatabase(DiskDbBiosSectors);
if (!string.IsNullOrEmpty(cylStr) && !string.IsNullOrEmpty(headsStr) &&
!string.IsNullOrEmpty(sectorsStr))
{
return new Geometry(
int.Parse(cylStr, CultureInfo.InvariantCulture),
int.Parse(headsStr, CultureInfo.InvariantCulture),
int.Parse(sectorsStr, CultureInfo.InvariantCulture));
}
return null;
}
set
{
SetDiskDatabase(DiskDbBiosCylinders, value.Cylinders.ToString(CultureInfo.InvariantCulture));
SetDiskDatabase(DiskDbBiosHeads, value.HeadsPerCylinder.ToString(CultureInfo.InvariantCulture));
SetDiskDatabase(DiskDbBiosSectors, value.SectorsPerTrack.ToString(CultureInfo.InvariantCulture));
}
}
public uint ContentId
{
get { return uint.Parse(GetHeader(HeaderContentId), NumberStyles.HexNumber, CultureInfo.InvariantCulture); }
set
{
SetHeader(HeaderContentId, value.ToString("x8", CultureInfo.InvariantCulture),
DescriptorFileEntryType.Plain);
}
}
public DiskCreateType CreateType
{
get { return ParseCreateType(GetHeader(HeaderCreateType)); }
set { SetHeader(HeaderCreateType, FormatCreateType(value), DescriptorFileEntryType.Plain); }
}
public Geometry DiskGeometry
{
get
{
string cylStr = GetDiskDatabase(DiskDbCylinders);
string headsStr = GetDiskDatabase(DiskDbHeads);
string sectorsStr = GetDiskDatabase(DiskDbSectors);
if (!string.IsNullOrEmpty(cylStr) && !string.IsNullOrEmpty(headsStr) &&
!string.IsNullOrEmpty(sectorsStr))
{
return new Geometry(
int.Parse(cylStr, CultureInfo.InvariantCulture),
int.Parse(headsStr, CultureInfo.InvariantCulture),
int.Parse(sectorsStr, CultureInfo.InvariantCulture));
}
return null;
}
set
{
SetDiskDatabase(DiskDbCylinders, value.Cylinders.ToString(CultureInfo.InvariantCulture));
SetDiskDatabase(DiskDbHeads, value.HeadsPerCylinder.ToString(CultureInfo.InvariantCulture));
SetDiskDatabase(DiskDbSectors, value.SectorsPerTrack.ToString(CultureInfo.InvariantCulture));
}
}
public List<ExtentDescriptor> Extents { get; }
public string HardwareVersion
{
get { return GetDiskDatabase(DiskDbHardwareVersion); }
set { SetDiskDatabase(DiskDbHardwareVersion, value); }
}
public uint ParentContentId
{
get { return uint.Parse(GetHeader(HeaderParentContentId), NumberStyles.HexNumber, CultureInfo.InvariantCulture); }
set
{
SetHeader(HeaderParentContentId, value.ToString("x8", CultureInfo.InvariantCulture),
DescriptorFileEntryType.Plain);
}
}
public string ParentFileNameHint
{
get { return GetHeader(HeaderParentFileNameHint); }
set { SetHeader(HeaderParentFileNameHint, value, DescriptorFileEntryType.Quoted); }
}
public Guid UniqueId
{
get { return ParseUuid(GetDiskDatabase(DiskDbUuid)); }
set { SetDiskDatabase(DiskDbUuid, FormatUuid(value)); }
}
internal void Write(Stream stream)
{
StringBuilder content = new StringBuilder();
content.Append("# Disk DescriptorFile\n");
for (int i = 0; i < _header.Count; ++i)
{
content.Append(_header[i].ToString(false) + "\n");
}
content.Append("\n");
content.Append("# Extent description\n");
for (int i = 0; i < Extents.Count; ++i)
{
content.Append(Extents[i] + "\n");
}
content.Append("\n");
content.Append("# The Disk Data Base\n");
content.Append("#DDB\n");
for (int i = 0; i < _diskDataBase.Count; ++i)
{
content.Append(_diskDataBase[i].ToString(true) + "\n");
}
byte[] contentBytes = Encoding.ASCII.GetBytes(content.ToString());
stream.Write(contentBytes, 0, contentBytes.Length);
}
private static DiskAdapterType ParseAdapterType(string value)
{
switch (value)
{
case "ide":
return DiskAdapterType.Ide;
case "buslogic":
return DiskAdapterType.BusLogicScsi;
case "lsilogic":
return DiskAdapterType.LsiLogicScsi;
case "legacyESX":
return DiskAdapterType.LegacyEsx;
default:
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture, "Unknown type: {0}", value), nameof(value));
}
}
private static string FormatAdapterType(DiskAdapterType value)
{
switch (value)
{
case DiskAdapterType.Ide:
return "ide";
case DiskAdapterType.BusLogicScsi:
return "buslogic";
case DiskAdapterType.LsiLogicScsi:
return "lsilogic";
case DiskAdapterType.LegacyEsx:
return "legacyESX";
default:
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture, "Unknown type: {0}", value), nameof(value));
}
}
private static DiskCreateType ParseCreateType(string value)
{
switch (value)
{
case "monolithicSparse":
return DiskCreateType.MonolithicSparse;
case "vmfsSparse":
return DiskCreateType.VmfsSparse;
case "monolithicFlat":
return DiskCreateType.MonolithicFlat;
case "vmfs":
return DiskCreateType.Vmfs;
case "twoGbMaxExtentSparse":
return DiskCreateType.TwoGbMaxExtentSparse;
case "twoGbMaxExtentFlat":
return DiskCreateType.TwoGbMaxExtentFlat;
case "fullDevice":
return DiskCreateType.FullDevice;
case "vmfsRaw":
return DiskCreateType.VmfsRaw;
case "partitionedDevice":
return DiskCreateType.PartitionedDevice;
case "vmfsRawDeviceMap":
return DiskCreateType.VmfsRawDeviceMap;
case "vmfsPassthroughRawDeviceMap":
return DiskCreateType.VmfsPassthroughRawDeviceMap;
case "streamOptimized":
return DiskCreateType.StreamOptimized;
default:
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture, "Unknown type: {0}", value), nameof(value));
}
}
private static string FormatCreateType(DiskCreateType value)
{
switch (value)
{
case DiskCreateType.MonolithicSparse:
return "monolithicSparse";
case DiskCreateType.VmfsSparse:
return "vmfsSparse";
case DiskCreateType.MonolithicFlat:
return "monolithicFlat";
case DiskCreateType.Vmfs:
return "vmfs";
case DiskCreateType.TwoGbMaxExtentSparse:
return "twoGbMaxExtentSparse";
case DiskCreateType.TwoGbMaxExtentFlat:
return "twoGbMaxExtentFlat";
case DiskCreateType.FullDevice:
return "fullDevice";
case DiskCreateType.VmfsRaw:
return "vmfsRaw";
case DiskCreateType.PartitionedDevice:
return "partitionedDevice";
case DiskCreateType.VmfsRawDeviceMap:
return "vmfsRawDeviceMap";
case DiskCreateType.VmfsPassthroughRawDeviceMap:
return "vmfsPassthroughRawDeviceMap";
case DiskCreateType.StreamOptimized:
return "streamOptimized";
default:
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture, "Unknown type: {0}", value), nameof(value));
}
}
private static Guid ParseUuid(string value)
{
byte[] data = new byte[16];
string[] bytesAsHex = value.Split(' ', '-');
if (bytesAsHex.Length != 16)
{
throw new ArgumentException("Invalid UUID", nameof(value));
}
for (int i = 0; i < 16; ++i)
{
data[i] = byte.Parse(bytesAsHex[i], NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return new Guid(data);
}
private static string FormatUuid(Guid value)
{
byte[] data = value.ToByteArray();
return string.Format(
CultureInfo.InvariantCulture,
"{0:x2} {1:x2} {2:x2} {3:x2} {4:x2} {5:x2} {6:x2} {7:x2}-{8:x2} {9:x2} {10:x2} {11:x2} {12:x2} {13:x2} {14:x2} {15:x2}",
data[0],
data[1],
data[2],
data[3],
data[4],
data[5],
data[6],
data[7],
data[8],
data[9],
data[10],
data[11],
data[12],
data[13],
data[14],
data[15]);
}
private string GetHeader(string key)
{
foreach (DescriptorFileEntry entry in _header)
{
if (entry.Key == key)
{
return entry.Value;
}
}
return null;
}
private void SetHeader(string key, string newValue, DescriptorFileEntryType type)
{
foreach (DescriptorFileEntry entry in _header)
{
if (entry.Key == key)
{
entry.Value = newValue;
return;
}
}
_header.Add(new DescriptorFileEntry(key, newValue, type));
}
private string GetDiskDatabase(string key)
{
foreach (DescriptorFileEntry entry in _diskDataBase)
{
if (entry.Key == key)
{
return entry.Value;
}
}
return null;
}
private void SetDiskDatabase(string key, string value)
{
foreach (DescriptorFileEntry entry in _diskDataBase)
{
if (entry.Key == key)
{
entry.Value = value;
return;
}
}
_diskDataBase.Add(new DescriptorFileEntry(key, value, DescriptorFileEntryType.Quoted));
}
private void Load(Stream source)
{
if (source.Length - source.Position > MaxSize)
{
throw new IOException(string.Format(CultureInfo.InvariantCulture,
"Invalid VMDK descriptor file, more than {0} bytes in length", MaxSize));
}
StreamReader reader = new StreamReader(source);
string line = reader.ReadLine();
while (line != null)
{
line = line.Trim('\0');
int commentPos = line.IndexOf('#');
if (commentPos >= 0)
{
line = line.Substring(0, commentPos);
}
if (line.Length > 0)
{
if (line.StartsWith("RW", StringComparison.Ordinal)
|| line.StartsWith("RDONLY", StringComparison.Ordinal)
|| line.StartsWith("NOACCESS", StringComparison.Ordinal))
{
Extents.Add(ExtentDescriptor.Parse(line));
}
else
{
DescriptorFileEntry entry = DescriptorFileEntry.Parse(line);
if (entry.Key.StartsWith("ddb.", StringComparison.Ordinal))
{
_diskDataBase.Add(entry);
}
else
{
_header.Add(entry);
}
}
}
line = reader.ReadLine();
}
}
}
}
| |
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.TextFormatting;
using MS.Internal.FontCache;
using MS.Internal.FontFace;
using MS.Internal.Shaping;
using MS.Win32;
namespace MS.Internal.TextFormatting
{
/// <summary>
/// DigitState contains the high-level logic used to convert the number culture implied by
/// text run properties to the low-level digit culture used for shaping.
/// </summary>
internal class DigitState
{
/// <summary>
/// DigitCulture gets a CultureInfo with the actual symbols and digits used for digit
/// substitution. If no substitution is required, this property is null.
/// </summary>
internal CultureInfo DigitCulture
{
get { return _digitCulture; }
}
/// <summary>
/// RequiresNumberSubstitution is true if digit substitution is required (DigitCulture != null)
/// and false if digit substitution is not required (DigitCulture == null).
/// </summary>
internal bool RequiresNumberSubstitution
{
get { return _digitCulture != null; }
}
/// <summary>
/// Contextual is true if contextual digit substitution is required. If so, DigitCulture specifies
/// the digits to use in Arabic contexts. In non-Arabic contexts, null should be used as the
/// digit culture.
/// </summary>
internal bool Contextual
{
get { return _contextual; }
}
/// <summary>
/// Resolves number substitution method to one of following values:
/// European
/// Traditional
/// NativeNational
/// </summary>
internal static NumberSubstitutionMethod GetResolvedSubstitutionMethod(TextRunProperties properties, CultureInfo digitCulture, out bool ignoreUserOverride)
{
ignoreUserOverride = true;
NumberSubstitutionMethod resolvedMethod = NumberSubstitutionMethod.European;
if (digitCulture != null)
{
NumberSubstitutionMethod method;
CultureInfo numberCulture = GetNumberCulture(properties, out method, out ignoreUserOverride);
if (numberCulture != null)
{
// First, disambiguate AsCulture method, which depends on digit substitution contained in CultureInfo.NumberFormat
if (method == NumberSubstitutionMethod.AsCulture)
{
switch (numberCulture.NumberFormat.DigitSubstitution)
{
case DigitShapes.Context:
method = NumberSubstitutionMethod.Context;
break;
case DigitShapes.NativeNational:
method = NumberSubstitutionMethod.NativeNational;
break;
default:
method = NumberSubstitutionMethod.European;
break;
}
}
// Next, disambiguate Context method, which maps to Traditional if digitCulture != null
resolvedMethod = method;
if (resolvedMethod == NumberSubstitutionMethod.Context)
{
resolvedMethod = NumberSubstitutionMethod.Traditional;
}
}
}
return resolvedMethod;
}
/// <summary>
/// SetTextRunProperties initializes the DigitCulture and Contextual properties to reflect the
/// specified text run properties.
/// </summary>
internal void SetTextRunProperties(TextRunProperties properties)
{
// Determine the number culture and substitution method.
bool ignoreUserOverride;
NumberSubstitutionMethod method;
CultureInfo numberCulture = GetNumberCulture(properties, out method, out ignoreUserOverride);
// The digit culture is a function of the number culture and the substitution method. Only
// determine the digit culture if either of these two parameters change.
if (!object.ReferenceEquals(numberCulture, _lastNumberCulture) || method != _lastMethod)
{
_lastNumberCulture = numberCulture;
_lastMethod = method;
_digitCulture = GetDigitCulture(numberCulture, method, out _contextual);
}
}
private static CultureInfo GetNumberCulture(TextRunProperties properties, out NumberSubstitutionMethod method, out bool ignoreUserOverride)
{
ignoreUserOverride = true;
NumberSubstitution sub = properties.NumberSubstitution;
if (sub == null)
{
method = NumberSubstitutionMethod.AsCulture;
return CultureMapper.GetSpecificCulture(properties.CultureInfo);
}
method = sub.Substitution;
switch (sub.CultureSource)
{
case NumberCultureSource.Text:
return CultureMapper.GetSpecificCulture(properties.CultureInfo);
case NumberCultureSource.User:
ignoreUserOverride = false;
return CultureInfo.CurrentCulture;
case NumberCultureSource.Override:
return sub.CultureOverride;
}
return null;
}
private CultureInfo GetDigitCulture(CultureInfo numberCulture, NumberSubstitutionMethod method, out bool contextual)
{
contextual = false;
if (numberCulture == null)
{
return null;
}
if (method == NumberSubstitutionMethod.AsCulture)
{
switch (numberCulture.NumberFormat.DigitSubstitution)
{
case DigitShapes.Context:
method = NumberSubstitutionMethod.Context;
break;
case DigitShapes.NativeNational:
method = NumberSubstitutionMethod.NativeNational;
break;
default:
return null;
}
}
CultureInfo digitCulture;
switch (method)
{
case NumberSubstitutionMethod.Context:
if (IsArabic(numberCulture) || IsFarsi(numberCulture))
{
contextual = true;
digitCulture = GetTraditionalCulture(numberCulture);
}
else
{
digitCulture = null;
}
break;
case NumberSubstitutionMethod.NativeNational:
if (!HasLatinDigits(numberCulture))
{
digitCulture = numberCulture;
}
else
{
digitCulture = null;
}
break;
case NumberSubstitutionMethod.Traditional:
digitCulture = GetTraditionalCulture(numberCulture);
break;
default:
digitCulture = null;
break;
}
return digitCulture;
}
private static bool HasLatinDigits(CultureInfo culture)
{
string[] digits = culture.NumberFormat.NativeDigits;
for (int i = 0; i < 10; ++i)
{
string d = digits[i];
if (d.Length != 1 || d[0] != (char)('0' + i))
return false;
}
return true;
}
private static bool IsArabic(CultureInfo culture)
{
return (culture.LCID & 0xFF) == 0x01;
}
private static bool IsFarsi(CultureInfo culture)
{
return (culture.LCID & 0xFF) == 0x29;
}
#region Traditional Cultures
/// <summary>
/// Returns the digit culture to use for traditional number substitution given the
/// specified number culture.
/// </summary>
private CultureInfo GetTraditionalCulture(CultureInfo numberCulture)
{
int lcid = numberCulture.LCID;
// Do we already have a traditional culture for this LCID?
if (_lastTraditionalCulture != null && _lastTraditionalCulture.LCID == lcid)
{
return _lastTraditionalCulture;
}
// Branch using the primary language ID (the low-order word of the LCID). If a language
// maps to more than one script, we then branch on the entire LCID. The mapping of cultures
// (LCIDs) to scripts is based on the following spreadsheet:
// http://winworld/teams/giftweb/lme/typography/Font%20Technology%20Infrastructure/OpenType%20and%20OTLS/lcid%20to%20OT%20ScriptLang.xls.
//
// If the LCID maps to a script for which we have traditional digits, we return the
// the corresponding property. For example, the Marathi and Sanscrit languages map to
// the Devangari script so we return the TraditionalDevangari property. The script names
// are the English names in ISO-15924 (http://www.unicode.org/iso15924/iso15924-codes.html).
// The "Arabic" script is a special case as it has two sets of digits, and therefore two
// properties: TraditionalArabic and TraditionalEasternArabic.
//
// See also the Uniscribe number substitution spec:
// http://winworld/teams/giftweb/lme/typography/Font%20Technology%20Infrastructure/Uniscribe%20and%20Shaping%20Engines/Digit%20Substitution.doc.
//
CultureInfo digitCulture = null;
switch (lcid & 0xFF)
{
case 0x01: // Arabic
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0660, // Unicode value of Arabic digit zero
true); // Arabic percent, decimal, and group symbols
break;
case 0x1e: // Thai
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0e50, // Unicode value of Thai digit zero
false); // European percent, decimal, and group symbols
break;
case 0x20: // Urdu
case 0x29: // Persian
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x06F0, // Unicode value of Eastern Arabic digit zero
true); // Arabic percent, decimal, and group symbols
break;
case 0x39: // Hindi
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0966, // Unicode value of Devanagari digit zero
false); // European percent, decimal, and group symbols
break;
case 0x45: // Bengali
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x09e6, // Unicode value of Bengali digit zero
false); // European percent, decimal, and group symbols
break;
case 0x46: // Punjabi
// This language maps to more than one script; branch on the lcid.
if (lcid == 0x0446) // Punjabi (India)
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0a66, // Unicode value of Gurmukhi digit zero
false); // European percent, decimal, and group symbols
else if (lcid == 0x0846) // Punjabi (Pakistan)
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x06F0, // Unicode value of Eastern Arabic digit zero
true); // Arabic percent, decimal, and group symbols
break;
case 0x47: // Gujarati
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0ae6, // Unicode value of Gujarati digit zero
false); // European percent, decimal, and group symbols
break;
case 0x48: // Oriya
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0b66, // Unicode value of Oriya digit zero
false); // European percent, decimal, and group symbols
break;
case 0x49: // Tamil
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0be6, // Unicode value of Tamil digit zero
false); // European percent, decimal, and group symbols
break;
case 0x4a: // Teluga
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0c66, // Unicode value of Teluga digit zero
false); // European percent, decimal, and group symbols
break;
case 0x4b: // Kannada
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0ce6, // Unicode value of Kannada digit zero
false); // European percent, decimal, and group symbols
break;
case 0x4c: // Malayalam
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0d66, // Unicode value of Malayalam digit zero
false); // European percent, decimal, and group symbols
break;
case 0x4d: // Assamese
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x09e6, // Unicode value of Bengali digit zero
false); // European percent, decimal, and group symbols
break;
case 0x4e: // Marathi
case 0x4f: // Sanskrit
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0966, // Unicode value of Devanagari digit zero
false); // European percent, decimal, and group symbols
break;
case 0x50: // Mongolian
// This language maps to more than one script; branch on the lcid.
if (lcid == 0x0850) // Mongolian (PRC)
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x1810, // Unicode value of Mongolian digit zero
false); // European percent, decimal, and group symbols
break;
case 0x51: // Tibetan
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0f20, // Unicode value of Tibetan digit zero
false); // European percent, decimal, and group symbols
break;
case 0x53: // Khmer
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x17e0, // Unicode value of Khmer digit zero
false); // European percent, decimal, and group symbols
break;
case 0x54: // Lao
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0ed0, // Unicode value of Lao digit zero
false); // European percent, decimal, and group symbols
break;
case 0x55: // Burmese
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x1040, // Unicode value of Myanmar (Burmese) digit zero
false); // European percent, decimal, and group symbols
break;
case 0x57: // Konkani
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0966, // Unicode value of Devanagari digit zero
false); // European percent, decimal, and group symbols
break;
case 0x58: // Manipuri - India
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x09e6, // Unicode value of Bengali digit zero
false); // European percent, decimal, and group symbols
break;
case 0x59: // Sindhi
// This language maps to more than one script; branch on the lcid.
if (lcid == 0x0459) // Sindhi (India)
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0966, // Unicode value of Devanagari digit zero
false); // European percent, decimal, and group symbols
else if (lcid == 0x0859) // Sindhi (Pakistan)
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x06F0, // Unicode value of Eastern Arabic digit zero
true); // Arabic percent, decimal, and group symbols
break;
case 0x5f: // Tamazight
// This language maps to more than one script; branch on the lcid.
if (lcid == 0x045f) // Tamazight (Berber/Arabic)
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0660, // Unicode value of Arabic digit zero
true); // Arabic percent, decimal, and group symbols
break;
case 0x60: // Kashmiri
// This language maps to more than one script; branch on the lcid.
if (lcid == 0x0460) // Kashmiri (Arabic); ks-PK
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x06F0, // Unicode value of Eastern Arabic digit zero
true); // Arabic percent, decimal, and group symbols
else if (lcid == 0x0860) // Kashmiri; ks-IN
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0966, // Unicode value of Devanagari digit zero
false); // European percent, decimal, and group symbols
break;
case 0x61: // Nepali
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x0966, // Unicode value of Devanagari digit zero
false); // European percent, decimal, and group symbols
break;
case 0x63: // Pashto
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x06F0, // Unicode value of Eastern Arabic digit zero
true); // Arabic percent, decimal, and group symbols
break;
case 0x8c: // Dari
digitCulture = CreateTraditionalCulture(
numberCulture, // culture to clone
0x06F0, // Unicode value of Eastern Arabic digit zero
true); // Arabic percent, decimal, and group symbols
break;
}
if (digitCulture == null)
{
// No hard-coded mapping for this LCID. Use the given culture if it has non-Latin digits,
// otherwise return null. Don't cache the number culture because we didn't create it and
// its digits may depend on other things than the LCID (e.g., it may be a custom culture).
if (!HasLatinDigits(numberCulture))
{
digitCulture = numberCulture;
}
}
else
{
// We have a mapping for this LCID. Cache the digit culture in case we're called with
// the same LCID again.
_lastTraditionalCulture = digitCulture;
}
return digitCulture;
}
// Create a modifiable culture with the same properties as the specified number culture,
// but with digits '0' through '9' starting at the specified unicode value.
private CultureInfo CreateTraditionalCulture(CultureInfo numberCulture, int firstDigit, bool arabic)
{
// Create the digit culture by cloning the given number culture. According to MSDN,
// "CultureInfo.Clone is a shallow copy with exceptions. The objects returned by
// the NumberFormat and the DateTimeFormat properties are also cloned, so that the
// CultureInfo clone can modify the properties of NumberFormat and DateTimeFormat
// without affecting the original CultureInfo."
CultureInfo digitCulture = (CultureInfo)numberCulture.Clone();
// Create the array of digits.
string[] digits = new string[10];
if (firstDigit < 0x10000)
{
for (int i = 0; i < 10; ++i)
{
digits[i] = new string((char)(firstDigit + i), 1);
}
}
else
{
for (int i = 0; i < 10; ++i)
{
int n = firstDigit + i - 0x10000;
digits[i] = new string(
new char[] {
(char)((n >> 10) | 0xD800), // high surrogate
(char)((n & 0x03FF) | 0xDC00) // low surrogate
}
);
}
}
// Set the digits.
digitCulture.NumberFormat.NativeDigits = digits;
if (arabic)
{
digitCulture.NumberFormat.PercentSymbol = "\u066a";
digitCulture.NumberFormat.NumberDecimalSeparator = "\u066b";
digitCulture.NumberFormat.NumberGroupSeparator = "\u066c";
}
else
{
digitCulture.NumberFormat.PercentSymbol = "%";
digitCulture.NumberFormat.NumberDecimalSeparator = ".";
digitCulture.NumberFormat.NumberGroupSeparator = ",";
}
return digitCulture;
}
private CultureInfo _lastTraditionalCulture;
#endregion
private NumberSubstitutionMethod _lastMethod;
private CultureInfo _lastNumberCulture;
private CultureInfo _digitCulture;
private bool _contextual;
}
/// <summary>
/// DigitMap maps unicode code points (from the backing store) to unicode code
/// points (to be rendered) based on a specified digit culture.
/// </summary>
internal struct DigitMap
{
private NumberFormatInfo _format;
private string[] _digits;
internal DigitMap(CultureInfo digitCulture)
{
if (digitCulture != null)
{
_format = digitCulture.NumberFormat;
_digits = _format.NativeDigits;
}
else
{
_format = null;
_digits = null;
}
}
internal int this[int ch]
{
get
{
if (_format != null && IsDigitOrSymbol(ch))
{
uint n = (uint)ch - '0';
if (n < 10)
{
ch = StringToScalar(_digits[n], ch);
}
else if (ch == '%')
{
ch = StringToScalar(_format.PercentSymbol, ch);
}
else if (ch == ',')
{
ch = StringToScalar(_format.NumberGroupSeparator, ch);
}
else
{
ch = StringToScalar(_format.NumberDecimalSeparator, ch);
}
}
return ch;
}
}
/// <summary>
/// In some cases, our first choice for a substituted code point is not present
/// in many older fonts. To avoid displaying missing glyphs in such cases, this
/// function returns the alternate character to fall back to if the specified
/// substituted character does not exist in the font. The return value is zero
/// if there is no fallback character.
/// </summary>
internal static int GetFallbackCharacter(int ch)
{
switch (ch)
{
case 0x066B: return (int)','; // Arabic decimal point -> Western comma
case 0x066C: return 0x060C; // Arabic thousands separator -> Arabic comma
case 0x0BE6: return (int)'0'; // Tamil zero -> Western zero
}
return 0; // no fallback character
}
private static int StringToScalar(string s, int defaultValue)
{
if (s.Length == 1)
{
return (int)s[0];
}
else if (s.Length == 2 &&
IsHighSurrogate((int)s[0]) &&
IsLowSurrogate((int)s[1]))
{
return MakeUnicodeScalar((int)s[0], (int)s[1]);
}
else
{
return defaultValue;
}
}
internal static bool IsHighSurrogate(int ch)
{
return ch >= 0xd800 && ch < 0xdc00;
}
internal static bool IsLowSurrogate(int ch)
{
return ch >= 0xdc00 && ch < 0xe000;
}
internal static bool IsSurrogate(int ch)
{
return IsHighSurrogate(ch) || IsLowSurrogate(ch);
}
internal static int MakeUnicodeScalar(int hi, int lo)
{
return ((hi & 0x03ff) << 10 | (lo & 0x03ff)) + 0x10000;
}
private static bool IsDigitOrSymbol(int ch)
{
// The code points we're interested in are in the range 0x25 - 0x39.
const int first = 0x25; // percent
const int last = 0x39; // '9'
// Make sure we're in range. This is necessary because (mask >> N)
// where N is some large number does not yield zero, but rather is
// equivalent to (mask >> (N % 32)).
if ((uint)(ch - first) <= (uint)(last - first))
{
// Let mask be an array of bits indexed by code point, with
// first as the base for indexing.
const uint mask =
(1U << ('%' - first)) | // U+0025
(1U << (',' - first)) | // U+002C
(1U << ('.' - first)) | // U+002E
(1U << ('0' - first)) | // U+0030
(1U << ('1' - first)) | // U+0031
(1U << ('2' - first)) | // U+0032
(1U << ('3' - first)) | // U+0033
(1U << ('4' - first)) | // U+0034
(1U << ('5' - first)) | // U+0035
(1U << ('6' - first)) | // U+0036
(1U << ('7' - first)) | // U+0037
(1U << ('8' - first)) | // U+0038
(1U << ('9' - first)); // U+0039
// Return the bit that correponds to the given code point.
return ((mask >> (ch - first)) & 1) != 0;
}
else
{
// The code point is out of our given range.
return false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Orleans.GrainDirectory;
using Orleans.Providers;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
using Orleans.Storage;
namespace Orleans.Runtime
{
internal class Catalog : SystemTarget, ICatalog, IPlacementContext, ISiloStatusListener
{
/// <summary>
/// Exception to indicate that the activation would have been a duplicate so messages pending for it should be redirected.
/// </summary>
[Serializable]
internal class DuplicateActivationException : Exception
{
public ActivationAddress ActivationToUse { get; private set; }
public SiloAddress PrimaryDirectoryForGrain { get; private set; } // for diagnostics only!
public DuplicateActivationException() : base("DuplicateActivationException") { }
public DuplicateActivationException(string msg) : base(msg) { }
public DuplicateActivationException(string message, Exception innerException) : base(message, innerException) { }
public DuplicateActivationException(ActivationAddress activationToUse)
: base("DuplicateActivationException")
{
ActivationToUse = activationToUse;
}
public DuplicateActivationException(ActivationAddress activationToUse, SiloAddress primaryDirectoryForGrain)
: base("DuplicateActivationException")
{
ActivationToUse = activationToUse;
PrimaryDirectoryForGrain = primaryDirectoryForGrain;
}
#if !NETSTANDARD
// Implementation of exception serialization with custom properties according to:
// http://stackoverflow.com/questions/94488/what-is-the-correct-way-to-make-a-custom-net-exception-serializable
protected DuplicateActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
ActivationToUse = (ActivationAddress) info.GetValue("ActivationToUse", typeof (ActivationAddress));
PrimaryDirectoryForGrain = (SiloAddress) info.GetValue("PrimaryDirectoryForGrain", typeof (SiloAddress));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("ActivationToUse", ActivationToUse, typeof (ActivationAddress));
info.AddValue("PrimaryDirectoryForGrain", PrimaryDirectoryForGrain, typeof (SiloAddress));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
#endif
}
[Serializable]
internal class NonExistentActivationException : Exception
{
public ActivationAddress NonExistentActivation { get; private set; }
public bool IsStatelessWorker { get; private set; }
public NonExistentActivationException() : base("NonExistentActivationException") { }
public NonExistentActivationException(string msg) : base(msg) { }
public NonExistentActivationException(string message, Exception innerException)
: base(message, innerException) { }
public NonExistentActivationException(string msg, ActivationAddress nonExistentActivation, bool isStatelessWorker)
: base(msg)
{
NonExistentActivation = nonExistentActivation;
IsStatelessWorker = isStatelessWorker;
}
#if !NETSTANDARD
protected NonExistentActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
NonExistentActivation = (ActivationAddress)info.GetValue("NonExistentActivation", typeof(ActivationAddress));
IsStatelessWorker = (bool)info.GetValue("IsStatelessWorker", typeof(bool));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("NonExistentActivation", NonExistentActivation, typeof(ActivationAddress));
info.AddValue("IsStatelessWorker", IsStatelessWorker, typeof(bool));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
#endif
}
public GrainTypeManager GrainTypeManager { get; private set; }
public SiloAddress LocalSilo { get; private set; }
internal ISiloStatusOracle SiloStatusOracle { get; set; }
internal readonly ActivationCollector ActivationCollector;
private readonly ILocalGrainDirectory directory;
private readonly OrleansTaskScheduler scheduler;
private readonly ActivationDirectory activations;
private IStorageProviderManager storageProviderManager;
private Dispatcher dispatcher;
private readonly Logger logger;
private int collectionNumber;
private int destroyActivationsNumber;
private IDisposable gcTimer;
private readonly GlobalConfiguration config;
private readonly string localSiloName;
private readonly CounterStatistic activationsCreated;
private readonly CounterStatistic activationsDestroyed;
private readonly CounterStatistic activationsFailedToActivate;
private readonly IntValueStatistic inProcessRequests;
private readonly CounterStatistic collectionCounter;
private readonly GrainCreator grainCreator;
internal Catalog(
GrainId grainId,
SiloAddress silo,
string siloName,
ILocalGrainDirectory grainDirectory,
GrainTypeManager typeManager,
OrleansTaskScheduler scheduler,
ActivationDirectory activationDirectory,
ClusterConfiguration config,
GrainCreator grainCreator,
out Action<Dispatcher> setDispatcher)
: base(grainId, silo)
{
LocalSilo = silo;
localSiloName = siloName;
directory = grainDirectory;
activations = activationDirectory;
this.scheduler = scheduler;
GrainTypeManager = typeManager;
collectionNumber = 0;
destroyActivationsNumber = 0;
this.grainCreator = grainCreator;
logger = LogManager.GetLogger("Catalog", Runtime.LoggerType.Runtime);
this.config = config.Globals;
setDispatcher = d => dispatcher = d;
ActivationCollector = new ActivationCollector(config);
GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value
config.OnConfigChange("Globals/Activation", () => scheduler.RunOrQueueAction(Start, SchedulingContext), false);
IntValueStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COUNT, () => activations.Count);
activationsCreated = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CREATED);
activationsDestroyed = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DESTROYED);
activationsFailedToActivate = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_FAILED_TO_ACTIVATE);
collectionCounter = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COLLECTION_NUMBER_OF_COLLECTIONS);
inProcessRequests = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGING_PROCESSING_ACTIVATION_DATA_ALL, () =>
{
long counter = 0;
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
counter += data.GetRequestCount();
}
}
return counter;
});
}
internal void SetStorageManager(IStorageProviderManager storageManager)
{
storageProviderManager = storageManager;
}
internal void Start()
{
if (gcTimer != null) gcTimer.Dispose();
var t = GrainTimer.FromTaskCallback(OnTimer, null, TimeSpan.Zero, ActivationCollector.Quantum, "Catalog.GCTimer");
t.Start();
gcTimer = t;
}
private Task OnTimer(object _)
{
return CollectActivationsImpl(true);
}
public Task CollectActivations(TimeSpan ageLimit)
{
return CollectActivationsImpl(false, ageLimit);
}
private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan))
{
var watch = new Stopwatch();
watch.Start();
var number = Interlocked.Increment(ref collectionNumber);
long memBefore = GC.GetTotalMemory(false) / (1024 * 1024);
logger.Info(ErrorCode.Catalog_BeforeCollection, "Before collection#{0}: memory={1}MB, #activations={2}, collector={3}.",
number, memBefore, activations.Count, ActivationCollector.ToString());
List<ActivationData> list = scanStale ? ActivationCollector.ScanStale() : ActivationCollector.ScanAll(ageLimit);
collectionCounter.Increment();
var count = 0;
if (list != null && list.Count > 0)
{
count = list.Count;
if (logger.IsVerbose) logger.Verbose("CollectActivations{0}", list.ToStrings(d => d.Grain.ToString() + d.ActivationId));
await DeactivateActivationsFromCollector(list);
}
long memAfter = GC.GetTotalMemory(false) / (1024 * 1024);
watch.Stop();
logger.Info(ErrorCode.Catalog_AfterCollection, "After collection#{0}: memory={1}MB, #activations={2}, collected {3} activations, collector={4}, collection time={5}.",
number, memAfter, activations.Count, count, ActivationCollector.ToString(), watch.Elapsed);
}
public List<Tuple<GrainId, string, int>> GetGrainStatistics()
{
var counts = new Dictionary<string, Dictionary<GrainId, int>>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
// TODO: generic type expansion
var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType);
Dictionary<GrainId, int> grains;
int n;
if (!counts.TryGetValue(grainTypeName, out grains))
{
counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } });
}
else if (!grains.TryGetValue(data.Grain, out n))
grains[data.Grain] = 1;
else
grains[data.Grain] = n + 1;
}
}
return counts
.SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value)))
.ToList();
}
public List<DetailedGrainStatistic> GetDetailedGrainStatistics(string[] types=null)
{
var stats = new List<DetailedGrainStatistic>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
if (types==null || types.Contains(TypeUtils.GetFullName(data.GrainInstanceType)))
{
stats.Add(new DetailedGrainStatistic()
{
GrainType = TypeUtils.GetFullName(data.GrainInstanceType),
GrainIdentity = data.Grain,
SiloAddress = data.Silo,
Category = data.Grain.Category.ToString()
});
}
}
}
return stats;
}
public IEnumerable<KeyValuePair<string, long>> GetSimpleGrainStatistics()
{
return activations.GetSimpleGrainStatistics();
}
public DetailedGrainReport GetDetailedGrainReport(GrainId grain)
{
var report = new DetailedGrainReport
{
Grain = grain,
SiloAddress = LocalSilo,
SiloName = localSiloName,
LocalCacheActivationAddresses = directory.GetLocalCacheData(grain),
LocalDirectoryActivationAddresses = directory.GetLocalDirectoryData(grain).Addresses,
PrimaryForGrain = directory.GetPrimaryForGrain(grain)
};
try
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
string grainClassName;
GrainTypeManager.GetTypeInfo(grain.GetTypeCode(), out grainClassName, out unused, out unusedActivationStrategy);
report.GrainClassTypeName = grainClassName;
}
catch (Exception exc)
{
report.GrainClassTypeName = exc.ToString();
}
List<ActivationData> acts = activations.FindTargets(grain);
report.LocalActivations = acts != null ?
acts.Select(activationData => activationData.ToDetailedString()).ToList() :
new List<string>();
return report;
}
#region MessageTargets
/// <summary>
/// Register a new object to which messages can be delivered with the local lookup table and scheduler.
/// </summary>
/// <param name="activation"></param>
public void RegisterMessageTarget(ActivationData activation)
{
var context = new SchedulingContext(activation);
scheduler.RegisterWorkContext(context);
activations.RecordNewTarget(activation);
activationsCreated.Increment();
}
/// <summary>
/// Unregister message target and stop delivering messages to it
/// </summary>
/// <param name="activation"></param>
public void UnregisterMessageTarget(ActivationData activation)
{
activations.RemoveTarget(activation);
// this should be removed once we've refactored the deactivation code path. For now safe to keep.
ActivationCollector.TryCancelCollection(activation);
activationsDestroyed.Increment();
scheduler.UnregisterWorkContext(new SchedulingContext(activation));
if (activation.GrainInstance == null) return;
var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType);
activations.DecrementGrainCounter(grainTypeName);
activation.SetGrainInstance(null);
}
/// <summary>
/// FOR TESTING PURPOSES ONLY!!
/// </summary>
/// <param name="grain"></param>
internal int UnregisterGrainForTesting(GrainId grain)
{
var acts = activations.FindTargets(grain);
if (acts == null) return 0;
int numActsBefore = acts.Count;
foreach (var act in acts)
UnregisterMessageTarget(act);
return numActsBefore;
}
#endregion
#region Grains
internal bool IsReentrantGrain(ActivationId running)
{
ActivationData target;
GrainTypeData data;
return TryGetActivationData(running, out target) &&
target.GrainInstance != null &&
GrainTypeManager.TryGetData(TypeUtils.GetFullName(target.GrainInstanceType), out data) &&
data.IsReentrant;
}
public void GetGrainTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null)
{
GrainTypeManager.GetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments);
}
#endregion
#region Activations
public int ActivationCount { get { return activations.Count; } }
/// <summary>
/// If activation already exists, use it
/// Otherwise, create an activation of an existing grain by reading its state.
/// Return immediately using a dummy that will queue messages.
/// Concurrently start creating and initializing the real activation and replace it when it is ready.
/// </summary>
/// <param name="address">Grain's activation address</param>
/// <param name="newPlacement">Creation of new activation was requested by the placement director.</param>
/// <param name="grainType">The type of grain to be activated or created</param>
/// <param name="genericArguments">Specific generic type of grain to be activated or created</param>
/// <param name="requestContextData">Request context data.</param>
/// <param name="activatedPromise"></param>
/// <returns></returns>
public ActivationData GetOrCreateActivation(
ActivationAddress address,
bool newPlacement,
string grainType,
string genericArguments,
Dictionary<string, object> requestContextData,
out Task activatedPromise)
{
ActivationData result;
activatedPromise = TaskDone.Done;
PlacementStrategy placement;
lock (activations)
{
if (TryGetActivationData(address.Activation, out result))
{
return result;
}
int typeCode = address.Grain.GetTypeCode();
string actualGrainType = null;
MultiClusterRegistrationStrategy activationStrategy;
if (typeCode != 0)
{
GetGrainTypeInfo(typeCode, out actualGrainType, out placement, out activationStrategy, genericArguments);
}
else
{
// special case for Membership grain.
placement = SystemPlacement.Singleton;
activationStrategy = ClusterLocalRegistration.Singleton;
}
if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating())
{
// create a dummy activation that will queue up messages until the real data arrives
if (string.IsNullOrEmpty(grainType))
{
grainType = actualGrainType;
}
// We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory.
result = new ActivationData(
address,
genericArguments,
placement,
activationStrategy,
ActivationCollector,
config.Application.GetCollectionAgeLimit(grainType));
RegisterMessageTarget(result);
}
} // End lock
// Did not find and did not start placing new
if (result == null)
{
var msg = String.Format("Non-existent activation: {0}, grain type: {1}.",
address.ToFullString(), grainType);
if (logger.IsVerbose) logger.Verbose(ErrorCode.CatalogNonExistingActivation2, msg);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment();
throw new NonExistentActivationException(msg, address, placement is StatelessWorkerPlacement);
}
SetupActivationInstance(result, grainType, genericArguments);
activatedPromise = InitActivation(result, grainType, genericArguments, requestContextData);
return result;
}
private void SetupActivationInstance(ActivationData result, string grainType, string genericArguments)
{
lock (result)
{
if (result.GrainInstance == null)
{
CreateGrainInstance(grainType, result, genericArguments);
}
}
}
private async Task InitActivation(ActivationData activation, string grainType, string genericArguments, Dictionary<string, object> requestContextData)
{
// We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly)
// the operations required to turn the "dummy" activation into a real activation
ActivationAddress address = activation.Address;
int initStage = 0;
// A chain of promises that will have to complete in order to complete the activation
// Register with the grain directory, register with the store if necessary and call the Activate method on the new activation.
try
{
initStage = 1;
await RegisterActivationInGrainDirectoryAndValidate(activation);
initStage = 2;
await SetupActivationState(activation, String.IsNullOrEmpty(genericArguments) ? grainType : $"{grainType}[{genericArguments}]");
initStage = 3;
await InvokeActivate(activation, requestContextData);
ActivationCollector.ScheduleCollection(activation);
// Success!! Log the result, and start processing messages
if (logger.IsVerbose) logger.Verbose("InitActivation is done: {0}", address);
}
catch (Exception ex)
{
lock (activation)
{
activation.SetState(ActivationState.Invalid);
try
{
UnregisterMessageTarget(activation);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget4, String.Format("UnregisterMessageTarget failed on {0}.", activation), exc);
}
switch (initStage)
{
case 1: // failed to RegisterActivationInGrainDirectory
ActivationAddress target = null;
Exception dupExc;
// Failure!! Could it be that this grain uses single activation placement, and there already was an activation?
if (Utils.TryFindException(ex, typeof (DuplicateActivationException), out dupExc))
{
target = ((DuplicateActivationException) dupExc).ActivationToUse;
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DUPLICATE_ACTIVATIONS)
.Increment();
}
activation.ForwardingAddress = target;
if (target != null)
{
var primary = ((DuplicateActivationException)dupExc).PrimaryDirectoryForGrain;
// If this was a duplicate, it's not an error, just a race.
// Forward on all of the pending messages, and then forget about this activation.
string logMsg = String.Format("Tried to create a duplicate activation {0}, but we'll use {1} instead. " +
"GrainInstanceType is {2}. " +
"{3}" +
"Full activation address is {4}. We have {5} messages to forward.",
address,
target,
activation.GrainInstanceType,
primary != null ? "Primary Directory partition for this grain is " + primary + ". " : String.Empty,
address.ToFullString(),
activation.WaitingCount);
if (activation.IsUsingGrainDirectory)
{
logger.Info(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
else
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
RerouteAllQueuedMessages(activation, target, "Duplicate activation", ex);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100064,
String.Format("Failed to RegisterActivationInGrainDirectory for {0}.",
activation), ex);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null,
"Failed RegisterActivationInGrainDirectory", ex);
}
break;
case 2: // failed to setup persistent state
logger.Warn(ErrorCode.Catalog_Failed_SetupActivationState,
String.Format("Failed to SetupActivationState for {0}.", activation), ex);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null, "Failed SetupActivationState", ex);
break;
case 3: // failed to InvokeActivate
logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate,
String.Format("Failed to InvokeActivate for {0}.", activation), ex);
// Need to undo the registration we just did earlier
if (activation.IsUsingGrainDirectory)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null, "Failed InvokeActivate", ex);
break;
}
}
throw;
}
}
/// <summary>
/// Perform just the prompt, local part of creating an activation object
/// Caller is responsible for registering locally, registering with store and calling its activate routine
/// </summary>
/// <param name="grainTypeName"></param>
/// <param name="data"></param>
/// <param name="genericArguments"></param>
/// <returns></returns>
private void CreateGrainInstance(string grainTypeName, ActivationData data, string genericArguments)
{
string grainClassName;
if (!GrainTypeManager.TryGetPrimaryImplementation(grainTypeName, out grainClassName))
{
// Lookup from grain type code
var typeCode = data.Grain.GetTypeCode();
if (typeCode != 0)
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
GetGrainTypeInfo(typeCode, out grainClassName, out unused, out unusedActivationStrategy, genericArguments);
}
else
{
grainClassName = grainTypeName;
}
}
GrainTypeData grainTypeData = GrainTypeManager[grainClassName];
//Get the grain's type
Type grainType = grainTypeData.Type;
//Gets the type for the grain's state
Type stateObjectType = grainTypeData.StateObjectType;
lock (data)
{
Grain grain;
//Create a new instance of a stateless grain
if (stateObjectType == null)
{
//Create a new instance of the given grain type
grain = grainCreator.CreateGrainInstance(grainType, data.Identity);
}
//Create a new instance of a stateful grain
else
{
SetupStorageProvider(grainType, data);
grain = grainCreator.CreateGrainInstance(grainType, data.Identity, stateObjectType, data.StorageProvider);
}
grain.Data = data;
data.SetGrainInstance(grain);
}
activations.IncrementGrainCounter(grainClassName);
if (logger.IsVerbose) logger.Verbose("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId);
}
private void SetupStorageProvider(Type grainType, ActivationData data)
{
var grainTypeName = grainType.FullName;
// Get the storage provider name, using the default if not specified.
var attr = grainType.GetTypeInfo().GetCustomAttributes<StorageProviderAttribute>(true).FirstOrDefault();
var storageProviderName = attr != null ? attr.ProviderName : Constants.DEFAULT_STORAGE_PROVIDER_NAME;
IStorageProvider provider;
if (storageProviderManager == null || storageProviderManager.GetNumLoadedProviders() == 0)
{
var errMsg = string.Format("No storage providers found loading grain type {0}", grainTypeName);
logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_1, errMsg);
throw new BadProviderConfigException(errMsg);
}
if (string.IsNullOrWhiteSpace(storageProviderName))
{
// Use default storage provider
provider = storageProviderManager.GetDefaultProvider();
}
else
{
// Look for MemoryStore provider as special case name
bool caseInsensitive = Constants.MEMORY_STORAGE_PROVIDER_NAME.Equals(storageProviderName, StringComparison.OrdinalIgnoreCase);
storageProviderManager.TryGetProvider(storageProviderName, out provider, caseInsensitive);
if (provider == null)
{
var errMsg = string.Format(
"Cannot find storage provider with Name={0} for grain type {1}", storageProviderName,
grainTypeName);
logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_2, errMsg);
throw new BadProviderConfigException(errMsg);
}
}
data.StorageProvider = provider;
if (logger.IsVerbose2)
{
string msg = string.Format("Assigned storage provider with Name={0} to grain type {1}",
storageProviderName, grainTypeName);
logger.Verbose2(ErrorCode.Provider_CatalogStorageProviderAllocated, msg);
}
}
private async Task SetupActivationState(ActivationData result, string grainType)
{
var statefulGrain = result.GrainInstance as IStatefulGrain;
if (statefulGrain == null)
{
return;
}
var state = statefulGrain.GrainState;
if (result.StorageProvider != null && state != null)
{
var sw = Stopwatch.StartNew();
var innerState = statefulGrain.GrainState.State;
// Populate state data
try
{
var grainRef = result.GrainReference;
await scheduler.RunOrQueueTask(() =>
result.StorageProvider.ReadStateAsync(grainType, grainRef, state),
new SchedulingContext(result));
sw.Stop();
StorageStatisticsGroup.OnStorageActivate(result.StorageProvider, grainType, result.GrainReference, sw.Elapsed);
}
catch (Exception ex)
{
StorageStatisticsGroup.OnStorageActivateError(result.StorageProvider, grainType, result.GrainReference);
sw.Stop();
if (!(ex.GetBaseException() is KeyNotFoundException))
throw;
statefulGrain.GrainState.State = innerState; // Just keep original empty state object
}
}
}
/// <summary>
/// Try to get runtime data for an activation
/// </summary>
/// <param name="activationId"></param>
/// <param name="data"></param>
/// <returns></returns>
public bool TryGetActivationData(ActivationId activationId, out ActivationData data)
{
data = null;
if (activationId.IsSystem) return false;
data = activations.FindTarget(activationId);
return data != null;
}
private Task DeactivateActivationsFromCollector(List<ActivationData> list)
{
logger.Info(ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {0} to promptly Destroy.", list.Count);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_COLLECTION).IncrementBy(list.Count);
foreach (var activation in list)
{
lock (activation)
{
activation.PrepareForDeactivation(); // Don't accept any new messages
}
}
return DestroyActivations(list);
}
// To be called fro within Activation context.
// Cannot be awaitable, since after DestroyActivation is done the activation is in Invalid state and cannot await any Task.
internal void DeactivateActivationOnIdle(ActivationData data)
{
bool promptly = false;
bool alreadBeingDestroyed = false;
lock (data)
{
if (data.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
data.PrepareForDeactivation(); // Don't accept any new messages
ActivationCollector.TryCancelCollection(data);
if (!data.IsCurrentlyExecuting)
{
promptly = true;
}
else // busy, so destroy later.
{
data.AddOnInactive(() => DestroyActivationVoid(data));
}
}
else if (data.State == ActivationState.Create)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within a constructor, which is not allowed.",
data.ToString()));
}
else if (data.State == ActivationState.Activating)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within OnActivateAsync, which is not allowed.",
data.ToString()));
}
else
{
alreadBeingDestroyed = true;
}
}
logger.Info(ErrorCode.Catalog_ShutdownActivations_2,
"DeactivateActivationOnIdle: {0} {1}.", data.ToString(), promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle"));
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE).Increment();
if (promptly)
{
DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed!
}
}
/// <summary>
/// Gracefully deletes activations, putting it into a shutdown state to
/// complete and commit outstanding transactions before deleting it.
/// To be called not from within Activation context, so can be awaited.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
internal async Task DeactivateActivations(List<ActivationData> list)
{
if (list == null || list.Count == 0) return;
if (logger.IsVerbose) logger.Verbose("DeactivateActivations: {0} activations.", list.Count);
List<ActivationData> destroyNow = null;
List<MultiTaskCompletionSource> destroyLater = null;
int alreadyBeingDestroyed = 0;
foreach (var d in list)
{
var activationData = d; // capture
lock (activationData)
{
if (activationData.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
activationData.PrepareForDeactivation(); // Don't accept any new messages
ActivationCollector.TryCancelCollection(activationData);
if (!activationData.IsCurrentlyExecuting)
{
if (destroyNow == null)
{
destroyNow = new List<ActivationData>();
}
destroyNow.Add(activationData);
}
else // busy, so destroy later.
{
if (destroyLater == null)
{
destroyLater = new List<MultiTaskCompletionSource>();
}
var tcs = new MultiTaskCompletionSource(1);
destroyLater.Add(tcs);
activationData.AddOnInactive(() => DestroyActivationAsync(activationData, tcs));
}
}
else
{
alreadyBeingDestroyed++;
}
}
}
int numDestroyNow = destroyNow == null ? 0 : destroyNow.Count;
int numDestroyLater = destroyLater == null ? 0 : destroyLater.Count;
logger.Info(ErrorCode.Catalog_ShutdownActivations_3,
"DeactivateActivations: total {0} to shutdown, out of them {1} promptly, {2} later when become idle and {3} are already being destroyed or invalid.",
list.Count, numDestroyNow, numDestroyLater, alreadyBeingDestroyed);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DIRECT_SHUTDOWN).IncrementBy(list.Count);
if (destroyNow != null && destroyNow.Count > 0)
{
await DestroyActivations(destroyNow);
}
if (destroyLater != null && destroyLater.Count > 0)
{
await Task.WhenAll(destroyLater.Select(t => t.Task).ToArray());
}
}
public Task DeactivateAllActivations()
{
logger.Info(ErrorCode.Catalog_DeactivateAllActivations, "DeactivateAllActivations.");
var activationsToShutdown = activations.Where(kv => !kv.Value.IsExemptFromCollection).Select(kv => kv.Value).ToList();
return DeactivateActivations(activationsToShutdown);
}
/// <summary>
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="activation"></param>
private void DestroyActivationVoid(ActivationData activation)
{
StartDestroyActivations(new List<ActivationData> { activation });
}
private void DestroyActivationAsync(ActivationData activation, MultiTaskCompletionSource tcs)
{
StartDestroyActivations(new List<ActivationData> { activation }, tcs);
}
/// <summary>
/// Forcibly deletes activations now, without waiting for any outstanding transactions to complete.
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
// Overall code flow:
// Deactivating state was already set before, in the correct context under lock.
// that means no more new requests will be accepted into this activation and all timer were stopped (no new ticks will be delivered or enqueued)
// Wait for all already scheduled ticks to finish
// CallGrainDeactivate
// when AsyncDeactivate promise is resolved (NOT when all Deactivate turns are done, which may be orphan tasks):
// Unregister in the directory
// when all AsyncDeactivate turns are done (Dispatcher.OnActivationCompletedRequest):
// Set Invalid state
// UnregisterMessageTarget -> no new tasks will be enqueue (if an orphan task get enqueud, it is ignored and dropped on the floor).
// InvalidateCacheEntry
// Reroute pending
private Task DestroyActivations(List<ActivationData> list)
{
var tcs = new MultiTaskCompletionSource(list.Count);
StartDestroyActivations(list, tcs);
return tcs.Task;
}
private async void StartDestroyActivations(List<ActivationData> list, MultiTaskCompletionSource tcs = null)
{
int number = destroyActivationsNumber;
destroyActivationsNumber++;
try
{
logger.Info(ErrorCode.Catalog_DestroyActivations, "Starting DestroyActivations #{0} of {1} activations", number, list.Count);
// step 1 - WaitForAllTimersToFinish
var tasks1 = new List<Task>();
foreach (var activation in list)
{
tasks1.Add(activation.WaitForAllTimersToFinish());
}
try
{
await Task.WhenAll(tasks1);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_WaitForAllTimersToFinish_Exception, String.Format("WaitForAllTimersToFinish {0} failed.", list.Count), exc);
}
// step 2 - CallGrainDeactivate
var tasks2 = new List<Tuple<Task, ActivationData>>();
foreach (var activation in list)
{
var activationData = activation; // Capture loop variable
var task = scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData), new SchedulingContext(activationData));
tasks2.Add(new Tuple<Task, ActivationData>(task, activationData));
}
var asyncQueue = new AsyncBatchedContinuationQueue<ActivationData>();
asyncQueue.Queue(tasks2, tupleList =>
{
FinishDestroyActivations(tupleList.Select(t => t.Item2).ToList(), number, tcs);
GC.KeepAlive(asyncQueue); // not sure about GC not collecting the asyncQueue local var prematuraly, so just want to capture it here to make sure. Just to be safe.
});
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, String.Format("StartDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private async void FinishDestroyActivations(List<ActivationData> list, int number, MultiTaskCompletionSource tcs)
{
try
{
//logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Starting FinishDestroyActivations #{0} - with {1} Activations.", number, list.Count);
// step 3 - UnregisterManyAsync
try
{
List<ActivationAddress> activationsToDeactivate = list.
Where((ActivationData d) => d.IsUsingGrainDirectory).
Select((ActivationData d) => ActivationAddress.GetAddress(LocalSilo, d.Grain, d.ActivationId)).ToList();
if (activationsToDeactivate.Count > 0)
{
await scheduler.RunOrQueueTask(() =>
directory.UnregisterManyAsync(activationsToDeactivate, UnregistrationCause.Force),
SchedulingContext);
}
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterManyAsync, String.Format("UnregisterManyAsync {0} failed.", list.Count), exc);
}
// step 4 - UnregisterMessageTarget and OnFinishedGrainDeactivate
foreach (var activationData in list)
{
try
{
lock (activationData)
{
activationData.SetState(ActivationState.Invalid); // Deactivate calls on this activation are finished
}
UnregisterMessageTarget(activationData);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget2, String.Format("UnregisterMessageTarget failed on {0}.", activationData), exc);
}
try
{
// IMPORTANT: no more awaits and .Ignore after that point.
// Just use this opportunity to invalidate local Cache Entry as well.
// If this silo is not the grain directory partition for this grain, it may have it in its cache.
directory.InvalidateCacheEntry(activationData.Address);
RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation");
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Last stage of DestroyActivations failed on {0}.", activationData), exc);
}
}
// step 5 - Resolve any waiting TaskCompletionSource
if (tcs != null)
{
tcs.SetMultipleResults(list.Count);
}
logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Done FinishDestroyActivations #{0} - Destroyed {1} Activations.", number, list.Count);
}catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishDeactivateActivation_Exception, String.Format("FinishDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private void RerouteAllQueuedMessages(ActivationData activation, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null)
{
lock (activation)
{
List<Message> msgs = activation.DequeueAllWaitingMessages();
if (msgs == null || msgs.Count <= 0) return;
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation));
dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc);
}
}
private async Task CallGrainActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
// Call OnActivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
RequestContext.Import(requestContextData);
await activation.GrainInstance.OnActivateAsync();
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
lock (activation)
{
if (activation.State == ActivationState.Activating)
{
activation.SetState(ActivationState.Valid); // Activate calls on this activation are finished
}
if (!activation.IsCurrentlyExecuting)
{
activation.RunOnInactive();
}
// Run message pump to see if there is a new request is queued to be processed
dispatcher.RunMessagePump(activation);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingActivate,
string.Format("Error calling grain's OnActivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
activation.SetState(ActivationState.Invalid); // Mark this activation as unusable
activationsFailedToActivate.Increment();
throw;
}
}
private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation)
{
try
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
// Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
// just check in case this activation data is already Invalid or not here at all.
ActivationData ignore;
if (TryGetActivationData(activation.ActivationId, out ignore) &&
activation.State == ActivationState.Deactivating)
{
RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake.
await activation.GrainInstance.OnDeactivateAsync();
}
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate,
string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
}
if (activation.IsUsingStreams)
{
try
{
await activation.DeactivateStreamResources();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc);
}
}
}
catch(Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc);
}
return activation;
}
private async Task RegisterActivationInGrainDirectoryAndValidate(ActivationData activation)
{
ActivationAddress address = activation.Address;
// Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker.
// Among those that are registered in the directory, we currently do not have any multi activations.
if (activation.IsUsingGrainDirectory)
{
var result = await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address, singleActivation:true), this.SchedulingContext);
if (address.Equals(result.Address)) return;
SiloAddress primaryDirectoryForGrain = directory.GetPrimaryForGrain(address.Grain);
throw new DuplicateActivationException(result.Address, primaryDirectoryForGrain);
}
else
{
StatelessWorkerPlacement stPlacement = activation.PlacedUsing as StatelessWorkerPlacement;
int maxNumLocalActivations = stPlacement.MaxLocal;
lock (activations)
{
List<ActivationData> local;
if (!LocalLookup(address.Grain, out local) || local.Count <= maxNumLocalActivations)
return;
var id = StatelessWorkerDirector.PickRandom(local).Address;
throw new DuplicateActivationException(id);
}
}
// We currently don't have any other case for multiple activations except for StatelessWorker.
}
#endregion
#region Activations - private
/// <summary>
/// Invoke the activate method on a newly created activation
/// </summary>
/// <param name="activation"></param>
/// <param name="requestContextData"></param>
/// <returns></returns>
private Task InvokeActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
// NOTE: This should only be called with the correct schedulering context for the activation to be invoked.
lock (activation)
{
activation.SetState(ActivationState.Activating);
}
return scheduler.QueueTask(() => CallGrainActivate(activation, requestContextData), new SchedulingContext(activation)); // Target grain's scheduler context);
// ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest
}
#endregion
#region IPlacementContext
public Logger Logger => logger;
public bool FastLookup(GrainId grain, out AddressesAndTag addresses)
{
return directory.LocalLookup(grain, out addresses) && addresses.Addresses != null && addresses.Addresses.Count > 0;
// NOTE: only check with the local directory cache.
// DO NOT check in the local activations TargetDirectory!!!
// The only source of truth about which activation should be legit to is the state of the ditributed directory.
// Everyone should converge to that (that is the meaning of "eventualy consistency - eventualy we converge to one truth").
// If we keep using the local activation, it may not be registered in th directory any more, but we will never know that and keep using it,
// thus volaiting the single-activation semantics and not converging even eventualy!
}
public Task<AddressesAndTag> FullLookup(GrainId grain)
{
return scheduler.RunOrQueueTask(() => directory.LookupAsync(grain), this.SchedulingContext);
}
public Task<AddressesAndTag> LookupInCluster(GrainId grain, string clusterId)
{
return scheduler.RunOrQueueTask(() => directory.LookupInCluster(grain, clusterId), this.SchedulingContext);
}
public bool LocalLookup(GrainId grain, out List<ActivationData> addresses)
{
addresses = activations.FindTargets(grain);
return addresses != null;
}
public List<SiloAddress> AllActiveSilos
{
get
{
var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Select(s => s.Key).ToList();
if (result.Count > 0) return result;
logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty");
return new List<SiloAddress> { LocalSilo };
}
}
#endregion
#region Implementation of ICatalog
public Task CreateSystemGrain(GrainId grainId, string grainType)
{
ActivationAddress target = ActivationAddress.NewActivationAddress(LocalSilo, grainId);
Task activatedPromise;
GetOrCreateActivation(target, true, grainType, null, null, out activatedPromise);
return activatedPromise ?? TaskDone.Done;
}
public Task DeleteActivations(List<ActivationAddress> addresses)
{
return DestroyActivations(TryGetActivationDatas(addresses));
}
private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addresses)
{
var datas = new List<ActivationData>(addresses.Count);
foreach (var activationAddress in addresses)
{
ActivationData data;
if (TryGetActivationData(activationAddress.Activation, out data))
datas.Add(data);
}
return datas;
}
#endregion
#region Implementation of ISiloStatusListener
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// ignore joining events and also events on myself.
if (updatedSilo.Equals(LocalSilo)) return;
// We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states,
// since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses,
// thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified.
// We may review the directory behaiviour in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well.
if (!status.IsTerminating()) return;
if (status == SiloStatus.Dead)
{
RuntimeClient.Current.BreakOutstandingMessagesToDeadSilo(updatedSilo);
}
var activationsToShutdown = new List<ActivationData>();
try
{
// scan all activations in activation directory and deactivate the ones that the removed silo is their primary partition owner.
lock (activations)
{
foreach (var activation in activations)
{
try
{
var activationData = activation.Value;
if (!activationData.IsUsingGrainDirectory) continue;
if (!directory.GetPrimaryForGrain(activationData.Grain).Equals(updatedSilo)) continue;
lock (activationData)
{
// adapted from InsideGarinClient.DeactivateOnIdle().
activationData.ResetKeepAliveRequest();
activationsToShutdown.Add(activationData);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception,
String.Format("Catalog has thrown an exception while executing SiloStatusChangeNotification of silo {0}.", updatedSilo.ToStringWithHashCode()), exc);
}
}
}
logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification,
String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partiton to these grain ids.",
activationsToShutdown.Count, updatedSilo.ToStringWithHashCode()));
}
finally
{
// outside the lock.
if (activationsToShutdown.Count > 0)
{
DeactivateActivations(activationsToShutdown).Ignore();
}
}
}
#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.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Numerics
{
/// <summary>
/// A structure encapsulating four single precision floating point values and provides hardware accelerated methods.
/// </summary>
[Intrinsic]
public partial struct Vector4 : IEquatable<Vector4>, IFormattable
{
#region Public Static Properties
/// <summary>
/// Returns the vector (0,0,0,0).
/// </summary>
public static Vector4 Zero
{
[Intrinsic]
get
{
return new Vector4();
}
}
/// <summary>
/// Returns the vector (1,1,1,1).
/// </summary>
public static Vector4 One
{
[Intrinsic]
get
{
return new Vector4(1.0f, 1.0f, 1.0f, 1.0f);
}
}
/// <summary>
/// Returns the vector (1,0,0,0).
/// </summary>
public static Vector4 UnitX { get { return new Vector4(1.0f, 0.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,1,0,0).
/// </summary>
public static Vector4 UnitY { get { return new Vector4(0.0f, 1.0f, 0.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,1,0).
/// </summary>
public static Vector4 UnitZ { get { return new Vector4(0.0f, 0.0f, 1.0f, 0.0f); } }
/// <summary>
/// Returns the vector (0,0,0,1).
/// </summary>
public static Vector4 UnitW { get { return new Vector4(0.0f, 0.0f, 0.0f, 1.0f); } }
#endregion Public Static Properties
#region Public instance methods
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>The hash code.</returns>
public override readonly int GetHashCode()
{
return HashCode.Combine(this.X.GetHashCode(), this.Y.GetHashCode(), this.Z.GetHashCode(), this.W.GetHashCode());
}
/// <summary>
/// Returns a boolean indicating whether the given Object is equal to this Vector4 instance.
/// </summary>
/// <param name="obj">The Object to compare against.</param>
/// <returns>True if the Object is equal to this Vector4; False otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override readonly bool Equals(object? obj)
{
if (!(obj is Vector4))
return false;
return Equals((Vector4)obj);
}
/// <summary>
/// Returns a String representing this Vector4 instance.
/// </summary>
/// <returns>The string representation.</returns>
public override readonly string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector4 instance, using the specified format to format individual elements.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <returns>The string representation.</returns>
public readonly string ToString(string? format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns a String representing this Vector4 instance, using the specified format to format individual elements
/// and the given IFormatProvider.
/// </summary>
/// <param name="format">The format of individual elements.</param>
/// <param name="formatProvider">The format provider to use when formatting elements.</param>
/// <returns>The string representation.</returns>
public readonly string ToString(string? format, IFormatProvider? formatProvider)
{
StringBuilder sb = new StringBuilder();
string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
sb.Append('<');
sb.Append(this.X.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(this.Y.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(this.Z.ToString(format, formatProvider));
sb.Append(separator);
sb.Append(' ');
sb.Append(this.W.ToString(format, formatProvider));
sb.Append('>');
return sb.ToString();
}
/// <summary>
/// Returns the length of the vector. This operation is cheaper than Length().
/// </summary>
/// <returns>The vector's length.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float Length()
{
if (Vector.IsHardwareAccelerated)
{
float ls = Vector4.Dot(this, this);
return MathF.Sqrt(ls);
}
else
{
float ls = X * X + Y * Y + Z * Z + W * W;
return MathF.Sqrt(ls);
}
}
/// <summary>
/// Returns the length of the vector squared.
/// </summary>
/// <returns>The vector's length squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly float LengthSquared()
{
if (Vector.IsHardwareAccelerated)
{
return Vector4.Dot(this, this);
}
else
{
return X * X + Y * Y + Z * Z + W * W;
}
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the Euclidean distance between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Distance(Vector4 value1, Vector4 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector4 difference = value1 - value2;
float ls = Vector4.Dot(difference, difference);
return MathF.Sqrt(ls);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
float dw = value1.W - value2.W;
float ls = dx * dx + dy * dy + dz * dz + dw * dw;
return MathF.Sqrt(ls);
}
}
/// <summary>
/// Returns the Euclidean distance squared between the two given points.
/// </summary>
/// <param name="value1">The first point.</param>
/// <param name="value2">The second point.</param>
/// <returns>The distance squared.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float DistanceSquared(Vector4 value1, Vector4 value2)
{
if (Vector.IsHardwareAccelerated)
{
Vector4 difference = value1 - value2;
return Vector4.Dot(difference, difference);
}
else
{
float dx = value1.X - value2.X;
float dy = value1.Y - value2.Y;
float dz = value1.Z - value2.Z;
float dw = value1.W - value2.W;
return dx * dx + dy * dy + dz * dz + dw * dw;
}
}
/// <summary>
/// Returns a vector with the same direction as the given vector, but with a length of 1.
/// </summary>
/// <param name="vector">The vector to normalize.</param>
/// <returns>The normalized vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Normalize(Vector4 vector)
{
if (Vector.IsHardwareAccelerated)
{
float length = vector.Length();
return vector / length;
}
else
{
float ls = vector.X * vector.X + vector.Y * vector.Y + vector.Z * vector.Z + vector.W * vector.W;
float invNorm = 1.0f / MathF.Sqrt(ls);
return new Vector4(
vector.X * invNorm,
vector.Y * invNorm,
vector.Z * invNorm,
vector.W * invNorm);
}
}
/// <summary>
/// Restricts a vector between a min and max value.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>The restricted vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max)
{
// This compare order is very important!!!
// We must follow HLSL behavior in the case user specified min value is bigger than max value.
float x = value1.X;
x = (min.X > x) ? min.X : x; // max(x, minx)
x = (max.X < x) ? max.X : x; // min(x, maxx)
float y = value1.Y;
y = (min.Y > y) ? min.Y : y; // max(y, miny)
y = (max.Y < y) ? max.Y : y; // min(y, maxy)
float z = value1.Z;
z = (min.Z > z) ? min.Z : z; // max(z, minz)
z = (max.Z < z) ? max.Z : z; // min(z, maxz)
float w = value1.W;
w = (min.W > w) ? min.W : w; // max(w, minw)
w = (max.W < w) ? max.W : w; // min(w, minw)
return new Vector4(x, y, z, w);
}
/// <summary>
/// Linearly interpolates between two vectors based on the given weighting.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param>
/// <returns>The interpolated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount)
{
return new Vector4(
value1.X + (value2.X - value1.X) * amount,
value1.Y + (value2.Y - value1.Y) * amount,
value1.Z + (value2.Z - value1.Z) * amount,
value1.W + (value2.W - value1.W) * amount);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector2 position, Matrix4x4 matrix)
{
return new Vector4(
position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41,
position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42,
position.X * matrix.M13 + position.Y * matrix.M23 + matrix.M43,
position.X * matrix.M14 + position.Y * matrix.M24 + matrix.M44);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="position">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector3 position, Matrix4x4 matrix)
{
return new Vector4(
position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41,
position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42,
position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43,
position.X * matrix.M14 + position.Y * matrix.M24 + position.Z * matrix.M34 + matrix.M44);
}
/// <summary>
/// Transforms a vector by the given matrix.
/// </summary>
/// <param name="vector">The source vector.</param>
/// <param name="matrix">The transformation matrix.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector4 vector, Matrix4x4 matrix)
{
return new Vector4(
vector.X * matrix.M11 + vector.Y * matrix.M21 + vector.Z * matrix.M31 + vector.W * matrix.M41,
vector.X * matrix.M12 + vector.Y * matrix.M22 + vector.Z * matrix.M32 + vector.W * matrix.M42,
vector.X * matrix.M13 + vector.Y * matrix.M23 + vector.Z * matrix.M33 + vector.W * matrix.M43,
vector.X * matrix.M14 + vector.Y * matrix.M24 + vector.Z * matrix.M34 + vector.W * matrix.M44);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector2 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector4(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2),
1.0f);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector3 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector4(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2),
1.0f);
}
/// <summary>
/// Transforms a vector by the given Quaternion rotation value.
/// </summary>
/// <param name="value">The source vector to be rotated.</param>
/// <param name="rotation">The rotation to apply.</param>
/// <returns>The transformed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Transform(Vector4 value, Quaternion rotation)
{
float x2 = rotation.X + rotation.X;
float y2 = rotation.Y + rotation.Y;
float z2 = rotation.Z + rotation.Z;
float wx2 = rotation.W * x2;
float wy2 = rotation.W * y2;
float wz2 = rotation.W * z2;
float xx2 = rotation.X * x2;
float xy2 = rotation.X * y2;
float xz2 = rotation.X * z2;
float yy2 = rotation.Y * y2;
float yz2 = rotation.Y * z2;
float zz2 = rotation.Z * z2;
return new Vector4(
value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2) + value.Z * (xz2 + wy2),
value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2) + value.Z * (yz2 - wx2),
value.X * (xz2 - wy2) + value.Y * (yz2 + wx2) + value.Z * (1.0f - xx2 - yy2),
value.W);
}
#endregion Public Static Methods
#region Public operator methods
// All these methods should be inlines as they are implemented
// over JIT intrinsics
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Add(Vector4 left, Vector4 right)
{
return left + right;
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Subtract(Vector4 left, Vector4 right)
{
return left - right;
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Multiply(Vector4 left, Vector4 right)
{
return left * right;
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Multiply(Vector4 left, float right)
{
return left * new Vector4(right, right, right, right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Multiply(float left, Vector4 right)
{
return new Vector4(left, left, left, left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Divide(Vector4 left, Vector4 right)
{
return left / right;
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="divisor">The scalar value.</param>
/// <returns>The result of the division.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Divide(Vector4 left, float divisor)
{
return left / divisor;
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector4 Negate(Vector4 value)
{
return -value;
}
#endregion Public operator methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Streams;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Versions;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
namespace Orleans.Runtime
{
internal class TypeManager : SystemTarget, IClusterTypeManager, ISiloTypeManager, ISiloStatusListener, IDisposable
{
private readonly Logger logger = LogManager.GetLogger("TypeManager");
private readonly GrainTypeManager grainTypeManager;
private readonly ISiloStatusOracle statusOracle;
private readonly ImplicitStreamSubscriberTable implicitStreamSubscriberTable;
private readonly IInternalGrainFactory grainFactory;
private readonly CachedVersionSelectorManager versionSelectorManager;
private readonly OrleansTaskScheduler scheduler;
private readonly TimeSpan refreshClusterMapInterval;
private bool hasToRefreshClusterGrainInterfaceMap;
private IDisposable refreshClusterGrainInterfaceMapTimer;
private IVersionStore versionStore;
internal TypeManager(
SiloAddress myAddr,
GrainTypeManager grainTypeManager,
ISiloStatusOracle oracle,
OrleansTaskScheduler scheduler,
TimeSpan refreshClusterMapInterval,
ImplicitStreamSubscriberTable implicitStreamSubscriberTable,
IInternalGrainFactory grainFactory,
CachedVersionSelectorManager versionSelectorManager)
: base(Constants.TypeManagerId, myAddr)
{
if (grainTypeManager == null)
throw new ArgumentNullException(nameof(grainTypeManager));
if (oracle == null)
throw new ArgumentNullException(nameof(oracle));
if (scheduler == null)
throw new ArgumentNullException(nameof(scheduler));
if (implicitStreamSubscriberTable == null)
throw new ArgumentNullException(nameof(implicitStreamSubscriberTable));
this.grainTypeManager = grainTypeManager;
this.statusOracle = oracle;
this.implicitStreamSubscriberTable = implicitStreamSubscriberTable;
this.grainFactory = grainFactory;
this.versionSelectorManager = versionSelectorManager;
this.scheduler = scheduler;
this.refreshClusterMapInterval = refreshClusterMapInterval;
// We need this so we can place needed local activations
this.grainTypeManager.SetInterfaceMapsBySilo(new Dictionary<SiloAddress, GrainInterfaceMap>
{
{this.Silo, grainTypeManager.GetTypeCodeMap()}
});
}
internal async Task Initialize(IVersionStore store)
{
this.versionStore = store;
this.hasToRefreshClusterGrainInterfaceMap = true;
await this.OnRefreshClusterMapTimer(null);
this.refreshClusterGrainInterfaceMapTimer = this.RegisterTimer(
OnRefreshClusterMapTimer,
null,
this.refreshClusterMapInterval,
this.refreshClusterMapInterval);
}
public Task<IGrainTypeResolver> GetClusterTypeCodeMap()
{
return Task.FromResult<IGrainTypeResolver>(grainTypeManager.ClusterGrainInterfaceMap);
}
public Task<GrainInterfaceMap> GetSiloTypeCodeMap()
{
return Task.FromResult(grainTypeManager.GetTypeCodeMap());
}
public Task<ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(SiloAddress silo)
{
return Task.FromResult(implicitStreamSubscriberTable);
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
hasToRefreshClusterGrainInterfaceMap = true;
}
private async Task OnRefreshClusterMapTimer(object _)
{
// Check if we have to refresh
if (!hasToRefreshClusterGrainInterfaceMap)
{
logger.Verbose3("OnRefreshClusterMapTimer: no refresh required");
return;
}
hasToRefreshClusterGrainInterfaceMap = false;
logger.Info("OnRefreshClusterMapTimer: refresh start");
var activeSilos = statusOracle.GetApproximateSiloStatuses(onlyActive: true);
var knownSilosClusterGrainInterfaceMap = grainTypeManager.GrainInterfaceMapsBySilo;
// Build the new map. Always start by himself
var newSilosClusterGrainInterfaceMap = new Dictionary<SiloAddress, GrainInterfaceMap>
{
{this.Silo, grainTypeManager.GetTypeCodeMap()}
};
var getGrainInterfaceMapTasks = new List<Task<KeyValuePair<SiloAddress, GrainInterfaceMap>>>();
foreach (var siloAddress in activeSilos.Keys)
{
if (siloAddress.Equals(this.Silo)) continue;
GrainInterfaceMap value;
if (knownSilosClusterGrainInterfaceMap.TryGetValue(siloAddress, out value))
{
logger.Verbose3($"OnRefreshClusterMapTimer: value already found locally for {siloAddress}");
newSilosClusterGrainInterfaceMap[siloAddress] = value;
}
else
{
// Value not found, let's get it
logger.Verbose3($"OnRefreshClusterMapTimer: value not found locally for {siloAddress}");
getGrainInterfaceMapTasks.Add(GetTargetSiloGrainInterfaceMap(siloAddress));
}
}
if (getGrainInterfaceMapTasks.Any())
{
foreach (var keyValuePair in await Task.WhenAll(getGrainInterfaceMapTasks))
{
if (keyValuePair.Value != null)
newSilosClusterGrainInterfaceMap.Add(keyValuePair.Key, keyValuePair.Value);
}
}
grainTypeManager.SetInterfaceMapsBySilo(newSilosClusterGrainInterfaceMap);
if (this.versionStore.IsEnabled)
{
await this.GetAndSetDefaultCompatibilityStrategy();
foreach (var kvp in await GetStoredCompatibilityStrategies())
{
this.versionSelectorManager.CompatibilityDirectorManager.SetStrategy(kvp.Key, kvp.Value);
}
await this.GetAndSetDefaultSelectorStrategy();
foreach (var kvp in await GetSelectorStrategies())
{
this.versionSelectorManager.VersionSelectorManager.SetSelector(kvp.Key, kvp.Value);
}
}
versionSelectorManager.ResetCache();
}
private async Task GetAndSetDefaultSelectorStrategy()
{
try
{
var strategy = await this.versionStore.GetSelectorStrategy();
this.versionSelectorManager.VersionSelectorManager.SetSelector(strategy);
}
catch (Exception)
{
hasToRefreshClusterGrainInterfaceMap = true;
}
}
private async Task GetAndSetDefaultCompatibilityStrategy()
{
try
{
var strategy = await this.versionStore.GetCompatibilityStrategy();
this.versionSelectorManager.CompatibilityDirectorManager.SetStrategy(strategy);
}
catch (Exception)
{
hasToRefreshClusterGrainInterfaceMap = true;
}
}
private async Task<Dictionary<int, CompatibilityStrategy>> GetStoredCompatibilityStrategies()
{
try
{
return await this.versionStore.GetCompatibilityStrategies();
}
catch (Exception)
{
hasToRefreshClusterGrainInterfaceMap = true;
return new Dictionary<int, CompatibilityStrategy>();
}
}
private async Task<Dictionary<int, VersionSelectorStrategy>> GetSelectorStrategies()
{
try
{
return await this.versionStore.GetSelectorStrategies();
}
catch (Exception)
{
hasToRefreshClusterGrainInterfaceMap = true;
return new Dictionary<int, VersionSelectorStrategy>();
}
}
private async Task<KeyValuePair<SiloAddress, GrainInterfaceMap>> GetTargetSiloGrainInterfaceMap(SiloAddress siloAddress)
{
try
{
var remoteTypeManager = this.grainFactory.GetSystemTarget<ISiloTypeManager>(Constants.TypeManagerId, siloAddress);
var siloTypeCodeMap = await scheduler.QueueTask(() => remoteTypeManager.GetSiloTypeCodeMap(), SchedulingContext);
return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, siloTypeCodeMap);
}
catch (Exception ex)
{
// Will be retried on the next timer hit
logger.Error(ErrorCode.TypeManager_GetSiloGrainInterfaceMapError, $"Exception when trying to get GrainInterfaceMap for silos {siloAddress}", ex);
hasToRefreshClusterGrainInterfaceMap = true;
return new KeyValuePair<SiloAddress, GrainInterfaceMap>(siloAddress, null);
}
}
public void Dispose()
{
if (this.refreshClusterGrainInterfaceMapTimer != null)
{
this.refreshClusterGrainInterfaceMapTimer.Dispose();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 SubtractInt32()
{
var test = new SimpleBinaryOpTest__SubtractInt32();
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__SubtractInt32
{
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(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
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<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, 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<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__SubtractInt32 testClass)
{
var result = Sse2.Subtract(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(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<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__SubtractInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleBinaryOpTest__SubtractInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Subtract(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Subtract(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Subtract(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(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<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.Subtract(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__SubtractInt32();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__SubtractInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.Subtract(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.Subtract(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&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<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(left[0] - right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(left[i] - right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<Int32>(Vector128<Int32>, Vector128<Int32>): {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;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
// These types were moved down to System.Runtime
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.CallingConventions))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.EventAttributes))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.FieldAttributes))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.GenericParameterAttributes))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.MethodAttributes))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.MethodImplAttributes))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.ParameterAttributes))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.PropertyAttributes))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.TypeAttributes))]
namespace System.Reflection.Emit
{
public enum FlowControl
{
Branch = 0,
Break = 1,
Call = 2,
Cond_Branch = 3,
Meta = 4,
Next = 5,
[Obsolete("This API has been deprecated. https://go.microsoft.com/fwlink/?linkid=14202")]
Phi = 6,
Return = 7,
Throw = 8,
}
public partial struct OpCode
{
private object _dummy;
public System.Reflection.Emit.FlowControl FlowControl { get { throw null; } }
public string Name { get { throw null; } }
public System.Reflection.Emit.OpCodeType OpCodeType { get { throw null; } }
public System.Reflection.Emit.OperandType OperandType { get { throw null; } }
public int Size { get { throw null; } }
public System.Reflection.Emit.StackBehaviour StackBehaviourPop { get { throw null; } }
public System.Reflection.Emit.StackBehaviour StackBehaviourPush { get { throw null; } }
public short Value { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Reflection.Emit.OpCode obj) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { throw null; }
public static bool operator !=(System.Reflection.Emit.OpCode a, System.Reflection.Emit.OpCode b) { throw null; }
public override string ToString() { throw null; }
}
public partial class OpCodes
{
internal OpCodes() { }
public static readonly System.Reflection.Emit.OpCode Add;
public static readonly System.Reflection.Emit.OpCode Add_Ovf;
public static readonly System.Reflection.Emit.OpCode Add_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode And;
public static readonly System.Reflection.Emit.OpCode Arglist;
public static readonly System.Reflection.Emit.OpCode Beq;
public static readonly System.Reflection.Emit.OpCode Beq_S;
public static readonly System.Reflection.Emit.OpCode Bge;
public static readonly System.Reflection.Emit.OpCode Bge_S;
public static readonly System.Reflection.Emit.OpCode Bge_Un;
public static readonly System.Reflection.Emit.OpCode Bge_Un_S;
public static readonly System.Reflection.Emit.OpCode Bgt;
public static readonly System.Reflection.Emit.OpCode Bgt_S;
public static readonly System.Reflection.Emit.OpCode Bgt_Un;
public static readonly System.Reflection.Emit.OpCode Bgt_Un_S;
public static readonly System.Reflection.Emit.OpCode Ble;
public static readonly System.Reflection.Emit.OpCode Ble_S;
public static readonly System.Reflection.Emit.OpCode Ble_Un;
public static readonly System.Reflection.Emit.OpCode Ble_Un_S;
public static readonly System.Reflection.Emit.OpCode Blt;
public static readonly System.Reflection.Emit.OpCode Blt_S;
public static readonly System.Reflection.Emit.OpCode Blt_Un;
public static readonly System.Reflection.Emit.OpCode Blt_Un_S;
public static readonly System.Reflection.Emit.OpCode Bne_Un;
public static readonly System.Reflection.Emit.OpCode Bne_Un_S;
public static readonly System.Reflection.Emit.OpCode Box;
public static readonly System.Reflection.Emit.OpCode Br;
public static readonly System.Reflection.Emit.OpCode Br_S;
public static readonly System.Reflection.Emit.OpCode Break;
public static readonly System.Reflection.Emit.OpCode Brfalse;
public static readonly System.Reflection.Emit.OpCode Brfalse_S;
public static readonly System.Reflection.Emit.OpCode Brtrue;
public static readonly System.Reflection.Emit.OpCode Brtrue_S;
public static readonly System.Reflection.Emit.OpCode Call;
public static readonly System.Reflection.Emit.OpCode Calli;
public static readonly System.Reflection.Emit.OpCode Callvirt;
public static readonly System.Reflection.Emit.OpCode Castclass;
public static readonly System.Reflection.Emit.OpCode Ceq;
public static readonly System.Reflection.Emit.OpCode Cgt;
public static readonly System.Reflection.Emit.OpCode Cgt_Un;
public static readonly System.Reflection.Emit.OpCode Ckfinite;
public static readonly System.Reflection.Emit.OpCode Clt;
public static readonly System.Reflection.Emit.OpCode Clt_Un;
public static readonly System.Reflection.Emit.OpCode Constrained;
public static readonly System.Reflection.Emit.OpCode Conv_I;
public static readonly System.Reflection.Emit.OpCode Conv_I1;
public static readonly System.Reflection.Emit.OpCode Conv_I2;
public static readonly System.Reflection.Emit.OpCode Conv_I4;
public static readonly System.Reflection.Emit.OpCode Conv_I8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I1_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I2_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I4_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_I8_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U1_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U2_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U4_Un;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8;
public static readonly System.Reflection.Emit.OpCode Conv_Ovf_U8_Un;
public static readonly System.Reflection.Emit.OpCode Conv_R_Un;
public static readonly System.Reflection.Emit.OpCode Conv_R4;
public static readonly System.Reflection.Emit.OpCode Conv_R8;
public static readonly System.Reflection.Emit.OpCode Conv_U;
public static readonly System.Reflection.Emit.OpCode Conv_U1;
public static readonly System.Reflection.Emit.OpCode Conv_U2;
public static readonly System.Reflection.Emit.OpCode Conv_U4;
public static readonly System.Reflection.Emit.OpCode Conv_U8;
public static readonly System.Reflection.Emit.OpCode Cpblk;
public static readonly System.Reflection.Emit.OpCode Cpobj;
public static readonly System.Reflection.Emit.OpCode Div;
public static readonly System.Reflection.Emit.OpCode Div_Un;
public static readonly System.Reflection.Emit.OpCode Dup;
public static readonly System.Reflection.Emit.OpCode Endfilter;
public static readonly System.Reflection.Emit.OpCode Endfinally;
public static readonly System.Reflection.Emit.OpCode Initblk;
public static readonly System.Reflection.Emit.OpCode Initobj;
public static readonly System.Reflection.Emit.OpCode Isinst;
public static readonly System.Reflection.Emit.OpCode Jmp;
public static readonly System.Reflection.Emit.OpCode Ldarg;
public static readonly System.Reflection.Emit.OpCode Ldarg_0;
public static readonly System.Reflection.Emit.OpCode Ldarg_1;
public static readonly System.Reflection.Emit.OpCode Ldarg_2;
public static readonly System.Reflection.Emit.OpCode Ldarg_3;
public static readonly System.Reflection.Emit.OpCode Ldarg_S;
public static readonly System.Reflection.Emit.OpCode Ldarga;
public static readonly System.Reflection.Emit.OpCode Ldarga_S;
public static readonly System.Reflection.Emit.OpCode Ldc_I4;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_0;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_1;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_2;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_3;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_4;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_5;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_6;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_7;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_8;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_M1;
public static readonly System.Reflection.Emit.OpCode Ldc_I4_S;
public static readonly System.Reflection.Emit.OpCode Ldc_I8;
public static readonly System.Reflection.Emit.OpCode Ldc_R4;
public static readonly System.Reflection.Emit.OpCode Ldc_R8;
public static readonly System.Reflection.Emit.OpCode Ldelem;
public static readonly System.Reflection.Emit.OpCode Ldelem_I;
public static readonly System.Reflection.Emit.OpCode Ldelem_I1;
public static readonly System.Reflection.Emit.OpCode Ldelem_I2;
public static readonly System.Reflection.Emit.OpCode Ldelem_I4;
public static readonly System.Reflection.Emit.OpCode Ldelem_I8;
public static readonly System.Reflection.Emit.OpCode Ldelem_R4;
public static readonly System.Reflection.Emit.OpCode Ldelem_R8;
public static readonly System.Reflection.Emit.OpCode Ldelem_Ref;
public static readonly System.Reflection.Emit.OpCode Ldelem_U1;
public static readonly System.Reflection.Emit.OpCode Ldelem_U2;
public static readonly System.Reflection.Emit.OpCode Ldelem_U4;
public static readonly System.Reflection.Emit.OpCode Ldelema;
public static readonly System.Reflection.Emit.OpCode Ldfld;
public static readonly System.Reflection.Emit.OpCode Ldflda;
public static readonly System.Reflection.Emit.OpCode Ldftn;
public static readonly System.Reflection.Emit.OpCode Ldind_I;
public static readonly System.Reflection.Emit.OpCode Ldind_I1;
public static readonly System.Reflection.Emit.OpCode Ldind_I2;
public static readonly System.Reflection.Emit.OpCode Ldind_I4;
public static readonly System.Reflection.Emit.OpCode Ldind_I8;
public static readonly System.Reflection.Emit.OpCode Ldind_R4;
public static readonly System.Reflection.Emit.OpCode Ldind_R8;
public static readonly System.Reflection.Emit.OpCode Ldind_Ref;
public static readonly System.Reflection.Emit.OpCode Ldind_U1;
public static readonly System.Reflection.Emit.OpCode Ldind_U2;
public static readonly System.Reflection.Emit.OpCode Ldind_U4;
public static readonly System.Reflection.Emit.OpCode Ldlen;
public static readonly System.Reflection.Emit.OpCode Ldloc;
public static readonly System.Reflection.Emit.OpCode Ldloc_0;
public static readonly System.Reflection.Emit.OpCode Ldloc_1;
public static readonly System.Reflection.Emit.OpCode Ldloc_2;
public static readonly System.Reflection.Emit.OpCode Ldloc_3;
public static readonly System.Reflection.Emit.OpCode Ldloc_S;
public static readonly System.Reflection.Emit.OpCode Ldloca;
public static readonly System.Reflection.Emit.OpCode Ldloca_S;
public static readonly System.Reflection.Emit.OpCode Ldnull;
public static readonly System.Reflection.Emit.OpCode Ldobj;
public static readonly System.Reflection.Emit.OpCode Ldsfld;
public static readonly System.Reflection.Emit.OpCode Ldsflda;
public static readonly System.Reflection.Emit.OpCode Ldstr;
public static readonly System.Reflection.Emit.OpCode Ldtoken;
public static readonly System.Reflection.Emit.OpCode Ldvirtftn;
public static readonly System.Reflection.Emit.OpCode Leave;
public static readonly System.Reflection.Emit.OpCode Leave_S;
public static readonly System.Reflection.Emit.OpCode Localloc;
public static readonly System.Reflection.Emit.OpCode Mkrefany;
public static readonly System.Reflection.Emit.OpCode Mul;
public static readonly System.Reflection.Emit.OpCode Mul_Ovf;
public static readonly System.Reflection.Emit.OpCode Mul_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode Neg;
public static readonly System.Reflection.Emit.OpCode Newarr;
public static readonly System.Reflection.Emit.OpCode Newobj;
public static readonly System.Reflection.Emit.OpCode Nop;
public static readonly System.Reflection.Emit.OpCode Not;
public static readonly System.Reflection.Emit.OpCode Or;
public static readonly System.Reflection.Emit.OpCode Pop;
public static readonly System.Reflection.Emit.OpCode Prefix1;
public static readonly System.Reflection.Emit.OpCode Prefix2;
public static readonly System.Reflection.Emit.OpCode Prefix3;
public static readonly System.Reflection.Emit.OpCode Prefix4;
public static readonly System.Reflection.Emit.OpCode Prefix5;
public static readonly System.Reflection.Emit.OpCode Prefix6;
public static readonly System.Reflection.Emit.OpCode Prefix7;
public static readonly System.Reflection.Emit.OpCode Prefixref;
public static readonly System.Reflection.Emit.OpCode Readonly;
public static readonly System.Reflection.Emit.OpCode Refanytype;
public static readonly System.Reflection.Emit.OpCode Refanyval;
public static readonly System.Reflection.Emit.OpCode Rem;
public static readonly System.Reflection.Emit.OpCode Rem_Un;
public static readonly System.Reflection.Emit.OpCode Ret;
public static readonly System.Reflection.Emit.OpCode Rethrow;
public static readonly System.Reflection.Emit.OpCode Shl;
public static readonly System.Reflection.Emit.OpCode Shr;
public static readonly System.Reflection.Emit.OpCode Shr_Un;
public static readonly System.Reflection.Emit.OpCode Sizeof;
public static readonly System.Reflection.Emit.OpCode Starg;
public static readonly System.Reflection.Emit.OpCode Starg_S;
public static readonly System.Reflection.Emit.OpCode Stelem;
public static readonly System.Reflection.Emit.OpCode Stelem_I;
public static readonly System.Reflection.Emit.OpCode Stelem_I1;
public static readonly System.Reflection.Emit.OpCode Stelem_I2;
public static readonly System.Reflection.Emit.OpCode Stelem_I4;
public static readonly System.Reflection.Emit.OpCode Stelem_I8;
public static readonly System.Reflection.Emit.OpCode Stelem_R4;
public static readonly System.Reflection.Emit.OpCode Stelem_R8;
public static readonly System.Reflection.Emit.OpCode Stelem_Ref;
public static readonly System.Reflection.Emit.OpCode Stfld;
public static readonly System.Reflection.Emit.OpCode Stind_I;
public static readonly System.Reflection.Emit.OpCode Stind_I1;
public static readonly System.Reflection.Emit.OpCode Stind_I2;
public static readonly System.Reflection.Emit.OpCode Stind_I4;
public static readonly System.Reflection.Emit.OpCode Stind_I8;
public static readonly System.Reflection.Emit.OpCode Stind_R4;
public static readonly System.Reflection.Emit.OpCode Stind_R8;
public static readonly System.Reflection.Emit.OpCode Stind_Ref;
public static readonly System.Reflection.Emit.OpCode Stloc;
public static readonly System.Reflection.Emit.OpCode Stloc_0;
public static readonly System.Reflection.Emit.OpCode Stloc_1;
public static readonly System.Reflection.Emit.OpCode Stloc_2;
public static readonly System.Reflection.Emit.OpCode Stloc_3;
public static readonly System.Reflection.Emit.OpCode Stloc_S;
public static readonly System.Reflection.Emit.OpCode Stobj;
public static readonly System.Reflection.Emit.OpCode Stsfld;
public static readonly System.Reflection.Emit.OpCode Sub;
public static readonly System.Reflection.Emit.OpCode Sub_Ovf;
public static readonly System.Reflection.Emit.OpCode Sub_Ovf_Un;
public static readonly System.Reflection.Emit.OpCode Switch;
public static readonly System.Reflection.Emit.OpCode Tailcall;
public static readonly System.Reflection.Emit.OpCode Throw;
public static readonly System.Reflection.Emit.OpCode Unaligned;
public static readonly System.Reflection.Emit.OpCode Unbox;
public static readonly System.Reflection.Emit.OpCode Unbox_Any;
public static readonly System.Reflection.Emit.OpCode Volatile;
public static readonly System.Reflection.Emit.OpCode Xor;
public static bool TakesSingleByteArgument(System.Reflection.Emit.OpCode inst) { throw null; }
}
public enum OpCodeType
{
[Obsolete("This API has been deprecated. https://go.microsoft.com/fwlink/?linkid=14202")]
Annotation = 0,
Macro = 1,
Nternal = 2,
Objmodel = 3,
Prefix = 4,
Primitive = 5,
}
public enum OperandType
{
InlineBrTarget = 0,
InlineField = 1,
InlineI = 2,
InlineI8 = 3,
InlineMethod = 4,
InlineNone = 5,
[Obsolete("This API has been deprecated. https://go.microsoft.com/fwlink/?linkid=14202")]
InlinePhi = 6,
InlineR = 7,
InlineSig = 9,
InlineString = 10,
InlineSwitch = 11,
InlineTok = 12,
InlineType = 13,
InlineVar = 14,
ShortInlineBrTarget = 15,
ShortInlineI = 16,
ShortInlineR = 17,
ShortInlineVar = 18,
}
public enum PackingSize
{
Size1 = 1,
Size128 = 128,
Size16 = 16,
Size2 = 2,
Size32 = 32,
Size4 = 4,
Size64 = 64,
Size8 = 8,
Unspecified = 0,
}
public enum StackBehaviour
{
Pop0 = 0,
Pop1 = 1,
Pop1_pop1 = 2,
Popi = 3,
Popi_pop1 = 4,
Popi_popi = 5,
Popi_popi_popi = 7,
Popi_popi8 = 6,
Popi_popr4 = 8,
Popi_popr8 = 9,
Popref = 10,
Popref_pop1 = 11,
Popref_popi = 12,
Popref_popi_pop1 = 28,
Popref_popi_popi = 13,
Popref_popi_popi8 = 14,
Popref_popi_popr4 = 15,
Popref_popi_popr8 = 16,
Popref_popi_popref = 17,
Push0 = 18,
Push1 = 19,
Push1_push1 = 20,
Pushi = 21,
Pushi8 = 22,
Pushr4 = 23,
Pushr8 = 24,
Pushref = 25,
Varpop = 26,
Varpush = 27,
}
}
| |
// 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 gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCustomerServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCustomerRequestObject()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
GetCustomerRequest request = new GetCustomerRequest
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
gagvr::Customer expectedResponse = new gagvr::Customer
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
CallReportingSetting = new gagvr::CallReportingSetting(),
ConversionTrackingSetting = new gagvr::ConversionTrackingSetting(),
RemarketingSetting = new gagvr::RemarketingSetting(),
PayPerConversionEligibilityFailureReasons =
{
gagve::CustomerPayPerConversionEligibilityFailureReasonEnum.Types.CustomerPayPerConversionEligibilityFailureReason.HasCampaignWithSharedBudget,
},
Id = -6774108720365892680L,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
TimeZone = "time_zone73f23b20",
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
AutoTaggingEnabled = true,
HasPartnersBadge = true,
Manager = false,
TestAccount = true,
OptimizationScore = -4.7741588361660064E+17,
OptimizationScoreWeight = -89016329767571470,
};
mockGrpcClient.Setup(x => x.GetCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Customer response = client.GetCustomer(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerRequestObjectAsync()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
GetCustomerRequest request = new GetCustomerRequest
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
gagvr::Customer expectedResponse = new gagvr::Customer
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
CallReportingSetting = new gagvr::CallReportingSetting(),
ConversionTrackingSetting = new gagvr::ConversionTrackingSetting(),
RemarketingSetting = new gagvr::RemarketingSetting(),
PayPerConversionEligibilityFailureReasons =
{
gagve::CustomerPayPerConversionEligibilityFailureReasonEnum.Types.CustomerPayPerConversionEligibilityFailureReason.HasCampaignWithSharedBudget,
},
Id = -6774108720365892680L,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
TimeZone = "time_zone73f23b20",
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
AutoTaggingEnabled = true,
HasPartnersBadge = true,
Manager = false,
TestAccount = true,
OptimizationScore = -4.7741588361660064E+17,
OptimizationScoreWeight = -89016329767571470,
};
mockGrpcClient.Setup(x => x.GetCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Customer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Customer responseCallSettings = await client.GetCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Customer responseCancellationToken = await client.GetCustomerAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomer()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
GetCustomerRequest request = new GetCustomerRequest
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
gagvr::Customer expectedResponse = new gagvr::Customer
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
CallReportingSetting = new gagvr::CallReportingSetting(),
ConversionTrackingSetting = new gagvr::ConversionTrackingSetting(),
RemarketingSetting = new gagvr::RemarketingSetting(),
PayPerConversionEligibilityFailureReasons =
{
gagve::CustomerPayPerConversionEligibilityFailureReasonEnum.Types.CustomerPayPerConversionEligibilityFailureReason.HasCampaignWithSharedBudget,
},
Id = -6774108720365892680L,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
TimeZone = "time_zone73f23b20",
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
AutoTaggingEnabled = true,
HasPartnersBadge = true,
Manager = false,
TestAccount = true,
OptimizationScore = -4.7741588361660064E+17,
OptimizationScoreWeight = -89016329767571470,
};
mockGrpcClient.Setup(x => x.GetCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Customer response = client.GetCustomer(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerAsync()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
GetCustomerRequest request = new GetCustomerRequest
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
gagvr::Customer expectedResponse = new gagvr::Customer
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
CallReportingSetting = new gagvr::CallReportingSetting(),
ConversionTrackingSetting = new gagvr::ConversionTrackingSetting(),
RemarketingSetting = new gagvr::RemarketingSetting(),
PayPerConversionEligibilityFailureReasons =
{
gagve::CustomerPayPerConversionEligibilityFailureReasonEnum.Types.CustomerPayPerConversionEligibilityFailureReason.HasCampaignWithSharedBudget,
},
Id = -6774108720365892680L,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
TimeZone = "time_zone73f23b20",
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
AutoTaggingEnabled = true,
HasPartnersBadge = true,
Manager = false,
TestAccount = true,
OptimizationScore = -4.7741588361660064E+17,
OptimizationScoreWeight = -89016329767571470,
};
mockGrpcClient.Setup(x => x.GetCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Customer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Customer responseCallSettings = await client.GetCustomerAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Customer responseCancellationToken = await client.GetCustomerAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerResourceNames()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
GetCustomerRequest request = new GetCustomerRequest
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
gagvr::Customer expectedResponse = new gagvr::Customer
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
CallReportingSetting = new gagvr::CallReportingSetting(),
ConversionTrackingSetting = new gagvr::ConversionTrackingSetting(),
RemarketingSetting = new gagvr::RemarketingSetting(),
PayPerConversionEligibilityFailureReasons =
{
gagve::CustomerPayPerConversionEligibilityFailureReasonEnum.Types.CustomerPayPerConversionEligibilityFailureReason.HasCampaignWithSharedBudget,
},
Id = -6774108720365892680L,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
TimeZone = "time_zone73f23b20",
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
AutoTaggingEnabled = true,
HasPartnersBadge = true,
Manager = false,
TestAccount = true,
OptimizationScore = -4.7741588361660064E+17,
OptimizationScoreWeight = -89016329767571470,
};
mockGrpcClient.Setup(x => x.GetCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Customer response = client.GetCustomer(request.ResourceNameAsCustomerName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerResourceNamesAsync()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
GetCustomerRequest request = new GetCustomerRequest
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
};
gagvr::Customer expectedResponse = new gagvr::Customer
{
ResourceNameAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
CallReportingSetting = new gagvr::CallReportingSetting(),
ConversionTrackingSetting = new gagvr::ConversionTrackingSetting(),
RemarketingSetting = new gagvr::RemarketingSetting(),
PayPerConversionEligibilityFailureReasons =
{
gagve::CustomerPayPerConversionEligibilityFailureReasonEnum.Types.CustomerPayPerConversionEligibilityFailureReason.HasCampaignWithSharedBudget,
},
Id = -6774108720365892680L,
DescriptiveName = "descriptive_nameee37a0bc",
CurrencyCode = "currency_code7f81e352",
TimeZone = "time_zone73f23b20",
TrackingUrlTemplate = "tracking_url_template157f152a",
FinalUrlSuffix = "final_url_suffix046ed37a",
AutoTaggingEnabled = true,
HasPartnersBadge = true,
Manager = false,
TestAccount = true,
OptimizationScore = -4.7741588361660064E+17,
OptimizationScoreWeight = -89016329767571470,
};
mockGrpcClient.Setup(x => x.GetCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Customer>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
gagvr::Customer responseCallSettings = await client.GetCustomerAsync(request.ResourceNameAsCustomerName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::Customer responseCancellationToken = await client.GetCustomerAsync(request.ResourceNameAsCustomerName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomerRequestObject()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
MutateCustomerRequest request = new MutateCustomerRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new CustomerOperation(),
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCustomerResponse expectedResponse = new MutateCustomerResponse
{
Result = new MutateCustomerResult(),
};
mockGrpcClient.Setup(x => x.MutateCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerResponse response = client.MutateCustomer(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerRequestObjectAsync()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
MutateCustomerRequest request = new MutateCustomerRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new CustomerOperation(),
ValidateOnly = true,
ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly,
};
MutateCustomerResponse expectedResponse = new MutateCustomerResponse
{
Result = new MutateCustomerResult(),
};
mockGrpcClient.Setup(x => x.MutateCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerResponse responseCallSettings = await client.MutateCustomerAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerResponse responseCancellationToken = await client.MutateCustomerAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomer()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
MutateCustomerRequest request = new MutateCustomerRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new CustomerOperation(),
};
MutateCustomerResponse expectedResponse = new MutateCustomerResponse
{
Result = new MutateCustomerResult(),
};
mockGrpcClient.Setup(x => x.MutateCustomer(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerResponse response = client.MutateCustomer(request.CustomerId, request.Operation);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerAsync()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
MutateCustomerRequest request = new MutateCustomerRequest
{
CustomerId = "customer_id3b3724cb",
Operation = new CustomerOperation(),
};
MutateCustomerResponse expectedResponse = new MutateCustomerResponse
{
Result = new MutateCustomerResult(),
};
mockGrpcClient.Setup(x => x.MutateCustomerAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerResponse responseCallSettings = await client.MutateCustomerAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerResponse responseCancellationToken = await client.MutateCustomerAsync(request.CustomerId, request.Operation, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void ListAccessibleCustomersRequestObject()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
ListAccessibleCustomersRequest request = new ListAccessibleCustomersRequest { };
ListAccessibleCustomersResponse expectedResponse = new ListAccessibleCustomersResponse
{
ResourceNames =
{
"resource_namese9b75273",
},
};
mockGrpcClient.Setup(x => x.ListAccessibleCustomers(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
ListAccessibleCustomersResponse response = client.ListAccessibleCustomers(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task ListAccessibleCustomersRequestObjectAsync()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
ListAccessibleCustomersRequest request = new ListAccessibleCustomersRequest { };
ListAccessibleCustomersResponse expectedResponse = new ListAccessibleCustomersResponse
{
ResourceNames =
{
"resource_namese9b75273",
},
};
mockGrpcClient.Setup(x => x.ListAccessibleCustomersAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ListAccessibleCustomersResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
ListAccessibleCustomersResponse responseCallSettings = await client.ListAccessibleCustomersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
ListAccessibleCustomersResponse responseCancellationToken = await client.ListAccessibleCustomersAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void CreateCustomerClientRequestObject()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
CreateCustomerClientRequest request = new CreateCustomerClientRequest
{
CustomerId = "customer_id3b3724cb",
CustomerClient = new gagvr::Customer(),
AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified,
EmailAddress = "email_addressf3aae0b5",
ValidateOnly = true,
};
CreateCustomerClientResponse expectedResponse = new CreateCustomerClientResponse
{
ResourceName = "resource_name8cc2e687",
InvitationLink = "invitation_linkd5742ce9",
};
mockGrpcClient.Setup(x => x.CreateCustomerClient(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
CreateCustomerClientResponse response = client.CreateCustomerClient(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task CreateCustomerClientRequestObjectAsync()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
CreateCustomerClientRequest request = new CreateCustomerClientRequest
{
CustomerId = "customer_id3b3724cb",
CustomerClient = new gagvr::Customer(),
AccessRole = gagve::AccessRoleEnum.Types.AccessRole.Unspecified,
EmailAddress = "email_addressf3aae0b5",
ValidateOnly = true,
};
CreateCustomerClientResponse expectedResponse = new CreateCustomerClientResponse
{
ResourceName = "resource_name8cc2e687",
InvitationLink = "invitation_linkd5742ce9",
};
mockGrpcClient.Setup(x => x.CreateCustomerClientAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CreateCustomerClientResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
CreateCustomerClientResponse responseCallSettings = await client.CreateCustomerClientAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
CreateCustomerClientResponse responseCancellationToken = await client.CreateCustomerClientAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void CreateCustomerClient()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
CreateCustomerClientRequest request = new CreateCustomerClientRequest
{
CustomerId = "customer_id3b3724cb",
CustomerClient = new gagvr::Customer(),
};
CreateCustomerClientResponse expectedResponse = new CreateCustomerClientResponse
{
ResourceName = "resource_name8cc2e687",
InvitationLink = "invitation_linkd5742ce9",
};
mockGrpcClient.Setup(x => x.CreateCustomerClient(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
CreateCustomerClientResponse response = client.CreateCustomerClient(request.CustomerId, request.CustomerClient);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task CreateCustomerClientAsync()
{
moq::Mock<CustomerService.CustomerServiceClient> mockGrpcClient = new moq::Mock<CustomerService.CustomerServiceClient>(moq::MockBehavior.Strict);
CreateCustomerClientRequest request = new CreateCustomerClientRequest
{
CustomerId = "customer_id3b3724cb",
CustomerClient = new gagvr::Customer(),
};
CreateCustomerClientResponse expectedResponse = new CreateCustomerClientResponse
{
ResourceName = "resource_name8cc2e687",
InvitationLink = "invitation_linkd5742ce9",
};
mockGrpcClient.Setup(x => x.CreateCustomerClientAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CreateCustomerClientResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerServiceClient client = new CustomerServiceClientImpl(mockGrpcClient.Object, null);
CreateCustomerClientResponse responseCallSettings = await client.CreateCustomerClientAsync(request.CustomerId, request.CustomerClient, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
CreateCustomerClientResponse responseCancellationToken = await client.CreateCustomerClientAsync(request.CustomerId, request.CustomerClient, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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.Reflection;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
#if FEATURE_HOST_ASSEMBLY_RESOLVER
namespace System.Runtime.Loader
{
[System.Security.SecuritySafeCritical]
public abstract class AssemblyLoadContext
{
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool OverrideDefaultAssemblyLoadContextForCurrentDomain(IntPtr ptrNativeAssemblyLoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly);
#if FEATURE_MULTICOREJIT
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalSetProfileRoot(string directoryPath);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
#endif // FEATURE_MULTICOREJIT
protected AssemblyLoadContext()
{
// Initialize the ALC representing non-TPA LoadContext
InitializeLoadContext(false);
}
internal AssemblyLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the ALC representing TPA LoadContext
InitializeLoadContext(fRepresentsTPALoadContext);
}
[System.Security.SecuritySafeCritical]
void InitializeLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the VM side of AssemblyLoadContext if not already done.
GCHandle gchALC = GCHandle.Alloc(this);
IntPtr ptrALC = GCHandle.ToIntPtr(gchALC);
m_pNativeAssemblyLoadContext = InitializeAssemblyLoadContext(ptrALC, fRepresentsTPALoadContext);
// Initialize the resolve event handler to be null by default
Resolving = null;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly);
// These are helpers that can be used by AssemblyLoadContext derivations.
// They are used to load assemblies in DefaultContext.
public Assembly LoadFromAssemblyPath(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException("assemblyPath");
}
if (Path.IsRelative(assemblyPath))
{
throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath");
}
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath)
{
if (nativeImagePath == null)
{
throw new ArgumentNullException("nativeImagePath");
}
if (Path.IsRelative(nativeImagePath))
{
throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), "nativeImagePath");
}
// Check if the nativeImagePath has ".ni.dll" or ".ni.exe" extension
if (!(nativeImagePath.EndsWith(".ni.dll", StringComparison.InvariantCultureIgnoreCase) ||
nativeImagePath.EndsWith(".ni.exe", StringComparison.InvariantCultureIgnoreCase)))
{
throw new ArgumentException("nativeImagePath");
}
if (assemblyPath != null && Path.IsRelative(assemblyPath))
{
throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "assemblyPath");
}
// Basic validation has succeeded - lets try to load the NI image.
// Ask LoadFile to load the specified assembly in the DefaultContext
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromStream(Stream assembly)
{
return LoadFromStream(assembly, null);
}
public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
int iAssemblyStreamLength = (int)assembly.Length;
int iSymbolLength = 0;
// Allocate the byte[] to hold the assembly
byte[] arrAssembly = new byte[iAssemblyStreamLength];
// Copy the assembly to the byte array
assembly.Read(arrAssembly, 0, iAssemblyStreamLength);
// Get the symbol stream in byte[] if provided
byte[] arrSymbols = null;
if (assemblySymbols != null)
{
iSymbolLength = (int)assemblySymbols.Length;
arrSymbols = new byte[iSymbolLength];
assemblySymbols.Read(arrSymbols, 0, iSymbolLength);
}
RuntimeAssembly loadedAssembly = null;
unsafe
{
fixed(byte *ptrAssembly = arrAssembly, ptrSymbols = arrSymbols)
{
LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
}
}
return loadedAssembly;
}
// Custom AssemblyLoadContext implementations can override this
// method to perform custom processing and use one of the protected
// helpers above to load the assembly.
protected abstract Assembly Load(AssemblyName assemblyName);
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.LoadFromAssemblyName(assemblyName);
}
private Assembly GetFirstResolvedAssembly(AssemblyName assemblyName)
{
Assembly resolvedAssembly = null;
Func<AssemblyLoadContext, AssemblyName, Assembly> assemblyResolveHandler = Resolving;
if (assemblyResolveHandler != null)
{
// Loop through the event subscribers and return the first non-null Assembly instance
Delegate [] arrSubscribers = assemblyResolveHandler.GetInvocationList();
for(int i = 0; i < arrSubscribers.Length; i++)
{
resolvedAssembly = ((Func<AssemblyLoadContext, AssemblyName, Assembly>)arrSubscribers[i])(this, assemblyName);
if (resolvedAssembly != null)
{
break;
}
}
}
return resolvedAssembly;
}
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
// AssemblyName is mutable. Cache the expected name before anybody gets a chance to modify it.
string requestedSimpleName = assemblyName.Name;
Assembly assembly = Load(assemblyName);
if (assembly == null)
{
// Invoke the AssemblyResolve event callbacks if wired up
assembly = GetFirstResolvedAssembly(assemblyName);
}
if (assembly == null)
{
throw new FileNotFoundException(Environment.GetResourceString("IO.FileLoad"), requestedSimpleName);
}
// Get the name of the loaded assembly
string loadedSimpleName = null;
// Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly
// which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder),
// we need to check for RuntimeAssembly.
RuntimeAssembly rtLoadedAssembly = assembly as RuntimeAssembly;
if (rtLoadedAssembly != null)
{
loadedSimpleName = rtLoadedAssembly.GetSimpleName();
}
// The simple names should match at the very least
if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase)))
throw new InvalidOperationException(Environment.GetResourceString("Argument_CustomAssemblyLoadContextRequestedNameMismatch"));
return assembly;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InternalLoadUnmanagedDllFromPath(string unmanagedDllPath);
// This method provides a way for overriders of LoadUnmanagedDll() to load an unmanaged DLL from a specific path in a
// platform-independent way. The DLL is loaded with default load flags.
protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath)
{
if (unmanagedDllPath == null)
{
throw new ArgumentNullException("unmanagedDllPath");
}
if (unmanagedDllPath.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "unmanagedDllPath");
}
if (Path.IsRelative(unmanagedDllPath))
{
throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), "unmanagedDllPath");
}
return InternalLoadUnmanagedDllFromPath(unmanagedDllPath);
}
// Custom AssemblyLoadContext implementations can override this
// method to perform the load of unmanaged native dll
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName)
{
//defer to default coreclr policy of loading unmanaged dll
return IntPtr.Zero;
}
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static IntPtr ResolveUnmanagedDll(String unmanagedDllName, IntPtr gchManagedAssemblyLoadContext)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.LoadUnmanagedDll(unmanagedDllName);
}
public static AssemblyLoadContext Default
{
get
{
while (m_DefaultAssemblyLoadContext == null)
{
// Try to initialize the default assembly load context with apppath one if we are allowed to
if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain())
{
#pragma warning disable 0420
Interlocked.CompareExchange(ref m_DefaultAssemblyLoadContext, new AppPathAssemblyLoadContext(), null);
break;
#pragma warning restore 0420
}
// Otherwise, need to yield to other thread to finish the initialization
Thread.Yield();
}
return m_DefaultAssemblyLoadContext;
}
}
// This will be used to set the AssemblyLoadContext for DefaultContext, for the AppDomain,
// by a host. Once set, the runtime will invoke the LoadFromAssemblyName method against it to perform
// assembly loads for the DefaultContext.
//
// This method will throw if the Default AssemblyLoadContext is already set or the Binding model is already locked.
public static void InitializeDefaultContext(AssemblyLoadContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
// Try to override the default assembly load context
if (!AssemblyLoadContext.OverrideDefaultAssemblyLoadContextForCurrentDomain(context.m_pNativeAssemblyLoadContext))
{
throw new InvalidOperationException(Environment.GetResourceString("AppDomain_BindingModelIsLocked"));
}
// Update the managed side as well.
m_DefaultAssemblyLoadContext = context;
}
// This call opens and closes the file, but does not add the
// assembly to the domain.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern AssemblyName nGetFileInformation(String s);
// Helper to return AssemblyName corresponding to the path of an IL assembly
public static AssemblyName GetAssemblyName(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException("assemblyPath");
}
String fullPath = Path.GetFullPathInternal(assemblyPath);
return nGetFileInformation(fullPath);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly);
// Returns the load context in which the specified assembly has been loaded
public static AssemblyLoadContext GetLoadContext(Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException("assembly");
}
AssemblyLoadContext loadContextForAssembly = null;
IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly((RuntimeAssembly)assembly);
if (ptrAssemblyLoadContext == IntPtr.Zero)
{
// If the load context is returned null, then the assembly was bound using the TPA binder
// and we shall return reference to the active "Default" binder - which could be the TPA binder
// or an overridden CLRPrivBinderAssemblyLoadContext instance.
loadContextForAssembly = AssemblyLoadContext.Default;
}
else
{
loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target);
}
return loadContextForAssembly;
}
// Set the root directory path for profile optimization.
public void SetProfileOptimizationRoot(string directoryPath)
{
#if FEATURE_MULTICOREJIT
InternalSetProfileRoot(directoryPath);
#endif // FEATURE_MULTICOREJIT
}
// Start profile optimization for the specified profile name.
public void StartProfileOptimization(string profile)
{
#if FEATURE_MULTICOREJIT
InternalStartProfile(profile, m_pNativeAssemblyLoadContext);
#endif // FEATURE_MULTICOREJI
}
public event Func<AssemblyLoadContext, AssemblyName, Assembly> Resolving;
// Contains the reference to VM's representation of the AssemblyLoadContext
private IntPtr m_pNativeAssemblyLoadContext;
// Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is
// specified by the host. By having the field as a static, we are
// making it an AppDomain-wide field.
private static volatile AssemblyLoadContext m_DefaultAssemblyLoadContext;
}
[System.Security.SecuritySafeCritical]
class AppPathAssemblyLoadContext : AssemblyLoadContext
{
internal AppPathAssemblyLoadContext() : base(true)
{
}
[System.Security.SecuritySafeCritical]
protected override Assembly Load(AssemblyName assemblyName)
{
// We were loading an assembly into TPA ALC that was not found on TPA list. As a result we are here.
// Returning null will result in the AssemblyResolve event subscribers to be invoked to help resolve the assembly.
return null;
}
}
}
#endif // FEATURE_HOST_ASSEMBLY_RESOLVER
| |
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using AllReady.Areas.Admin.Controllers;
using AllReady.Areas.Admin.Features.Campaigns;
using AllReady.Areas.Admin.Models;
using AllReady.Models;
using AllReady.Services;
using AllReady.UnitTest.Extensions;
using MediatR;
using Microsoft.AspNet.Http;
using Moq;
using Xunit;
using Microsoft.AspNet.Mvc;
namespace AllReady.UnitTest.Areas.Admin.Controllers
{
public class CampaignAdminControllerTests
{
//delete this line when all unit tests using it have been completed
private readonly Task taskFromResultZero = Task.FromResult(0);
[Fact(Skip = "NotImplemented")]
public void IndexSendsCampaignListQueryWithCorrectDataWhenUserIsOrgAdmin()
{
}
[Fact(Skip = "NotImplemented")]
public void IndexSendsCampaignListQueryWithCorrectDataWhenUserIsNotOrgAdmin()
{
}
[Fact(Skip = "NotImplemented")]
public void IndexReturnsCorrectViewModel()
{
}
[Fact(Skip = "NotImplemented")]
public async Task DetailsSendsCampaignDetailQueryWithCorrectCampaignId()
{
//delete this line when starting work on this unit test
await taskFromResultZero;
}
[Fact]
public async Task DetailsReturnsHttpNotFoundResultWhenVieModelIsNull()
{
CampaignController controller;
MockMediatorCampaignDetailQuery(out controller);
Assert.IsType<HttpNotFoundResult>(await controller.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsHttpUnauthorizedResultIfUserIsNotOrgAdmin()
{
var controller = CampaignControllerWithDetailQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<HttpUnauthorizedResult>(await controller.Details(It.IsAny<int>()));
}
[Fact]
public async Task DetailsReturnsCorrectViewWhenViewModelIsNotNullAndUserIsOrgAdmin()
{
var controller = CampaignControllerWithDetailQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await controller.Details(It.IsAny<int>()));
}
[Fact(Skip = "NotImplemented")]
public async Task DetailsReturnsCorrectViewModelWhenViewModelIsNotNullAndUserIsOrgAdmin()
{
//delete this line when starting work on this unit test
await taskFromResultZero;
}
[Fact(Skip = "NotImplemented")]
public void CreateReturnsCorrectViewWithCorrectViewModel()
{
}
[Fact(Skip = "NotImplemented")]
public async Task EditGetSendsCampaignSummaryQueryWithCorrectCampaignId()
{
//delete this line when starting work on this unit test
await taskFromResultZero;
}
[Fact]
public async Task EditGetReturnsHttpNotFoundResultWhenViewModelIsNull()
{
CampaignController controller;
MockMediatorCampaignSummaryQuery(out controller);
Assert.IsType<HttpNotFoundResult>(await controller.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditGetReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<HttpUnauthorizedResult>(await controller.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditGetReturnsCorrectViewModelWhenUserIsOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await controller.Edit(It.IsAny<int>()));
}
[Fact]
public async Task EditPostReturnsBadRequestWhenCampaignIsNull()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var result = await controller.Edit(null, null);
Assert.IsType<BadRequestResult>(result);
}
[Fact]
public async Task EditPostReturnsHttpUnauthorizedResultWhenUserIsNotAnOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
var result = await controller.Edit(new CampaignSummaryModel { OrganizationId = It.IsAny<int>() }, null);
Assert.IsType<HttpUnauthorizedResult>(result);
}
[Fact]
public async Task EditPostRedirectsToCorrectActionWithCorrectRouteValuesWhenModelStateIsValid()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var result = await controller.Edit(new CampaignSummaryModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, null);
//TODO: test result for correct Action name and Route values
Assert.IsType<RedirectToActionResult>(result);
}
[Fact]
public async Task EditPostAddsErrorToModelStateWhenInvalidImageFormatIsSupplied()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
var file = FormFile("");
await controller.Edit(new CampaignSummaryModel { Name = "Foo", OrganizationId = It.IsAny<int>() }, file);
Assert.False(controller.ModelState.IsValid);
Assert.True(controller.ModelState.ContainsKey("ImageUrl"));
//TODO: test that the value associated with the key is correct
}
[Fact(Skip = "NotImplemented")]
public async Task EditPostReturnsCorrectViewModelWhenInvalidImageFormatIsSupplied()
{
//delete this line when starting work on this unit test
await taskFromResultZero;
}
[Fact]
public async Task EditPostUploadsImageToImageService()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
var mockImageService = new Mock<IImageService>();
mockImageService.Setup(mock => mock.UploadCampaignImageAsync(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<IFormFile>())).Returns(() => Task.FromResult("")).Verifiable();
var sut = new CampaignController(mockMediator.Object, mockImageService.Object);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
var file = FormFile("image/jpeg");
await sut.Edit(new CampaignSummaryModel { Name = "Foo", OrganizationId = organizationId, Id = campaignId}, file);
mockImageService.Verify(mock => mock.UploadCampaignImageAsync(
It.Is<int>(i => i == organizationId),
It.Is<int>(i => i == campaignId),
It.Is<IFormFile>(i => i == file)), Times.Once);
}
[Fact(Skip = "NotImplemented")]
public void EditPostHasHttpPostAttribute()
{
}
[Fact(Skip = "NotImplemented")]
public void EditPostHasHValidateAntiForgeryTokenttribute()
{
}
[Fact(Skip = "NotImplemented")]
public async Task DeleteSendsCampaignSummaryQueryWithCorrectCampaignId()
{
//delete this line when starting work on this unit test
await taskFromResultZero;
}
[Fact]
public async Task DeleteReturnsHttpNotFoundResultWhenCampaignIsNotFound()
{
CampaignController controller;
MockMediatorCampaignSummaryQuery(out controller);
Assert.IsType<HttpNotFoundResult>(await controller.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<HttpUnauthorizedResult>(await controller.Delete(It.IsAny<int>()));
}
[Fact]
public async Task DeleteReturnsCorrectViewWhenUserIsOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.OrgAdmin.ToString(), It.IsAny<int>());
Assert.IsType<ViewResult>(await controller.Delete(It.IsAny<int>()));
}
[Fact(Skip = "NotImplemented")]
public async Task DeleteReturnsCorrectViewModelWhenUserIsOrgAdmin()
{
//delete this line when starting work on this unit test
await taskFromResultZero;
}
public async Task DeleteConfirmedSendsCampaignSummaryQueryWithCorrectCampaignId()
{
const int campaignId = 1;
var mediator = new Mock<IMediator>();
var sut = new CampaignController(mediator.Object, null);
await sut.DeleteConfirmed(campaignId);
mediator.Verify(mock => mock.SendAsync(It.Is<CampaignSummaryQuery>(i => i.CampaignId == campaignId)), Times.Once);
}
[Fact]
public async Task DetailConfirmedReturnsHttpUnauthorizedResultWhenUserIsNotOrgAdmin()
{
var controller = CampaignControllerWithSummaryQuery(UserType.BasicUser.ToString(), It.IsAny<int>());
Assert.IsType<HttpUnauthorizedResult>(await controller.DeleteConfirmed(It.IsAny<int>()));
}
[Fact]
public async Task DetailConfirmedSendsDeleteCampaignCommandWithCorrectCampaignIdWhenUserIsOrgAdmin()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(new CampaignSummaryModel { OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
await sut.DeleteConfirmed(campaignId);
mockMediator.Verify(mock => mock.SendAsync(It.Is<DeleteCampaignCommand>(i => i.CampaignId == campaignId)), Times.Once);
}
[Fact]
public async Task DetailConfirmedRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsOrgAdmin()
{
const int organizationId = 1;
const int campaignId = 100;
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(new CampaignSummaryModel { OrganizationId = organizationId });
var sut = new CampaignController(mockMediator.Object, null);
sut.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, UserType.OrgAdmin.ToString()),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
var routeValues = new Dictionary<string, object> { ["area"] = "Admin" };
var result = await sut.DeleteConfirmed(campaignId) as RedirectToActionResult;
Assert.Equal(result.ActionName, nameof(CampaignController.Index));
Assert.Equal(result.RouteValues, routeValues);
}
[Fact(Skip = "NotImplemented")]
public void DeleteConfirmedHasHttpPostAttribute()
{
}
[Fact(Skip = "NotImplemented")]
public void DeleteConfirmedHasActionNameAttributeWithCorrectName()
{
}
[Fact(Skip = "NotImplemented")]
public void DeleteConfirmedHasValidateAntiForgeryTokenAttribute()
{
}
[Fact(Skip = "NotImplemented")]
public async Task LockUnlockReturnsHttpUnauthorizedResultWhenUserIsNotSiteAdmin()
{
//delete this line when starting work on this unit test
await taskFromResultZero;
}
[Fact(Skip = "NotImplemented")]
public async Task LockUnlockSendsLockUnlockCampaignCommandWithCorrectCampaignIdWhenUserIsSiteAdmin()
{
//delete this line when starting work on this unit test
await taskFromResultZero;
}
[Fact(Skip = "NotImplemented")]
public async Task LockUnlockRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsSiteAdmin()
{
//delete this line when starting work on this unit test
await taskFromResultZero;
}
[Fact(Skip = "NotImplemented")]
public void LockUnlockHasHttpPostAttribute()
{
}
[Fact(Skip = "NotImplemented")]
public void LockUnlockdHasValidateAntiForgeryTokenAttribute()
{
}
#region Helper Methods
private static Mock<IMediator> MockMediatorCampaignDetailQuery(out CampaignController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(null).Verifiable();
var mockImageService = new Mock<IImageService>();
controller = new CampaignController(mockMediator.Object, mockImageService.Object);
return mockMediator;
}
private static Mock<IMediator> MockMediatorCampaignSummaryQuery(out CampaignController controller)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>())).ReturnsAsync(null).Verifiable();
var mockImageService = new Mock<IImageService>();
controller = new CampaignController(mockMediator.Object, mockImageService.Object);
return mockMediator;
}
private static CampaignController CampaignControllerWithDetailQuery(string userType, int organizationId)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignDetailQuery>())).ReturnsAsync(new CampaignDetailModel { OrganizationId = organizationId }).Verifiable();
var mockImageService = new Mock<IImageService>();
var controller = new CampaignController(mockMediator.Object, mockImageService.Object);
controller.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, userType),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
return controller;
}
private static CampaignController CampaignControllerWithSummaryQuery(string userType, int organizationId)
{
var mockMediator = new Mock<IMediator>();
mockMediator.Setup(mock => mock.SendAsync(It.IsAny<CampaignSummaryQuery>()))
.ReturnsAsync(new CampaignSummaryModel { OrganizationId = organizationId, Location = new LocationEditModel() }).Verifiable();
var mockImageService = new Mock<IImageService>();
var controller = new CampaignController(mockMediator.Object, mockImageService.Object);
controller.SetClaims(new List<Claim>
{
new Claim(AllReady.Security.ClaimTypes.UserType, userType),
new Claim(AllReady.Security.ClaimTypes.Organization, organizationId.ToString())
});
return controller;
}
private static IFormFile FormFile(string fileType)
{
var mockFormFile = new Mock<IFormFile>();
mockFormFile.Setup(mock => mock.ContentType).Returns(fileType);
return mockFormFile.Object;
}
#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.Collections.Generic;
using System.Diagnostics;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
namespace System.Data.ProviderBase
{
internal abstract class DbConnectionFactory
{
private Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> _connectionPoolGroups;
private readonly List<DbConnectionPool> _poolsToRelease;
private readonly List<DbConnectionPoolGroup> _poolGroupsToRelease;
private readonly Timer _pruningTimer;
private const int PruningDueTime = 4 * 60 * 1000; // 4 minutes
private const int PruningPeriod = 30 * 1000; // thirty seconds
// s_pendingOpenNonPooled is an array of tasks used to throttle creation of non-pooled connections to
// a maximum of Environment.ProcessorCount at a time.
private static uint s_pendingOpenNonPooledNext = 0;
private static Task<DbConnectionInternal>[] s_pendingOpenNonPooled = new Task<DbConnectionInternal>[Environment.ProcessorCount];
private static Task<DbConnectionInternal> s_completedTask;
protected DbConnectionFactory()
{
_connectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>();
_poolsToRelease = new List<DbConnectionPool>();
_poolGroupsToRelease = new List<DbConnectionPoolGroup>();
_pruningTimer = CreatePruningTimer();
}
abstract public DbProviderFactory ProviderFactory
{
get;
}
public void ClearAllPools()
{
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
DbConnectionPoolGroup poolGroup = entry.Value;
if (null != poolGroup)
{
poolGroup.Clear();
}
}
}
public void ClearPool(DbConnection connection)
{
ADP.CheckArgumentNull(connection, nameof(connection));
DbConnectionPoolGroup poolGroup = GetConnectionPoolGroup(connection);
if (null != poolGroup)
{
poolGroup.Clear();
}
}
public void ClearPool(DbConnectionPoolKey key)
{
Debug.Assert(key != null, "key cannot be null");
ADP.CheckArgumentNull(key.ConnectionString, nameof(key) + "." + nameof(key.ConnectionString));
DbConnectionPoolGroup poolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (connectionPoolGroups.TryGetValue(key, out poolGroup))
{
poolGroup.Clear();
}
}
internal virtual DbConnectionPoolProviderInfo CreateConnectionPoolProviderInfo(DbConnectionOptions connectionOptions)
{
return null;
}
internal DbConnectionInternal CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
{
Debug.Assert(null != owningConnection, "null owningConnection?");
Debug.Assert(null != poolGroup, "null poolGroup?");
DbConnectionOptions connectionOptions = poolGroup.ConnectionOptions;
DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = poolGroup.ProviderInfo;
DbConnectionPoolKey poolKey = poolGroup.PoolKey;
DbConnectionInternal newConnection = CreateConnection(connectionOptions, poolKey, poolGroupProviderInfo, null, owningConnection, userOptions);
if (null != newConnection)
{
newConnection.MakeNonPooledObject(owningConnection);
}
return newConnection;
}
internal DbConnectionInternal CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
{
Debug.Assert(null != pool, "null pool?");
DbConnectionPoolGroupProviderInfo poolGroupProviderInfo = pool.PoolGroup.ProviderInfo;
DbConnectionInternal newConnection = CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningObject, userOptions);
if (null != newConnection)
{
newConnection.MakePooledConnection(pool);
}
return newConnection;
}
virtual internal DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupProviderInfo(DbConnectionOptions connectionOptions)
{
return null;
}
private Timer CreatePruningTimer() =>
ADP.UnsafeCreateTimer(
new TimerCallback(PruneConnectionPoolGroups),
null,
PruningDueTime,
PruningPeriod);
protected DbConnectionOptions FindConnectionOptions(DbConnectionPoolKey key)
{
Debug.Assert(key != null, "key cannot be null");
if (!string.IsNullOrEmpty(key.ConnectionString))
{
DbConnectionPoolGroup connectionPoolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
{
return connectionPoolGroup.ConnectionOptions;
}
}
return null;
}
private static Task<DbConnectionInternal> GetCompletedTask()
{
Debug.Assert(Monitor.IsEntered(s_pendingOpenNonPooled), $"Expected {nameof(s_pendingOpenNonPooled)} lock to be held.");
return s_completedTask ?? (s_completedTask = Task.FromResult<DbConnectionInternal>(null));
}
internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
{
Debug.Assert(null != owningConnection, "null owningConnection?");
DbConnectionPoolGroup poolGroup;
DbConnectionPool connectionPool;
connection = null;
// Work around race condition with clearing the pool between GetConnectionPool obtaining pool
// and GetConnection on the pool checking the pool state. Clearing the pool in this window
// will switch the pool into the ShuttingDown state, and GetConnection will return null.
// There is probably a better solution involving locking the pool/group, but that entails a major
// re-design of the connection pooling synchronization, so is postponed for now.
// Use retriesLeft to prevent CPU spikes with incremental sleep
// start with one msec, double the time every retry
// max time is: 1 + 2 + 4 + ... + 2^(retries-1) == 2^retries -1 == 1023ms (for 10 retries)
int retriesLeft = 10;
int timeBetweenRetriesMilliseconds = 1;
do
{
poolGroup = GetConnectionPoolGroup(owningConnection);
// Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread.
connectionPool = GetConnectionPool(owningConnection, poolGroup);
if (null == connectionPool)
{
// If GetConnectionPool returns null, we can be certain that
// this connection should not be pooled via DbConnectionPool
// or have a disabled pool entry.
poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled
if (retry != null)
{
Task<DbConnectionInternal> newTask;
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
lock (s_pendingOpenNonPooled)
{
// look for an available task slot (completed or empty)
int idx;
for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++)
{
Task task = s_pendingOpenNonPooled[idx];
if (task == null)
{
s_pendingOpenNonPooled[idx] = GetCompletedTask();
break;
}
else if (task.IsCompleted)
{
break;
}
}
// if didn't find one, pick the next one in round-robin fashion
if (idx == s_pendingOpenNonPooled.Length)
{
idx = (int)(s_pendingOpenNonPooledNext % s_pendingOpenNonPooled.Length);
unchecked
{
s_pendingOpenNonPooledNext++;
}
}
// now that we have an antecedent task, schedule our work when it is completed.
// If it is a new slot or a completed task, this continuation will start right away.
newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) =>
{
Transactions.Transaction originalTransaction = ADP.GetCurrentTransaction();
try
{
ADP.SetCurrentTransaction(retry.Task.AsyncState as Transactions.Transaction);
var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open))
{
oldConnection.PrepareForReplaceConnection();
oldConnection.Dispose();
}
return newConnection;
}
finally
{
ADP.SetCurrentTransaction(originalTransaction);
}
}, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
// Place this new task in the slot so any future work will be queued behind it
s_pendingOpenNonPooled[idx] = newTask;
}
// Set up the timeout (if needed)
if (owningConnection.ConnectionTimeout > 0)
{
int connectionTimeoutMilliseconds = owningConnection.ConnectionTimeout * 1000;
cancellationTokenSource.CancelAfter(connectionTimeoutMilliseconds);
}
// once the task is done, propagate the final results to the original caller
newTask.ContinueWith((task) =>
{
cancellationTokenSource.Dispose();
if (task.IsCanceled)
{
retry.TrySetException(ADP.ExceptionWithStackTrace(ADP.NonPooledOpenTimeout()));
}
else if (task.IsFaulted)
{
retry.TrySetException(task.Exception.InnerException);
}
else
{
if (!retry.TrySetResult(task.Result))
{
// The outer TaskCompletionSource was already completed
// Which means that we don't know if someone has messed with the outer connection in the middle of creation
// So the best thing to do now is to destroy the newly created connection
task.Result.DoomThisConnection();
task.Result.Dispose();
}
}
}, TaskScheduler.Default);
return false;
}
connection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
}
else
{
if (((SqlClient.SqlConnection)owningConnection).ForceNewConnection)
{
Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection");
connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection);
}
else
{
if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection))
{
return false;
}
}
if (connection == null)
{
// connection creation failed on semaphore waiting or if max pool reached
if (connectionPool.IsRunning)
{
// If GetConnection failed while the pool is running, the pool timeout occurred.
throw ADP.PooledOpenTimeout();
}
else
{
// We've hit the race condition, where the pool was shut down after we got it from the group.
// Yield time slice to allow shut down activities to complete and a new, running pool to be instantiated
// before retrying.
Threading.Thread.Sleep(timeBetweenRetriesMilliseconds);
timeBetweenRetriesMilliseconds *= 2; // double the wait time for next iteration
}
}
}
} while (connection == null && retriesLeft-- > 0);
if (connection == null)
{
// exhausted all retries or timed out - give up
throw ADP.PooledOpenTimeout();
}
return true;
}
private DbConnectionPool GetConnectionPool(DbConnection owningObject, DbConnectionPoolGroup connectionPoolGroup)
{
// if poolgroup is disabled, it will be replaced with a new entry
Debug.Assert(null != owningObject, "null owningObject?");
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?");
// It is possible that while the outer connection object has
// been sitting around in a closed and unused state in some long
// running app, the pruner may have come along and remove this
// the pool entry from the master list. If we were to use a
// pool entry in this state, we would create "unmanaged" pools,
// which would be bad. To avoid this problem, we automagically
// re-create the pool entry whenever it's disabled.
// however, don't rebuild connectionOptions if no pooling is involved - let new connections do that work
if (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions))
{
// reusing existing pool option in case user originally used SetConnectionPoolOptions
DbConnectionPoolGroupOptions poolOptions = connectionPoolGroup.PoolGroupOptions;
// get the string to hash on again
DbConnectionOptions connectionOptions = connectionPoolGroup.ConnectionOptions;
Debug.Assert(null != connectionOptions, "prevent expansion of connectionString");
connectionPoolGroup = GetConnectionPoolGroup(connectionPoolGroup.PoolKey, poolOptions, ref connectionOptions);
Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup?");
SetConnectionPoolGroup(owningObject, connectionPoolGroup);
}
DbConnectionPool connectionPool = connectionPoolGroup.GetConnectionPool(this);
return connectionPool;
}
internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions)
{
if (string.IsNullOrEmpty(key.ConnectionString))
{
return (DbConnectionPoolGroup)null;
}
DbConnectionPoolGroup connectionPoolGroup;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup) || (connectionPoolGroup.IsDisabled && (null != connectionPoolGroup.PoolGroupOptions)))
{
// If we can't find an entry for the connection string in
// our collection of pool entries, then we need to create a
// new pool entry and add it to our collection.
DbConnectionOptions connectionOptions = CreateConnectionOptions(key.ConnectionString, userConnectionOptions);
if (null == connectionOptions)
{
throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing);
}
if (null == userConnectionOptions)
{ // we only allow one expansion on the connection string
userConnectionOptions = connectionOptions;
}
// We don't support connection pooling on Win9x
if (null == poolOptions)
{
if (null != connectionPoolGroup)
{
// reusing existing pool option in case user originally used SetConnectionPoolOptions
poolOptions = connectionPoolGroup.PoolGroupOptions;
}
else
{
// Note: may return null for non-pooled connections
poolOptions = CreateConnectionPoolGroupOptions(connectionOptions);
}
}
lock (this)
{
connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
{
DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions);
newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions);
// build new dictionary with space for new connection string
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(1 + connectionPoolGroups.Count);
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
// lock prevents race condition with PruneConnectionPoolGroups
newConnectionPoolGroups.Add(key, newConnectionPoolGroup);
connectionPoolGroup = newConnectionPoolGroup;
_connectionPoolGroups = newConnectionPoolGroups;
}
else
{
Debug.Assert(!connectionPoolGroup.IsDisabled, "Disabled pool entry discovered");
}
}
Debug.Assert(null != connectionPoolGroup, "how did we not create a pool entry?");
Debug.Assert(null != userConnectionOptions, "how did we not have user connection options?");
}
else if (null == userConnectionOptions)
{
userConnectionOptions = connectionPoolGroup.ConnectionOptions;
}
return connectionPoolGroup;
}
private void PruneConnectionPoolGroups(object state)
{
// First, walk the pool release list and attempt to clear each
// pool, when the pool is finally empty, we dispose of it. If the
// pool isn't empty, it's because there are active connections or
// distributed transactions that need it.
lock (_poolsToRelease)
{
if (0 != _poolsToRelease.Count)
{
DbConnectionPool[] poolsToRelease = _poolsToRelease.ToArray();
foreach (DbConnectionPool pool in poolsToRelease)
{
if (null != pool)
{
pool.Clear();
if (0 == pool.Count)
{
_poolsToRelease.Remove(pool);
}
}
}
}
}
// Next, walk the pool entry release list and dispose of each
// pool entry when it is finally empty. If the pool entry isn't
// empty, it's because there are active pools that need it.
lock (_poolGroupsToRelease)
{
if (0 != _poolGroupsToRelease.Count)
{
DbConnectionPoolGroup[] poolGroupsToRelease = _poolGroupsToRelease.ToArray();
foreach (DbConnectionPoolGroup poolGroup in poolGroupsToRelease)
{
if (null != poolGroup)
{
int poolsLeft = poolGroup.Clear(); // may add entries to _poolsToRelease
if (0 == poolsLeft)
{
_poolGroupsToRelease.Remove(poolGroup);
}
}
}
}
}
// Finally, we walk through the collection of connection pool entries
// and prune each one. This will cause any empty pools to be put
// into the release list.
lock (this)
{
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> connectionPoolGroups = _connectionPoolGroups;
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(connectionPoolGroups.Count);
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
{
if (null != entry.Value)
{
Debug.Assert(!entry.Value.IsDisabled, "Disabled pool entry discovered");
// entries start active and go idle during prune if all pools are gone
// move idle entries from last prune pass to a queue for pending release
// otherwise process entry which may move it from active to idle
if (entry.Value.Prune())
{ // may add entries to _poolsToRelease
QueuePoolGroupForRelease(entry.Value);
}
else
{
newConnectionPoolGroups.Add(entry.Key, entry.Value);
}
}
}
_connectionPoolGroups = newConnectionPoolGroups;
}
}
internal void QueuePoolForRelease(DbConnectionPool pool, bool clearing)
{
// Queue the pool up for release -- we'll clear it out and dispose
// of it as the last part of the pruning timer callback so we don't
// do it with the pool entry or the pool collection locked.
Debug.Assert(null != pool, "null pool?");
// set the pool to the shutdown state to force all active
// connections to be automatically disposed when they
// are returned to the pool
pool.Shutdown();
lock (_poolsToRelease)
{
if (clearing)
{
pool.Clear();
}
_poolsToRelease.Add(pool);
}
}
internal void QueuePoolGroupForRelease(DbConnectionPoolGroup poolGroup)
{
Debug.Assert(null != poolGroup, "null poolGroup?");
lock (_poolGroupsToRelease)
{
_poolGroupsToRelease.Add(poolGroup);
}
}
virtual protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
{
return CreateConnection(options, poolKey, poolGroupProviderInfo, pool, owningConnection);
}
internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPoolGroup, DbConnectionInternal internalConnection)
{
Debug.Assert(connectionPoolGroup != null, "connectionPoolGroup may not be null.");
// get the matadatafactory from the pool entry. If it does not already have one
// create one and save it on the pool entry
DbMetaDataFactory metaDataFactory = connectionPoolGroup.MetaDataFactory;
// consider serializing this so we don't construct multiple metadata factories
// if two threads happen to hit this at the same time. One will be GC'd
if (metaDataFactory == null)
{
bool allowCache = false;
metaDataFactory = CreateMetaDataFactory(internalConnection, out allowCache);
if (allowCache)
{
connectionPoolGroup.MetaDataFactory = metaDataFactory;
}
}
return metaDataFactory;
}
protected virtual DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory)
{
// providers that support GetSchema must override this with a method that creates a meta data
// factory appropriate for them.
cacheMetaDataFactory = false;
throw ADP.NotSupported();
}
abstract protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection);
abstract protected DbConnectionOptions CreateConnectionOptions(string connectionString, DbConnectionOptions previous);
abstract protected DbConnectionPoolGroupOptions CreateConnectionPoolGroupOptions(DbConnectionOptions options);
abstract internal DbConnectionPoolGroup GetConnectionPoolGroup(DbConnection connection);
abstract internal DbConnectionInternal GetInnerConnection(DbConnection connection);
abstract internal void PermissionDemand(DbConnection outerConnection);
abstract internal void SetConnectionPoolGroup(DbConnection outerConnection, DbConnectionPoolGroup poolGroup);
abstract internal void SetInnerConnectionEvent(DbConnection owningObject, DbConnectionInternal to);
abstract internal bool SetInnerConnectionFrom(DbConnection owningObject, DbConnectionInternal to, DbConnectionInternal from);
abstract internal void SetInnerConnectionTo(DbConnection owningObject, DbConnectionInternal to);
}
}
| |
using Line.Messaging;
using Line.Messaging.Webhooks;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
namespace FunctionAppSample
{
class FlexMessageSampleApp : WebhookApplication
{
private LineMessagingClient MessagingClient { get; }
private TraceWriter Log { get; }
public FlexMessageSampleApp(LineMessagingClient lineMessagingClient, TraceWriter log)
{
MessagingClient = lineMessagingClient;
Log = log;
}
private static readonly string FlexJson =
@"{
""type"": ""flex"",
""contents"": {
""type"": ""bubble"",
""direction"": ""ltr"",
""hero"": {
""type"": ""image"",
""url"": ""https://scdn.line-apps.com/n/channel_devcenter/img/fx/01_1_cafe.png"",
""size"": ""full"",
""aspectRatio"": ""20:13"",
""aspectMode"": ""cover"",
""action"": {
""type"": ""uri"",
""uri"": ""http://linecorp.com/""
}
},
""body"": {
""type"": ""box"",
""layout"": ""vertical"",
""contents"": [
{
""type"": ""text"",
""text"": ""Broun Cafe"",
""size"": ""xl"",
""weight"": ""bold""
},
{
""type"": ""box"",
""layout"": ""baseline"",
""contents"": [
{
""type"": ""icon"",
""url"": ""https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"",
""size"": ""sm""
},
{
""type"": ""icon"",
""url"": ""https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"",
""size"": ""sm""
},
{
""type"": ""icon"",
""url"": ""https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"",
""size"": ""sm""
},
{
""type"": ""icon"",
""url"": ""https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"",
""size"": ""sm""
},
{
""type"": ""icon"",
""url"": ""https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gray_star_28.png"",
""size"": ""sm""
},
{
""type"": ""text"",
""text"": ""4.0"",
""flex"": 0,
""margin"": ""md"",
""size"": ""sm"",
""color"": ""#999999""
}
],
""margin"": ""md""
},
{
""type"": ""box"",
""layout"": ""vertical"",
""contents"": [
{
""type"": ""box"",
""layout"": ""baseline"",
""contents"": [
{
""type"": ""text"",
""text"": ""Place"",
""flex"": 1,
""size"": ""sm"",
""color"": ""#aaaaaa""
},
{
""type"": ""text"",
""text"": ""Miraina Tower, 4-1-6 Shinjuku, Tokyo"",
""flex"": 5,
""size"": ""sm"",
""wrap"": true,
""color"": ""#666666""
}
],
""spacing"": ""sm""
}
],
""spacing"": ""sm"",
""margin"": ""lg""
},
{
""type"": ""box"",
""layout"": ""baseline"",
""contents"": [
{
""type"": ""text"",
""text"": ""Time"",
""flex"": 1,
""size"": ""sm"",
""color"": ""#aaaaaa""
},
{
""type"": ""text"",
""text"": ""10:00 - 23:00"",
""flex"": 5,
""size"": ""sm"",
""wrap"": true,
""color"": ""#666666""
}
],
""spacing"": ""sm""
}
]
},
""footer"": {
""type"": ""box"",
""layout"": ""vertical"",
""contents"": [
{
""type"": ""button"",
""action"": {
""type"": ""uri"",
""label"": ""Call"",
""uri"": ""https://linecorp.com""
},
""height"": ""sm"",
""style"": ""link""
},
{
""type"": ""button"",
""action"": {
""type"": ""uri"",
""label"": ""WEBSITE"",
""uri"": ""https://linecorp.com""
},
""height"": ""sm"",
""style"": ""link""
},
{
""type"": ""spacer"",
""size"": ""sm""
}
],
""flex"": 0,
""spacing"": ""sm""
}
},
""altText"": ""Restrant""
}";
private static readonly string TextMessageJson = "{ \"type\" : \"text\", \"text\" : \"I Sent a flex message with json string.\" }";
protected override async Task OnMessageAsync(MessageEvent ev)
{
if (!(ev.Message is TextEventMessage msg)) { return; }
if (msg.Text == "s")
{
await ReplyFlexWithJson(ev);
}
else if (msg.Text == "e")
{
await ReplyFlexWithExtensions(ev);
}
else
{
await ReplyFlexWithObjectInitializer(ev);
}
}
private async Task ReplyFlexWithJson(MessageEvent ev)
{
await MessagingClient.ReplyMessageWithJsonAsync(ev.ReplyToken, FlexJson, TextMessageJson);
}
private async Task ReplyFlexWithExtensions(MessageEvent ev)
{
var restrant = CreateRestrantWithObjectInitializer();
var news = CreateNewsWithExtensions();
var receipt = CreateReceiptWithExtensions();
var bubble = FlexMessage.CreateBubbleMessage("Bubble Message")
.SetBubbleContainer(restrant);
var carousel = FlexMessage.CreateCarouselMessage("Carousel Message")
.AddBubbleContainer(restrant)
.AddBubbleContainer(news)
.AddBubbleContainer(receipt)
.SetQuickReply(new QuickReply(new[]
{
new QuickReplyButtonObject(new CameraTemplateAction("Camera")),
new QuickReplyButtonObject(new LocationTemplateAction("Location"))
}));
await MessagingClient.ReplyMessageAsync(ev.ReplyToken, new FlexMessage[] { bubble, carousel });
}
private async Task ReplyFlexWithObjectInitializer(MessageEvent ev)
{
var restrant = CreateRestrantWithObjectInitializer();
var news = CreateNewsWithExtensions();
var receipt = CreateReceiptWithExtensions();
var bubble = new FlexMessage("Bubble Message")
{
Contents = restrant
};
var carousel = new FlexMessage("Carousel Message")
{
Contents = new CarouselContainer()
{
Contents = new BubbleContainer[]
{
restrant,
news,
receipt
}
},
QuickReply = new QuickReply(new[]
{
new QuickReplyButtonObject(new CameraRollTemplateAction("CameraRoll")),
new QuickReplyButtonObject(new CameraTemplateAction("Camera")),
new QuickReplyButtonObject(new LocationTemplateAction("Location"))
})
};
await MessagingClient.ReplyMessageAsync(ev.ReplyToken, new FlexMessage[] { bubble, carousel });
}
private static BubbleContainer CreateNewsWithExtensions()
{
return new BubbleContainer()
.SetHeader(BoxLayout.Horizontal)
.AddHeaderContents(new TextComponent("NEWS DIGEST") { Weight = Weight.Bold, Color = "#aaaaaa", Size = ComponentSize.Sm })
.SetHero(imageUrl: "https://scdn.line-apps.com/n/channel_devcenter/img/fx/01_4_news.png",
size: ComponentSize.Full, aspectRatio: AspectRatio._20_13, aspectMode: AspectMode.Cover)
.SetHeroAction(new UriTemplateAction(null, "http://linecorp.com/"))
.SetBody(boxLayout: BoxLayout.Horizontal, spacing: Spacing.Md)
.AddBodyContents(new BoxComponent(BoxLayout.Vertical) { Flex = 1 }
.AddContents(new ImageComponent("https://scdn.line-apps.com/n/channel_devcenter/img/fx/02_1_news_thumbnail_1.png")
{ AspectMode = AspectMode.Cover, AspectRatio = AspectRatio._4_3, Size = ComponentSize.Sm, Gravity = Gravity.Bottom })
.AddContents(new ImageComponent("https://scdn.line-apps.com/n/channel_devcenter/img/fx/02_1_news_thumbnail_2.png")
{ AspectMode = AspectMode.Cover, AspectRatio = AspectRatio._4_3, Size = ComponentSize.Sm, Gravity = Gravity.Bottom }))
.AddBodyContents(new BoxComponent(BoxLayout.Vertical) { Flex = 2 }
.AddContents(new TextComponent("7 Things to Know for Today") { Gravity = Gravity.Top, Size = ComponentSize.Xs, Flex = 1 })
.AddContents(new SeparatorComponent())
.AddContents(new TextComponent("Hay fever goes wild") { Gravity = Gravity.Center, Size = ComponentSize.Xs, Flex = 2 })
.AddContents(new SeparatorComponent())
.AddContents(new TextComponent("LINE Pay Begins Barcode Payment Service") { Gravity = Gravity.Center, Size = ComponentSize.Xs, Flex = 2 })
.AddContents(new SeparatorComponent())
.AddContents(new TextComponent("LINE Adds LINE Wallet") { Gravity = Gravity.Bottom, Size = ComponentSize.Xs, Flex = 1 }))
.SetFooter(BoxLayout.Horizontal)
.AddFooterContents(new ButtonComponent() { Action = new UriTemplateAction("More", "https://linecorp.com") });
}
private static BubbleContainer CreateReceiptWithExtensions()
{
return new BubbleContainer()
.SetFooterStyle(new BlockStyle() { Separator = true })
.SetBody(BoxLayout.Vertical)
.AddBodyContents(new TextComponent("RECEIPT") { Weight = Weight.Bold, Color = "#1DB446", Size = ComponentSize.Sm })
.AddBodyContents(new TextComponent("Brown Store") { Weight = Weight.Bold, Size = ComponentSize.Xxl, Margin = Spacing.Md })
.AddBodyContents(new TextComponent("Miraina Tower, 4 - 1 - 6 Shinjuku, Tokyo") { Size = ComponentSize.Xs, Color = "#aaaaaa", Wrap = true })
.AddBodyContents(new SeparatorComponent() { Margin = Spacing.Xxl })
.AddBodyContents(new BoxComponent(BoxLayout.Vertical) { Margin = Spacing.Xxl, Spacing = Spacing.Sm }
.AddContents(new BoxComponent(BoxLayout.Horizontal)
.AddContents(new TextComponent("Energy Drink") { Size = ComponentSize.Sm, Color = "#555555", Flex = 0 })
.AddContents(new TextComponent("$2.99") { Size = ComponentSize.Sm, Color = "#111111", Align = Align.End }))
.AddContents(new BoxComponent(BoxLayout.Horizontal)
.AddContents(new TextComponent("Chewing Gum") { Size = ComponentSize.Sm, Color = "#555555", Flex = 0 })
.AddContents(new TextComponent("$0.99") { Size = ComponentSize.Sm, Color = "#111111", Align = Align.End }))
.AddContents(new BoxComponent(BoxLayout.Horizontal)
.AddContents(new TextComponent("Bottled Water") { Size = ComponentSize.Sm, Color = "#555555", Flex = 0 })
.AddContents(new TextComponent("$3.33") { Size = ComponentSize.Sm, Color = "#111111", Align = Align.End }))
.AddContents(new SeparatorComponent() { Margin = Spacing.Xxl })
.AddContents(new BoxComponent(BoxLayout.Horizontal)
.AddContents(new TextComponent("ITEMS") { Size = ComponentSize.Sm, Color = "#555555", Flex = 0 })
.AddContents(new TextComponent("3") { Size = ComponentSize.Sm, Color = "#111111", Align = Align.End }))
.AddContents(new BoxComponent(BoxLayout.Horizontal)
.AddContents(new TextComponent("TOTAL") { Size = ComponentSize.Sm, Color = "#555555", Flex = 0 })
.AddContents(new TextComponent("$7.31") { Size = ComponentSize.Sm, Color = "#111111", Align = Align.End }))
.AddContents(new BoxComponent(BoxLayout.Horizontal)
.AddContents(new TextComponent("CASH") { Size = ComponentSize.Sm, Color = "#555555", Flex = 0 })
.AddContents(new TextComponent("$8.0") { Size = ComponentSize.Sm, Color = "#111111", Align = Align.End }))
.AddContents(new BoxComponent(BoxLayout.Horizontal)
.AddContents(new TextComponent("CHANGE") { Size = ComponentSize.Sm, Color = "#555555", Flex = 0 })
.AddContents(new TextComponent("$0.69") { Size = ComponentSize.Sm, Color = "#111111", Align = Align.End })))
.AddBodyContents(new SeparatorComponent() { Margin = Spacing.Xl })
.AddBodyContents(new BoxComponent(BoxLayout.Horizontal) { Margin = Spacing.Md }
.AddContents(new TextComponent("PAYMENT ID") { Size = ComponentSize.Xs, Color = "#aaaaaa", Flex = 0 })
.AddContents(new TextComponent("#743289384279") { Size = ComponentSize.Xs, Color = "#aaaaaa", Align = Align.End }));
}
private static BubbleContainer CreateRestrantWithObjectInitializer()
{
return new BubbleContainer()
{
Hero = new ImageComponent()
{
Url = "https://scdn.line-apps.com/n/channel_devcenter/img/fx/01_1_cafe.png",
Size = ComponentSize.Full,
AspectRatio = AspectRatio._20_13,
AspectMode = AspectMode.Cover,
Action = new UriTemplateAction(null, "http://linecorp.com/")
},
Body = new BoxComponent()
{
Layout = BoxLayout.Vertical,
Contents = new IFlexComponent[]
{
new TextComponent()
{
Text = "Broun Cafe",
Weight = Weight.Bold,
Size = ComponentSize.Xl
},
new BoxComponent()
{
Layout = BoxLayout.Baseline,
Margin = Spacing.Md,
Contents = new IFlexComponent[]
{
new IconComponent()
{
Url = "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png",
Size = ComponentSize.Sm
},
new IconComponent()
{
Url = "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png",
Size = ComponentSize.Sm
},
new IconComponent()
{
Url = "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png",
Size = ComponentSize.Sm
},
new IconComponent()
{
Url = "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png",
Size = ComponentSize.Sm
},
new IconComponent()
{
Url = "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gray_star_28.png",
Size = ComponentSize.Sm
},
new TextComponent()
{
Text = "4.0",
Size = ComponentSize.Sm,
Margin = Spacing.Md,
Flex = 0,
Color = "#999999"
}
}
},
new BoxComponent()
{
Layout = BoxLayout.Vertical,
Margin = Spacing.Lg,
Spacing = Spacing.Sm,
Contents = new IFlexComponent[]
{
new BoxComponent()
{
Layout = BoxLayout.Baseline,
Spacing = Spacing.Sm,
Contents = new IFlexComponent[]
{
new TextComponent()
{
Text = "Place",
Size = ComponentSize.Sm,
Color = "#aaaaaa",
Flex = 1
},
new TextComponent()
{
Text = "Miraina Tower, 4-1-6 Shinjuku, Tokyo",
Size = ComponentSize.Sm,
Wrap = true,
Color = "#666666",
Flex = 5
}
}
}
}
},
new BoxComponent(BoxLayout.Baseline)
{
Spacing = Spacing.Sm,
Contents = new IFlexComponent[]
{
new TextComponent()
{
Text = "Time",
Size = ComponentSize.Sm,
Color = "#aaaaaa",
Flex = 1
},
new TextComponent()
{
Text = "10:00 - 23:00",
Size = ComponentSize.Sm,
Wrap = true,
Color = "#666666",
Flex=5
}
}
}
}
},
Footer = new BoxComponent()
{
Layout = BoxLayout.Vertical,
Spacing = Spacing.Sm,
Flex = 0,
Contents = new IFlexComponent[]
{
new ButtonComponent()
{
Action = new UriTemplateAction("Call", "https://linecorp.com"),
Style = ButtonStyle.Link,
Height = ButtonHeight.Sm
},
new ButtonComponent()
{
Action = new UriTemplateAction("WEBSITE", "https://linecorp.com"),
Style = ButtonStyle.Link,
Height = ButtonHeight.Sm
},
new SpacerComponent()
{
Size = ComponentSize.Sm
}
}
},
Styles = new BubbleStyles()
{
Body = new BlockStyle()
{
BackgroundColor = ColorCode.FromRgb(192, 200, 200),
Separator = true,
SeparatorColor = ColorCode.DarkViolet
},
Footer = new BlockStyle()
{
BackgroundColor = ColorCode.Ivory
}
}
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using DereTore.Common;
namespace DereTore.Exchange.Archive.ACB {
public partial class UtfTable {
internal UtfTable(Stream stream, long offset, long size, string acbFileName, bool disposeStream) {
_acbFileName = acbFileName;
_stream = stream;
_offset = offset;
_size = size;
_disposeStream = disposeStream;
}
internal virtual void Initialize() {
var stream = _stream;
var offset = _offset;
var magic = stream.PeekBytes(offset, 4);
magic = CheckEncryption(magic);
if (!AcbHelper.AreDataIdentical(magic, UtfSignature)) {
throw new FormatException($"'@UTF' signature (or its encrypted equivalent) is not found in '{_acbFileName}' at offset 0x{offset:x8}.");
}
using (var tableDataStream = GetTableDataStream()) {
var header = GetUtfHeader(tableDataStream);
_utfHeader = header;
_rows = new Dictionary<string, UtfField>[header.RowCount];
if (header.TableSize > 0) {
InitializeUtfSchema(stream, tableDataStream, 0x20);
}
}
}
protected override void Dispose(bool disposing) {
if (_disposeStream) {
try {
_stream.Dispose();
} catch (ObjectDisposedException) {
}
}
}
private static bool GetKeysForEncryptedUtfTable(byte[] encryptedUtfSignature, out byte seed, out byte increment) {
for (var s = 0; s <= byte.MaxValue; s++) {
if ((encryptedUtfSignature[0] ^ s) != UtfSignature[0]) {
continue;
}
for (var i = 0; i <= byte.MaxValue; i++) {
var m = (byte)(s * i);
if ((encryptedUtfSignature[1] ^ m) != UtfSignature[1]) {
continue;
}
var t = (byte)i;
for (var j = 2; j < UtfSignature.Length; j++) {
m *= t;
if ((encryptedUtfSignature[j] ^ m) != UtfSignature[j]) {
break;
}
if (j < UtfSignature.Length - 1) {
continue;
}
seed = (byte)s;
increment = (byte)i;
return true;
}
}
}
seed = 0;
increment = 0;
return false;
}
private byte[] CheckEncryption(byte[] magicBytes) {
if (AcbHelper.AreDataIdentical(magicBytes, UtfSignature)) {
_isEncrypted = false;
_utfReader = new UtfReader();
return magicBytes;
} else {
_isEncrypted = true;
byte seed, increment;
var keysFound = GetKeysForEncryptedUtfTable(magicBytes, out seed, out increment);
if (!keysFound) {
throw new FormatException($"Unable to decrypt UTF table at offset 0x{_offset:x8}");
} else {
_utfReader = new UtfReader(seed, increment);
}
return UtfSignature;
}
}
private Stream GetTableDataStream() {
var stream = _stream;
var offset = _offset;
var tableSize = (int)_utfReader.PeekUInt32(stream, offset, 4) + 8;
if (!IsEncrypted) {
return AcbHelper.ExtractToNewStream(stream, offset, tableSize);
}
// Another reading process. Unlike the one with direct reading, this may encounter UTF table decryption.
var originalPosition = stream.Position;
var totalBytesRead = 0;
var memory = new byte[tableSize];
var currentIndex = 0;
var currentOffset = offset;
do {
var shouldRead = tableSize - totalBytesRead;
var buffer = _utfReader.PeekBytes(stream, currentOffset, shouldRead, totalBytesRead);
Array.Copy(buffer, 0, memory, currentIndex, buffer.Length);
currentOffset += buffer.Length;
currentIndex += buffer.Length;
totalBytesRead += buffer.Length;
} while (totalBytesRead < tableSize);
stream.Position = originalPosition;
var memoryStream = new MemoryStream(memory, false) {
Capacity = tableSize
};
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
private static UtfHeader GetUtfHeader(Stream stream) {
return GetUtfHeader(stream, stream.Position);
}
private static UtfHeader GetUtfHeader(Stream stream, long offset) {
if (offset != stream.Position) {
stream.Seek(offset, SeekOrigin.Begin);
}
var header = new UtfHeader {
TableSize = stream.PeekUInt32BE(offset + 4),
Unknown1 = stream.PeekUInt16BE(offset + 8),
PerRowDataOffset = (uint)stream.PeekUInt16BE(offset + 10) + 8,
StringTableOffset = stream.PeekUInt32BE(offset + 12) + 8,
ExtraDataOffset = stream.PeekUInt32BE(offset + 16) + 8,
TableNameOffset = stream.PeekUInt32BE(offset + 20),
FieldCount = stream.PeekUInt16BE(offset + 24),
RowSize = stream.PeekUInt16BE(offset + 26),
RowCount = stream.PeekUInt32BE(offset + 28)
};
header.TableName = stream.PeekZeroEndedStringAsAscii(header.StringTableOffset + header.TableNameOffset);
return header;
}
private void InitializeUtfSchema(Stream sourceStream, Stream tableDataStream, long schemaOffset) {
var header = _utfHeader;
var rows = _rows;
var baseOffset = _offset;
for (uint i = 0; i < header.RowCount; i++) {
var currentOffset = schemaOffset;
var row = new Dictionary<string, UtfField>();
rows[i] = row;
long currentRowOffset = 0;
long currentRowBase = header.PerRowDataOffset + header.RowSize * i;
for (var j = 0; j < header.FieldCount; j++) {
var field = new UtfField {
Type = tableDataStream.PeekByte(currentOffset)
};
long nameOffset = tableDataStream.PeekInt32BE(currentOffset + 1);
field.Name = tableDataStream.PeekZeroEndedStringAsAscii(header.StringTableOffset + nameOffset);
var union = new NumericUnion();
var constrainedStorage = (ColumnStorage)(field.Type & (byte)ColumnStorage.Mask);
var constrainedType = (ColumnType)(field.Type & (byte)ColumnType.Mask);
switch (constrainedStorage) {
case ColumnStorage.Constant:
case ColumnStorage.Constant2:
var constantOffset = currentOffset + 5;
long dataOffset;
switch (constrainedType) {
case ColumnType.String:
dataOffset = tableDataStream.PeekInt32BE(constantOffset);
field.StringValue = tableDataStream.PeekZeroEndedStringAsAscii(header.StringTableOffset + dataOffset);
currentOffset += 4;
break;
case ColumnType.Int64:
union.S64 = tableDataStream.PeekInt64BE(constantOffset);
currentOffset += 8;
break;
case ColumnType.UInt64:
union.U64 = tableDataStream.PeekUInt64BE(constantOffset);
currentOffset += 8;
break;
case ColumnType.Data:
dataOffset = tableDataStream.PeekUInt32BE(constantOffset);
long dataSize = tableDataStream.PeekUInt32BE(constantOffset + 4);
field.Offset = baseOffset + header.ExtraDataOffset + dataOffset;
field.Size = dataSize;
// don't think this is encrypted, need to check
field.DataValue = sourceStream.PeekBytes(field.Offset, (int)dataSize);
currentOffset += 8;
break;
case ColumnType.Double:
union.R64 = tableDataStream.PeekDoubleBE(constantOffset);
currentOffset += 8;
break;
case ColumnType.Single:
union.R32 = tableDataStream.PeekSingleBE(constantOffset);
currentOffset += 4;
break;
case ColumnType.Int32:
union.S32 = tableDataStream.PeekInt32BE(constantOffset);
currentOffset += 4;
break;
case ColumnType.UInt32:
union.U32 = tableDataStream.PeekUInt32BE(constantOffset);
currentOffset += 4;
break;
case ColumnType.Int16:
union.S16 = tableDataStream.PeekInt16BE(constantOffset);
currentOffset += 2;
break;
case ColumnType.UInt16:
union.U16 = tableDataStream.PeekUInt16BE(constantOffset);
currentOffset += 2;
break;
case ColumnType.SByte:
union.S8 = tableDataStream.PeekSByte(constantOffset);
currentOffset += 1;
break;
case ColumnType.Byte:
union.U8 = tableDataStream.PeekByte(constantOffset);
currentOffset += 1;
break;
default:
throw new FormatException($"Unknown column type at offset: 0x{currentOffset:x8}");
}
break;
case ColumnStorage.PerRow:
// read the constant depending on the type
long rowDataOffset;
switch (constrainedType) {
case ColumnType.String:
rowDataOffset = tableDataStream.PeekUInt32BE(currentRowBase + currentRowOffset);
field.StringValue = tableDataStream.PeekZeroEndedStringAsAscii(header.StringTableOffset + rowDataOffset);
currentRowOffset += 4;
break;
case ColumnType.Int64:
union.S64 = tableDataStream.PeekInt64BE(currentRowBase + currentRowOffset);
currentRowOffset += 8;
break;
case ColumnType.UInt64:
union.U64 = tableDataStream.PeekUInt64BE(currentRowBase + currentRowOffset);
currentRowOffset += 8;
break;
case ColumnType.Data:
rowDataOffset = tableDataStream.PeekUInt32BE(currentRowBase + currentRowOffset);
long rowDataSize = tableDataStream.PeekUInt32BE(currentRowBase + currentRowOffset + 4);
field.Offset = baseOffset + header.ExtraDataOffset + rowDataOffset;
field.Size = rowDataSize;
// don't think this is encrypted
field.DataValue = sourceStream.PeekBytes(field.Offset, (int)rowDataSize);
currentRowOffset += 8;
break;
case ColumnType.Double:
union.R64 = tableDataStream.PeekDoubleBE(currentRowBase + currentRowOffset);
currentRowOffset += 8;
break;
case ColumnType.Single:
union.R32 = tableDataStream.PeekSingleBE(currentRowBase + currentRowOffset);
currentRowOffset += 4;
break;
case ColumnType.Int32:
union.S32 = tableDataStream.PeekInt32BE(currentRowBase + currentRowOffset);
currentRowOffset += 4;
break;
case ColumnType.UInt32:
union.U32 = tableDataStream.PeekUInt32BE(currentRowBase + currentRowOffset);
currentRowOffset += 4;
break;
case ColumnType.Int16:
union.S16 = tableDataStream.PeekInt16BE(currentRowBase + currentRowOffset);
currentRowOffset += 2;
break;
case ColumnType.UInt16:
union.U16 = tableDataStream.PeekUInt16BE(currentRowBase + currentRowOffset);
currentRowOffset += 2;
break;
case ColumnType.SByte:
union.S8 = tableDataStream.PeekSByte(currentRowBase + currentRowOffset);
currentRowOffset += 1;
break;
case ColumnType.Byte:
union.U8 = tableDataStream.PeekByte(currentRowBase + currentRowOffset);
currentRowOffset += 1;
break;
default:
throw new FormatException($"Unknown column type at offset: 0x{currentOffset:x8}");
}
field.ConstrainedType = (ColumnType)field.Type;
break;
default:
throw new FormatException($"Unknown column storage at offset: 0x{currentOffset:x8}");
}
// Union polyfill
field.ConstrainedType = constrainedType;
switch (constrainedType) {
case ColumnType.String:
case ColumnType.Data:
break;
default:
field.NumericValue = union;
break;
}
row.Add(field.Name, field);
currentOffset += 5; // sizeof(CriField.Type + CriField.NameOffset)
}
}
}
private object GetFieldValue(int rowIndex, string fieldName) {
var rows = Rows;
if (rowIndex >= rows.Length) {
return null;
}
var row = rows[rowIndex];
return row.ContainsKey(fieldName) ? row[fieldName].GetValue() : null;
}
internal T? GetFieldValueAsNumber<T>(int rowIndex, string fieldName) where T : struct {
return (T?)GetFieldValue(rowIndex, fieldName);
}
internal string GetFieldValueAsString(int rowIndex, string fieldName) {
return (string)GetFieldValue(rowIndex, fieldName);
}
internal byte[] GetFieldValueAsData(int rowIndex, string fieldName) {
return (byte[])GetFieldValue(rowIndex, fieldName);
}
internal long? GetFieldOffset(int rowIndex, string fieldName) {
var rows = Rows;
if (rowIndex >= rows.Length) {
return null;
}
var row = rows[rowIndex];
if (row.ContainsKey(fieldName)) {
return row[fieldName].Offset;
}
return null;
}
internal long? GetFieldSize(int rowIndex, string fieldName) {
var rows = Rows;
if (rowIndex >= rows.Length) {
return null;
}
var row = rows[rowIndex];
if (row.ContainsKey(fieldName)) {
return row[fieldName].Size;
}
return null;
}
internal static readonly byte[] UtfSignature = { 0x40, 0x55, 0x54, 0x46 }; // '@UTF'
private readonly string _acbFileName;
private readonly Stream _stream;
private readonly long _offset;
private readonly long _size;
private readonly bool _disposeStream;
private UtfReader _utfReader;
private bool _isEncrypted;
private UtfHeader _utfHeader;
private Dictionary<string, UtfField>[] _rows;
}
}
| |
// 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.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System.Globalization
{
// needs to be kept in sync with CalendarDataType in System.Globalization.Native
internal enum CalendarDataType
{
Uninitialized = 0,
NativeName = 1,
MonthDay = 2,
ShortDates = 3,
LongDates = 4,
YearMonths = 5,
DayNames = 6,
AbbrevDayNames = 7,
MonthNames = 8,
AbbrevMonthNames = 9,
SuperShortDayNames = 10,
MonthGenitiveNames = 11,
AbbrevMonthGenitiveNames = 12,
EraNames = 13,
AbbrevEraNames = 14,
}
// needs to be kept in sync with CalendarDataResult in System.Globalization.Native
internal enum CalendarDataResult
{
Success = 0,
UnknownError = 1,
InsufficentBuffer = 2,
}
internal partial class CalendarData
{
private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId)
{
bool result = true;
result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName);
result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay);
this.sMonthDay = NormalizeDatePattern(this.sMonthDay);
result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates);
result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates);
result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths);
result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames);
result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames);
result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames);
result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames);
result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames);
result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames);
return result;
}
internal static int GetTwoDigitYearMax(CalendarId calendarId)
{
// There is no user override for this value on Linux or in ICU.
// So just return -1 to use the hard-coded defaults.
return -1;
}
// Call native side to figure out which calendars are allowed
[SecuritySafeCritical]
internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars)
{
// NOTE: there are no 'user overrides' on Linux
int count = Interop.GlobalizationInterop.GetCalendars(localeName, calendars, calendars.Length);
// ensure there is at least 1 calendar returned
if (count == 0 && calendars.Length > 0)
{
calendars[0] = CalendarId.GREGORIAN;
count = 1;
}
return count;
}
private static bool SystemSupportsTaiwaneseCalendar()
{
return true;
}
// PAL Layer ends here
[SecuritySafeCritical]
private static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString)
{
calendarString = null;
const int initialStringSize = 80;
const int maxDoubleAttempts = 5;
for (int i = 0; i < maxDoubleAttempts; i++)
{
StringBuilder stringBuilder = StringBuilderCache.Acquire((int)(initialStringSize * Math.Pow(2, i)));
CalendarDataResult result = Interop.GlobalizationInterop.GetCalendarInfo(
localeName,
calendarId,
dataType,
stringBuilder,
stringBuilder.Capacity);
if (result == CalendarDataResult.Success)
{
calendarString = StringBuilderCache.GetStringAndRelease(stringBuilder);
return true;
}
else
{
StringBuilderCache.Release(stringBuilder);
if (result != CalendarDataResult.InsufficentBuffer)
{
return false;
}
// else, it is an InsufficentBuffer error, so loop and increase the string size
}
}
return false;
}
private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] datePatterns)
{
datePatterns = null;
CallbackContext callbackContext = new CallbackContext();
callbackContext.DisallowDuplicates = true;
bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
if (result)
{
List<string> datePatternsList = callbackContext.Results;
datePatterns = new string[datePatternsList.Count];
for (int i = 0; i < datePatternsList.Count; i++)
{
datePatterns[i] = NormalizeDatePattern(datePatternsList[i]);
}
}
return result;
}
/// <summary>
/// The ICU date format characters are not exactly the same as the .NET date format characters.
/// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern.
/// </summary>
/// <remarks>
/// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// </remarks>
private static string NormalizeDatePattern(string input)
{
StringBuilder destination = StringBuilderCache.Acquire(input.Length);
int index = 0;
while (index < input.Length)
{
switch (input[index])
{
case '\'':
// single quotes escape characters, like 'de' in es-SP
// so read verbatim until the next single quote
destination.Append(input[index++]);
while (index < input.Length)
{
char current = input[index++];
destination.Append(current);
if (current == '\'')
{
break;
}
}
break;
case 'E':
case 'e':
case 'c':
// 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET
// 'e' in ICU is the local day of the week, which has no representation in .NET, but
// maps closest to 3 or 4 'd's in .NET
// 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but
// maps closest to 3 or 4 'd's in .NET
NormalizeDayOfWeek(input, destination, ref index);
break;
case 'L':
case 'M':
// 'L' in ICU is the stand-alone name of the month,
// which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns
// 'M' in both ICU and .NET is the month,
// but ICU supports 5 'M's, which is the super short month name
int occurrences = CountOccurrences(input, input[index], ref index);
if (occurrences > 4)
{
// 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET
occurrences = 3;
}
destination.Append('M', occurrences);
break;
case 'G':
// 'G' in ICU is the era, which maps to 'g' in .NET
occurrences = CountOccurrences(input, 'G', ref index);
// it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they
// have the same meaning
destination.Append('g');
break;
case 'y':
// a single 'y' in ICU is the year with no padding or trimming.
// a single 'y' in .NET is the year with 1 or 2 digits
// so convert any single 'y' to 'yyyy'
occurrences = CountOccurrences(input, 'y', ref index);
if (occurrences == 1)
{
occurrences = 4;
}
destination.Append('y', occurrences);
break;
default:
const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
Contract.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
string.Format(CultureInfo.InvariantCulture,
"Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.",
input[index]));
destination.Append(input[index++]);
break;
}
}
return StringBuilderCache.GetStringAndRelease(destination);
}
private static void NormalizeDayOfWeek(string input, StringBuilder destination, ref int index)
{
char dayChar = input[index];
int occurrences = CountOccurrences(input, dayChar, ref index);
occurrences = Math.Max(occurrences, 3);
if (occurrences > 4)
{
// 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET
occurrences = 3;
}
destination.Append('d', occurrences);
}
private static int CountOccurrences(string input, char value, ref int index)
{
int startIndex = index;
while (index < input.Length && input[index] == value)
{
index++;
}
return index - startIndex;
}
[SecuritySafeCritical]
private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] monthNames)
{
monthNames = null;
CallbackContext callbackContext = new CallbackContext();
bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
if (result)
{
// the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an
// extra empty string to fill the array.
if (callbackContext.Results.Count == 12)
{
callbackContext.Results.Add(string.Empty);
}
monthNames = callbackContext.Results.ToArray();
}
return result;
}
[SecuritySafeCritical]
private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] eraNames)
{
bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames);
// .NET expects that only the Japanese calendars have more than 1 era.
// So for other calendars, only return the latest era.
if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames.Length > 0)
{
string[] latestEraName = new string[] { eraNames[eraNames.Length - 1] };
eraNames = latestEraName;
}
return result;
}
[SecuritySafeCritical]
internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] calendarData)
{
calendarData = null;
CallbackContext callbackContext = new CallbackContext();
bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
if (result)
{
calendarData = callbackContext.Results.ToArray();
}
return result;
}
[SecuritySafeCritical]
private static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, CallbackContext callbackContext)
{
GCHandle context = GCHandle.Alloc(callbackContext);
try
{
return Interop.GlobalizationInterop.EnumCalendarInfo(EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)context);
}
finally
{
context.Free();
}
}
[SecuritySafeCritical]
private static void EnumCalendarInfoCallback(string calendarString, IntPtr context)
{
CallbackContext callbackContext = (CallbackContext)((GCHandle)context).Target;
if (callbackContext.DisallowDuplicates)
{
foreach (string existingResult in callbackContext.Results)
{
if (string.Equals(calendarString, existingResult, StringComparison.Ordinal))
{
// the value is already in the results, so don't add it again
return;
}
}
}
callbackContext.Results.Add(calendarString);
}
private class CallbackContext
{
private List<string> _results = new List<string>();
public CallbackContext()
{
}
public List<string> Results { get { return _results; } }
public bool DisallowDuplicates { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 ShiftLeftLogicalUInt1616()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt1616();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogicalUInt1616
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(UInt16);
private const int RetElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data = new UInt16[Op1ElementCount];
private static Vector256<UInt16> _clsVar;
private Vector256<UInt16> _fld;
private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable;
static SimpleUnaryOpTest__ShiftLeftLogicalUInt1616()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftLeftLogicalUInt1616()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftLeftLogical(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftLeftLogical(
Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftLeftLogical(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftLeftLogical(
_clsVar,
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftLeftLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt1616();
var result = Avx2.ShiftLeftLogical(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftLeftLogical(_fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt16> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray = new UInt16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
if (0 != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<UInt16>(Vector256<UInt16><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Failure;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Tests.Process;
using NUnit.Framework;
/// <summary>
/// Test utility methods.
/// </summary>
public static class TestUtils
{
/** Indicates long running and/or memory/cpu intensive test. */
public const string CategoryIntensive = "LONG_TEST";
/** Indicates examples tests. */
public const string CategoryExamples = "EXAMPLES_TEST";
/** */
public const int DfltBusywaitSleepInterval = 200;
/** System cache name. */
public const string UtilityCacheName = "ignite-sys-cache";
/** Work dir. */
private static readonly string WorkDir =
// ReSharper disable once AssignNullToNotNullAttribute
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ignite_work");
/** */
private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess
? new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms1g",
"-Xmx4g",
"-ea",
"-DIGNITE_QUIET=true",
"-Duser.timezone=UTC"
}
: new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms64m",
"-Xmx99m",
"-ea",
"-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000",
"-DIGNITE_QUIET=true",
"-Duser.timezone=UTC"
};
/** */
private static readonly IList<string> JvmDebugOpts =
new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", "-DIGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP=false" };
/** */
public static bool JvmDebug = true;
/** */
[ThreadStatic]
private static Random _random;
/** */
private static int _seed = Environment.TickCount;
/// <summary>
///
/// </summary>
public static Random Random
{
get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); }
}
/// <summary>
/// Gets current test name.
/// </summary>
public static string TestName
{
get { return TestContext.CurrentContext.Test.Name; }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IList<string> TestJavaOptions(bool? jvmDebug = null)
{
IList<string> ops = new List<string>(TestJvmOpts);
if (jvmDebug ?? JvmDebug)
{
foreach (string opt in JvmDebugOpts)
ops.Add(opt);
}
return ops;
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
public static void RunMultiThreaded(Action action, int threadNum)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
action();
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
/// <param name="duration">Duration of test execution in seconds</param>
public static void RunMultiThreaded(Action action, int threadNum, int duration)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
bool stop = false;
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
while (true)
{
Thread.MemoryBarrier();
// ReSharper disable once AccessToModifiedClosure
if (stop)
break;
action();
}
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
Thread.Sleep(duration * 1000);
stop = true;
Thread.MemoryBarrier();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
/// Wait for particular topology size.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="size">Size.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000)
{
int left = timeout;
while (true)
{
if (grid.GetCluster().GetNodes().Count != size)
{
if (left > 0)
{
Thread.Sleep(100);
left -= 100;
}
else
break;
}
else
return true;
}
return false;
}
/// <summary>
/// Waits for particular topology on specific cache (system cache by default).
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="waitingTop">Topology version.</param>
/// <param name="cacheName">Cache name.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, AffinityTopologyVersion waitingTop,
string cacheName = UtilityCacheName, int timeout = 30000)
{
int checkPeriod = 200;
// Wait for late affinity.
for (var iter = 0;; iter++)
{
var result = grid.GetCompute().ExecuteJavaTask<long[]>(
"org.apache.ignite.platform.PlatformCacheAffinityVersionTask", cacheName);
var top = new AffinityTopologyVersion(result[0], (int) result[1]);
if (top.CompareTo(waitingTop) >= 0)
{
Console.Out.WriteLine("Current topology: " + top);
break;
}
if (iter % 10 == 0)
Console.Out.WriteLine("Waiting topology cur=" + top + " wait=" + waitingTop);
if (iter * checkPeriod > timeout)
return false;
Thread.Sleep(checkPeriod);
}
return true;
}
/// <summary>
/// Waits for condition, polling in busy wait loop.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <returns>True if condition predicate returned true within interval; false otherwise.</returns>
public static bool WaitForCondition(Func<bool> cond, int timeout)
{
if (timeout <= 0)
return cond();
var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval);
while (DateTime.Now < maxTime)
{
if (cond())
return true;
Thread.Sleep(DfltBusywaitSleepInterval);
}
return false;
}
/// <summary>
/// Waits for condition, polling in a busy wait loop, then asserts that condition is true.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="message">Assertion message.</param>
public static void WaitForTrueCondition(Func<bool> cond, int timeout = 1000, string message = null)
{
WaitForTrueCondition(cond, message == null ? (Func<string>) null : () => message, timeout);
}
/// <summary>
/// Waits for condition, polling in a busy wait loop, then asserts that condition is true.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="messageFunc">Assertion message func.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void WaitForTrueCondition(Func<bool> cond, Func<string> messageFunc, int timeout = 1000)
{
var res = WaitForCondition(cond, timeout);
var message = string.Format("Condition not reached within {0} ms", timeout);
if (messageFunc != null)
{
message += string.Format(" ({0})", messageFunc());
}
Assert.IsTrue(res, message);
}
/// <summary>
/// Gets the static discovery.
/// </summary>
public static TcpDiscoverySpi GetStaticDiscovery()
{
return new TcpDiscoverySpi
{
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] { "127.0.0.1:47500" }
},
SocketTimeout = TimeSpan.FromSeconds(0.3)
};
}
/// <summary>
/// Gets cache keys.
/// </summary>
public static IEnumerable<int> GetKeys(IIgnite ignite, string cacheName,
IClusterNode node = null, bool primary = true)
{
var aff = ignite.GetAffinity(cacheName);
node = node ?? ignite.GetCluster().GetLocalNode();
return Enumerable.Range(1, int.MaxValue).Where(x => aff.IsPrimary(node, x) == primary);
}
/// <summary>
/// Gets the primary keys.
/// </summary>
public static IEnumerable<int> GetPrimaryKeys(IIgnite ignite, string cacheName,
IClusterNode node = null)
{
return GetKeys(ignite, cacheName, node);
}
/// <summary>
/// Gets the primary key.
/// </summary>
public static int GetPrimaryKey(IIgnite ignite, string cacheName, IClusterNode node = null)
{
return GetPrimaryKeys(ignite, cacheName, node).First();
}
/// <summary>
/// Gets the primary key.
/// </summary>
public static int GetKey(IIgnite ignite, string cacheName, IClusterNode node = null, bool primaryKey = false)
{
return GetKeys(ignite, cacheName, node, primaryKey).First();
}
/// <summary>
/// Asserts that the handle registry is empty.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, 0, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, expectedCount, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="grid">The grid to check.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
{
var handleRegistry = ((Ignite)grid).HandleRegistry;
expectedCount++; // Skip default lifecycle bean
if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout))
return;
var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleHandlerHolder)).ToList();
if (items.Any())
{
Assert.Fail("HandleRegistry is not empty in grid '{0}' (expected {1}, actual {2}):\n '{3}'",
grid.Name, expectedCount, handleRegistry.Count,
items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
}
}
/// <summary>
/// Serializes and deserializes back an object.
/// </summary>
public static T SerializeDeserialize<T>(T obj, bool raw = false)
{
var cfg = new BinaryConfiguration
{
Serializer = raw ? new BinaryReflectiveSerializer {RawMode = true} : null
};
var marsh = new Marshaller(cfg) { CompactFooter = false };
return marsh.Unmarshal<T>(marsh.Marshal(obj));
}
/// <summary>
/// Clears the work dir.
/// </summary>
public static void ClearWorkDir()
{
if (!Directory.Exists(WorkDir))
{
return;
}
// Delete everything we can. Some files may be locked.
foreach (var e in Directory.GetFileSystemEntries(WorkDir, "*", SearchOption.AllDirectories))
{
try
{
File.Delete(e);
}
catch (Exception)
{
// Ignore
}
try
{
Directory.Delete(e, true);
}
catch (Exception)
{
// Ignore
}
}
}
/// <summary>
/// Gets the dot net source dir.
/// </summary>
public static DirectoryInfo GetDotNetSourceDir()
{
// ReSharper disable once AssignNullToNotNullAttribute
var dir = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
while (dir != null)
{
if (dir.GetFiles().Any(x => x.Name == "Apache.Ignite.sln"))
return dir;
dir = dir.Parent;
}
throw new InvalidOperationException("Could not resolve Ignite.NET source directory.");
}
/// <summary>
/// Gets a value indicating whether specified partition is reserved.
/// </summary>
public static bool IsPartitionReserved(IIgnite ignite, string cacheName, int part)
{
Debug.Assert(ignite != null);
Debug.Assert(cacheName != null);
const string taskName = "org.apache.ignite.platform.PlatformIsPartitionReservedTask";
return ignite.GetCompute().ExecuteJavaTask<bool>(taskName, new object[] {cacheName, part});
}
/// <summary>
/// Gets the innermost exception.
/// </summary>
public static Exception GetInnermostException(this Exception ex)
{
while (ex.InnerException != null)
{
ex = ex.InnerException;
}
return ex;
}
/// <summary>
/// Gets the private field value.
/// </summary>
public static T GetPrivateField<T>(object obj, string name)
{
Assert.IsNotNull(obj);
var field = obj.GetType().GetField(name, BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(field);
return (T) field.GetValue(obj);
}
/// <summary>
/// Gets active notification listeners.
/// </summary>
public static ICollection GetActiveNotificationListeners(this IIgniteClient client)
{
var failoverSocket = GetPrivateField<ClientFailoverSocket>(client, "_socket");
var socket = GetPrivateField<ClientSocket>(failoverSocket, "_socket");
return GetPrivateField<ICollection>(socket, "_notificationListeners");
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string CreateTestClasspath()
{
var home = IgniteHome.Resolve();
return Classpath.CreateClasspath(null, home, forceTestClasspath: true);
}
/// <summary>
/// Kill Ignite processes.
/// </summary>
public static void KillProcesses()
{
IgniteProcess.KillAll();
}
/// <summary>
/// Gets the default code-based test configuration.
/// </summary>
public static IgniteConfiguration GetTestConfiguration(bool? jvmDebug = null, string name = null)
{
return new IgniteConfiguration
{
DiscoverySpi = GetStaticDiscovery(),
Localhost = "127.0.0.1",
JvmOptions = TestJavaOptions(jvmDebug),
JvmClasspath = CreateTestClasspath(),
IgniteInstanceName = name,
DataStorageConfiguration = new DataStorageConfiguration
{
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = DataStorageConfiguration.DefaultDataRegionName,
InitialSize = 128 * 1024 * 1024,
MaxSize = Environment.Is64BitProcess
? DataRegionConfiguration.DefaultMaxSize
: 256 * 1024 * 1024
}
},
FailureHandler = new NoOpFailureHandler(),
WorkDirectory = WorkDir,
Logger = new TestContextLogger()
};
}
/// <summary>
/// Runs the test in new process.
/// </summary>
[SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")]
public static void RunTestInNewProcess(string fixtureName, string testName)
{
var procStart = new ProcessStartInfo
{
FileName = typeof(TestUtils).Assembly.Location,
Arguments = fixtureName + " " + testName,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var proc = System.Diagnostics.Process.Start(procStart);
Assert.IsNotNull(proc);
try
{
proc.AttachProcessConsoleReader();
Assert.IsTrue(proc.WaitForExit(50000));
Assert.AreEqual(0, proc.ExitCode);
}
finally
{
if (!proc.HasExited)
{
proc.Kill();
}
}
}
/// <summary>
/// Deploys the Java service.
/// </summary>
public static string DeployJavaService(IIgnite ignite)
{
const string serviceName = "javaService";
ignite.GetCompute()
.ExecuteJavaTask<object>("org.apache.ignite.platform.PlatformDeployServiceTask", serviceName);
var services = ignite.GetServices();
WaitForCondition(() => services.GetServiceDescriptors().Any(x => x.Name == serviceName), 1000);
return serviceName;
}
/// <summary>
/// Logs to test progress. Produces immediate console output on .NET Core.
/// </summary>
public class TestContextLogger : ILogger
{
/** <inheritdoc /> */
public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider,
string category, string nativeErrorInfo, Exception ex)
{
if (!IsEnabled(level))
{
return;
}
var text = args != null
? string.Format(formatProvider ?? CultureInfo.InvariantCulture, message, args)
: message;
#if NETCOREAPP
TestContext.Progress.WriteLine(text);
#else
Console.WriteLine(text);
#endif
}
/** <inheritdoc /> */
public bool IsEnabled(LogLevel level)
{
return level >= LogLevel.Info;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using P3Net.Kraken;
namespace Tests.P3Net.Kraken
{
public partial class StringExtensionsTests
{
#region EnsureEndsWith
#region Char
[TestMethod]
public void EnsureEndsWith_Char_IsTrue ()
{
var target = "Test/";
var actual = target.EnsureEndsWith('/');
actual.Should().Be(target);
}
[TestMethod]
public void EnsureEndsWith_Char_IsFalse ()
{
var target = "Test";
var actual = target.EnsureEndsWith('/');
actual.Should().Be(target + "/");
}
[TestMethod]
public void EnsureEndsWith_Char_IsCaseSensitive ()
{
var target = "TestA";
var actual = target.EnsureEndsWith('a');
actual.Should().Be(target + 'a');
}
[TestMethod]
public void EnsureEndsWith_Char_WithComparison ()
{
var target = "TestA";
var actual = target.EnsureEndsWith('a', StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureEndsWith_Char_WithCulture ()
{
var target = "Test/";
var culture = CultureInfo.InvariantCulture;
var actual = target.EnsureEndsWith('/', true, culture);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureEndsWith_Char_WithNullCulture ()
{
var target = "Test/";
var actual = target.EnsureEndsWith('/', true, null);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureEndsWith_Char_SourceIsNull ()
{
var target = (string)null;
var actual = target.EnsureEndsWith("/", true, null);
actual.Should().Be("/");
}
[TestMethod]
public void EnsureEndsWith_Char_SourceIsEmpty ()
{
var actual = "".EnsureEndsWith("/", true, null);
actual.Should().Be("/");
}
#endregion
#region String
[TestMethod]
public void EnsureEndsWith_String_IsTrue ()
{
var target = "Test/";
var actual = target.EnsureEndsWith("/");
actual.Should().Be(target);
}
[TestMethod]
public void EnsureEndsWith_String_IsFalse ()
{
var target = "Test";
var actual = target.EnsureEndsWith("/");
actual.Should().Be(target + "/");
}
[TestMethod]
public void EnsureEndsWith_String_IsCaseSensitive ()
{
var target = "TestA";
var actual = target.EnsureEndsWith("a");
actual.Should().Be(target + "a");
}
[TestMethod]
public void EnsureEndsWith_String_WithComparison ()
{
var target = "TestA";
var actual = target.EnsureEndsWith("a", StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureEndsWith_String_WithCulture ()
{
var target = "Test/";
var culture = CultureInfo.InvariantCulture;
var actual = target.EnsureEndsWith("/", true, culture);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureEndsWith_String_WithNullCulture ()
{
var target = "Test/";
var actual = target.EnsureEndsWith("/", true, null);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureEndsWith_String_SourceIsNull ()
{
var target = (string)null;
var actual = target.EnsureEndsWith("[]");
actual.Should().Be("[]");
}
[TestMethod]
public void EnsureEndsWith_String_SourceIsEmpty ()
{
var actual = "".EnsureEndsWith("[]");
actual.Should().Be("[]");
}
[TestMethod]
public void EnsureEndsWith_String_WithCulture_IsFalse ()
{
var target = "Test";
var culture = CultureInfo.InvariantCulture;
var actual = target.EnsureEndsWith("/", true, culture);
actual.Should().Be(target + "/");
}
[TestMethod]
public void EnsureEndsWith_String_SourceIsNullWithComparison ()
{
var target = (string)null;
var actual = target.EnsureEndsWith("[]", StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be("[]");
}
[TestMethod]
public void EnsureEndsWith_StringWithComparison_IsTrue ()
{
var target = "Test[]";
var actual = target.EnsureEndsWith("[]", StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureEndsWith_StringWithComparison_IsFalse ()
{
var target = "Test";
var actual = target.EnsureEndsWith("[]", StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be(target + "[]");
}
#endregion
#endregion
#region EnsureStartsWith
#region Char
[TestMethod]
public void EnsureStartsWith_Char_IsTrue ()
{
var target = "/Test";
var actual = target.EnsureStartsWith('/');
actual.Should().Be(target);
}
[TestMethod]
public void EnsureStartsWith_Char_IsFalse ()
{
var target = "Test";
var actual = target.EnsureStartsWith('/');
actual.Should().Be("/" + target);
}
[TestMethod]
public void EnsureStartsWith_Char_IsCaseSensitive ()
{
var target = "ATest";
var actual = target.EnsureStartsWith('a');
actual.Should().Be("a" + target);
}
[TestMethod]
public void EnsureStartsWith_Char_WithComparison ()
{
var target = "ATest";
var actual = target.EnsureStartsWith('a', StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureStartsWith_Char_WithCulture ()
{
var target = "/Test";
var culture = CultureInfo.InvariantCulture;
var actual = target.EnsureStartsWith('/', true, culture);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureStartsWith_Char_WithNullCulture ()
{
var target = "/Test";
var actual = target.EnsureStartsWith('/', true, null);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureStartsWith_Char_SourceIsNull ()
{
var target = (string)null;
var actual = target.EnsureStartsWith('/');
actual.Should().Be("/");
}
[TestMethod]
public void EnsureStartsWith_Char_SourceIsEmpty ()
{
var actual = "".EnsureStartsWith('/');
actual.Should().Be("/");
}
#endregion
#region String
[TestMethod]
public void EnsureStartsWith_String_IsTrue ()
{
var target = "/Test";
var actual = target.EnsureStartsWith("/");
actual.Should().Be(target);
}
[TestMethod]
public void EnsureStartsWith_String_IsFalse ()
{
var target = "Test";
var actual = target.EnsureStartsWith("/");
actual.Should().Be("/" + target);
}
[TestMethod]
public void EnsureStartsWith_String_IsCaseSensitive ()
{
var target = "ATest";
var actual = target.EnsureStartsWith("a");
actual.Should().Be("a" + target);
}
[TestMethod]
public void EnsureStartsWith_String_WithComparison ()
{
var target = "ATest";
var actual = target.EnsureStartsWith("a", StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureStartsWith_String_WithCulture ()
{
var target = "/Test";
var culture = CultureInfo.InvariantCulture;
var actual = target.EnsureStartsWith("/", true, culture);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureStartsWith_String_WithNullCulture ()
{
var target = "/Test";
var actual = target.EnsureStartsWith("/", true, null);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureStartsWith_String_SourceIsNull ()
{
var target = (string)null;
var actual = target.EnsureStartsWith("[]");
actual.Should().Be("[]");
}
[TestMethod]
public void EnsureStartsWith_String_SourceIsEmpty ()
{
var actual = "".EnsureStartsWith("[]");
actual.Should().Be("[]");
}
[TestMethod]
public void EnsureStartsWith_String_SourceIsNullWithComparison ()
{
var target = (string)null;
var actual = target.EnsureStartsWith("[]", StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be("[]");
}
[TestMethod]
public void EnsureStartsWith_StringWithComparison_IsTrue ()
{
var target = "[]Test";
var actual = target.EnsureStartsWith("[]", StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be(target);
}
[TestMethod]
public void EnsureStartsWith_StringWithComparison_IsFalse ()
{
var target = "Test";
var actual = target.EnsureStartsWith("[]", StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be("[]" + target);
}
#endregion
#endregion
#region EnsureSurroundedWith
[TestMethod]
public void EnsureSurroundedWith_NeedsBoth ()
{
var target = "Field1";
var delimiter = "@";
var expected = delimiter + target + delimiter;
var actual = target.EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_NeedsPrefix ()
{
var delimiter = "@";
var target = "Field1" + delimiter;
var expected = delimiter + target;
var actual = target.EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_NeedsSuffix ()
{
var delimiter = "@";
var target = delimiter + "Field1";
var expected = target + delimiter;
var actual = target.EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_NeedsNeither ()
{
var delimiter = "@";
var target = delimiter + "Field1" + delimiter;
var expected = target;
var actual = target.EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_TargetIsNull ()
{
var delimiter = "@";
var expected = delimiter + delimiter;
var actual = ((string)null).EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_TargetIsEmpty ()
{
var delimiter = "@";
var expected = delimiter + delimiter;
var actual = "".EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_DelimiterIsNull ()
{
var target = "Field1";
var expected = target;
var actual = target.EnsureSurroundedWith(null);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_DelimiterIsEmpty ()
{
var target = "Field1";
var expected = target;
var actual = target.EnsureSurroundedWith("");
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_WithComparison_DiffersByCaseWithSensitive ()
{
var target = "XField1X";
var delimiter = "x";
var expected = delimiter + target + delimiter;
var actual = target.EnsureSurroundedWith(delimiter, StringComparison.CurrentCulture);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_WithComparison_DiffersByCaseWithInsensitive ()
{
var target = "XField1X";
var delimiter = "x";
var expected = target;
var actual = target.EnsureSurroundedWith(delimiter, StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_WithCulture_DiffersByCaseWithSensitive ()
{
var target = "XField1X";
var delimiter = "x";
var expected = delimiter + target + delimiter;
var actual = target.EnsureSurroundedWith(delimiter, false, CultureInfo.CurrentCulture);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_WithCulture_DiffersByCaseWithInsensitive ()
{
var target = "XField1X";
var delimiter = "x";
var expected = target;
var actual = target.EnsureSurroundedWith(delimiter, true, CultureInfo.CurrentCulture);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_NeedsBoth ()
{
var target = "Field1";
var delimiter = '@';
var expected = delimiter + target + delimiter;
var actual = target.EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_NeedsPrefix ()
{
var delimiter = '@';
var target = "Field1" + delimiter;
var expected = delimiter + target;
var actual = target.EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_NeedsSuffix ()
{
var delimiter = '@';
var target = delimiter + "Field1";
var expected = target + delimiter;
var actual = target.EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_NeedsNeither ()
{
var delimiter = '@';
var target = delimiter + "Field1" + delimiter;
var expected = target;
var actual = target.EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_TargetIsNull ()
{
var delimiter = '@';
var expected = delimiter.ToString() + delimiter.ToString();
var actual = ((string)null).EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_TargetIsEmpty ()
{
var delimiter = '@';
var expected = delimiter.ToString() + delimiter.ToString();
var actual = "".EnsureSurroundedWith(delimiter);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_WithComparison_DiffersByCaseWithSensitive ()
{
var target = "XField1X";
var delimiter = 'x';
var expected = delimiter + target + delimiter;
var actual = target.EnsureSurroundedWith(delimiter, StringComparison.CurrentCulture);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_WithComparison_DiffersByCaseWithInsensitive ()
{
var target = "XField1X";
var delimiter = 'x';
var expected = target;
var actual = target.EnsureSurroundedWith(delimiter, StringComparison.CurrentCultureIgnoreCase);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_WithCulture_DiffersByCaseWithSensitive ()
{
var target = "XField1X";
var delimiter = 'x';
var expected = delimiter + target + delimiter;
var actual = target.EnsureSurroundedWith(delimiter, false, CultureInfo.CurrentCulture);
actual.Should().Be(expected);
}
[TestMethod]
public void EnsureSurroundedWith_CharDelimiter_WithCulture_DiffersByCaseWithInsensitive ()
{
var target = "XField1X";
var delimiter = 'x';
var expected = target;
var actual = target.EnsureSurroundedWith(delimiter, true, CultureInfo.CurrentCulture);
actual.Should().Be(expected);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute.Models
{
/// <summary>
/// Parameters supplied to the Create Virtual Machine VM Image operation.
/// </summary>
public partial class VirtualMachineVMImageCreateParameters
{
private IList<DataDiskConfigurationCreateParameters> _dataDiskConfigurations;
/// <summary>
/// Optional. Specifies configuration information for the data disks
/// that are associated with the image. A VM Image might not have data
/// disks associated with it.
/// </summary>
public IList<DataDiskConfigurationCreateParameters> DataDiskConfigurations
{
get { return this._dataDiskConfigurations; }
set { this._dataDiskConfigurations = value; }
}
private string _description;
/// <summary>
/// Optional. Gets or sets the description of the image.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
private string _eula;
/// <summary>
/// Optional. Gets or sets the End User License Agreement that is
/// associated with the image. The value for this element is a string,
/// but it is recommended that the value be a URL that points to a
/// EULA.
/// </summary>
public string Eula
{
get { return this._eula; }
set { this._eula = value; }
}
private Uri _iconUri;
/// <summary>
/// Optional. Gets or sets the URI to the icon that is displayed for
/// the image in the Management Portal.
/// </summary>
public Uri IconUri
{
get { return this._iconUri; }
set { this._iconUri = value; }
}
private string _imageFamily;
/// <summary>
/// Optional. Gets or sets a value that can be used to group VM Images.
/// </summary>
public string ImageFamily
{
get { return this._imageFamily; }
set { this._imageFamily = value; }
}
private string _label;
/// <summary>
/// Required. Gets or sets an identifier for the image.
/// </summary>
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _language;
/// <summary>
/// Optional. Gets or sets the language of the image.
/// </summary>
public string Language
{
get { return this._language; }
set { this._language = value; }
}
private string _name;
/// <summary>
/// Required. Gets or sets the name of the image.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private OSDiskConfigurationCreateParameters _oSDiskConfiguration;
/// <summary>
/// Required. Gets or sets configuration information for the operating
/// system disk that is associated with the image.
/// </summary>
public OSDiskConfigurationCreateParameters OSDiskConfiguration
{
get { return this._oSDiskConfiguration; }
set { this._oSDiskConfiguration = value; }
}
private Uri _privacyUri;
/// <summary>
/// Optional. Gets or sets the URI that points to a document that
/// contains the privacy policy related to the image.
/// </summary>
public Uri PrivacyUri
{
get { return this._privacyUri; }
set { this._privacyUri = value; }
}
private System.DateTime? _publishedDate;
/// <summary>
/// Optional. Gets or sets the date when the image was added to the
/// image repository.
/// </summary>
public System.DateTime? PublishedDate
{
get { return this._publishedDate; }
set { this._publishedDate = value; }
}
private string _recommendedVMSize;
/// <summary>
/// Optional. Gets or sets the size to use for the Virtual Machine that
/// is created from the VM Image.
/// </summary>
public string RecommendedVMSize
{
get { return this._recommendedVMSize; }
set { this._recommendedVMSize = value; }
}
private bool? _showInGui;
/// <summary>
/// Optional. Gets or sets whether the VM Images should be listed in
/// the portal.
/// </summary>
public bool? ShowInGui
{
get { return this._showInGui; }
set { this._showInGui = value; }
}
private Uri _smallIconUri;
/// <summary>
/// Optional. Gets or sets the URI to the small icon that is displayed
/// for the image in the Management Portal.
/// </summary>
public Uri SmallIconUri
{
get { return this._smallIconUri; }
set { this._smallIconUri = value; }
}
/// <summary>
/// Initializes a new instance of the
/// VirtualMachineVMImageCreateParameters class.
/// </summary>
public VirtualMachineVMImageCreateParameters()
{
this.DataDiskConfigurations = new LazyList<DataDiskConfigurationCreateParameters>();
}
/// <summary>
/// Initializes a new instance of the
/// VirtualMachineVMImageCreateParameters class with required
/// arguments.
/// </summary>
public VirtualMachineVMImageCreateParameters(string name, string label, OSDiskConfigurationCreateParameters oSDiskConfiguration)
: this()
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (label == null)
{
throw new ArgumentNullException("label");
}
if (oSDiskConfiguration == null)
{
throw new ArgumentNullException("oSDiskConfiguration");
}
this.Name = name;
this.Label = label;
this.OSDiskConfiguration = oSDiskConfiguration;
}
}
}
| |
using NUnit.Framework;
using StructureMap.Configuration.DSL;
using StructureMap.Pipeline;
using StructureMap.Testing.Acceptance;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget2;
using AWidget = StructureMap.Testing.Widget.AWidget;
using IWidget = StructureMap.Testing.Widget.IWidget;
namespace StructureMap.Testing.Configuration.DSL
{
[TestFixture]
public class profiles_acceptance_tester : Registry
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
}
#endregion
[Test]
public void Add_default_instance_by_lambda()
{
var theProfileName = "something";
IContainer container = new Container(r => {
r.Profile(theProfileName, x => {
x.For<IWidget>().Use(() => new AWidget());
x.For<Rule>().Use(() => new DefaultRule());
});
});
var profile = container.GetProfile(theProfileName);
profile.GetInstance<IWidget>().ShouldBeOfType<AWidget>();
profile.GetInstance<Rule>().ShouldBeOfType<DefaultRule>();
}
[Test]
public void Add_default_instance_by_lambda2()
{
var theProfileName = "something";
IContainer container = new Container(registry => {
registry.Profile(theProfileName, x => {
x.For<IWidget>().Use(() => new AWidget());
x.For<Rule>().Use(() => new DefaultRule());
});
});
var profile = container.GetProfile(theProfileName);
profile.GetInstance<IWidget>().ShouldBeOfType<AWidget>();
profile.GetInstance<Rule>().ShouldBeOfType<Rule>();
}
[Test]
public void Add_default_instance_with_concrete_type()
{
var theProfileName = "something";
IContainer container = new Container(registry => {
registry.Profile(theProfileName, p => {
p.For<IWidget>().Use<AWidget>();
p.For<Rule>().Use<DefaultRule>();
});
});
var profile = container.GetProfile(theProfileName);
profile.GetInstance<IWidget>().ShouldBeOfType<AWidget>();
profile.GetInstance<Rule>().ShouldBeOfType<DefaultRule>();
}
[Test]
public void Add_default_instance_with_concrete_type_with_a_non_transient_lifecycle()
{
var theProfileName = "something";
IContainer container = new Container(registry => {
registry.For<IWidget>().Use<MoneyWidget>();
registry.Profile(theProfileName, p =>
{
p.For<IWidget>().Use<AWidget>().Singleton();
p.For<Rule>().Use<DefaultRule>();
});
});
var profile = container.GetProfile(theProfileName);
profile.GetInstance<IWidget>().ShouldBeOfType<AWidget>();
profile.GetInstance<Rule>().ShouldBeOfType<DefaultRule>();
profile.GetNestedContainer().GetInstance<IWidget>()
.ShouldBeOfType<AWidget>();
}
[Test]
public void Add_default_instance_with_literal()
{
var registry = new Registry();
var theWidget = new AWidget();
var theProfileName = "something";
registry.Profile(theProfileName, p => { p.For<IWidget>().Use(theWidget); });
var graph = registry.Build();
graph.Profile("something").Families[typeof (IWidget)].GetDefaultInstance()
.ShouldBeOfType<ObjectInstance<AWidget, IWidget>>()
.Object.ShouldBeTheSameAs(theWidget);
}
public class NamedWidget : IWidget
{
private readonly string _name;
public void DoSomething()
{
throw new System.NotImplementedException();
}
public NamedWidget(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
}
}
[Test]
public void AddAProfileWithANamedDefault()
{
var theProfileName = "TheProfile";
var theDefaultName = "TheDefaultName";
var registry = new Registry();
registry.For<IWidget>().Add(new NamedWidget(theDefaultName)).Named(theDefaultName);
registry.For<IWidget>().Use<AWidget>();
registry.Profile(theProfileName, p => {
p.For<IWidget>().Use(theDefaultName);
p.For<Rule>().Use("DefaultRule");
});
var container = new Container(registry);
container.GetProfile(theProfileName).GetInstance<IWidget>().ShouldBeOfType<NamedWidget>()
.Name.ShouldEqual(theDefaultName);
}
[Test]
public void AddAProfileWithInlineInstanceDefinition()
{
var theProfileName = "TheProfile";
var container = new Container(registry => {
registry.For<IWidget>().Use(new NamedWidget("default"));
registry.Profile(theProfileName, x => { x.For<IWidget>().Use<AWidget>(); });
});
container.GetProfile(theProfileName).GetInstance<IWidget>().ShouldBeOfType<AWidget>();
}
public interface IFoo<T>
{
}
public class DefaultFoo<T> : IFoo<T>
{
}
public class AzureFoo<T> : IFoo<T>
{
}
[Test]
public void respects_open_generics_in_the_profile()
{
var container = new Container(x => {
x.For(typeof (IFoo<>)).Use(typeof (DefaultFoo<>));
x.Profile("Azure", cfg => { cfg.For(typeof (IFoo<>)).Use(typeof (AzureFoo<>)); });
});
container.GetInstance<IFoo<string>>().ShouldBeOfType<DefaultFoo<string>>();
container.GetProfile("Azure").GetInstance<IFoo<string>>()
.ShouldBeOfType<AzureFoo<string>>();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Convert.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System
{
static public partial class Convert
{
#region Methods and constructors
public static Object ChangeType(Object value, TypeCode typeCode)
{
return default(Object);
}
public static Object ChangeType(Object value, Type conversionType)
{
return default(Object);
}
public static Object ChangeType(Object value, TypeCode typeCode, IFormatProvider provider)
{
return default(Object);
}
public static Object ChangeType(Object value, Type conversionType, IFormatProvider provider)
{
return default(Object);
}
public static byte[] FromBase64CharArray(char[] inArray, int offset, int length)
{
return default(byte[]);
}
public static byte[] FromBase64String(string s)
{
return default(byte[]);
}
public static TypeCode GetTypeCode(Object value)
{
Contract.Ensures(((System.TypeCode)(0)) <= Contract.Result<System.TypeCode>());
Contract.Ensures(Contract.Result<System.TypeCode>() <= ((System.TypeCode)(18)));
return default(TypeCode);
}
public static bool IsDBNull(Object value)
{
return default(bool);
}
public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut)
{
Contract.Ensures(0 <= Contract.Result<int>());
return default(int);
}
public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options)
{
Contract.Ensures(0 <= Contract.Result<int>());
return default(int);
}
public static string ToBase64String(byte[] inArray, Base64FormattingOptions options)
{
return default(string);
}
public static string ToBase64String(byte[] inArray)
{
return default(string);
}
public static string ToBase64String(byte[] inArray, int offset, int length)
{
return default(string);
}
public static string ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options)
{
return default(string);
}
public static bool ToBoolean(Decimal value)
{
return default(bool);
}
public static bool ToBoolean(double value)
{
Contract.Ensures(Contract.Result<bool>() == ((value == 0) == false));
return default(bool);
}
public static bool ToBoolean(DateTime value)
{
return default(bool);
}
public static bool ToBoolean(Object value)
{
return default(bool);
}
public static bool ToBoolean(Object value, IFormatProvider provider)
{
return default(bool);
}
public static bool ToBoolean(float value)
{
Contract.Ensures(Contract.Result<bool>() == ((value == 0) == false));
return default(bool);
}
public static bool ToBoolean(byte value)
{
Contract.Ensures(Contract.Result<bool>() == ((value == 0) == false));
return default(bool);
}
public static bool ToBoolean(short value)
{
Contract.Ensures(Contract.Result<bool>() == ((value == 0) == false));
return default(bool);
}
public static bool ToBoolean(ushort value)
{
Contract.Ensures(Contract.Result<bool>() == ((value == 0) == false));
return default(bool);
}
public static bool ToBoolean(bool value)
{
Contract.Ensures(Contract.Result<bool>() == value);
return default(bool);
}
public static bool ToBoolean(sbyte value)
{
Contract.Ensures(Contract.Result<bool>() == ((value == 0) == false));
return default(bool);
}
public static bool ToBoolean(char value)
{
return default(bool);
}
public static bool ToBoolean(int value)
{
Contract.Ensures(Contract.Result<bool>() == ((value == 0) == false));
return default(bool);
}
public static bool ToBoolean(ulong value)
{
return default(bool);
}
public static bool ToBoolean(string value)
{
return default(bool);
}
public static bool ToBoolean(string value, IFormatProvider provider)
{
return default(bool);
}
public static bool ToBoolean(uint value)
{
Contract.Ensures(Contract.Result<bool>() == ((value == 0) == false));
return default(bool);
}
public static bool ToBoolean(long value)
{
Contract.Ensures(Contract.Result<bool>() == ((value == (long)(0)) == false));
return default(bool);
}
public static byte ToByte(bool value)
{
Contract.Ensures(0 <= Contract.Result<byte>());
Contract.Ensures(Contract.Result<byte>() <= 1);
return default(byte);
}
public static byte ToByte(byte value)
{
Contract.Ensures(Contract.Result<byte>() == value);
return default(byte);
}
public static byte ToByte(Object value, IFormatProvider provider)
{
return default(byte);
}
public static byte ToByte(string value, int fromBase)
{
Contract.Ensures(0 <= Contract.Result<byte>());
Contract.Ensures(Contract.Result<byte>() <= 255);
return default(byte);
}
public static byte ToByte(Object value)
{
return default(byte);
}
public static byte ToByte(char value)
{
Contract.Ensures(Contract.Result<byte>() == (byte)(value));
return default(byte);
}
public static byte ToByte(Decimal value)
{
return default(byte);
}
public static byte ToByte(double value)
{
return default(byte);
}
public static byte ToByte(float value)
{
return default(byte);
}
public static byte ToByte(DateTime value)
{
return default(byte);
}
public static byte ToByte(string value, IFormatProvider provider)
{
return default(byte);
}
public static byte ToByte(string value)
{
return default(byte);
}
public static byte ToByte(ulong value)
{
Contract.Ensures(Contract.Result<byte>() == (byte)(value));
return default(byte);
}
public static byte ToByte(ushort value)
{
Contract.Ensures(Contract.Result<byte>() == (byte)(value));
return default(byte);
}
public static byte ToByte(short value)
{
Contract.Ensures(Contract.Result<byte>() == (byte)(value));
return default(byte);
}
public static byte ToByte(sbyte value)
{
Contract.Ensures(Contract.Result<byte>() == (byte)(value));
return default(byte);
}
public static byte ToByte(long value)
{
Contract.Ensures(0 <= Contract.Result<byte>());
Contract.Ensures(Contract.Result<byte>() == (byte)(value));
return default(byte);
}
public static byte ToByte(uint value)
{
Contract.Ensures(Contract.Result<byte>() == (byte)(value));
return default(byte);
}
public static byte ToByte(int value)
{
Contract.Ensures(Contract.Result<byte>() == (byte)(value));
return default(byte);
}
public static char ToChar(long value)
{
return default(char);
}
public static char ToChar(uint value)
{
return default(char);
}
public static char ToChar(int value)
{
Contract.Ensures(Contract.Result<char>() == (unchecked(char)(value)));
return default(char);
}
public static char ToChar(string value, IFormatProvider provider)
{
Contract.Ensures(value.Length == 1);
return default(char);
}
public static char ToChar(string value)
{
Contract.Ensures(value.Length == 1);
return default(char);
}
public static char ToChar(ulong value)
{
return default(char);
}
public static char ToChar(char value)
{
Contract.Ensures(Contract.Result<char>() == value);
return default(char);
}
public static char ToChar(bool value)
{
return default(char);
}
public static char ToChar(Object value, IFormatProvider provider)
{
return default(char);
}
public static char ToChar(short value)
{
return default(char);
}
public static char ToChar(byte value)
{
return default(char);
}
public static char ToChar(sbyte value)
{
return default(char);
}
public static char ToChar(float value)
{
return default(char);
}
public static char ToChar(Object value)
{
return default(char);
}
public static char ToChar(ushort value)
{
return default(char);
}
public static char ToChar(DateTime value)
{
return default(char);
}
public static char ToChar(Decimal value)
{
return default(char);
}
public static char ToChar(double value)
{
return default(char);
}
public static DateTime ToDateTime(Object value)
{
return default(DateTime);
}
public static DateTime ToDateTime(ulong value)
{
return default(DateTime);
}
public static DateTime ToDateTime(byte value)
{
return default(DateTime);
}
public static DateTime ToDateTime(DateTime value)
{
return default(DateTime);
}
public static DateTime ToDateTime(int value)
{
return default(DateTime);
}
public static DateTime ToDateTime(ushort value)
{
return default(DateTime);
}
public static DateTime ToDateTime(short value)
{
return default(DateTime);
}
public static DateTime ToDateTime(long value)
{
return default(DateTime);
}
public static DateTime ToDateTime(uint value)
{
return default(DateTime);
}
public static DateTime ToDateTime(double value)
{
return default(DateTime);
}
public static DateTime ToDateTime(float value)
{
return default(DateTime);
}
public static DateTime ToDateTime(string value)
{
return default(DateTime);
}
public static DateTime ToDateTime(Decimal value)
{
return default(DateTime);
}
public static DateTime ToDateTime(char value)
{
return default(DateTime);
}
public static DateTime ToDateTime(Object value, IFormatProvider provider)
{
return default(DateTime);
}
public static DateTime ToDateTime(sbyte value)
{
return default(DateTime);
}
public static DateTime ToDateTime(bool value)
{
return default(DateTime);
}
public static DateTime ToDateTime(string value, IFormatProvider provider)
{
return default(DateTime);
}
public static Decimal ToDecimal(double value)
{
return default(Decimal);
}
public static Decimal ToDecimal(Object value)
{
return default(Decimal);
}
public static Decimal ToDecimal(sbyte value)
{
return default(Decimal);
}
public static Decimal ToDecimal(Object value, IFormatProvider provider)
{
return default(Decimal);
}
public static Decimal ToDecimal(int value)
{
return default(Decimal);
}
public static Decimal ToDecimal(ushort value)
{
return default(Decimal);
}
public static Decimal ToDecimal(short value)
{
return default(Decimal);
}
public static Decimal ToDecimal(uint value)
{
return default(Decimal);
}
public static Decimal ToDecimal(float value)
{
return default(Decimal);
}
public static Decimal ToDecimal(ulong value)
{
return default(Decimal);
}
public static Decimal ToDecimal(long value)
{
return default(Decimal);
}
public static Decimal ToDecimal(Decimal value)
{
return default(Decimal);
}
public static Decimal ToDecimal(bool value)
{
return default(Decimal);
}
public static Decimal ToDecimal(DateTime value)
{
return default(Decimal);
}
public static Decimal ToDecimal(string value, IFormatProvider provider)
{
return default(Decimal);
}
public static Decimal ToDecimal(char value)
{
return default(Decimal);
}
public static Decimal ToDecimal(byte value)
{
return default(Decimal);
}
public static Decimal ToDecimal(string value)
{
return default(Decimal);
}
public static double ToDouble(sbyte value)
{
Contract.Ensures(Contract.Result<double>() == (double)(value));
return default(double);
}
public static double ToDouble(ushort value)
{
Contract.Ensures(Contract.Result<double>() == (double)(value));
return default(double);
}
public static double ToDouble(char value)
{
return default(double);
}
public static double ToDouble(uint value)
{
Contract.Ensures(Contract.Result<double>() == (double)((double)(value)));
return default(double);
}
public static double ToDouble(int value)
{
Contract.Ensures(Contract.Result<double>() == (double)(value));
return default(double);
}
public static double ToDouble(Object value, IFormatProvider provider)
{
return default(double);
}
public static double ToDouble(byte value)
{
Contract.Ensures(Contract.Result<double>() == (double)(value));
return default(double);
}
public static double ToDouble(short value)
{
Contract.Ensures(Contract.Result<double>() == (double)(value));
return default(double);
}
public static double ToDouble(Object value)
{
return default(double);
}
public static double ToDouble(long value)
{
Contract.Ensures(Contract.Result<double>() == (double)(value));
return default(double);
}
public static double ToDouble(string value, IFormatProvider provider)
{
return default(double);
}
public static double ToDouble(string value)
{
return default(double);
}
public static double ToDouble(DateTime value)
{
return default(double);
}
public static double ToDouble(bool value)
{
return default(double);
}
public static double ToDouble(float value)
{
Contract.Ensures(Contract.Result<double>() == (double)(value));
return default(double);
}
public static double ToDouble(ulong value)
{
Contract.Ensures(Contract.Result<double>() == (double)((double)(value)));
return default(double);
}
public static double ToDouble(Decimal value)
{
return default(double);
}
public static double ToDouble(double value)
{
Contract.Ensures(Contract.Result<double>() == value);
return default(double);
}
public static short ToInt16(long value)
{
Contract.Ensures(Contract.Result<short>() == (short)(value));
return default(short);
}
public static short ToInt16(ulong value)
{
Contract.Ensures(Contract.Result<short>() == (short)(value));
return default(short);
}
public static short ToInt16(short value)
{
Contract.Ensures(Contract.Result<short>() == value);
return default(short);
}
public static short ToInt16(int value)
{
Contract.Ensures(Contract.Result<short>() == ((short)(value)));
Contract.Ensures(Contract.Result<short>() == (short)(value));
return default(short);
}
public static short ToInt16(uint value)
{
Contract.Ensures(Contract.Result<short>() == (short)(value));
return default(short);
}
public static short ToInt16(DateTime value)
{
return default(short);
}
public static short ToInt16(string value, IFormatProvider provider)
{
return default(short);
}
public static short ToInt16(Decimal value)
{
return default(short);
}
public static short ToInt16(float value)
{
return default(short);
}
public static short ToInt16(double value)
{
return default(short);
}
public static short ToInt16(Object value)
{
return default(short);
}
public static short ToInt16(Object value, IFormatProvider provider)
{
return default(short);
}
public static short ToInt16(string value)
{
return default(short);
}
public static short ToInt16(string value, int fromBase)
{
Contract.Ensures(-32768 <= Contract.Result<short>());
Contract.Ensures(Contract.Result<short>() <= 32767);
return default(short);
}
public static short ToInt16(bool value)
{
Contract.Ensures(0 <= Contract.Result<short>());
Contract.Ensures(Contract.Result<short>() <= 1);
return default(short);
}
public static short ToInt16(byte value)
{
return default(short);
}
public static short ToInt16(ushort value)
{
Contract.Ensures(Contract.Result<short>() == (short)(value));
return default(short);
}
public static short ToInt16(char value)
{
Contract.Ensures(Contract.Result<short>() == (short)(value));
return default(short);
}
public static short ToInt16(sbyte value)
{
return default(short);
}
public static int ToInt32(string value, int fromBase)
{
return default(int);
}
public static int ToInt32(long value)
{
Contract.Ensures(Contract.Result<int>() == (int)(value));
Contract.Ensures(Contract.Result<int>() == value);
return default(int);
}
public static int ToInt32(string value, IFormatProvider provider)
{
return default(int);
}
public static int ToInt32(string value)
{
return default(int);
}
public static int ToInt32(int value)
{
Contract.Ensures(Contract.Result<int>() == value);
return default(int);
}
public static int ToInt32(DateTime value)
{
return default(int);
}
public static int ToInt32(float value)
{
return default(int);
}
public static int ToInt32(ulong value)
{
Contract.Ensures(Contract.Result<int>() == (int)(value));
Contract.Ensures(Contract.Result<int>() == value);
return default(int);
}
public static int ToInt32(Decimal value)
{
return default(int);
}
public static int ToInt32(double value)
{
return default(int);
}
public static int ToInt32(uint value)
{
Contract.Ensures(Contract.Result<int>() <= 2147483647);
Contract.Ensures(Contract.Result<int>() == value);
return default(int);
}
public static int ToInt32(bool value)
{
Contract.Ensures(0 <= Contract.Result<int>());
Contract.Ensures(Contract.Result<int>() <= 1);
return default(int);
}
public static int ToInt32(char value)
{
Contract.Ensures(Contract.Result<int>() == value);
return default(int);
}
public static int ToInt32(Object value)
{
return default(int);
}
public static int ToInt32(Object value, IFormatProvider provider)
{
return default(int);
}
public static int ToInt32(short value)
{
Contract.Ensures(Contract.Result<int>() == value);
return default(int);
}
public static int ToInt32(ushort value)
{
Contract.Ensures(Contract.Result<int>() == value);
return default(int);
}
public static int ToInt32(sbyte value)
{
Contract.Ensures(Contract.Result<int>() == value);
return default(int);
}
public static int ToInt32(byte value)
{
Contract.Ensures(Contract.Result<int>() == value);
return default(int);
}
public static long ToInt64(DateTime value)
{
return default(long);
}
public static long ToInt64(string value, IFormatProvider provider)
{
Contract.Ensures(-9223372036854775808 <= Contract.Result<long>());
Contract.Ensures(Contract.Result<long>() <= 9223372036854775807);
return default(long);
}
public static long ToInt64(string value, int fromBase)
{
return default(long);
}
public static long ToInt64(byte value)
{
return default(long);
}
public static long ToInt64(bool value)
{
Contract.Ensures(0 <= Contract.Result<long>());
Contract.Ensures(Contract.Result<long>() <= 1);
return default(long);
}
public static long ToInt64(char value)
{
return default(long);
}
public static long ToInt64(sbyte value)
{
Contract.Ensures(Contract.Result<long>() == (long)(value));
return default(long);
}
public static long ToInt64(double value)
{
Contract.Ensures(-9223372036854775807 <= Contract.Result<long>());
Contract.Ensures(-9223372036854775808 <= Contract.Result<long>());
Contract.Ensures(Contract.Result<long>() <= 9223372036854775807);
return default(long);
}
public static long ToInt64(Object value)
{
Contract.Ensures(-9223372036854775808 <= Contract.Result<long>());
Contract.Ensures(Contract.Result<long>() <= 9223372036854775807);
return default(long);
}
public static long ToInt64(Object value, IFormatProvider provider)
{
Contract.Ensures(-9223372036854775808 <= Contract.Result<long>());
Contract.Ensures(Contract.Result<long>() <= 9223372036854775807);
return default(long);
}
public static long ToInt64(short value)
{
Contract.Ensures(Contract.Result<long>() == (long)(value));
return default(long);
}
public static long ToInt64(ulong value)
{
Contract.Ensures(Contract.Result<long>() <= 9223372036854775807);
return default(long);
}
public static long ToInt64(long value)
{
Contract.Ensures(Contract.Result<long>() == value);
return default(long);
}
public static long ToInt64(float value)
{
Contract.Ensures(-9223372036854775807 <= Contract.Result<long>());
return default(long);
}
public static long ToInt64(ushort value)
{
return default(long);
}
public static long ToInt64(int value)
{
Contract.Ensures(-2147483648 <= Contract.Result<long>());
Contract.Ensures(Contract.Result<long>() <= 2147483647);
Contract.Ensures(Contract.Result<long>() == (long)(value));
Contract.Ensures(Contract.Result<long>() == value);
return default(long);
}
public static long ToInt64(uint value)
{
return default(long);
}
public static long ToInt64(string value)
{
Contract.Ensures(-9223372036854775808 <= Contract.Result<long>());
Contract.Ensures(Contract.Result<long>() <= 9223372036854775807);
return default(long);
}
public static long ToInt64(Decimal value)
{
return default(long);
}
public static sbyte ToSByte(byte value)
{
Contract.Ensures(Contract.Result<sbyte>() <= 127);
Contract.Ensures(Contract.Result<sbyte>() == (sbyte)(value));
return default(sbyte);
}
public static sbyte ToSByte(char value)
{
Contract.Ensures(Contract.Result<sbyte>() <= 127);
Contract.Ensures(Contract.Result<sbyte>() == (sbyte)(value));
return default(sbyte);
}
public static sbyte ToSByte(ushort value)
{
Contract.Ensures(Contract.Result<sbyte>() <= 127);
Contract.Ensures(Contract.Result<sbyte>() == (sbyte)(value));
return default(sbyte);
}
public static sbyte ToSByte(short value)
{
Contract.Ensures(-128 <= Contract.Result<sbyte>());
Contract.Ensures(Contract.Result<sbyte>() <= 127);
Contract.Ensures(Contract.Result<sbyte>() == (sbyte)(value));
return default(sbyte);
}
public static sbyte ToSByte(Object value, IFormatProvider provider)
{
return default(sbyte);
}
public static sbyte ToSByte(Decimal value)
{
return default(sbyte);
}
public static sbyte ToSByte(sbyte value)
{
Contract.Ensures(Contract.Result<sbyte>() == value);
return default(sbyte);
}
public static sbyte ToSByte(bool value)
{
Contract.Ensures(0 <= Contract.Result<sbyte>());
Contract.Ensures(Contract.Result<sbyte>() <= 1);
return default(sbyte);
}
public static sbyte ToSByte(int value)
{
Contract.Ensures(-128 <= Contract.Result<sbyte>());
Contract.Ensures(Contract.Result<sbyte>() <= 127);
Contract.Ensures(Contract.Result<sbyte>() == (sbyte)(value));
return default(sbyte);
}
public static sbyte ToSByte(ulong value)
{
Contract.Ensures(Contract.Result<sbyte>() <= 127);
Contract.Ensures(Contract.Result<sbyte>() == (sbyte)(value));
return default(sbyte);
}
public static sbyte ToSByte(string value)
{
return default(sbyte);
}
public static sbyte ToSByte(double value)
{
return default(sbyte);
}
public static sbyte ToSByte(string value, int fromBase)
{
Contract.Ensures(-128 <= Contract.Result<sbyte>());
Contract.Ensures(Contract.Result<sbyte>() <= 127);
return default(sbyte);
}
public static sbyte ToSByte(float value)
{
return default(sbyte);
}
public static sbyte ToSByte(long value)
{
Contract.Ensures(-128 <= Contract.Result<sbyte>());
Contract.Ensures(Contract.Result<sbyte>() <= 127);
Contract.Ensures(Contract.Result<sbyte>() == (sbyte)(value));
return default(sbyte);
}
public static sbyte ToSByte(uint value)
{
Contract.Ensures(Contract.Result<sbyte>() <= 127);
Contract.Ensures(Contract.Result<sbyte>() == (sbyte)(value));
return default(sbyte);
}
public static sbyte ToSByte(Object value)
{
return default(sbyte);
}
public static sbyte ToSByte(string value, IFormatProvider provider)
{
return default(sbyte);
}
public static sbyte ToSByte(DateTime value)
{
return default(sbyte);
}
public static float ToSingle(ushort value)
{
Contract.Ensures(Contract.Result<float>() == (float)(value));
return default(float);
}
public static float ToSingle(short value)
{
Contract.Ensures(Contract.Result<float>() == (float)(value));
return default(float);
}
public static float ToSingle(uint value)
{
Contract.Ensures(Contract.Result<float>() == (float)((double)(value)));
return default(float);
}
public static float ToSingle(int value)
{
Contract.Ensures(Contract.Result<float>() == (float)(value));
return default(float);
}
public static float ToSingle(char value)
{
return default(float);
}
public static float ToSingle(Object value, IFormatProvider provider)
{
return default(float);
}
public static float ToSingle(Object value)
{
return default(float);
}
public static float ToSingle(byte value)
{
Contract.Ensures(Contract.Result<float>() == (float)(value));
return default(float);
}
public static float ToSingle(sbyte value)
{
Contract.Ensures(Contract.Result<float>() == (float)(value));
return default(float);
}
public static float ToSingle(bool value)
{
return default(float);
}
public static float ToSingle(DateTime value)
{
return default(float);
}
public static float ToSingle(string value)
{
return default(float);
}
public static float ToSingle(string value, IFormatProvider provider)
{
return default(float);
}
public static float ToSingle(Decimal value)
{
return default(float);
}
public static float ToSingle(ulong value)
{
Contract.Ensures(Contract.Result<float>() == (float)((double)(value)));
return default(float);
}
public static float ToSingle(long value)
{
Contract.Ensures(Contract.Result<float>() == (float)(value));
return default(float);
}
public static float ToSingle(double value)
{
Contract.Ensures(Contract.Result<float>() == (float)(value));
return default(float);
}
public static float ToSingle(float value)
{
Contract.Ensures(Contract.Result<float>() == value);
return default(float);
}
public static string ToString(ushort value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(ushort value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(short value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(short value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(uint value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(uint value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(int value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(int value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(byte value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(bool value)
{
return default(string);
}
public static string ToString(bool value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(Object value)
{
return default(string);
}
public static string ToString(Object value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(char value)
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
public static string ToString(sbyte value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(byte value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(char value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(sbyte value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(DateTime value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(string value)
{
Contract.Ensures(Contract.Result<string>() == value);
return default(string);
}
public static string ToString(Decimal value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(DateTime value)
{
return default(string);
}
public static string ToString(string value, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<string>() == value);
return default(string);
}
public static string ToString(int value, int toBase)
{
return default(string);
}
public static string ToString(long value, int toBase)
{
return default(string);
}
public static string ToString(byte value, int toBase)
{
return default(string);
}
public static string ToString(short value, int toBase)
{
return default(string);
}
public static string ToString(ulong value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(ulong value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(long value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(long value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(float value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(Decimal value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(double value, IFormatProvider provider)
{
return default(string);
}
public static string ToString(double value)
{
Contract.Ensures(System.Globalization.CultureInfo.CurrentCulture == System.Threading.Thread.CurrentThread.CurrentCulture);
return default(string);
}
public static string ToString(float value, IFormatProvider provider)
{
return default(string);
}
public static ushort ToUInt16(string value, int fromBase)
{
Contract.Ensures(0 <= Contract.Result<ushort>());
Contract.Ensures(Contract.Result<ushort>() <= 65535);
return default(ushort);
}
public static ushort ToUInt16(Decimal value)
{
return default(ushort);
}
public static ushort ToUInt16(long value)
{
Contract.Ensures(Contract.Result<ushort>() == (ushort)(value));
return default(ushort);
}
public static ushort ToUInt16(ulong value)
{
Contract.Ensures(Contract.Result<ushort>() == (ushort)(value));
return default(ushort);
}
public static ushort ToUInt16(ushort value)
{
Contract.Ensures(Contract.Result<ushort>() == value);
return default(ushort);
}
public static ushort ToUInt16(short value)
{
Contract.Ensures(Contract.Result<ushort>() == (ushort)(value));
return default(ushort);
}
public static ushort ToUInt16(int value)
{
Contract.Ensures(Contract.Result<ushort>() == (unchecked(ushort)(value)));
Contract.Ensures(Contract.Result<ushort>() == (ushort)(value));
return default(ushort);
}
public static ushort ToUInt16(string value, IFormatProvider provider)
{
return default(ushort);
}
public static ushort ToUInt16(DateTime value)
{
return default(ushort);
}
public static ushort ToUInt16(string value)
{
return default(ushort);
}
public static ushort ToUInt16(float value)
{
return default(ushort);
}
public static ushort ToUInt16(double value)
{
return default(ushort);
}
public static ushort ToUInt16(Object value, IFormatProvider provider)
{
return default(ushort);
}
public static ushort ToUInt16(bool value)
{
Contract.Ensures(0 <= Contract.Result<ushort>());
Contract.Ensures(Contract.Result<ushort>() <= 1);
return default(ushort);
}
public static ushort ToUInt16(uint value)
{
Contract.Ensures(Contract.Result<ushort>() == (ushort)(value));
return default(ushort);
}
public static ushort ToUInt16(Object value)
{
return default(ushort);
}
public static ushort ToUInt16(byte value)
{
return default(ushort);
}
public static ushort ToUInt16(char value)
{
return default(ushort);
}
public static ushort ToUInt16(sbyte value)
{
Contract.Ensures(Contract.Result<ushort>() == (ushort)(value));
return default(ushort);
}
public static uint ToUInt32(int value)
{
Contract.Ensures(0 <= Contract.Result<uint>());
Contract.Ensures(Contract.Result<uint>() <= 2147483647);
Contract.Ensures(Contract.Result<uint>() == (unchecked(uint)(value)));
return default(uint);
}
public static uint ToUInt32(float value)
{
return default(uint);
}
public static uint ToUInt32(ulong value)
{
Contract.Ensures(Contract.Result<uint>() <= 4294967295);
Contract.Ensures(Contract.Result<uint>() == (uint)(value));
return default(uint);
}
public static uint ToUInt32(long value)
{
Contract.Ensures(Contract.Result<uint>() <= 4294967295);
Contract.Ensures(Contract.Result<uint>() == (uint)(value));
return default(uint);
}
public static uint ToUInt32(uint value)
{
Contract.Ensures(Contract.Result<uint>() == value);
return default(uint);
}
public static uint ToUInt32(double value)
{
return default(uint);
}
public static uint ToUInt32(Decimal value)
{
return default(uint);
}
public static uint ToUInt32(string value)
{
return default(uint);
}
public static uint ToUInt32(DateTime value)
{
return default(uint);
}
public static uint ToUInt32(string value, int fromBase)
{
return default(uint);
}
public static uint ToUInt32(string value, IFormatProvider provider)
{
return default(uint);
}
public static uint ToUInt32(ushort value)
{
return default(uint);
}
public static uint ToUInt32(bool value)
{
Contract.Ensures(0 <= Contract.Result<uint>());
Contract.Ensures(Contract.Result<uint>() <= 1);
return default(uint);
}
public static uint ToUInt32(Object value)
{
return default(uint);
}
public static uint ToUInt32(Object value, IFormatProvider provider)
{
return default(uint);
}
public static uint ToUInt32(char value)
{
return default(uint);
}
public static uint ToUInt32(short value)
{
Contract.Ensures(0 <= Contract.Result<uint>());
return default(uint);
}
public static uint ToUInt32(byte value)
{
return default(uint);
}
public static uint ToUInt32(sbyte value)
{
Contract.Ensures(0 <= Contract.Result<uint>());
return default(uint);
}
public static ulong ToUInt64(bool value)
{
Contract.Ensures(0 <= Contract.Result<ulong>());
Contract.Ensures(Contract.Result<ulong>() <= 1);
return default(ulong);
}
public static ulong ToUInt64(Object value, IFormatProvider provider)
{
Contract.Ensures(0 <= Contract.Result<ulong>());
return default(ulong);
}
public static ulong ToUInt64(string value)
{
Contract.Ensures(0 <= Contract.Result<ulong>());
return default(ulong);
}
public static ulong ToUInt64(Object value)
{
Contract.Ensures(0 <= Contract.Result<ulong>());
return default(ulong);
}
public static ulong ToUInt64(ushort value)
{
Contract.Ensures(Contract.Result<ulong>() == (ulong)(value));
return default(ulong);
}
public static ulong ToUInt64(sbyte value)
{
return default(ulong);
}
public static ulong ToUInt64(char value)
{
Contract.Ensures(Contract.Result<ulong>() == (ulong)(value));
return default(ulong);
}
public static ulong ToUInt64(short value)
{
return default(ulong);
}
public static ulong ToUInt64(byte value)
{
Contract.Ensures(Contract.Result<ulong>() == (ulong)(value));
return default(ulong);
}
public static ulong ToUInt64(Decimal value)
{
return default(ulong);
}
public static ulong ToUInt64(float value)
{
Contract.Ensures(Contract.Result<ulong>() <= 4294967295);
return default(ulong);
}
public static ulong ToUInt64(DateTime value)
{
return default(ulong);
}
public static ulong ToUInt64(double value)
{
Contract.Ensures(0 <= Contract.Result<ulong>());
Contract.Ensures(Contract.Result<ulong>() <= 4294967295);
return default(ulong);
}
public static ulong ToUInt64(string value, IFormatProvider provider)
{
Contract.Ensures(0 <= Contract.Result<ulong>());
return default(ulong);
}
public static ulong ToUInt64(int value)
{
Contract.Ensures(Contract.Result<ulong>() <= 2147483647);
Contract.Ensures(Contract.Result<ulong>() == (unchecked(ulong)(value)));
return default(ulong);
}
public static ulong ToUInt64(string value, int fromBase)
{
Contract.Ensures(Contract.Result<ulong>() <= 9223372036854775807);
return default(ulong);
}
public static ulong ToUInt64(uint value)
{
Contract.Ensures(Contract.Result<ulong>() == (ulong)(value));
return default(ulong);
}
public static ulong ToUInt64(ulong value)
{
Contract.Ensures(Contract.Result<ulong>() == value);
return default(ulong);
}
public static ulong ToUInt64(long value)
{
Contract.Ensures(Contract.Result<ulong>() <= 9223372036854775807);
return default(ulong);
}
#endregion
#region Fields
public readonly static Object DBNull;
#endregion
}
}
| |
//
// Copyright 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.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MonoMac.Foundation;
namespace MonoMac.ObjCRuntime {
internal abstract class NativeImplementationBuilder {
internal static AssemblyBuilder builder;
internal static ModuleBuilder module;
#if !MONOMAC_BOOTSTRAP
private static MethodInfo convertarray = typeof (NSArray).GetMethod ("ArrayFromHandle", new Type [] { typeof (IntPtr) });
private static MethodInfo convertsarray = typeof (NSArray).GetMethod ("StringArrayFromHandle", new Type [] { typeof (IntPtr) });
private static MethodInfo convertstring = typeof (NSString).GetMethod ("ToString", new Type [] {});
private static MethodInfo getobject = typeof (Runtime).GetMethod ("GetNSObject", BindingFlags.Static | BindingFlags.Public);
private static MethodInfo gethandle = typeof (NSObject).GetMethod ("get_Handle", BindingFlags.Instance | BindingFlags.Public);
private static FieldInfo intptrzero = typeof (IntPtr).GetField ("Zero", BindingFlags.Static | BindingFlags.Public);
#endif
private Delegate del;
static NativeImplementationBuilder () {
builder = AppDomain.CurrentDomain.DefineDynamicAssembly (new AssemblyName {Name = "ObjCImplementations"}, AssemblyBuilderAccess.Run, null, null, null, null, null, true);
module = builder.DefineDynamicModule ("Implementations", false);
}
internal abstract Delegate CreateDelegate ();
internal int ArgumentOffset {
get; set;
}
internal IntPtr Selector {
get; set;
}
internal Type [] ParameterTypes {
get; set;
}
internal ParameterInfo [] Parameters {
get; set;
}
internal Delegate Delegate {
get {
if (del == null)
del = CreateDelegate ();
return del;
}
}
internal Type DelegateType {
get; set;
}
internal string Signature {
get; set;
}
protected Type CreateDelegateType (Type return_type, Type [] argument_types) {
TypeBuilder type = module.DefineType (Guid.NewGuid ().ToString (), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof (MulticastDelegate));
type.SetCustomAttribute (new CustomAttributeBuilder (typeof (MarshalAsAttribute).GetConstructor (new Type [] { typeof (UnmanagedType) }), new object [] { UnmanagedType.FunctionPtr }));
ConstructorBuilder constructor = type.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard, new Type [] { typeof (object), typeof (int) });
constructor.SetImplementationFlags (MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
MethodBuilder method = null;
method = type.DefineMethod ("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, return_type, argument_types);
if (NeedsCustomMarshaler (return_type))
SetupParameter (method, 0, return_type);
for (int i = 1; i <= argument_types.Length; i++)
if (NeedsCustomMarshaler (argument_types [i - 1]))
SetupParameter (method, i, argument_types [i - 1]);
method.SetImplementationFlags (MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
return type.CreateType ();
}
private bool NeedsCustomMarshaler (Type t) {
if (t == typeof (NSObject) || t.IsSubclassOf (typeof (NSObject)))
return true;
if (t == typeof (Selector))
return true;
return false;
}
private Type MarshalerForType (Type t) {
if (t == typeof (NSObject) || t.IsSubclassOf (typeof (NSObject)))
return typeof (NSObjectMarshaler<>).MakeGenericType (t);
if (t == typeof (Selector))
return typeof (SelectorMarshaler);
throw new ArgumentException ("Cannot determine marshaler type for: " + t);
}
private void SetupParameter (MethodBuilder builder, int index, Type t) {
ParameterBuilder pb = builder.DefineParameter (index, ParameterAttributes.HasFieldMarshal, string.Format ("arg{0}", index));
ConstructorInfo cinfo = typeof (MarshalAsAttribute).GetConstructor (new Type[] { typeof (UnmanagedType) });
FieldInfo mtrfld = typeof (MarshalAsAttribute).GetField ("MarshalTypeRef");
CustomAttributeBuilder cabuilder = new CustomAttributeBuilder (cinfo, new object [] { UnmanagedType.CustomMarshaler }, new FieldInfo [] { mtrfld }, new object [] { MarshalerForType (t) });
pb.SetCustomAttribute (cabuilder);
}
protected bool IsWrappedType (Type type) {
if (type == typeof (NSObject) || type.IsSubclassOf (typeof (NSObject)) || type == typeof (string))
return true;
return false;
}
protected void ConvertParameters (ParameterInfo [] parms, bool isstatic, bool isstret) {
if (isstret) {
ArgumentOffset = 3;
ParameterTypes = new Type [ArgumentOffset + parms.Length];
ParameterTypes [0] = typeof (IntPtr);
ParameterTypes [1] = isstatic ? typeof (IntPtr) : typeof (NSObject);
ParameterTypes [2] = typeof (Selector);
} else {
ArgumentOffset = 2;
ParameterTypes = new Type [ArgumentOffset + parms.Length];
ParameterTypes [0] = isstatic ? typeof (IntPtr) : typeof (NSObject);
ParameterTypes [1] = typeof (Selector);
}
for (int i = 0; i < Parameters.Length; i++) {
if (Parameters [i].ParameterType.IsByRef && IsWrappedType (Parameters [i].ParameterType.GetElementType ()))
ParameterTypes [i + ArgumentOffset] = typeof (IntPtr).MakeByRefType ();
else if (Parameters [i].ParameterType.IsArray && IsWrappedType (Parameters [i].ParameterType.GetElementType ()))
ParameterTypes [i + ArgumentOffset] = typeof (IntPtr);
else if (typeof (INativeObject).IsAssignableFrom (Parameters [i].ParameterType) && !IsWrappedType (Parameters [i].ParameterType))
ParameterTypes [i + ArgumentOffset] = typeof (IntPtr);
else if (Parameters [i].ParameterType == typeof (string))
ParameterTypes [i + ArgumentOffset] = typeof (NSString);
else
ParameterTypes [i + ArgumentOffset] = Parameters [i].ParameterType;
// The TypeConverter will emit a ^@ for a byref type that is a NSObject or NSObject subclass in this case
// If we passed the ParameterTypes [i+ArgumentOffset] as would be more logical we would emit a ^^v for that case, which
// while currently acceptible isn't representative of what obj-c wants.
Signature += TypeConverter.ToNative (Parameters [i].ParameterType);
}
}
protected void DeclareLocals (ILGenerator il) {
for (int i = 0; i < Parameters.Length; i++) {
if (Parameters [i].ParameterType.IsByRef && IsWrappedType (Parameters [i].ParameterType.GetElementType ())) {
il.DeclareLocal (Parameters [i].ParameterType.GetElementType ());
} else if (Parameters [i].ParameterType.IsArray && IsWrappedType (Parameters [i].ParameterType.GetElementType ())) {
il.DeclareLocal (Parameters [i].ParameterType);
} else if (Parameters [i].ParameterType == typeof (string)) {
il.DeclareLocal (typeof (string));
}
}
}
protected void ConvertArguments (ILGenerator il, int locoffset) {
#if !MONOMAC_BOOTSTRAP
for (int i = ArgumentOffset, j = 0; i < ParameterTypes.Length; i++) {
if (Parameters [i-ArgumentOffset].ParameterType.IsByRef && IsWrappedType (Parameters[i-ArgumentOffset].ParameterType.GetElementType ())) {
il.Emit (OpCodes.Ldarg, i);
il.Emit (OpCodes.Ldind_I);
il.Emit (OpCodes.Call, getobject);
il.Emit (OpCodes.Stloc, j+locoffset);
j++;
} else if (Parameters [i-ArgumentOffset].ParameterType.IsArray && IsWrappedType (Parameters [i-ArgumentOffset].ParameterType.GetElementType ())) {
il.Emit (OpCodes.Ldarg, i);
if (Parameters [i-ArgumentOffset].ParameterType.GetElementType () == typeof (string))
il.Emit (OpCodes.Call, convertsarray);
else
il.Emit (OpCodes.Call, convertarray.MakeGenericMethod (Parameters [i-ArgumentOffset].ParameterType.GetElementType ()));
il.Emit (OpCodes.Stloc, j+locoffset);
j++;
} else if (Parameters [i-ArgumentOffset].ParameterType == typeof (string)) {
il.Emit (OpCodes.Ldarg, i);
il.Emit (OpCodes.Call, convertstring);
il.Emit (OpCodes.Stloc, j+locoffset);
j++;
}
}
#endif
}
protected void LoadArguments (ILGenerator il, int locoffset) {
for (int i = ArgumentOffset, j = 0; i < ParameterTypes.Length; i++) {
if (Parameters [i-ArgumentOffset].ParameterType.IsByRef && IsWrappedType (Parameters[i-ArgumentOffset].ParameterType.GetElementType ())) {
il.Emit (OpCodes.Ldloca_S, j+locoffset);
j++;
} else if (Parameters [i-ArgumentOffset].ParameterType.IsArray && IsWrappedType (Parameters [i-ArgumentOffset].ParameterType.GetElementType ())) {
il.Emit (OpCodes.Ldloc, j+locoffset);
j++;
} else if (typeof (INativeObject).IsAssignableFrom (Parameters [i-ArgumentOffset].ParameterType) && !IsWrappedType (Parameters [i-ArgumentOffset].ParameterType)) {
il.Emit (OpCodes.Ldarg, i);
il.Emit (OpCodes.Newobj, Parameters [i-ArgumentOffset].ParameterType.GetConstructor (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type [] { typeof (IntPtr) }, null));
} else if (Parameters [i-ArgumentOffset].ParameterType == typeof (string)) {
il.Emit (OpCodes.Ldloc, j+locoffset);
j++;
} else {
il.Emit (OpCodes.Ldarg, i);
}
}
}
protected void UpdateByRefArguments (ILGenerator il, int locoffset) {
#if !MONOMAC_BOOTSTRAP
for (int i = ArgumentOffset, j = 0; i < ParameterTypes.Length; i++) {
if (Parameters [i-ArgumentOffset].ParameterType.IsByRef && IsWrappedType (Parameters[i-ArgumentOffset].ParameterType.GetElementType ())) {
Label nullout = il.DefineLabel ();
Label done = il.DefineLabel ();
il.Emit (OpCodes.Ldloc, j+locoffset);
il.Emit (OpCodes.Brfalse, nullout);
il.Emit (OpCodes.Ldarg, i);
il.Emit (OpCodes.Ldloc, j+locoffset);
il.Emit (OpCodes.Call, gethandle);
il.Emit (OpCodes.Stind_I);
il.Emit (OpCodes.Br, done);
il.MarkLabel (nullout);
il.Emit (OpCodes.Ldarg, i);
il.Emit (OpCodes.Ldsfld, intptrzero);
il.Emit (OpCodes.Stind_I);
il.MarkLabel (done);
j++;
}
}
#endif
}
}
}
| |
#if DOTNET35 // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Security;
namespace System.Numerics
{
// ATTENTION: always pass BitsBuffer by reference,
// it's a structure for performance reasons. Furthermore
// it's a mutable one, so use it only with care!
internal static partial class BigIntegerCalculator
{
// To spare memory allocations a buffer helps reusing memory!
// We just create the target array twice and switch between every
// operation. In order to not compute unnecessarily with all those
// leading zeros we take care of the current actual length.
internal struct BitsBuffer
{
private uint[] _bits;
private int _length;
public BitsBuffer(int size, uint value)
{
Debug.Assert(size >= 1);
_bits = new uint[size];
_length = value != 0 ? 1 : 0;
_bits[0] = value;
}
public BitsBuffer(int size, uint[] value)
{
Debug.Assert(value != null);
Debug.Assert(size >= ActualLength(value));
_bits = new uint[size];
_length = ActualLength(value);
Array.Copy(value, 0, _bits, 0, _length);
}
[SecuritySafeCritical]
public unsafe void MultiplySelf(ref BitsBuffer value,
ref BitsBuffer temp)
{
Debug.Assert(temp._length == 0);
Debug.Assert(_length + value._length <= temp._bits.Length);
// Executes a multiplication for this and value, writes the
// result to temp. Switches this and temp arrays afterwards.
fixed (uint* b = _bits, v = value._bits, t = temp._bits)
{
if (_length < value._length)
{
Multiply(v, value._length,
b, _length,
t, _length + value._length);
}
else
{
Multiply(b, _length,
v, value._length,
t, _length + value._length);
}
}
Apply(ref temp, _length + value._length);
}
[SecuritySafeCritical]
public unsafe void SquareSelf(ref BitsBuffer temp)
{
Debug.Assert(temp._length == 0);
Debug.Assert(_length + _length <= temp._bits.Length);
// Executes a square for this, writes the result to temp.
// Switches this and temp arrays afterwards.
fixed (uint* b = _bits, t = temp._bits)
{
Square(b, _length,
t, _length + _length);
}
Apply(ref temp, _length + _length);
}
public void Reduce(ref FastReducer reducer)
{
// Executes a modulo operation using an optimized reducer.
// Thus, no need of any switching here, happens in-line.
_length = reducer.Reduce(_bits, _length);
}
[SecuritySafeCritical]
public unsafe void Reduce(uint[] modulus)
{
Debug.Assert(modulus != null);
// Executes a modulo operation using the divide operation.
// Thus, no need of any switching here, happens in-line.
if (_length >= modulus.Length)
{
fixed (uint* b = _bits, m = modulus)
{
Divide(b, _length,
m, modulus.Length,
null, 0);
}
_length = ActualLength(_bits, modulus.Length);
}
}
[SecuritySafeCritical]
public unsafe void Reduce(ref BitsBuffer modulus)
{
// Executes a modulo operation using the divide operation.
// Thus, no need of any switching here, happens in-line.
if (_length >= modulus._length)
{
fixed (uint* b = _bits, m = modulus._bits)
{
Divide(b, _length,
m, modulus._length,
null, 0);
}
_length = ActualLength(_bits, modulus._length);
}
}
public void Overwrite(ulong value)
{
Debug.Assert(_bits.Length >= 2);
if (_length > 2)
{
// Ensure leading zeros
Array.Clear(_bits, 2, _length - 2);
}
uint lo = unchecked((uint)value);
uint hi = (uint)(value >> 32);
_bits[0] = lo;
_bits[1] = hi;
_length = hi != 0 ? 2 : lo != 0 ? 1 : 0;
}
public void Overwrite(uint value)
{
Debug.Assert(_bits.Length >= 1);
if (_length > 1)
{
// Ensure leading zeros
Array.Clear(_bits, 1, _length - 1);
}
_bits[0] = value;
_length = value != 0 ? 1 : 0;
}
public uint[] GetBits()
{
return _bits;
}
public int GetSize()
{
return _bits.Length;
}
public int GetLength()
{
return _length;
}
public void Refresh(int maxLength)
{
Debug.Assert(_bits.Length >= maxLength);
if (_length > maxLength)
{
// Ensure leading zeros
Array.Clear(_bits, maxLength, _length - maxLength);
}
_length = ActualLength(_bits, maxLength);
}
private void Apply(ref BitsBuffer temp, int maxLength)
{
Debug.Assert(temp._length == 0);
Debug.Assert(maxLength <= temp._bits.Length);
// Resets this and switches this and temp afterwards.
// The caller assumed an empty temp, the next will too.
Array.Clear(_bits, 0, _length);
uint[] t = temp._bits;
temp._bits = _bits;
_bits = t;
_length = ActualLength(_bits, maxLength);
}
}
}
}
#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 Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "GalleryImageDefinition", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)]
[OutputType(typeof(PSGalleryImage))]
public partial class NewAzureRmGalleryImage : ComputeAutomationBaseCmdlet
{
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (ShouldProcess(this.Name, VerbsCommon.New))
{
string resourceGroupName = this.ResourceGroupName;
string galleryName = this.GalleryName;
string galleryImageName = this.Name;
GalleryImage galleryImage = new GalleryImage();
galleryImage.Location = this.Location;
galleryImage.Identifier = new GalleryImageIdentifier(this.Publisher, this.Offer, this.Sku);
galleryImage.OsState = this.OsState;
galleryImage.OsType = this.OsType;
if (this.MyInvocation.BoundParameters.ContainsKey("Description"))
{
galleryImage.Description = this.Description;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Eula"))
{
galleryImage.Eula = this.Eula;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PrivacyStatementUri"))
{
galleryImage.PrivacyStatementUri = this.PrivacyStatementUri;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ReleaseNoteUri"))
{
galleryImage.ReleaseNoteUri = this.ReleaseNoteUri;
}
if (this.MyInvocation.BoundParameters.ContainsKey("EndOfLifeDate"))
{
galleryImage.EndOfLifeDate = this.EndOfLifeDate;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Tag"))
{
galleryImage.Tags = this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value);
}
if (this.MyInvocation.BoundParameters.ContainsKey("MinimumVCPU"))
{
if (galleryImage.Recommended == null)
{
galleryImage.Recommended = new RecommendedMachineConfiguration();
}
if (galleryImage.Recommended.VCPUs == null)
{
galleryImage.Recommended.VCPUs = new ResourceRange();
}
galleryImage.Recommended.VCPUs.Min = this.MinimumVCPU;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaximumVCPU"))
{
if (galleryImage.Recommended == null)
{
galleryImage.Recommended = new RecommendedMachineConfiguration();
}
if (galleryImage.Recommended.VCPUs == null)
{
galleryImage.Recommended.VCPUs = new ResourceRange();
}
galleryImage.Recommended.VCPUs.Max = this.MaximumVCPU;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MinimumMemory"))
{
if (galleryImage.Recommended == null)
{
galleryImage.Recommended = new RecommendedMachineConfiguration();
}
if (galleryImage.Recommended.Memory == null)
{
galleryImage.Recommended.Memory = new ResourceRange();
}
galleryImage.Recommended.Memory.Min = this.MinimumMemory;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaximumMemory"))
{
if (galleryImage.Recommended == null)
{
galleryImage.Recommended = new RecommendedMachineConfiguration();
}
if (galleryImage.Recommended.Memory == null)
{
galleryImage.Recommended.Memory = new ResourceRange();
}
galleryImage.Recommended.Memory.Max = this.MaximumMemory;
}
if (this.MyInvocation.BoundParameters.ContainsKey("DisallowedDiskType"))
{
if (galleryImage.Disallowed == null)
{
galleryImage.Disallowed = new Disallowed();
}
galleryImage.Disallowed.DiskTypes = this.DisallowedDiskType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PurchasePlanName"))
{
if (galleryImage.PurchasePlan == null)
{
galleryImage.PurchasePlan = new ImagePurchasePlan();
}
galleryImage.PurchasePlan.Name = this.PurchasePlanName;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PurchasePlanPublisher"))
{
if (galleryImage.PurchasePlan == null)
{
galleryImage.PurchasePlan = new ImagePurchasePlan();
}
galleryImage.PurchasePlan.Publisher = this.PurchasePlanPublisher;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PurchasePlanProduct"))
{
if (galleryImage.PurchasePlan == null)
{
galleryImage.PurchasePlan = new ImagePurchasePlan();
}
galleryImage.PurchasePlan.Product = this.PurchasePlanProduct;
}
var result = GalleryImagesClient.CreateOrUpdate(resourceGroupName, galleryName, galleryImageName, galleryImage);
var psObject = new PSGalleryImage();
ComputeAutomationAutoMapperProfile.Mapper.Map<GalleryImage, PSGalleryImage>(result, psObject);
WriteObject(psObject);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[ResourceGroupCompleter]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string GalleryName { get; set; }
[Alias("GalleryImageDefinitionName")]
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string Name { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }
[Parameter(
Mandatory = true,
Position = 3,
ValueFromPipelineByPropertyName = true)]
[LocationCompleter("Microsoft.Compute/Galleries")]
public string Location { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string Publisher { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string Offer { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string Sku { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public OperatingSystemStateTypes OsState { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public OperatingSystemTypes OsType { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string Description { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string Eula { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PrivacyStatementUri { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string ReleaseNoteUri { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public DateTime EndOfLifeDate { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public int MinimumVCPU { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public int MaximumVCPU { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public int MinimumMemory { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public int MaximumMemory { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string[] DisallowedDiskType { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PurchasePlanName { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PurchasePlanPublisher { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PurchasePlanProduct { get; set; }
}
[Cmdlet(VerbsData.Update, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "GalleryImageDefinition", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)]
[OutputType(typeof(PSGalleryImage))]
public partial class UpdateAzureRmGalleryImage : ComputeAutomationBaseCmdlet
{
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (ShouldProcess(this.Name, VerbsData.Update))
{
string resourceGroupName;
string galleryName;
string galleryImageName;
switch (this.ParameterSetName)
{
case "ResourceIdParameter":
resourceGroupName = GetResourceGroupName(this.ResourceId);
galleryName = GetResourceName(this.ResourceId, "Microsoft.Compute/Galleries", "Images");
galleryImageName = GetInstanceId(this.ResourceId, "Microsoft.Compute/Galleries", "Images");
break;
case "ObjectParameter":
resourceGroupName = GetResourceGroupName(this.InputObject.Id);
galleryName = GetResourceName(this.InputObject.Id, "Microsoft.Compute/Galleries", "Images");
galleryImageName = GetInstanceId(this.InputObject.Id, "Microsoft.Compute/Galleries", "Images");
break;
default:
resourceGroupName = this.ResourceGroupName;
galleryName = this.GalleryName;
galleryImageName = this.Name;
break;
}
var galleryImage = new GalleryImage();
if (this.ParameterSetName == "ObjectParameter")
{
ComputeAutomationAutoMapperProfile.Mapper.Map<PSGalleryImage, GalleryImage>(this.InputObject, galleryImage);
}
else
{
galleryImage = GalleryImagesClient.Get(resourceGroupName, galleryName, galleryImageName);
}
if (this.MyInvocation.BoundParameters.ContainsKey("Description"))
{
galleryImage.Description = this.Description;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Eula"))
{
galleryImage.Eula = this.Eula;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PrivacyStatementUri"))
{
galleryImage.PrivacyStatementUri = this.PrivacyStatementUri;
}
if (this.MyInvocation.BoundParameters.ContainsKey("ReleaseNoteUri"))
{
galleryImage.ReleaseNoteUri = this.ReleaseNoteUri;
}
if (this.MyInvocation.BoundParameters.ContainsKey("EndOfLifeDate"))
{
galleryImage.EndOfLifeDate = this.EndOfLifeDate;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Tag"))
{
galleryImage.Tags = this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value);
}
if (this.MyInvocation.BoundParameters.ContainsKey("MinimumVCPU"))
{
if (galleryImage.Recommended == null)
{
galleryImage.Recommended = new RecommendedMachineConfiguration();
}
if (galleryImage.Recommended.VCPUs == null)
{
galleryImage.Recommended.VCPUs = new ResourceRange();
}
galleryImage.Recommended.VCPUs.Min = this.MinimumVCPU;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaximumVCPU"))
{
if (galleryImage.Recommended == null)
{
galleryImage.Recommended = new RecommendedMachineConfiguration();
}
if (galleryImage.Recommended.VCPUs == null)
{
galleryImage.Recommended.VCPUs = new ResourceRange();
}
galleryImage.Recommended.VCPUs.Max = this.MaximumVCPU;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MinimumMemory"))
{
if (galleryImage.Recommended == null)
{
galleryImage.Recommended = new RecommendedMachineConfiguration();
}
if (galleryImage.Recommended.Memory == null)
{
galleryImage.Recommended.Memory = new ResourceRange();
}
galleryImage.Recommended.Memory.Min = this.MinimumMemory;
}
if (this.MyInvocation.BoundParameters.ContainsKey("MaximumMemory"))
{
if (galleryImage.Recommended == null)
{
galleryImage.Recommended = new RecommendedMachineConfiguration();
}
if (galleryImage.Recommended.Memory == null)
{
galleryImage.Recommended.Memory = new ResourceRange();
}
galleryImage.Recommended.Memory.Max = this.MaximumMemory;
}
if (this.MyInvocation.BoundParameters.ContainsKey("DisallowedDiskType"))
{
if (galleryImage.Disallowed == null)
{
galleryImage.Disallowed = new Disallowed();
}
galleryImage.Disallowed.DiskTypes = this.DisallowedDiskType;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PurchasePlanName"))
{
if (galleryImage.PurchasePlan == null)
{
galleryImage.PurchasePlan = new ImagePurchasePlan();
}
galleryImage.PurchasePlan.Name = this.PurchasePlanName;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PurchasePlanPublisher"))
{
if (galleryImage.PurchasePlan == null)
{
galleryImage.PurchasePlan = new ImagePurchasePlan();
}
galleryImage.PurchasePlan.Publisher = this.PurchasePlanPublisher;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PurchasePlanProduct"))
{
if (galleryImage.PurchasePlan == null)
{
galleryImage.PurchasePlan = new ImagePurchasePlan();
}
galleryImage.PurchasePlan.Product = this.PurchasePlanProduct;
}
var result = GalleryImagesClient.CreateOrUpdate(resourceGroupName, galleryName, galleryImageName, galleryImage);
var psObject = new PSGalleryImage();
ComputeAutomationAutoMapperProfile.Mapper.Map<GalleryImage, PSGalleryImage>(result, psObject);
WriteObject(psObject);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
[ResourceGroupCompleter]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string GalleryName { get; set; }
[Alias("GalleryImageDefinitionName")]
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string Name { get; set; }
[Parameter(
ParameterSetName = "ResourceIdParameter",
Position = 0,
Mandatory = true,
ValueFromPipelineByPropertyName = true)]
public string ResourceId { get; set; }
[Alias("GalleryImageDefinition")]
[Parameter(
ParameterSetName = "ObjectParameter",
Position = 0,
Mandatory = true,
ValueFromPipeline = true)]
public PSGalleryImage InputObject { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string Description { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string Eula { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PrivacyStatementUri { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string ReleaseNoteUri { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public DateTime EndOfLifeDate { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public int MinimumVCPU { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public int MaximumVCPU { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public int MinimumMemory { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public int MaximumMemory { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string[] DisallowedDiskType { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PurchasePlanName { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PurchasePlanPublisher { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string PurchasePlanProduct { get; set; }
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Modes;
using NBitcoin.BouncyCastle.Crypto.Paddings;
using NBitcoin.BouncyCastle.Crypto.Parameters;
namespace NBitcoin.BouncyCastle.Crypto.Macs
{
/**
* implements a Cipher-FeedBack (CFB) mode on top of a simple cipher.
*/
class MacCFBBlockCipher
: IBlockCipher
{
private byte[] IV;
private byte[] cfbV;
private byte[] cfbOutV;
private readonly int blockSize;
private readonly IBlockCipher cipher;
/**
* Basic constructor.
*
* @param cipher the block cipher to be used as the basis of the
* feedback mode.
* @param blockSize the block size in bits (note: a multiple of 8)
*/
public MacCFBBlockCipher(
IBlockCipher cipher,
int bitBlockSize)
{
this.cipher = cipher;
this.blockSize = bitBlockSize / 8;
this.IV = new byte[cipher.GetBlockSize()];
this.cfbV = new byte[cipher.GetBlockSize()];
this.cfbOutV = new byte[cipher.GetBlockSize()];
}
/**
* Initialise the cipher and, possibly, the initialisation vector (IV).
* If an IV isn't passed as part of the parameter, the IV will be all zeros.
* An IV which is too short is handled in FIPS compliant fashion.
*
* @param param the key and other data required by the cipher.
* @exception ArgumentException if the parameters argument is
* inappropriate.
*/
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
if (parameters is ParametersWithIV)
{
ParametersWithIV ivParam = (ParametersWithIV)parameters;
byte[] iv = ivParam.GetIV();
if (iv.Length < IV.Length)
{
Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length);
}
else
{
Array.Copy(iv, 0, IV, 0, IV.Length);
}
parameters = ivParam.Parameters;
}
Reset();
cipher.Init(true, parameters);
}
/**
* return the algorithm name and mode.
*
* @return the name of the underlying algorithm followed by "/CFB"
* and the block size in bits.
*/
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); }
}
public bool IsPartialBlockOkay
{
get { return true; }
}
/**
* return the block size we are operating at.
*
* @return the block size we are operating at (in bytes).
*/
public int GetBlockSize()
{
return blockSize;
}
/**
* Process one block of input from the array in and write it to
* the out array.
*
* @param in the array containing the input data.
* @param inOff offset into the in array the data starts at.
* @param out the array the output data will be copied into.
* @param outOff the offset into the out array the output will start at.
* @exception DataLengthException if there isn't enough data in in, or
* space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
* @return the number of bytes processed and produced.
*/
public int ProcessBlock(
byte[] input,
int inOff,
byte[] outBytes,
int outOff)
{
if ((inOff + blockSize) > input.Length)
throw new DataLengthException("input buffer too short");
if ((outOff + blockSize) > outBytes.Length)
throw new DataLengthException("output buffer too short");
cipher.ProcessBlock(cfbV, 0, cfbOutV, 0);
//
// XOR the cfbV with the plaintext producing the cipher text
//
for (int i = 0; i < blockSize; i++)
{
outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]);
}
//
// change over the input block.
//
Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize);
Array.Copy(outBytes, outOff, cfbV, cfbV.Length - blockSize, blockSize);
return blockSize;
}
/**
* reset the chaining vector back to the IV and reset the underlying
* cipher.
*/
public void Reset()
{
IV.CopyTo(cfbV, 0);
cipher.Reset();
}
public void GetMacBlock(
byte[] mac)
{
cipher.ProcessBlock(cfbV, 0, mac, 0);
}
}
public class CfbBlockCipherMac
: IMac
{
private byte[] mac;
private byte[] Buffer;
private int bufOff;
private MacCFBBlockCipher cipher;
private IBlockCipherPadding padding;
private int macSize;
/**
* create a standard MAC based on a CFB block cipher. This will produce an
* authentication code half the length of the block size of the cipher, with
* the CFB mode set to 8 bits.
*
* @param cipher the cipher to be used as the basis of the MAC generation.
*/
public CfbBlockCipherMac(
IBlockCipher cipher)
: this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, null)
{
}
/**
* create a standard MAC based on a CFB block cipher. This will produce an
* authentication code half the length of the block size of the cipher, with
* the CFB mode set to 8 bits.
*
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param padding the padding to be used.
*/
public CfbBlockCipherMac(
IBlockCipher cipher,
IBlockCipherPadding padding)
: this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, padding)
{
}
/**
* create a standard MAC based on a block cipher with the size of the
* MAC been given in bits. This class uses CFB mode as the basis for the
* MAC generation.
* <p>
* Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
* or 16 bits if being used as a data authenticator (FIPS Publication 113),
* and in general should be less than the size of the block cipher as it reduces
* the chance of an exhaustive attack (see Handbook of Applied Cryptography).
* </p>
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param cfbBitSize the size of an output block produced by the CFB mode.
* @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
*/
public CfbBlockCipherMac(
IBlockCipher cipher,
int cfbBitSize,
int macSizeInBits)
: this(cipher, cfbBitSize, macSizeInBits, null)
{
}
/**
* create a standard MAC based on a block cipher with the size of the
* MAC been given in bits. This class uses CFB mode as the basis for the
* MAC generation.
* <p>
* Note: the size of the MAC must be at least 24 bits (FIPS Publication 81),
* or 16 bits if being used as a data authenticator (FIPS Publication 113),
* and in general should be less than the size of the block cipher as it reduces
* the chance of an exhaustive attack (see Handbook of Applied Cryptography).
* </p>
* @param cipher the cipher to be used as the basis of the MAC generation.
* @param cfbBitSize the size of an output block produced by the CFB mode.
* @param macSizeInBits the size of the MAC in bits, must be a multiple of 8.
* @param padding a padding to be used.
*/
public CfbBlockCipherMac(
IBlockCipher cipher,
int cfbBitSize,
int macSizeInBits,
IBlockCipherPadding padding)
{
if ((macSizeInBits % 8) != 0)
throw new ArgumentException("MAC size must be multiple of 8");
mac = new byte[cipher.GetBlockSize()];
this.cipher = new MacCFBBlockCipher(cipher, cfbBitSize);
this.padding = padding;
this.macSize = macSizeInBits / 8;
Buffer = new byte[this.cipher.GetBlockSize()];
bufOff = 0;
}
public string AlgorithmName
{
get { return cipher.AlgorithmName; }
}
public void Init(
ICipherParameters parameters)
{
Reset();
cipher.Init(true, parameters);
}
public int GetMacSize()
{
return macSize;
}
public void Update(
byte input)
{
if (bufOff == Buffer.Length)
{
cipher.ProcessBlock(Buffer, 0, mac, 0);
bufOff = 0;
}
Buffer[bufOff++] = input;
}
public void BlockUpdate(
byte[] input,
int inOff,
int len)
{
if (len < 0)
throw new ArgumentException("Can't have a negative input length!");
int blockSize = cipher.GetBlockSize();
int resultLen = 0;
int gapLen = blockSize - bufOff;
if (len > gapLen)
{
Array.Copy(input, inOff, Buffer, bufOff, gapLen);
resultLen += cipher.ProcessBlock(Buffer, 0, mac, 0);
bufOff = 0;
len -= gapLen;
inOff += gapLen;
while (len > blockSize)
{
resultLen += cipher.ProcessBlock(input, inOff, mac, 0);
len -= blockSize;
inOff += blockSize;
}
}
Array.Copy(input, inOff, Buffer, bufOff, len);
bufOff += len;
}
public int DoFinal(
byte[] output,
int outOff)
{
int blockSize = cipher.GetBlockSize();
// pad with zeroes
if (this.padding == null)
{
while (bufOff < blockSize)
{
Buffer[bufOff++] = 0;
}
}
else
{
padding.AddPadding(Buffer, bufOff);
}
cipher.ProcessBlock(Buffer, 0, mac, 0);
cipher.GetMacBlock(mac);
Array.Copy(mac, 0, output, outOff, macSize);
Reset();
return macSize;
}
/**
* Reset the mac generator.
*/
public void Reset()
{
// Clear the buffer.
Array.Clear(Buffer, 0, Buffer.Length);
bufOff = 0;
// Reset the underlying cipher.
cipher.Reset();
}
}
}
| |
//
// Copyright (C) 2009 Amr Hassan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
using System;
using System.Xml;
using System.Collections.Generic;
namespace UB.LastFM.Services
{
/// <summary>
/// A Last.fm album.
/// </summary>
public class Album : Base, IEquatable<Album>, IHasImage, IHasURL
{
/// <summary>
/// The album title.
/// </summary>
public string Title {get; private set;}
/// <summary>
/// The album title/name.
/// </summary>
public string Name {get { return Title; } }
/// <summary>
/// The album's artist.
/// </summary>
public Artist Artist {get; private set; }
/// <summary>
/// The album's wiki on Last.fm.
/// </summary>
public AlbumWiki Wiki {get { return new AlbumWiki(this, Session); } }
/// <summary>
/// Createa an album object.
/// </summary>
/// <param name="artistName">
/// A <see cref="System.String"/>
/// </param>
/// <param name="title">
/// A <see cref="System.String"/>
/// </param>
/// <param name="session">
/// A <see cref="Session"/>
/// </param>
public Album(string artistName, string title, Session session)
:base(session)
{
Artist = new Artist(artistName, Session);
Title = title;
}
/// <summary>
/// Create an album.
/// </summary>
/// <param name="artist">
/// A <see cref="Artist"/>
/// </param>
/// <param name="title">
/// A <see cref="System.String"/>
/// </param>
/// <param name="session">
/// A <see cref="Session"/>
/// </param>
public Album(Artist artist, string title, Session session)
:base(session)
{
Artist = artist;
Title = title;
}
/// <summary>
/// String representation of the object.
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public override string ToString ()
{
return Artist.Name + " - " + Title;
}
internal override RequestParameters getParams ()
{
RequestParameters p = new RequestParameters();
p["artist"] = Artist.Name;
p["album"] = Title;
return p;
}
/// <summary>
/// Returns the album's MusicBrainz ID if available.
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public string GetMBID()
{
XmlDocument doc = request("album.getInfo");
return extract(doc, "mbid");
}
/// <summary>
/// Returns the album ID on Last.fm.
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public string GetID()
{
XmlDocument doc = request("album.getInfo");
return extract(doc, "id");
}
/// <summary>
/// Returns the album's release date.
/// </summary>
/// <returns>
/// A <see cref="DateTime"/>
/// </returns>
public DateTime GetReleaseDate()
{
XmlDocument doc = request("album.getInfo");
return DateTime.Parse(extract(doc, "releasedate"));
}
/// <summary>
/// Returns the url to the album cover if available.
/// </summary>
/// <param name="size">
/// A <see cref="AlbumImageSize"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public string GetImageURL(AlbumImageSize size)
{
XmlDocument doc = request("album.getInfo");
var properties = extractAll(doc, "image", 4);
if (properties.Length >= ((int)size) - 1)
return properties[(int)size];
else
return String.Empty;
}
/// <summary>
/// Returns the url to the album cover if available.
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public string GetImageURL()
{
return GetImageURL(AlbumImageSize.ExtraLarge);
}
/// <summary>
/// Returns the number of listeners on Last.fm.
/// </summary>
/// <returns>
/// A <see cref="System.Int32"/>
/// </returns>
public int GetListenerCount()
{
XmlDocument doc = request("album.getInfo");
return Int32.Parse(extract(doc, "listeners"));
}
/// <summary>
/// Returns the play count on Last.fm.
/// </summary>
/// <returns>
/// A <see cref="System.Int32"/>
/// </returns>
public int GetPlaycount()
{
XmlDocument doc = request("album.getInfo");
return Int32.Parse(extract(doc, "playcount"));
}
/// <summary>
/// Returns an array of the tracks on this album.
/// </summary>
/// <returns>
/// A <see cref="Track"/>
/// </returns>
public Track[] GetTracks()
{
string url = "lastfm://playlist/album/" + this.GetID();
return (new XSPF(url, Session)).GetTracks();
}
/// <summary>
/// Returns the top tags for this album on Last.fm.
/// </summary>
/// <returns>
/// A <see cref="TopTag"/>
/// </returns>
public TopTag[] GetTopTags()
{
XmlDocument doc = request("album.getInfo");
XmlNode node = doc.GetElementsByTagName("toptags")[0];
List<TopTag> list = new List<TopTag>();
foreach(XmlNode n in ((XmlElement)node).GetElementsByTagName("tag"))
{
Tag tag = new Tag(extract(n, "name"), Session);
int count = Int32.Parse(extract(n, "count"));
list.Add(new TopTag(tag, count));
}
return list.ToArray();
}
/// <summary>
/// Returns the top tags for this album on Last.fm.
/// </summary>
/// <param name="limit">
/// A <see cref="System.Int32"/>
/// </param>
/// <returns>
/// A <see cref="TopTag"/>
/// </returns>
public TopTag[] GetTopTags(int limit)
{
return sublist<TopTag>(GetTopTags(), limit);
}
/// <summary>
/// Check to see if this object equals another.
/// </summary>
/// <param name="album">
/// A <see cref="Album"/>
/// </param>
/// <returns>
/// A <see cref="System.Boolean"/>
/// </returns>
public bool Equals(Album album)
{
if(album.Title == this.Title && album.Artist.Name == this.Artist.Name)
return true;
else
return false;
}
/// <summary>
/// Search for an album on Last.fm.
/// </summary>
/// <param name="albumName">
/// A <see cref="System.String"/>
/// </param>
/// <param name="session">
/// A <see cref="Session"/>
/// </param>
/// <returns>
/// A <see cref="AlbumSearch"/>
/// </returns>
public static AlbumSearch Search(string albumName, Session session)
{
return new AlbumSearch(albumName, session);
}
/// <summary>
/// Add tags to this album.
/// </summary>
/// <param name="tags">
/// A <see cref="Tag"/>
/// </param>
public void AddTags(params Tag[] tags)
{
//This method requires authentication
requireAuthentication();
foreach(Tag tag in tags)
{
RequestParameters p = getParams();
p["tags"] = tag.Name;
request("album.addTags", p);
}
}
/// <summary>
/// Add tags to this album.
/// </summary>
/// <param name="tags">
/// A <see cref="System.String"/>
/// </param>
public void AddTags(params string[] tags)
{
foreach(string tag in tags)
AddTags(new Tag(tag, Session));
}
/// <summary>
/// Add tags to this album.
/// </summary>
/// <param name="tags">
/// A <see cref="TagCollection"/>
/// </param>
public void AddTags(TagCollection tags)
{
foreach(Tag tag in tags)
AddTags(tag);
}
/// <summary>
/// Returns the tags set by the authenticated user to this album.
/// </summary>
/// <returns>
/// A <see cref="Tag"/>
/// </returns>
public Tag[] GetTags()
{
//This method requires authentication
requireAuthentication();
XmlDocument doc = request("album.getTags");
TagCollection collection = new TagCollection(Session);
foreach(string name in this.extractAll(doc, "name"))
collection.Add(name);
return collection.ToArray();
}
/// <summary>
/// Remove from your tags on this album.
/// </summary>
/// <param name="tags">
/// A <see cref="Tag"/>
/// </param>
public void RemoveTags(params Tag[] tags)
{
//This method requires authentication
requireAuthentication();
foreach(Tag tag in tags)
{
RequestParameters p = getParams();
p["tag"] = tag.Name;
request("album.removeTag", p);
}
}
/// <summary>
/// Remove from your tags on this album.
/// </summary>
/// <param name="tags">
/// A <see cref="System.String"/>
/// </param>
public void RemoveTags(params string[] tags)
{
//This method requires authentication
requireAuthentication();
foreach(string tag in tags)
RemoveTags(new Tag(tag, Session));
}
/// <summary>
/// Remove from the authenticated user's tags on this album.
/// </summary>
/// <param name="tags">
/// A <see cref="TagCollection"/>
/// </param>
public void RemoveTags(TagCollection tags)
{
foreach(Tag tag in tags)
RemoveTags(tag);
}
/// <summary>
/// Set the authenticated user's tags to only those tags.
/// </summary>
/// <param name="tags">
/// A <see cref="System.String"/>
/// </param>
public void SetTags(string[] tags)
{
List<Tag> list = new List<Tag>();
foreach(string name in tags)
list.Add(new Tag(name, Session));
SetTags(list.ToArray());
}
/// <summary>
/// Set the authenticated user's tags to only those tags.
/// </summary>
/// <param name="tags">
/// A <see cref="Tag"/>
/// </param>
public void SetTags(Tag[] tags)
{
List<Tag> newSet = new List<Tag>(tags);
List<Tag> current = new List<Tag>(GetTags());
List<Tag> toAdd = new List<Tag>();
List<Tag> toRemove = new List<Tag>();
foreach(Tag tag in newSet)
if(!current.Contains(tag))
toAdd.Add(tag);
foreach(Tag tag in current)
if(!newSet.Contains(tag))
toRemove.Add(tag);
if (toAdd.Count > 0)
AddTags(toAdd.ToArray());
if (toRemove.Count > 0)
RemoveTags(toRemove.ToArray());
}
/// <summary>
/// Set the authenticated user's tags to only those tags.
/// </summary>
/// <param name="tags">
/// A <see cref="TagCollection"/>
/// </param>
public void SetTags(TagCollection tags)
{
SetTags(tags.ToArray());
}
/// <summary>
/// Clears all the tags that the authenticated user has set to this album.
/// </summary>
public void ClearTags()
{
foreach(Tag tag in GetTags())
RemoveTags(tag);
}
/// <summary>
/// Returns an album by it's MusicBrainz id.
/// </summary>
/// <param name="mbid">
/// A <see cref="System.String"/>
/// </param>
/// <param name="session">
/// A <see cref="Session"/>
/// </param>
/// <returns>
/// A <see cref="Album"/>
/// </returns>
public static Album GetByMBID(string mbid, Session session)
{
RequestParameters p = new RequestParameters();
p["mbid"] = mbid;
XmlDocument doc = (new Request("album.getInfo", session, p)).execute();
string title = doc.GetElementsByTagName("name")[0].InnerText;
string artist = doc.GetElementsByTagName("artist")[0].InnerText;
return new Album(artist, title, session);
}
/// <summary>
/// Returns the Last.fm page of this object.
/// </summary>
/// <param name="language">
/// A <see cref="SiteLanguage"/>
/// </param>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public string GetURL(SiteLanguage language)
{
string domain = getSiteDomain(language);
return "http://" + domain + "/music/" + urlSafe(Artist.Name) + "/" + urlSafe(Name);
}
/// <value>
/// The Last.fm page of this object.
/// </value>
public string URL
{ get { return GetURL(SiteLanguage.English); } }
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGAssetBroker")]
public class HGAssetBroker : ISharedRegionModule, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private IImprovedAssetCache m_Cache = null;
private IAssetService m_GridService;
private IAssetService m_HGService;
private Scene m_aScene;
private string m_LocalAssetServiceURI;
private bool m_Enabled = false;
private AssetPermissions m_AssetPerms;
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "HGAssetBroker"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetServices", "");
if (name == Name)
{
IConfig assetConfig = source.Configs["AssetService"];
if (assetConfig == null)
{
m_log.Error("[HG ASSET CONNECTOR]: AssetService missing from OpenSim.ini");
return;
}
string localDll = assetConfig.GetString("LocalGridAssetService",
String.Empty);
string HGDll = assetConfig.GetString("HypergridAssetService",
String.Empty);
if (localDll == String.Empty)
{
m_log.Error("[HG ASSET CONNECTOR]: No LocalGridAssetService named in section AssetService");
return;
}
if (HGDll == String.Empty)
{
m_log.Error("[HG ASSET CONNECTOR]: No HypergridAssetService named in section AssetService");
return;
}
Object[] args = new Object[] { source };
m_GridService =
ServerUtils.LoadPlugin<IAssetService>(localDll,
args);
m_HGService =
ServerUtils.LoadPlugin<IAssetService>(HGDll,
args);
if (m_GridService == null)
{
m_log.Error("[HG ASSET CONNECTOR]: Can't load local asset service");
return;
}
if (m_HGService == null)
{
m_log.Error("[HG ASSET CONNECTOR]: Can't load hypergrid asset service");
return;
}
m_LocalAssetServiceURI = assetConfig.GetString("AssetServerURI", string.Empty);
if (m_LocalAssetServiceURI == string.Empty)
{
IConfig netConfig = source.Configs["Network"];
m_LocalAssetServiceURI = netConfig.GetString("asset_server_url", string.Empty);
}
if (m_LocalAssetServiceURI != string.Empty)
m_LocalAssetServiceURI = m_LocalAssetServiceURI.Trim('/');
IConfig hgConfig = source.Configs["HGAssetService"];
m_AssetPerms = new AssetPermissions(hgConfig); // it's ok if arg is null
m_Enabled = true;
m_log.Info("[HG ASSET CONNECTOR]: HG asset broker enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_aScene = scene;
m_aScene.RegisterModuleInterface<IAssetService>(this);
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
if (m_Cache == null)
{
m_Cache = scene.RequestModuleInterface<IImprovedAssetCache>();
if (!(m_Cache is ISharedRegionModule))
m_Cache = null;
}
m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled hypergrid asset broker for region {0}", scene.RegionInfo.RegionName);
if (m_Cache != null)
{
m_log.InfoFormat("[HG ASSET CONNECTOR]: Enabled asset caching for region {0}", scene.RegionInfo.RegionName);
}
}
private bool IsHG(string id)
{
Uri assetUri;
if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) &&
assetUri.Scheme == Uri.UriSchemeHttp)
return true;
return false;
}
public AssetBase Get(string id)
{
//m_log.DebugFormat("[HG ASSET CONNECTOR]: Get {0}", id);
AssetBase asset = null;
if (m_Cache != null)
{
asset = m_Cache.Get(id);
if (asset != null)
return asset;
}
if (IsHG(id))
{
asset = m_HGService.Get(id);
if (asset != null)
{
// Now store it locally, if allowed
if (m_AssetPerms.AllowedImport(asset.Type))
m_GridService.Store(asset);
else
return null;
}
}
else
asset = m_GridService.Get(id);
if (m_Cache != null)
m_Cache.Cache(asset);
return asset;
}
public AssetBase GetCached(string id)
{
if (m_Cache != null)
return m_Cache.Get(id);
return null;
}
public AssetMetadata GetMetadata(string id)
{
AssetBase asset = null;
if (m_Cache != null)
{
if (m_Cache != null)
m_Cache.Get(id);
if (asset != null)
return asset.Metadata;
}
AssetMetadata metadata;
if (IsHG(id))
metadata = m_HGService.GetMetadata(id);
else
metadata = m_GridService.GetMetadata(id);
return metadata;
}
public byte[] GetData(string id)
{
AssetBase asset = null;
if (m_Cache != null)
{
if (m_Cache != null)
m_Cache.Get(id);
if (asset != null)
return asset.Data;
}
if (IsHG(id))
return m_HGService.GetData(id);
else
return m_GridService.GetData(id);
}
public bool Get(string id, Object sender, AssetRetrieved handler)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset != null)
{
Util.FireAndForget(delegate { handler(id, sender, asset); });
return true;
}
if (IsHG(id))
{
return m_HGService.Get(id, sender, delegate (string assetID, Object s, AssetBase a)
{
if (m_Cache != null)
m_Cache.Cache(a);
handler(assetID, s, a);
});
}
else
{
return m_GridService.Get(id, sender, delegate (string assetID, Object s, AssetBase a)
{
if (m_Cache != null)
m_Cache.Cache(a);
handler(assetID, s, a);
});
}
}
public virtual bool[] AssetsExist(string[] ids)
{
int numHG = 0;
foreach (string id in ids)
{
if (IsHG(id))
++numHG;
}
if (numHG == 0)
return m_GridService.AssetsExist(ids);
else if (numHG == ids.Length)
return m_HGService.AssetsExist(ids);
else
throw new Exception("[HG ASSET CONNECTOR]: AssetsExist: all the assets must be either local or foreign");
}
public string Store(AssetBase asset)
{
bool isHG = IsHG(asset.ID);
if ((m_Cache != null) && !isHG)
// Don't store it in the cache if the asset is to
// be sent to the other grid, because this is already
// a copy of the local asset.
m_Cache.Cache(asset);
if (asset.Local)
{
if (m_Cache != null)
m_Cache.Cache(asset);
return asset.ID;
}
string id;
if (IsHG(asset.ID))
{
if (m_AssetPerms.AllowedExport(asset.Type))
id = m_HGService.Store(asset);
else
return String.Empty;
}
else
id = m_GridService.Store(asset);
if (String.IsNullOrEmpty(id))
return string.Empty;
asset.ID = id;
if (m_Cache != null)
m_Cache.Cache(asset);
return id;
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset = null;
if (m_Cache != null)
asset = m_Cache.Get(id);
if (asset != null)
{
asset.Data = data;
m_Cache.Cache(asset);
}
if (IsHG(id))
return m_HGService.UpdateContent(id, data);
else
return m_GridService.UpdateContent(id, data);
}
public bool Delete(string id)
{
if (m_Cache != null)
m_Cache.Expire(id);
bool result = false;
if (IsHG(id))
result = m_HGService.Delete(id);
else
result = m_GridService.Delete(id);
if (result && m_Cache != null)
m_Cache.Expire(id);
return result;
}
}
}
| |
using Loon.Core;
using System.Collections.Generic;
using System.Text;
using System;
using Loon.Core.Resource;
using System.IO;
using Loon.Java;
namespace Loon.Utils.Xml {
public class XMLParser : LRelease {
internal const int OPEN_TAG = 0;
internal const int CLOSE_TAG = 1;
internal const int OPEN_CLOSE_TAG = 2;
private Stack<XMLElement> stack = new Stack<XMLElement>();
private XMLElement topElement;
private XMLElement rootElement;
private StringBuilder header = new StringBuilder(1024);
private void PushElement(XMLElement root, int idx, XMLListener l) {
if (this.topElement == null) {
this.rootElement = root;
} else {
this.topElement.AddContents(root);
}
this.stack.Push(root);
this.topElement = root;
if (l != null) {
l.AddElement(idx, root);
}
}
private void PopElement(int idx, XMLListener l) {
if (l != null) {
l.EndElement(idx, this.topElement);
}
this.stack.Pop();
if (stack.Count > 0) {
this.topElement = (this.stack.Peek());
} else {
this.topElement = null;
}
}
private void NewElement(string context, XMLListener l, int index) {
string o = "";
int i;
string str1;
if (context.EndsWith("/>")) {
i = 2;
str1 = context.Substring(1,(context.Length - 2)-(1));
} else if (context.StartsWith("</")) {
i = 1;
str1 = context.Substring(2,(context.Length - 1)-(2));
} else {
i = 0;
str1 = context.Substring(1,(context.Length - 1)-(1));
}
try {
if (str1.IndexOf(' ') < 0) {
o = str1;
switch (i) {
case OPEN_TAG:
PushElement(new XMLElement(o), index, l);
break;
case CLOSE_TAG:
if (this.topElement.GetName().Equals(o)) {
PopElement(index, l);
} else {
throw new Exception("Expected close of '"
+ this.topElement.GetName() + "' instead of "
+ context);
}
break;
case OPEN_CLOSE_TAG:
PushElement(new XMLElement(o), index, l);
PopElement(index, l);
break;
}
} else {
XMLElement el = null;
o = str1.Substring(0,(str1.IndexOf(' '))-(0));
switch (i) {
case OPEN_TAG:
el = new XMLElement(o);
PushElement(el, index, l);
break;
case CLOSE_TAG:
throw new Exception("Syntax Error: " + context);
case OPEN_CLOSE_TAG:
el = new XMLElement(o);
PushElement(el, index, l);
PopElement(index, l);
break;
}
string str2 = str1.Substring(str1.IndexOf(' ') + 1);
int start = 0;
int end = 0;
StringBuilder sbr1 = new StringBuilder(128);
StringBuilder sbr2 = new StringBuilder(32);
for (int m = 0; m < str2.Length; m++) {
switch ((int) str2[m]) {
case '"':
start = (start != 0) ? 0 : 1;
break;
case ' ':
if ((end == 1) && (start == 1)) {
sbr1.Append(str2[m]);
} else if (sbr2.Length > 0) {
string key = sbr2.ToString();
string value_ren = sbr1.ToString();
if (key.Length > 0) {
XMLAttribute a = el.AddAttribute(key, value_ren);
a.element = el;
if (l != null) {
l.AddAttribute(index, a);
}
}
end = 0;
sbr1.Remove(0,sbr1.Length-(0));
sbr2.Remove(0,sbr2.Length-(0));
}
break;
case '=':
if (start == 0) {
end = 1;
}
break;
case '!':
case '#':
case '$':
case '%':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case '-':
case '.':
case '/':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case ':':
case ';':
case '<':
default:
if (end != 0) {
sbr1.Append(str2[m]);
} else {
sbr2.Append(str2[m]);
}
break;
}
}
if (sbr1.Length > 0) {
string key_0 = sbr2.ToString();
string value_1 = sbr1.ToString();
XMLAttribute a_2 = el.AddAttribute(key_0, value_1);
a_2.element = el;
if (l != null) {
l.AddAttribute(index, a_2);
}
}
}
} catch (Exception e) {
throw new Exception("Cannot parse element '" + context
+ "' - (" + e + ")");
}
}
private void NewData(string data, XMLListener l, int index) {
if (this.topElement != null) {
XMLData xdata = new XMLData(data);
this.topElement.AddContents(xdata);
if (l != null) {
l.AddData(index, xdata);
}
} else if (this.rootElement == null) {
this.header.Append(data);
}
}
private void NewComment(string comment, XMLListener l, int index) {
if (this.topElement != null) {
XMLComment c = new XMLComment(comment.Substring(4,(comment.Length - 3)-(4)));
this.topElement.AddContents(c);
if (l != null) {
l.AddComment(index, c);
}
} else if (this.rootElement == null) {
this.header.Append(comment);
}
}
private void NewProcessing(string p, XMLListener l, int index) {
if (this.topElement != null) {
XMLProcessing xp = new XMLProcessing(p.Substring(2,(p.Length - 2)-(2)));
this.topElement.AddContents(xp);
if (l != null) {
l.AddHeader(index, xp);
}
} else if (this.rootElement == null) {
this.header.Append(p);
}
}
private XMLDocument ParseText(string text, XMLListener l) {
int count = 0;
for (XMLTokenizer tokenizer = new XMLTokenizer(text); tokenizer
.HasMoreElements(); )
{
string str = tokenizer.NextElement();
if ((str.StartsWith("<?")) && (str.EndsWith("?>")))
{
NewProcessing(str, l, count);
}
else if ((str.StartsWith("<!--")) && (str.EndsWith("-->")))
{
NewComment(str, l, count);
}
else if (str[0] == '<')
{
NewElement(str, l, count);
}
else
{
NewData(str, l, count);
}
count++;
}
return new XMLDocument(this.header.ToString(), this.rootElement);
}
public static XMLDocument Parse(string file) {
return Parse(file, null);
}
public static XMLDocument Parse(string file, XMLListener l) {
try {
return Parse(Resources.OpenStream(file), l);
} catch (IOException e) {
throw new Exception(e.Message, e);
}
}
public static XMLDocument Parse(Stream ins0) {
return Parse(ins0, null);
}
public static XMLDocument Parse(Stream ins, XMLListener l) {
StringBuilder sbr = new StringBuilder();
try
{
int i = 0;
while (ins.Length == 0)
{
i++;
try
{
Thread.Sleep(100L);
}
catch
{
}
if (i <= 100)
{
continue;
}
throw new System.Exception("Parser: InputStream timed out !");
}
using (System.IO.StreamReader reader = new System.IO.StreamReader(ins, System.Text.Encoding.UTF8))
{
while (reader.Peek() > -1)
{
sbr.Append(reader.ReadLine());
sbr.Append('\n');
}
if (reader != null)
{
reader.Close();
}
}
}
catch (System.Exception ex)
{
Loon.Utils.Debugging.Log.Exception(ex);
}
finally
{
if (ins != null)
{
ins.Close();
ins = null;
}
}
return new XMLParser().ParseText(sbr.ToString(), l);
}
public void Dispose() {
if (stack != null)
{
stack.Clear();
stack = null;
}
if (topElement != null)
{
topElement.Dispose();
topElement = null;
}
if (rootElement != null)
{
rootElement.Dispose();
rootElement = null;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Linq;
using NUnit.Framework.Constraints;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData;
using NUnit.TestUtilities;
#if ASYNC
using System.Threading.Tasks;
#endif
#if NET40
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.Framework.Assertions
{
[TestFixture]
public class WarningTests
{
[TestCase(nameof(WarningFixture.WarnUnless_Passes_Boolean))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_Boolean))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanWithMessageAndArgs))]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanLambda))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanLambda))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanLambdaWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanLambdaWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanLambdaWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanLambdaWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_BooleanLambdaWithWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_BooleanLambdaWithWithMessageStringFunc))]
#endif
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualAndConstraint))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualAndConstraint))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualAndConstraintWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualAndConstraintWithMessageAndArgs))]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualAndConstraintWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualAndConstraintWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualLambdaAndConstraint))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualLambdaAndConstraint))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualLambdaAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualLambdaAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualLambdaAndConstraintWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualLambdaAndConstraintWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_ActualLambdaAndConstraintWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_ActualLambdaAndConstraintWithMessageStringFunc))]
#endif
[TestCase(nameof(WarningFixture.WarnUnless_Passes_DelegateAndConstraint))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraint))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_DelegateAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraintWithMessage))]
[TestCase(nameof(WarningFixture.WarnUnless_Passes_DelegateAndConstraintWithMessageAndArgs))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraintWithMessageAndArgs))]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Passes_DelegateAndConstraintWithMessageStringFunc))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_DelegateAndConstraintWithMessageStringFunc))]
#endif
#if ASYNC
[TestCase(nameof(WarningFixture.WarnUnless_Passes_Async))]
[TestCase(nameof(WarningFixture.WarnIf_Passes_Async))]
#endif
public void WarningPasses(string methodName)
{
var result = TestBuilder.RunTestCase(typeof(WarningFixture), methodName);
Assert.That(result.ResultState, Is.EqualTo(ResultState.Success));
Assert.That(result.AssertCount, Is.EqualTo(1), "Incorrect AssertCount");
Assert.That(result.AssertionResults.Count, Is.EqualTo(0), "There should be no AssertionResults");
}
[TestCase(nameof(WarningFixture.WarnUnless_Fails_Boolean), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_Boolean), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanWithMessage), "message")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanWithMessage), "message")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanWithMessageAndArgs), "got 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanWithMessageAndArgs), "got 5")]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanWithMessageStringFunc), "got 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanWithMessageStringFunc), "got 5")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanLambda), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanLambda), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanLambdaWithMessage), "message")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanLambdaWithMessage), "message")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanLambdaWithMessageAndArgs), "got 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanLambdaWithMessageAndArgs), "got 5")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_BooleanLambdaWithMessageStringFunc), "got 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_BooleanLambdaWithMessageStringFunc), "got 5")]
#endif
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualAndConstraintWithMessageAndArgs), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualAndConstraintWithMessageAndArgs), "Should be 5")]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualAndConstraintWithMessageStringFunc), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualAndConstraintWithMessageStringFunc), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualLambdaAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualLambdaAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualLambdaAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualLambdaAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualLambdaAndConstraintWithMessageAndArgs), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualLambdaAndConstraintWithMessageAndArgs), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_ActualLambdaAndConstraintWithMessageStringFunc), "Should be 5")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_ActualLambdaAndConstraintWithMessageStringFunc), "Should be 5")]
#endif
[TestCase(nameof(WarningFixture.WarnUnless_Fails_DelegateAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraint), null)]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_DelegateAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraintWithMessage), "Error")]
[TestCase(nameof(WarningFixture.WarnUnless_Fails_DelegateAndConstraintWithMessageAndArgs), "Should be 4")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraintWithMessageAndArgs), "Should be 4")]
#if !NET20
[TestCase(nameof(WarningFixture.WarnUnless_Fails_DelegateAndConstraintWithMessageStringFunc), "Should be 4")]
[TestCase(nameof(WarningFixture.WarnIf_Fails_DelegateAndConstraintWithMessageStringFunc), "Should be 4")]
#endif
#if ASYNC
[TestCase(nameof(WarningFixture.WarnUnless_Fails_Async), null)]
[TestCase(nameof(WarningFixture.WarnIf_Fails_Async), null)]
#endif
public void WarningFails(string methodName, string expectedMessage)
{
var result = TestBuilder.RunTestCase(typeof(WarningFixture), methodName);
Assert.That(result.ResultState, Is.EqualTo(ResultState.Warning));
Assert.That(result.AssertCount, Is.EqualTo(1), "Incorrect AssertCount");
Assert.That(result.AssertionResults.Count, Is.EqualTo(1), "Incorrect number of AssertionResults");
Assert.That(result.AssertionResults[0].Status, Is.EqualTo(AssertionStatus.Warning));
Assert.That(result.AssertionResults[0].Message, Is.Not.Null, "Assertion Message should not be null");
Assert.That(result.Message, Is.Not.Null, "Result Message should not be null");
Assert.That(result.Message, Contains.Substring(result.AssertionResults[0].Message), "Result message should contain assertion message");
Assert.That(result.AssertionResults[0].StackTrace, Does.Contain("WarningFixture"));
Assert.That(result.AssertionResults[0].StackTrace.Split(new char[] { '\n' }).Length, Is.LessThan(3));
if (expectedMessage != null)
{
Assert.That(result.Message, Does.Contain(expectedMessage));
Assert.That(result.AssertionResults[0].Message, Does.Contain(expectedMessage));
}
}
[TestCase(typeof(WarningInSetUpPasses), nameof(WarningInSetUpPasses.WarningPassesInTest), 2, 0)]
[TestCase(typeof(WarningInSetUpPasses), nameof(WarningInSetUpPasses.WarningFailsInTest), 2, 1)]
[TestCase(typeof(WarningInSetUpPasses), nameof(WarningInSetUpPasses.ThreeWarningsFailInTest), 4, 3)]
[TestCase(typeof(WarningInSetUpFails), nameof(WarningInSetUpFails.WarningPassesInTest), 2, 1)]
[TestCase(typeof(WarningInSetUpFails), nameof(WarningInSetUpFails.WarningFailsInTest), 2, 2)]
[TestCase(typeof(WarningInSetUpFails), nameof(WarningInSetUpFails.ThreeWarningsFailInTest), 4, 4)]
[TestCase(typeof(WarningInTearDownPasses), nameof(WarningInTearDownPasses.WarningPassesInTest), 2, 0)]
[TestCase(typeof(WarningInTearDownPasses), nameof(WarningInTearDownPasses.WarningFailsInTest), 2, 1)]
[TestCase(typeof(WarningInTearDownPasses), nameof(WarningInTearDownPasses.ThreeWarningsFailInTest), 4, 3)]
[TestCase(typeof(WarningInTearDownFails), nameof(WarningInTearDownFails.WarningPassesInTest), 2, 1)]
[TestCase(typeof(WarningInTearDownFails), nameof(WarningInTearDownFails.WarningFailsInTest), 2, 2)]
[TestCase(typeof(WarningInTearDownFails), nameof(WarningInTearDownFails.ThreeWarningsFailInTest), 4, 4)]
public void WarningUsedInSetUpOrTearDown(Type fixtureType, string methodName, int expectedAsserts, int expectedWarnings)
{
var result = TestBuilder.RunTestCase(fixtureType, methodName);
Assert.That(result.ResultState, Is.EqualTo(expectedWarnings == 0 ? ResultState.Success : ResultState.Warning));
Assert.That(result.AssertCount, Is.EqualTo(expectedAsserts), "Incorrect AssertCount");
Assert.That(result.AssertionResults.Count, Is.EqualTo(expectedWarnings), $"There should be {expectedWarnings} AssertionResults");
}
#if !NET20
[Test]
public void PassingAssertion_DoesNotCallExceptionStringFunc()
{
// Arrange
var funcWasCalled = false;
Func<string> getExceptionMessage = () =>
{
funcWasCalled = true;
return "Func was called";
};
// Act
using (new TestExecutionContext.IsolatedContext())
Warn.Unless(0 + 1 == 1, getExceptionMessage);
// Assert
Assert.That(!funcWasCalled, "The getExceptionMessage function was called when it should not have been.");
}
[Test]
public void FailingWarning_CallsExceptionStringFunc()
{
// Arrange
var funcWasCalled = false;
Func<string> getExceptionMessage = () =>
{
funcWasCalled = true;
return "Func was called";
};
// Act
using (new TestExecutionContext.IsolatedContext())
Warn.Unless(1 + 1 == 1, getExceptionMessage);
// Assert
Assert.That(funcWasCalled, "The getExceptionMessage function was not called when it should have been.");
}
#endif
#if ASYNC
[Test]
public void WarnUnless_Async_Error()
{
#if !NET40
var exception =
#endif
Assert.Throws<InvalidOperationException>(() =>
Warn.Unless(async () => await ThrowExceptionGenericTask(), Is.EqualTo(1)));
#if !NET40
Assert.That(exception.StackTrace, Does.Contain("ThrowExceptionGenericTask"));
#endif
}
[Test]
public void WarnIf_Async_Error()
{
#if !NET40
var exception =
#endif
Assert.Throws<InvalidOperationException>(() =>
Warn.If(async () => await ThrowExceptionGenericTask(), Is.Not.EqualTo(1)));
#if !NET40
Assert.That(exception.StackTrace, Does.Contain("ThrowExceptionGenericTask"));
#endif
}
private static Task<int> One()
{
return Task.Run(() => 1);
}
private static async Task<int> ThrowExceptionGenericTask()
{
await One();
throw new InvalidOperationException();
}
#endif
// We decided to trim ExecutionContext and below because ten lines per warning adds up
// and makes it hard to read build logs.
// See https://github.com/nunit/nunit/pull/2431#issuecomment-328404432.
[TestCase(nameof(WarningFixture.WarningSynchronous), 1)]
[TestCase(nameof(WarningFixture.WarningInThreadStart), 2)]
#if !PLATFORM_DETECTION
[TestCase(nameof(WarningFixture.WarningInBeginInvoke), 5)]
#else
[TestCase(nameof(WarningFixture.WarningInBeginInvoke), 5, ExcludePlatform = "mono", Reason = "Warning has no effect inside BeginInvoke on Mono")]
#endif
[TestCase(nameof(WarningFixture.WarningInThreadPoolQueueUserWorkItem), 2)]
#if ASYNC
[TestCase(nameof(WarningFixture.WarningInTaskRun), 4)]
[TestCase(nameof(WarningFixture.WarningAfterAwaitTaskDelay), 5)]
#endif
public static void StackTracesAreFiltered(string methodName, int maxLineCount)
{
var result = TestBuilder.RunTestCase(typeof(WarningFixture), methodName);
if (result.FailCount != 0 && result.Message.StartsWith(typeof(PlatformNotSupportedException).FullName))
{
return; // BeginInvoke causes PlatformNotSupportedException on .NET Core
}
if (result.AssertionResults.Count != 1 || result.AssertionResults[0].Status != AssertionStatus.Warning)
{
Assert.Fail("Expected a single warning assertion. Message: " + result.Message);
}
var warningStackTrace = result.AssertionResults[0].StackTrace;
var lines = warningStackTrace.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (maxLineCount < lines.Length)
{
Assert.Fail(
$"Expected the number of lines to be no more than {maxLineCount}, but it was {lines.Length}:" + Environment.NewLine
+ Environment.NewLine
+ string.Concat(lines.Select((line, i) => $" {i + 1}. {line.Trim()}" + Environment.NewLine).ToArray())
+ "(end)");
// ^ Most of that is to differentiate it from the current method's stack trace
// reported directly underneath at the same level of indentation.
}
}
}
}
| |
using System;
using System.Collections.Generic;
using ALinq.Mapping;
using System.Globalization;
using System.Linq.Expressions;
namespace ALinq.SqlClient
{
internal static class PreBindDotNetConverter
{
// Methods
internal static bool CanConvert(SqlNode node)
{
var bo = node as SqlBinary;
if ((bo == null) || (!IsCompareToValue(bo) && !IsVbCompareStringEqualsValue(bo)))
{
var m = node as SqlMember;
if ((m == null) || !IsSupportedMember(m))
{
var mc = node as SqlMethodCall;
if ((mc == null) || (!IsSupportedMethod(mc) && !IsSupportedVbHelperMethod(mc)))
{
return false;
}
}
}
return true;
}
internal static SqlNode Convert(SqlNode node, SqlFactory sql, MetaModel model)
{
return new Visitor(sql, model).Visit(node);
}
private static bool IsCompareMethod(SqlMethodCall call)
{
return (((call.Method.IsStatic && (call.Method.Name == "Compare")) && (call.Arguments.Count > 1)) &&
(call.Method.ReturnType == typeof(int)));
}
private static bool IsCompareToMethod(SqlMethodCall call)
{
return (((!call.Method.IsStatic && (call.Method.Name == "CompareTo")) && (call.Arguments.Count == 1)) &&
(call.Method.ReturnType == typeof(int)));
}
private static bool IsCompareToValue(SqlBinary bo)
{
if ((!IsComparison(bo.NodeType) || (bo.Left.NodeType != SqlNodeType.MethodCall)) ||
(bo.Right.NodeType != SqlNodeType.Value))
{
return false;
}
var left = (SqlMethodCall)bo.Left;
if (!IsCompareToMethod(left))
{
return IsCompareMethod(left);
}
return true;
}
private static bool IsComparison(SqlNodeType nodeType)
{
switch (nodeType)
{
case SqlNodeType.EQ:
case SqlNodeType.EQ2V:
case SqlNodeType.LE:
case SqlNodeType.LT:
case SqlNodeType.GE:
case SqlNodeType.GT:
case SqlNodeType.NE:
case SqlNodeType.NE2V:
return true;
}
return false;
}
private static bool IsNullableHasValue(SqlMember m)
{
return (TypeSystem.IsNullableType(m.Expression.ClrType) && (m.Member.Name == "HasValue"));
}
private static bool IsNullableValue(SqlMember m)
{
return (TypeSystem.IsNullableType(m.Expression.ClrType) && (m.Member.Name == "Value"));
}
private static bool IsSupportedMember(SqlMember m)
{
if (!IsNullableHasValue(m))
{
return IsNullableHasValue(m);
}
return true;
}
private static bool IsSupportedMethod(SqlMethodCall mc)
{
if (mc.Method.IsStatic)
{
switch (mc.Method.Name)
{
case "op_Equality":
case "op_Inequality":
case "op_LessThan":
case "op_LessThanOrEqual":
case "op_GreaterThan":
case "op_GreaterThanOrEqual":
case "op_Multiply":
case "op_Division":
case "op_Subtraction":
case "op_Addition":
case "op_Modulus":
case "op_BitwiseAnd":
case "op_BitwiseOr":
case "op_ExclusiveOr":
case "op_UnaryNegation":
case "op_OnesComplement":
case "op_False":
return true;
case "Equals":
return (mc.Arguments.Count == 2);
case "Concat":
return (mc.Method.DeclaringType == typeof(string));
}
return false;
}
return (((mc.Method.Name == "Equals") && (mc.Arguments.Count == 1)) ||
((mc.Method.Name == "GetType") && (mc.Arguments.Count == 0)));
}
private static bool IsSupportedVbHelperMethod(SqlMethodCall mc)
{
return IsVbIIF(mc);
}
private static bool IsVbCompareString(SqlMethodCall call)
{
return ((call.Method.IsStatic &&
(call.Method.DeclaringType.FullName == "Microsoft.VisualBasic.CompilerServices.Operators")) &&
(call.Method.Name == "CompareString"));
}
private static bool IsVbCompareStringEqualsValue(SqlBinary bo)
{
return (((IsComparison(bo.NodeType) && (bo.Left.NodeType == SqlNodeType.MethodCall)) &&
(bo.Right.NodeType == SqlNodeType.Value)) && IsVbCompareString((SqlMethodCall)bo.Left));
}
private static bool IsVbIIF(SqlMethodCall mc)
{
return ((mc.Method.IsStatic && (mc.Method.DeclaringType.FullName == "Microsoft.VisualBasic.Interaction")) &&
(mc.Method.Name == "IIf"));
}
// Nested Types
private class Visitor : SqlVisitor
{
// Fields
private readonly MetaModel model;
private readonly SqlFactory sql;
// Methods
internal Visitor(SqlFactory sql, MetaModel model)
{
this.sql = sql;
this.model = model;
}
private SqlExpression CreateComparison(SqlExpression a, SqlExpression b, Expression source)
{
SqlExpression match = this.sql.Binary(SqlNodeType.LT, a, b);
SqlExpression expression2 = this.sql.Binary(SqlNodeType.EQ2V, a, b);
return sql.SearchedCase(
new[] {
new SqlWhen(match, this.sql.ValueFromObject(-1, false, source)),
new SqlWhen(expression2, this.sql.ValueFromObject(0, false, source))
},
this.sql.ValueFromObject(1, false, source), source);
}
private SqlBinary MakeCompareTo(SqlExpression left, SqlExpression right, SqlNodeType op, int iValue)
{
if (iValue == 0)
{
return this.sql.Binary(op, left, right);
}
if ((op == SqlNodeType.EQ) || (op == SqlNodeType.EQ2V))
{
switch (iValue)
{
case -1:
return this.sql.Binary(SqlNodeType.LT, left, right);
case 1:
return this.sql.Binary(SqlNodeType.GT, left, right);
}
}
return null;
}
private SqlExpression TranslateVbIIF(SqlMethodCall mc)
{
if (mc.Arguments[1].ClrType != mc.Arguments[2].ClrType)
{
throw Error.IifReturnTypesMustBeEqual(mc.Arguments[1].ClrType.Name, mc.Arguments[2].ClrType.Name);
}
var list = new List<SqlWhen>(1) { new SqlWhen(mc.Arguments[0], mc.Arguments[1]) };
var @else = mc.Arguments[2];
while (@else.NodeType == SqlNodeType.SearchedCase)
{
var @case = (SqlSearchedCase)@else;
list.AddRange(@case.Whens);
@else = @case.Else;
}
return this.sql.SearchedCase(list.ToArray(), @else, mc.SourceExpression);
}
internal override SqlExpression VisitBinaryOperator(SqlBinary bo)
{
if (IsCompareToValue(bo))
{
var left = (SqlMethodCall)bo.Left;
if (IsCompareToMethod(left))
{
int iValue = System.Convert.ToInt32(Eval(bo.Right), CultureInfo.InvariantCulture);
bo = MakeCompareTo(left.Object, left.Arguments[0], bo.NodeType, iValue) ?? bo;
}
else if (IsCompareMethod(left))
{
int num2 = System.Convert.ToInt32(Eval(bo.Right), CultureInfo.InvariantCulture);
bo = MakeCompareTo(left.Arguments[0], left.Arguments[1], bo.NodeType, num2) ?? bo;
}
}
else if (IsVbCompareStringEqualsValue(bo))
{
var call2 = (SqlMethodCall)bo.Left;
int num3 = System.Convert.ToInt32(Eval(bo.Right), CultureInfo.InvariantCulture);
var value2 = call2.Arguments[1] as SqlValue;
if ((value2 != null) && (value2.Value == null))
{
var right = new SqlValue(value2.ClrType, value2.SqlType, string.Empty,
value2.IsClientSpecified, value2.SourceExpression);
bo = MakeCompareTo(call2.Arguments[0], right, bo.NodeType, num3) ?? bo;
}
else
{
bo = MakeCompareTo(call2.Arguments[0], call2.Arguments[1], bo.NodeType, num3) ?? bo;
}
}
return base.VisitBinaryOperator(bo);
}
protected override SqlNode VisitMember(SqlMember m)
{
m.Expression = this.VisitExpression(m.Expression);
if (IsNullableValue(m))
{
return sql.UnaryValueOf(m.Expression, m.SourceExpression);
}
if (IsNullableHasValue(m))
{
return sql.Unary(SqlNodeType.IsNotNull, m.Expression, m.SourceExpression);
}
return m;
}
internal override SqlExpression VisitMethodCall(SqlMethodCall mc)
{
mc.Object = this.VisitExpression(mc.Object);
int num = 0;
int count = mc.Arguments.Count;
while (num < count)
{
mc.Arguments[num] = this.VisitExpression(mc.Arguments[num]);
num++;
}
if (mc.Method.IsStatic)
{
if ((mc.Method.Name == "Equals") && (mc.Arguments.Count == 2))
{
return this.sql.Binary(SqlNodeType.EQ2V, mc.Arguments[0], mc.Arguments[1], mc.Method);
}
if ((mc.Method.DeclaringType == typeof(string)) && (mc.Method.Name == "Concat"))
{
SqlExpression expression;
var array = mc.Arguments[0] as SqlClientArray;
var expressions = array != null ? array.Expressions : mc.Arguments;
if (expressions.Count == 0)
{
return this.sql.ValueFromObject("", false, mc.SourceExpression);
}
if (expressions[0].SqlType.IsString || expressions[0].SqlType.IsChar)
{
expression = expressions[0];
}
else
{
expression = this.sql.ConvertTo(typeof(string), expressions[0]);
}
for (int i = 1; i < expressions.Count; i++)
{
if (expressions[i].SqlType.IsString || expressions[i].SqlType.IsChar)
{
expression = this.sql.Concat(new SqlExpression[] { expression, expressions[i] }, mc.SourceExpression);
}
else
{
expression =
this.sql.Concat(new SqlExpression[]
{
expression, this.sql.ConvertTo(typeof (string), expressions[i])
}, mc.SourceExpression);
}
}
return expression;
}
if (PreBindDotNetConverter.IsVbIIF(mc))
{
return this.TranslateVbIIF(mc);
}
switch (mc.Method.Name)
{
case "op_Equality":
return this.sql.Binary(SqlNodeType.EQ, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_Inequality":
return this.sql.Binary(SqlNodeType.NE, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_LessThan":
return this.sql.Binary(SqlNodeType.LT, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_LessThanOrEqual":
return this.sql.Binary(SqlNodeType.LE, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_GreaterThan":
return this.sql.Binary(SqlNodeType.GT, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_GreaterThanOrEqual":
return this.sql.Binary(SqlNodeType.GE, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_Multiply":
return this.sql.Binary(SqlNodeType.Mul, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_Division":
return this.sql.Binary(SqlNodeType.Div, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_Subtraction":
return this.sql.Binary(SqlNodeType.Sub, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_Addition":
return this.sql.Binary(SqlNodeType.Add, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_Modulus":
return this.sql.Binary(SqlNodeType.Mod, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_BitwiseAnd":
return this.sql.Binary(SqlNodeType.BitAnd, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_BitwiseOr":
return this.sql.Binary(SqlNodeType.BitOr, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_ExclusiveOr":
return this.sql.Binary(SqlNodeType.BitXor, mc.Arguments[0], mc.Arguments[1], mc.Method,
mc.ClrType);
case "op_UnaryNegation":
return this.sql.Unary(SqlNodeType.Negate, mc.Arguments[0], mc.Method, mc.SourceExpression);
case "op_OnesComplement":
return this.sql.Unary(SqlNodeType.BitNot, mc.Arguments[0], mc.Method, mc.SourceExpression);
case "op_False":
return this.sql.Unary(SqlNodeType.Not, mc.Arguments[0], mc.Method, mc.SourceExpression);
}
return mc;
}
if ((mc.Method.Name == "Equals") && (mc.Arguments.Count == 1))
{
return this.sql.Binary(SqlNodeType.EQ, mc.Object, mc.Arguments[0]);
}
if (!(mc.Method.Name == "GetType") || (mc.Arguments.Count != 0))
{
return mc;
}
MetaType sourceMetaType = TypeSource.GetSourceMetaType(mc.Object, this.model);
if (sourceMetaType.HasInheritance)
{
Type type = sourceMetaType.Discriminator.Type;
var discriminator = new SqlDiscriminatorOf(mc.Object, type,
this.sql.TypeProvider.From(type),
mc.SourceExpression);
return this.VisitExpression(this.sql.DiscriminatedType(discriminator, sourceMetaType));
}
return this.VisitExpression(this.sql.StaticType(sourceMetaType, mc.SourceExpression));
}
internal override SqlExpression VisitTreat(SqlUnary t)
{
t.Operand = this.VisitExpression(t.Operand);
Type clrType = t.ClrType;
Type type = this.model.GetMetaType(t.Operand.ClrType).InheritanceRoot.Type;
clrType = TypeSystem.GetNonNullableType(clrType);
type = TypeSystem.GetNonNullableType(type);
if (clrType == type)
{
return t.Operand;
}
if (clrType.IsAssignableFrom(type))
{
t.Operand.SetClrType(clrType);
return t.Operand;
}
if ((!clrType.IsAssignableFrom(type) && !type.IsAssignableFrom(clrType)) &&
(!clrType.IsInterface && !type.IsInterface))
{
return this.sql.TypedLiteralNull(clrType, t.SourceExpression);
}
return t;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO.Pipelines;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.SignalR.Protocol;
using Microsoft.AspNetCore.SignalR.Tests;
using Microsoft.AspNetCore.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.SignalR.Client.Tests
{
public partial class HubConnectionTests
{
public class Reconnect : VerifiableLoggedTest
{
[Fact]
public async Task IsNotEnabledByDefault()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ShutdownWithError" ||
writeContext.EventId.Name == "ServerDisconnectedWithError");
}
using (StartVerifiableLog(ExpectedErrors))
{
var exception = new Exception();
var testConnection = new TestConnection();
await using var hubConnection = CreateHubConnection(testConnection, loggerFactory: LoggerFactory);
var reconnectingCalled = false;
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCalled = true;
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
await hubConnection.StartAsync().DefaultTimeout();
testConnection.CompleteFromTransport(exception);
Assert.Same(exception, await closedErrorTcs.Task.DefaultTimeout());
Assert.False(reconnectingCalled);
}
}
[Fact]
public async Task CanBeOptedInto()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ServerDisconnectedWithError" ||
writeContext.EventId.Name == "ReconnectingWithError");
}
var failReconnectTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var testConnectionFactory = default(ReconnectingConnectionFactory);
var startCallCount = 0;
var originalConnectionId = "originalConnectionId";
var reconnectedConnectionId = "reconnectedConnectionId";
async Task OnTestConnectionStart()
{
startCallCount++;
// Only fail the first reconnect attempt.
if (startCallCount == 2)
{
await failReconnectTcs.Task;
}
var testConnection = await testConnectionFactory.GetNextOrCurrentTestConnection();
// Change the connection id before reconnecting.
if (startCallCount == 3)
{
testConnection.ConnectionId = reconnectedConnectionId;
}
else
{
testConnection.ConnectionId = originalConnectionId;
}
}
testConnectionFactory = new ReconnectingConnectionFactory(() => new TestConnection(OnTestConnectionStart));
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var retryContexts = new List<RetryContext>();
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
retryContexts.Add(context);
return TimeSpan.Zero;
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var reconnectedConnectionIdTcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
reconnectingErrorTcs.SetResult(error);
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
reconnectedConnectionIdTcs.SetResult(connectionId);
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
await hubConnection.StartAsync().DefaultTimeout();
Assert.Same(originalConnectionId, hubConnection.ConnectionId);
var firstException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(firstException);
Assert.Same(firstException, await reconnectingErrorTcs.Task.DefaultTimeout());
Assert.Single(retryContexts);
Assert.Same(firstException, retryContexts[0].RetryReason);
Assert.Equal(0, retryContexts[0].PreviousRetryCount);
Assert.Equal(TimeSpan.Zero, retryContexts[0].ElapsedTime);
var reconnectException = new Exception();
failReconnectTcs.SetException(reconnectException);
Assert.Same(reconnectedConnectionId, await reconnectedConnectionIdTcs.Task.DefaultTimeout());
Assert.Equal(2, retryContexts.Count);
Assert.Same(reconnectException, retryContexts[1].RetryReason);
Assert.Equal(1, retryContexts[1].PreviousRetryCount);
Assert.True(TimeSpan.Zero <= retryContexts[1].ElapsedTime);
await hubConnection.StopAsync().DefaultTimeout();
var closeError = await closedErrorTcs.Task.DefaultTimeout();
Assert.Null(closeError);
Assert.Equal(1, reconnectingCount);
Assert.Equal(1, reconnectedCount);
}
}
[Fact]
public async Task StopsIfTheReconnectPolicyReturnsNull()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ServerDisconnectedWithError" ||
writeContext.EventId.Name == "ReconnectingWithError");
}
var failReconnectTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var startCallCount = 0;
Task OnTestConnectionStart()
{
startCallCount++;
// Fail the first reconnect attempts.
if (startCallCount > 1)
{
return failReconnectTcs.Task;
}
return Task.CompletedTask;
}
var testConnectionFactory = new ReconnectingConnectionFactory(() => new TestConnection(OnTestConnectionStart));
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var retryContexts = new List<RetryContext>();
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
retryContexts.Add(context);
return context.PreviousRetryCount == 0 ? TimeSpan.Zero : (TimeSpan?)null;
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
reconnectingErrorTcs.SetResult(error);
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
await hubConnection.StartAsync().DefaultTimeout();
var firstException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(firstException);
Assert.Same(firstException, await reconnectingErrorTcs.Task.DefaultTimeout());
Assert.Single(retryContexts);
Assert.Same(firstException, retryContexts[0].RetryReason);
Assert.Equal(0, retryContexts[0].PreviousRetryCount);
Assert.Equal(TimeSpan.Zero, retryContexts[0].ElapsedTime);
var reconnectException = new Exception();
failReconnectTcs.SetException(reconnectException);
var closeError = await closedErrorTcs.Task.DefaultTimeout();
Assert.IsType<OperationCanceledException>(closeError);
Assert.Equal(2, retryContexts.Count);
Assert.Same(reconnectException, retryContexts[1].RetryReason);
Assert.Equal(1, retryContexts[1].PreviousRetryCount);
Assert.True(TimeSpan.Zero <= retryContexts[1].ElapsedTime);
Assert.Equal(1, reconnectingCount);
Assert.Equal(0, reconnectedCount);
}
}
[Fact]
[LogLevel(LogLevel.Trace)]
public async Task HasCorrectRetryNumberAfterRetriesExhausted()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ServerDisconnectedWithError" ||
writeContext.EventId.Name == "ReconnectingWithError");
}
var failReconnectTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using (var logCollector = StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var startCallCount = 0;
Task OnTestConnectionStart()
{
startCallCount++;
// Fail the first reconnect attempts.
if (startCallCount > 1)
{
return failReconnectTcs.Task;
}
return Task.CompletedTask;
}
var testConnectionFactory = new ReconnectingConnectionFactory(() => new TestConnection(OnTestConnectionStart));
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var retryContexts = new List<RetryContext>();
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
retryContexts.Add(context);
return context.PreviousRetryCount == 0 ? TimeSpan.Zero : (TimeSpan?)null;
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
reconnectingErrorTcs.SetResult(error);
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
await hubConnection.StartAsync().DefaultTimeout();
var firstException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(firstException);
Assert.Same(firstException, await reconnectingErrorTcs.Task.DefaultTimeout());
var reconnectException = new Exception();
failReconnectTcs.SetException(reconnectException);
var closeError = await closedErrorTcs.Task.DefaultTimeout();
Assert.IsType<OperationCanceledException>(closeError);
Assert.Contains($"after {reconnectingCount} failed attempts", closeError.Message);
var logs = logCollector.GetLogs();
var attemptsLog = logs.SingleOrDefault(r => r.Write.EventId.Name == "ReconnectAttemptsExhausted");
Assert.NotNull(attemptsLog);
Assert.Contains($"after {reconnectingCount} failed attempts", attemptsLog.Write.Message);
Assert.Equal(LogLevel.Information, attemptsLog.Write.LogLevel);
var waitingLog = logs.SingleOrDefault(r => r.Write.EventId.Name == "AwaitingReconnectRetryDelay");
Assert.NotNull(waitingLog);
Assert.Contains($"Reconnect attempt number 1 will start in ", waitingLog.Write.Message);
Assert.Equal(LogLevel.Trace, waitingLog.Write.LogLevel);
Assert.Equal(0, reconnectedCount);
}
}
[Fact]
public async Task CanHappenMultipleTimes()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ServerDisconnectedWithError" ||
writeContext.EventId.Name == "ReconnectingWithError");
}
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var testConnectionFactory = new ReconnectingConnectionFactory();
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var retryContexts = new List<RetryContext>();
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
retryContexts.Add(context);
return TimeSpan.Zero;
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var reconnectedConnectionIdTcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
reconnectingErrorTcs.SetResult(error);
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
reconnectedConnectionIdTcs.SetResult(connectionId);
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
await hubConnection.StartAsync().DefaultTimeout();
var firstException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(firstException);
Assert.Same(firstException, await reconnectingErrorTcs.Task.DefaultTimeout());
Assert.Single(retryContexts);
Assert.Same(firstException, retryContexts[0].RetryReason);
Assert.Equal(0, retryContexts[0].PreviousRetryCount);
Assert.Equal(TimeSpan.Zero, retryContexts[0].ElapsedTime);
await reconnectedConnectionIdTcs.Task.DefaultTimeout();
Assert.Equal(1, reconnectingCount);
Assert.Equal(1, reconnectedCount);
Assert.Equal(TaskStatus.WaitingForActivation, closedErrorTcs.Task.Status);
reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
reconnectedConnectionIdTcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var secondException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(secondException);
Assert.Same(secondException, await reconnectingErrorTcs.Task.DefaultTimeout());
Assert.Equal(2, retryContexts.Count);
Assert.Same(secondException, retryContexts[1].RetryReason);
Assert.Equal(0, retryContexts[1].PreviousRetryCount);
Assert.Equal(TimeSpan.Zero, retryContexts[1].ElapsedTime);
await reconnectedConnectionIdTcs.Task.DefaultTimeout();
Assert.Equal(2, reconnectingCount);
Assert.Equal(2, reconnectedCount);
Assert.Equal(TaskStatus.WaitingForActivation, closedErrorTcs.Task.Status);
await hubConnection.StopAsync().DefaultTimeout();
var closeError = await closedErrorTcs.Task.DefaultTimeout();
Assert.Null(closeError);
Assert.Equal(2, reconnectingCount);
Assert.Equal(2, reconnectedCount);
}
}
[Fact]
public async Task CanBeInducedByCloseMessageWithAllowReconnectSet()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ReceivedCloseWithError" ||
writeContext.EventId.Name == "ReconnectingWithError");
}
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var testConnectionFactory = default(ReconnectingConnectionFactory);
testConnectionFactory = new ReconnectingConnectionFactory(() => new TestConnection());
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var retryContexts = new List<RetryContext>();
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
retryContexts.Add(context);
return TimeSpan.Zero;
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var reconnectedConnectionIdTcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
reconnectingErrorTcs.SetResult(error);
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
reconnectedConnectionIdTcs.SetResult(connectionId);
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
await hubConnection.StartAsync().DefaultTimeout();
var currentConnection = await testConnectionFactory.GetNextOrCurrentTestConnection();
await currentConnection.ReceiveJsonMessage(new
{
type = HubProtocolConstants.CloseMessageType,
error = "Error!",
allowReconnect = true,
});
var reconnectingException = await reconnectingErrorTcs.Task.DefaultTimeout();
var expectedMessage = "The server closed the connection with the following error: Error!";
Assert.Equal(expectedMessage, reconnectingException.Message);
Assert.Single(retryContexts);
Assert.Equal(expectedMessage, retryContexts[0].RetryReason.Message);
Assert.Equal(0, retryContexts[0].PreviousRetryCount);
Assert.Equal(TimeSpan.Zero, retryContexts[0].ElapsedTime);
await reconnectedConnectionIdTcs.Task.DefaultTimeout();
await hubConnection.StopAsync().DefaultTimeout();
var closeError = await closedErrorTcs.Task.DefaultTimeout();
Assert.Null(closeError);
Assert.Equal(1, reconnectingCount);
Assert.Equal(1, reconnectedCount);
}
}
[Fact]
public async Task CannotBeInducedByCloseMessageWithAllowReconnectOmitted()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ReceivedCloseWithError" ||
writeContext.EventId.Name == "ShutdownWithError");
}
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var testConnectionFactory = default(ReconnectingConnectionFactory);
testConnectionFactory = new ReconnectingConnectionFactory(() => new TestConnection());
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var reconnectingCount = 0;
var nextRetryDelayCallCount = 0;
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
nextRetryDelayCallCount++;
return TimeSpan.Zero;
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
await hubConnection.StartAsync().DefaultTimeout();
var currentConnection = await testConnectionFactory.GetNextOrCurrentTestConnection();
await currentConnection.ReceiveJsonMessage(new
{
type = HubProtocolConstants.CloseMessageType,
error = "Error!",
});
var closeError = await closedErrorTcs.Task.DefaultTimeout();
Assert.Equal("The server closed the connection with the following error: Error!", closeError.Message);
Assert.Equal(0, nextRetryDelayCallCount);
Assert.Equal(0, reconnectingCount);
}
}
[Fact]
public async Task EventsNotFiredIfFirstRetryDelayIsNull()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
writeContext.EventId.Name == "ServerDisconnectedWithError";
}
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var testConnectionFactory = new ReconnectingConnectionFactory();
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<TimeSpan?>(null);
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
await hubConnection.StartAsync().DefaultTimeout();
var firstException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(firstException);
await closedErrorTcs.Task.DefaultTimeout();
Assert.Equal(0, reconnectingCount);
Assert.Equal(0, reconnectedCount);
}
}
[Fact]
public async Task DoesNotStartIfConnectionIsLostDuringInitialHandshake()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ErrorReceivingHandshakeResponse" ||
writeContext.EventId.Name == "ErrorStartingConnection");
}
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var testConnectionFactory = new ReconnectingConnectionFactory(() => new TestConnection(autoHandshake: false));
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<TimeSpan?>(null);
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var closedCount = 0;
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedCount++;
return Task.CompletedTask;
};
var startTask = hubConnection.StartAsync().DefaultTimeout();
var firstException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(firstException);
Assert.Same(firstException, await Assert.ThrowsAsync<Exception>(() => startTask).DefaultTimeout());
Assert.Equal(HubConnectionState.Disconnected, hubConnection.State);
Assert.Equal(0, reconnectingCount);
Assert.Equal(0, reconnectedCount);
Assert.Equal(0, closedCount);
}
}
[Fact]
public async Task ContinuesIfConnectionLostDuringReconnectHandshake()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ServerDisconnectedWithError" ||
writeContext.EventId.Name == "ReconnectingWithError" ||
writeContext.EventId.Name == "ErrorReceivingHandshakeResponse" ||
writeContext.EventId.Name == "ErrorStartingConnection");
}
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var testConnectionFactory = new ReconnectingConnectionFactory(() => new TestConnection(autoHandshake: false));
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var retryContexts = new List<RetryContext>();
var secondRetryDelayTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
retryContexts.Add(context);
if (retryContexts.Count == 2)
{
secondRetryDelayTcs.SetResult();
}
return TimeSpan.Zero;
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var reconnectedConnectionIdTcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
reconnectingErrorTcs.SetResult(error);
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
reconnectedConnectionIdTcs.SetResult(connectionId);
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
var startTask = hubConnection.StartAsync();
// Complete handshake
var currentTestConnection = await testConnectionFactory.GetNextOrCurrentTestConnection();
await currentTestConnection.ReadHandshakeAndSendResponseAsync().DefaultTimeout();
await startTask.DefaultTimeout();
var firstException = new Exception();
currentTestConnection.CompleteFromTransport(firstException);
Assert.Same(firstException, await reconnectingErrorTcs.Task.DefaultTimeout());
Assert.Single(retryContexts);
Assert.Same(firstException, retryContexts[0].RetryReason);
Assert.Equal(0, retryContexts[0].PreviousRetryCount);
Assert.Equal(TimeSpan.Zero, retryContexts[0].ElapsedTime);
var secondException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(secondException);
await secondRetryDelayTcs.Task.DefaultTimeout();
Assert.Equal(2, retryContexts.Count);
Assert.Same(secondException, retryContexts[1].RetryReason);
Assert.Equal(1, retryContexts[1].PreviousRetryCount);
Assert.True(TimeSpan.Zero <= retryContexts[0].ElapsedTime);
// Complete handshake
currentTestConnection = await testConnectionFactory.GetNextOrCurrentTestConnection();
await currentTestConnection.ReadHandshakeAndSendResponseAsync().DefaultTimeout();
await reconnectedConnectionIdTcs.Task.DefaultTimeout();
Assert.Equal(1, reconnectingCount);
Assert.Equal(1, reconnectedCount);
Assert.Equal(TaskStatus.WaitingForActivation, closedErrorTcs.Task.Status);
await hubConnection.StopAsync().DefaultTimeout();
var closeError = await closedErrorTcs.Task.DefaultTimeout();
Assert.Null(closeError);
Assert.Equal(1, reconnectingCount);
Assert.Equal(1, reconnectedCount);
}
}
[Fact]
public async Task ContinuesIfInvalidHandshakeResponse()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ServerDisconnectedWithError" ||
writeContext.EventId.Name == "ReconnectingWithError" ||
writeContext.EventId.Name == "ErrorReceivingHandshakeResponse" ||
writeContext.EventId.Name == "HandshakeServerError" ||
writeContext.EventId.Name == "ErrorStartingConnection");
}
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var testConnectionFactory = new ReconnectingConnectionFactory(() => new TestConnection(autoHandshake: false));
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var retryContexts = new List<RetryContext>();
var secondRetryDelayTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
retryContexts.Add(context);
if (retryContexts.Count == 2)
{
secondRetryDelayTcs.SetResult();
}
return TimeSpan.Zero;
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var reconnectedConnectionIdTcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
reconnectingErrorTcs.SetResult(error);
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
reconnectedConnectionIdTcs.SetResult(connectionId);
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
var startTask = hubConnection.StartAsync();
// Complete handshake
var currentTestConnection = await testConnectionFactory.GetNextOrCurrentTestConnection();
await currentTestConnection.ReadHandshakeAndSendResponseAsync().DefaultTimeout();
await startTask.DefaultTimeout();
var firstException = new Exception();
currentTestConnection.CompleteFromTransport(firstException);
Assert.Same(firstException, await reconnectingErrorTcs.Task.DefaultTimeout());
Assert.Single(retryContexts);
Assert.Same(firstException, retryContexts[0].RetryReason);
Assert.Equal(0, retryContexts[0].PreviousRetryCount);
Assert.Equal(TimeSpan.Zero, retryContexts[0].ElapsedTime);
// Respond to handshake with error.
currentTestConnection = await testConnectionFactory.GetNextOrCurrentTestConnection();
await currentTestConnection.ReadSentTextMessageAsync().DefaultTimeout();
var output = MemoryBufferWriter.Get();
try
{
HandshakeProtocol.WriteResponseMessage(new HandshakeResponseMessage("Error!"), output);
await currentTestConnection.Application.Output.WriteAsync(output.ToArray()).DefaultTimeout();
}
finally
{
MemoryBufferWriter.Return(output);
}
await secondRetryDelayTcs.Task.DefaultTimeout();
Assert.Equal(2, retryContexts.Count);
Assert.IsType<HubException>(retryContexts[1].RetryReason);
Assert.Equal(1, retryContexts[1].PreviousRetryCount);
Assert.True(TimeSpan.Zero <= retryContexts[0].ElapsedTime);
// Complete handshake
currentTestConnection = await testConnectionFactory.GetNextOrCurrentTestConnection();
await currentTestConnection.ReadHandshakeAndSendResponseAsync().DefaultTimeout();
await reconnectedConnectionIdTcs.Task.DefaultTimeout();
Assert.Equal(1, reconnectingCount);
Assert.Equal(1, reconnectedCount);
Assert.Equal(TaskStatus.WaitingForActivation, closedErrorTcs.Task.Status);
await hubConnection.StopAsync().DefaultTimeout();
var closeError = await closedErrorTcs.Task.DefaultTimeout();
Assert.Null(closeError);
Assert.Equal(1, reconnectingCount);
Assert.Equal(1, reconnectedCount);
}
}
[Fact]
public async Task CanBeStoppedWhileRestartingUnderlyingConnection()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ServerDisconnectedWithError" ||
writeContext.EventId.Name == "ReconnectingWithError" ||
writeContext.EventId.Name == "ErrorHandshakeCanceled" ||
writeContext.EventId.Name == "ErrorStartingConnection");
}
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var connectionStartTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
async Task OnTestConnectionStart()
{
try
{
await connectionStartTcs.Task;
}
finally
{
connectionStartTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
}
var testConnectionFactory = new ReconnectingConnectionFactory(() => new TestConnection(OnTestConnectionStart));
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var retryContexts = new List<RetryContext>();
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
retryContexts.Add(context);
return TimeSpan.Zero;
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
reconnectingErrorTcs.SetResult(error);
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
// Allow the first connection to start successfully.
connectionStartTcs.SetResult();
await hubConnection.StartAsync().DefaultTimeout();
var firstException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(firstException);
Assert.Same(firstException, await reconnectingErrorTcs.Task.DefaultTimeout());
Assert.Single(retryContexts);
Assert.Same(firstException, retryContexts[0].RetryReason);
Assert.Equal(0, retryContexts[0].PreviousRetryCount);
Assert.Equal(TimeSpan.Zero, retryContexts[0].ElapsedTime);
var secondException = new Exception();
var stopTask = hubConnection.StopAsync();
connectionStartTcs.SetResult();
Assert.IsType<OperationCanceledException>(await closedErrorTcs.Task.DefaultTimeout());
Assert.Single(retryContexts);
Assert.Equal(1, reconnectingCount);
Assert.Equal(0, reconnectedCount);
await stopTask.DefaultTimeout();
}
}
[Fact]
public async Task CanBeStoppedDuringRetryDelay()
{
bool ExpectedErrors(WriteContext writeContext)
{
return writeContext.LoggerName == typeof(HubConnection).FullName &&
(writeContext.EventId.Name == "ServerDisconnectedWithError" ||
writeContext.EventId.Name == "ReconnectingWithError" ||
writeContext.EventId.Name == "ErrorReceivingHandshakeResponse" ||
writeContext.EventId.Name == "ErrorStartingConnection");
}
using (StartVerifiableLog(ExpectedErrors))
{
var builder = new HubConnectionBuilder().WithLoggerFactory(LoggerFactory).WithUrl("http://example.com");
var testConnectionFactory = new ReconnectingConnectionFactory();
builder.Services.AddSingleton<IConnectionFactory>(testConnectionFactory);
var retryContexts = new List<RetryContext>();
var mockReconnectPolicy = new Mock<IRetryPolicy>();
mockReconnectPolicy.Setup(p => p.NextRetryDelay(It.IsAny<RetryContext>())).Returns<RetryContext>(context =>
{
retryContexts.Add(context);
// Hopefully this test never takes over a minute.
return TimeSpan.FromMinutes(1);
});
builder.WithAutomaticReconnect(mockReconnectPolicy.Object);
await using var hubConnection = builder.Build();
var reconnectingCount = 0;
var reconnectedCount = 0;
var reconnectingErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
var closedErrorTcs = new TaskCompletionSource<Exception>(TaskCreationOptions.RunContinuationsAsynchronously);
hubConnection.Reconnecting += error =>
{
reconnectingCount++;
reconnectingErrorTcs.SetResult(error);
return Task.CompletedTask;
};
hubConnection.Reconnected += connectionId =>
{
reconnectedCount++;
return Task.CompletedTask;
};
hubConnection.Closed += error =>
{
closedErrorTcs.SetResult(error);
return Task.CompletedTask;
};
// Allow the first connection to start successfully.
await hubConnection.StartAsync().DefaultTimeout();
var firstException = new Exception();
(await testConnectionFactory.GetNextOrCurrentTestConnection()).CompleteFromTransport(firstException);
Assert.Same(firstException, await reconnectingErrorTcs.Task.DefaultTimeout());
Assert.Single(retryContexts);
Assert.Same(firstException, retryContexts[0].RetryReason);
Assert.Equal(0, retryContexts[0].PreviousRetryCount);
Assert.Equal(TimeSpan.Zero, retryContexts[0].ElapsedTime);
await hubConnection.StopAsync().DefaultTimeout();
Assert.IsType<OperationCanceledException>(await closedErrorTcs.Task.DefaultTimeout());
Assert.Single(retryContexts);
Assert.Equal(1, reconnectingCount);
Assert.Equal(0, reconnectedCount);
}
}
private class ReconnectingConnectionFactory : IConnectionFactory
{
public readonly Func<TestConnection> _testConnectionFactory;
public TaskCompletionSource<TestConnection> _testConnectionTcs = new TaskCompletionSource<TestConnection>(TaskCreationOptions.RunContinuationsAsynchronously);
public ReconnectingConnectionFactory()
: this(() => new TestConnection())
{
}
public ReconnectingConnectionFactory(Func<TestConnection> testConnectionFactory)
{
_testConnectionFactory = testConnectionFactory;
}
public Task<TestConnection> GetNextOrCurrentTestConnection()
{
return _testConnectionTcs.Task;
}
public async ValueTask<ConnectionContext> ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken = default)
{
var testConnection = _testConnectionFactory();
_testConnectionTcs.SetResult(testConnection);
try
{
return new DisposeInterceptingConnectionContextDecorator(await testConnection.StartAsync(), this);
}
catch
{
_testConnectionTcs = new TaskCompletionSource<TestConnection>(TaskCreationOptions.RunContinuationsAsynchronously);
throw;
}
}
public async Task DisposeAsync(ConnectionContext connection)
{
var disposingTestConnection = await _testConnectionTcs.Task;
_testConnectionTcs = new TaskCompletionSource<TestConnection>(TaskCreationOptions.RunContinuationsAsynchronously);
await disposingTestConnection.DisposeAsync();
}
}
private class DisposeInterceptingConnectionContextDecorator : ConnectionContext
{
private readonly ConnectionContext _inner;
private readonly ReconnectingConnectionFactory _reconnectingConnectionFactory;
public DisposeInterceptingConnectionContextDecorator(ConnectionContext inner, ReconnectingConnectionFactory reconnectingConnectionFactory)
{
_inner = inner;
_reconnectingConnectionFactory = reconnectingConnectionFactory;
}
public override string ConnectionId { get => _inner.ConnectionId; set => _inner.ConnectionId = value; }
public override IFeatureCollection Features => _inner.Features;
public override IDictionary<object, object> Items { get => _inner.Items; set => _inner.Items = value; }
public override IDuplexPipe Transport { get => _inner.Transport; set => _inner.Transport = value; }
public override CancellationToken ConnectionClosed { get => _inner.ConnectionClosed; set => _inner.ConnectionClosed = value; }
public override EndPoint LocalEndPoint { get => _inner.LocalEndPoint; set => _inner.LocalEndPoint = value; }
public override EndPoint RemoteEndPoint { get => _inner.RemoteEndPoint; set => _inner.RemoteEndPoint = value; }
public override void Abort(ConnectionAbortedException abortReason) => _inner.Abort(abortReason);
public override void Abort() => _inner.Abort();
public override ValueTask DisposeAsync() => new ValueTask(_reconnectingConnectionFactory.DisposeAsync(_inner));
}
}
}
}
| |
/*
* Copyright (c) 2011, Cloud Hsu
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Cloud Hsu 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 CLOUD HSU "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 REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
/*
* Design rule:
* 1. Server only handle one ID of Client.
* 2. If Client ID duplicate server will release old Client, and handle new client.
*/
namespace CloudBox.TcpObject
{
/// <summary>
/// TCP server
/// </summary>
public sealed class TCPIPServer
{
string m_sIP;
int m_i4Port;
Socket m_pServer;
List<TCPSocket> m_pClientList = new List<TCPSocket>();
Thread m_pAcceptThread;
bool m_bIsRunning;
/// <summary>
/// event for server log
/// </summary>
public event TCPIPClient.TraceLogHandler EventTraceLog;
/// <summary>
/// event for server receive data from all client.
/// </summary>
public event TCPIPClient.MessageContentHandler EventAllClientReceive;
/// <summary>
/// event for handshake fail from all client.
/// </summary>
public event TCPIPClient.HandshakeHandler EventAllClientHandshakeFail;
/// <summary>
/// get client count in server m_pClientList.
/// </summary>
public int ClientListCount
{
get { return m_pClientList.Count; }
}
public List<TCPSocket> Clients
{
get { return m_pClientList; }
}
/// <summary>
/// Trace Log
/// </summary>
/// <param name="a_i4Level">Log level</param>
/// <param name="a_sLog">Log content</param>
private void TraceLog(int a_i4Level,string a_sLog)
{
if (EventTraceLog != null)
{
try
{
EventTraceLog(a_i4Level, "[Server]:" + a_sLog);
}catch{}
}
}
/// <summary>
/// MTCPIPServer construct.
/// </summary>
/// <param name="a_sIP">Server IP</param>
/// <param name="a_i4Port">Server Port</param>
public TCPIPServer(string a_sIP, int a_i4Port)
{
m_sIP = a_sIP;
m_i4Port = a_i4Port;
} // end of MTCPIPServer(string a_sIP, int a_i4Port)
/// <summary>
/// Destructor
/// </summary>
~TCPIPServer()
{
ShutdownServer();
} // end of ~MTCPIPServer()
/// <summary>
/// Check Client is connected
/// </summary>
/// <param name="a_i4ClientID">Client ID</param>
/// <returns>true is connected</returns>
public bool CheckClientConnected(int a_i4ClientID)
{
if (m_pClientList.Count == 0)
return false;
for (int t_i4ClientIndex = 0; t_i4ClientIndex < m_pClientList.Count; t_i4ClientIndex++)
{
TCPSocket t_pTcpClient = m_pClientList[t_i4ClientIndex];
if (t_pTcpClient.ClientID == (byte)a_i4ClientID)
{
return true;
}
}
return false;
}
/// <summary>
/// Start server
/// </summary>
public void StartServer()
{
try
{
m_pServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// connect to server
m_pServer.Bind(new IPEndPoint(IPAddress.Parse(m_sIP), m_i4Port));
m_pServer.Listen(100);
TraceLog(LogLevel.LOG_LEVEL_NORMAL, "Bind to" + m_sIP + ":" + m_i4Port + " success.");
if (m_pAcceptThread != null)
{
m_pAcceptThread.Abort();
m_pAcceptThread = null;
}
m_pAcceptThread = new Thread(new ThreadStart(this.AcceptClient));
m_pAcceptThread.Name = "ServerAccept";
m_bIsRunning = true;
m_pAcceptThread.Start();
TraceLog(LogLevel.LOG_LEVEL_NORMAL, "Start Accept.");
}
catch (SocketException ex)
{
Debug.WriteLine(ex.NativeErrorCode + ":" + ex.Message);
TraceLog(LogLevel.LOG_LEVEL_WARRING, String.Format("[ErrorCode]:{0},[SocketException]:{1} In [StartServer]", ex.NativeErrorCode, ex.Message));
throw;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
TraceLog(LogLevel.LOG_LEVEL_WARRING, String.Format("[Exception]:{0} In [StartServer]", ex.Message));
throw;
}
} // end of StartServer()
/// <summary>
/// Shutdown server.
/// </summary>
public void ShutdownServer()
{
try
{
// Shutdown server
if (m_pServer != null)
{
try
{
m_pServer.Close();
m_pServer = null;
}
catch (Exception) { }
}
for (int i = m_pClientList.Count-1; i >=0 ; i--)
{
TCPSocket t_pShutDownTcpClient = m_pClientList[i];
try
{
t_pShutDownTcpClient.Destory();
}
catch (Exception) { }
}
}
catch (SocketException ex)
{
Debug.WriteLine(ex.NativeErrorCode + ":" + ex.Message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
try
{
m_bIsRunning = false;
if (m_pAcceptThread != null)
{
m_pAcceptThread.Abort();
m_pAcceptThread = null;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
TraceLog(LogLevel.LOG_LEVEL_TRACE, "Shutdown success");
} // end of ShutdownServer()
/// <summary>
/// Accept client with Thread.
/// </summary>
void AcceptClient()
{
while (m_bIsRunning)
{
Socket t_pNewClient = null;
try
{
t_pNewClient = m_pServer.Accept();
t_pNewClient.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 409600);
byte[] t_bData = new byte[1024];
int t_i4Length = t_pNewClient.Receive(t_bData);
if (t_i4Length > 0)
{
MessageContent t_pMsg = TCPSocket.AnalyzeClientID(t_bData, t_i4Length);
byte t_i1ClientID = t_pMsg.Content[0];
TCPSocket t_pNewTcpClient = new TCPSocket(t_pNewClient, t_i1ClientID);
TraceLog(LogLevel.LOG_LEVEL_NORMAL, t_pNewTcpClient.ToString() + " create connection succeed.");
t_pNewTcpClient.EventDataReceive += new TCPSocket.MessageContentHandler(TcpClient_EventDataReceive);
t_pNewTcpClient.EventHandshakeFail += new TCPSocket.HandshakeHandler(TcpClient_EventHandshakeFail);
t_pNewTcpClient.EventClientShutdown += new TCPSocket.ClientShutdownHandler(TcpClient_EventClientShutdown);
t_pNewTcpClient.EventTraceLog += new TCPSocket.TraceLogHandler(TraceLog);
t_pNewTcpClient.EventIsExistInServer += new TCPSocket.IsExistInServerHandler(TcpClient_EventIsExistInServer);
t_pNewTcpClient.StartReceive();
AddNewClient(t_pNewTcpClient);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
Thread.Sleep(1);
}
}
bool TcpClient_EventIsExistInServer(TCPSocket a_pClient)
{
foreach(TCPSocket t_pExistClient in m_pClientList)
{
if (a_pClient.ClientID == t_pExistClient.ClientID)
return true;
}
TraceLog(LogLevel.LOG_LEVEL_WARRING, a_pClient.ToString() + " dose not exist in server. Please restart client.");
return false;
} // end of AcceptClient()
/// <summary>
/// Add new client for list when accept a client.
/// If client already exist,to shutdown the old exist client and to handle the new client.
/// </summary>
/// <param name="t_pNewClient">New Client</param>
void AddNewClient(TCPSocket t_pNewClient)
{
for (int t_i4ClientIndex = 0; t_i4ClientIndex < m_pClientList.Count; t_i4ClientIndex++)
{
TCPSocket t_pExistTcpClient = m_pClientList[t_i4ClientIndex];
if (t_pExistTcpClient.ClientID.Equals(t_pNewClient.ClientID))
{
m_pClientList.Remove(t_pExistTcpClient);
t_pExistTcpClient.Destory();
TraceLog(LogLevel.LOG_LEVEL_NORMAL, t_pExistTcpClient.ToString() + " already Exist and will remove it.");
t_pExistTcpClient = null;
break;
}
}
m_pClientList.Add(t_pNewClient);
TraceLog(LogLevel.LOG_LEVEL_NORMAL, t_pNewClient.ToString() + " Added to server to manage.");
}
/// <summary>
/// delegate function, using for MTCPIPClient.EventClientShutdown
/// </summary>
/// <param name="a_i1ClientID">Shutdown client Id</param>
void TcpClient_EventClientShutdown(byte a_i1ClientID)
{
TCPSocket t_pShutDownTcpClient = null;
try
{
TraceLog(LogLevel.LOG_LEVEL_NORMAL, "Client[" + a_i1ClientID + "] will shutdown in server.");
for (int t_i4ClientIndex = 0; t_i4ClientIndex < m_pClientList.Count; t_i4ClientIndex++)
{
t_pShutDownTcpClient = m_pClientList[t_i4ClientIndex];
if (t_pShutDownTcpClient.ClientID == a_i1ClientID)
{
m_pClientList.Remove(t_pShutDownTcpClient);
t_pShutDownTcpClient.Destory();
TraceLog(LogLevel.LOG_LEVEL_NORMAL, t_pShutDownTcpClient.ToString() + " disconnected");
t_pShutDownTcpClient = null;
break;
}
}
}
catch (SocketException ex)
{
Debug.WriteLine(ex.NativeErrorCode + ":" + ex.Message);
TraceLog(LogLevel.LOG_LEVEL_DEBUG, String.Format("[ErrorCode]:{0},[SocketException]:{1} In [TcpClient_EventClientShutdown]", ex.NativeErrorCode, ex.Message));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
TraceLog(LogLevel.LOG_LEVEL_DEBUG, String.Format("[Exception]:{0} In [TcpClient_EventClientShutdown]", ex.Message));
}
} // end of TcpClient_EventClientShutdown()
/// <summary>
/// delegate function, using for MTCPIPClient.EventHandshakeFail
/// </summary>
/// <param name="a_pClient">MTCPSocket.</param>
/// <param name="a_pMsg">MessageContent object.</param>
void TcpClient_EventHandshakeFail(TCPSocket a_pClient, MessageContent a_pMsg)
{
if (EventAllClientHandshakeFail != null)
{
EventAllClientHandshakeFail(a_pClient, a_pMsg);
}
} // end of TcpClient_EventDataReceive()
/// <summary>
/// delegate function, using for MTCPIPClient.EventDataReceive
/// </summary>
/// <param name="a_pMsg">MessageContent object.</param>
void TcpClient_EventDataReceive(MessageContent a_pMsg)
{
if (EventAllClientReceive != null)
{
EventAllClientReceive(a_pMsg);
}
} // end of TcpClient_EventDataReceive()
/// <summary>
/// Send text data to appoint client.
/// </summary>
/// <param name="a_i1ClientID">Appoint client</param>
/// <param name="a_i1MsgType">Message Type</param>
/// <param name="a_sMsgContent">Text data content</param>
public void SendDataToClient(byte a_i1ClientID, byte a_i1MsgType, string a_sMsgContent)
{
TCPSocket t_pTargetTcpClient = null;
try
{
bool t_bIsFoundTarget = false;
int retry = 0;
while (retry < 5)
{
for (int t_i4ClientIndex = 0; t_i4ClientIndex < m_pClientList.Count; t_i4ClientIndex++)
{
t_pTargetTcpClient = m_pClientList[t_i4ClientIndex];
if (t_pTargetTcpClient.ClientID == a_i1ClientID)
{
t_bIsFoundTarget = true;
break;
}
}
if (t_bIsFoundTarget)
break;
retry++;
Thread.Sleep(200);
}
if (!t_bIsFoundTarget)
{
throw new Exception("Client is not exist");
}
MessageContent t_pMsg = new MessageContent(a_i1MsgType,
MessageConst.SERVER_ID, a_i1ClientID, Encoding.ASCII.GetBytes(a_sMsgContent));
t_pTargetTcpClient.SendMessage(t_pMsg);
}
catch (SocketException ex)
{
Debug.WriteLine(ex.NativeErrorCode + ":" + ex.Message);
Debug.WriteLine("Remove " + t_pTargetTcpClient.ToString());
TraceLog(LogLevel.LOG_LEVEL_DEBUG, String.Format("[ErrorCode]:{0},[SocketException]:{1} In [SendDataToClient]", ex.NativeErrorCode, ex.Message));
// if got socket exception, release client
m_pClientList.Remove(t_pTargetTcpClient);
t_pTargetTcpClient.Destory();
throw;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
TraceLog(LogLevel.LOG_LEVEL_DEBUG, String.Format("[Exception]:{0} In [SendDataToClient]", ex.Message));
throw;
}
} // end of SendDataToClient(string a_sClientID,int a_i4MsgID, string a_sMsg,int a_i4CmdID)
/// <summary>
/// Send text data to appoint client.
/// </summary>
/// <param name="a_i1ClientID">Appoint client</param>
/// <param name="a_i1MsgType">Message Type</param>
/// <param name="a_i4CmdID">Command ID</param>
/// <param name="a_sMsgContent">Text data content</param>
public void SendDataToClient(byte a_i1ClientID, byte a_i1MsgType, byte a_i4CmdID, string a_sMsgContent)
{
TCPSocket t_pTargetTcpClient = null;
try
{
bool t_bIsFoundTarget = false;
int retry = 0;
while (retry < 5)
{
for (int t_i4ClientIndex = 0; t_i4ClientIndex < m_pClientList.Count; t_i4ClientIndex++)
{
t_pTargetTcpClient = m_pClientList[t_i4ClientIndex];
if (t_pTargetTcpClient.ClientID == a_i1ClientID)
{
t_bIsFoundTarget = true;
break;
}
}
if (t_bIsFoundTarget)
break;
retry++;
Thread.Sleep(200);
}
if (!t_bIsFoundTarget)
{
throw new Exception("Client is not exist");
}
MessageContent t_pMsg = new MessageContent(a_i1MsgType,
MessageConst.SERVER_ID, a_i1ClientID, Encoding.ASCII.GetBytes(a_sMsgContent), a_i4CmdID);
t_pTargetTcpClient.SendMessage(t_pMsg);
}
catch (SocketException ex)
{
Debug.WriteLine(ex.NativeErrorCode + ":" + ex.Message);
Debug.WriteLine("Remove " + t_pTargetTcpClient.ToString());
TraceLog(LogLevel.LOG_LEVEL_DEBUG, String.Format("[ErrorCode]:{0},[SocketException]:{1} In [SendDataToClient]", ex.NativeErrorCode, ex.Message));
// if got socket exception, release client
m_pClientList.Remove(t_pTargetTcpClient);
t_pTargetTcpClient.Destory();
throw;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
TraceLog(LogLevel.LOG_LEVEL_DEBUG, String.Format("[Exception]:{0} In [SendDataToClient]", ex.Message));
throw;
}
} // end of SendDataToClient(string a_sClientID,int a_i4MsgID, string a_sMsg)
public ClientStatus GetClientStatus(int a_i4ClientID,string a_sClientName)
{
ClientStatus t_pStatus = new ClientStatus(a_i4ClientID, a_sClientName);
foreach (TCPSocket t_pShutDownTcpClient in m_pClientList)
{
if(t_pShutDownTcpClient.ClientID == t_pStatus.ClientID)
{
t_pStatus.IsConnect = t_pShutDownTcpClient.IsConnected;
break;
}
}
return t_pStatus;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.