context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
namespace Azure.Quantum
{
public partial class QuantumJobClientOptions : Azure.Core.ClientOptions
{
public const Azure.Quantum.QuantumJobClientOptions.ServiceVersion LatestVersion = Azure.Quantum.QuantumJobClientOptions.ServiceVersion.V1Preview;
public QuantumJobClientOptions(Azure.Quantum.QuantumJobClientOptions.ServiceVersion version = Azure.Quantum.QuantumJobClientOptions.ServiceVersion.V1Preview) { }
public enum ServiceVersion
{
V1Preview = 1,
}
}
}
namespace Azure.Quantum.Jobs
{
public partial class QuantumJobClient
{
protected QuantumJobClient() { }
public QuantumJobClient(string subscriptionId, string resourceGroupName, string workspaceName, string location, Azure.Core.TokenCredential credential = null, Azure.Quantum.QuantumJobClientOptions options = null) { }
public virtual Azure.Response CancelJob(string jobId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> CancelJobAsync(string jobId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Quantum.Jobs.Models.JobDetails> CreateJob(string jobId, Azure.Quantum.Jobs.Models.JobDetails job, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Quantum.Jobs.Models.JobDetails>> CreateJobAsync(string jobId, Azure.Quantum.Jobs.Models.JobDetails job, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Quantum.Jobs.Models.JobDetails> GetJob(string jobId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Quantum.Jobs.Models.JobDetails>> GetJobAsync(string jobId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.Quantum.Jobs.Models.JobDetails> GetJobs(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.Quantum.Jobs.Models.JobDetails> GetJobsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.Quantum.Jobs.Models.ProviderStatus> GetProviderStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.Quantum.Jobs.Models.ProviderStatus> GetProviderStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Pageable<Azure.Quantum.Jobs.Models.QuantumJobQuota> GetQuotas(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.Quantum.Jobs.Models.QuantumJobQuota> GetQuotasAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Quantum.Jobs.Models.SasUriResponse> GetStorageSasUri(Azure.Quantum.Jobs.Models.BlobDetails blobDetails, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Quantum.Jobs.Models.SasUriResponse>> GetStorageSasUriAsync(Azure.Quantum.Jobs.Models.BlobDetails blobDetails, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
}
namespace Azure.Quantum.Jobs.Models
{
public partial class BlobDetails
{
public BlobDetails(string containerName) { }
public string BlobName { get { throw null; } set { } }
public string ContainerName { get { throw null; } }
}
public partial class CostEstimate
{
internal CostEstimate() { }
public string CurrencyCode { get { throw null; } }
public float? EstimatedTotal { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Quantum.Jobs.Models.UsageEvent> Events { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct DimensionScope : System.IEquatable<Azure.Quantum.Jobs.Models.DimensionScope>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public DimensionScope(string value) { throw null; }
public static Azure.Quantum.Jobs.Models.DimensionScope Subscription { get { throw null; } }
public static Azure.Quantum.Jobs.Models.DimensionScope Workspace { get { throw null; } }
public bool Equals(Azure.Quantum.Jobs.Models.DimensionScope other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Quantum.Jobs.Models.DimensionScope left, Azure.Quantum.Jobs.Models.DimensionScope right) { throw null; }
public static implicit operator Azure.Quantum.Jobs.Models.DimensionScope (string value) { throw null; }
public static bool operator !=(Azure.Quantum.Jobs.Models.DimensionScope left, Azure.Quantum.Jobs.Models.DimensionScope right) { throw null; }
public override string ToString() { throw null; }
}
public partial class ErrorData
{
internal ErrorData() { }
public string Code { get { throw null; } }
public string Message { get { throw null; } }
}
public partial class JobDetails
{
public JobDetails(string containerUri, string inputDataFormat, string providerId, string target) { }
public System.DateTimeOffset? BeginExecutionTime { get { throw null; } }
public System.DateTimeOffset? CancellationTime { get { throw null; } }
public string ContainerUri { get { throw null; } set { } }
public Azure.Quantum.Jobs.Models.CostEstimate CostEstimate { get { throw null; } }
public System.DateTimeOffset? CreationTime { get { throw null; } }
public System.DateTimeOffset? EndExecutionTime { get { throw null; } }
public Azure.Quantum.Jobs.Models.ErrorData ErrorData { get { throw null; } }
public string Id { get { throw null; } set { } }
public string InputDataFormat { get { throw null; } set { } }
public string InputDataUri { get { throw null; } set { } }
public object InputParams { get { throw null; } set { } }
public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
public string OutputDataFormat { get { throw null; } set { } }
public string OutputDataUri { get { throw null; } set { } }
public string ProviderId { get { throw null; } set { } }
public Azure.Quantum.Jobs.Models.JobStatus? Status { get { throw null; } }
public System.Collections.Generic.IList<string> Tags { get { throw null; } set { } }
public string Target { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct JobStatus : System.IEquatable<Azure.Quantum.Jobs.Models.JobStatus>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public JobStatus(string value) { throw null; }
public static Azure.Quantum.Jobs.Models.JobStatus Cancelled { get { throw null; } }
public static Azure.Quantum.Jobs.Models.JobStatus Executing { get { throw null; } }
public static Azure.Quantum.Jobs.Models.JobStatus Failed { get { throw null; } }
public static Azure.Quantum.Jobs.Models.JobStatus Succeeded { get { throw null; } }
public static Azure.Quantum.Jobs.Models.JobStatus Waiting { get { throw null; } }
public bool Equals(Azure.Quantum.Jobs.Models.JobStatus other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Quantum.Jobs.Models.JobStatus left, Azure.Quantum.Jobs.Models.JobStatus right) { throw null; }
public static implicit operator Azure.Quantum.Jobs.Models.JobStatus (string value) { throw null; }
public static bool operator !=(Azure.Quantum.Jobs.Models.JobStatus left, Azure.Quantum.Jobs.Models.JobStatus right) { throw null; }
public override string ToString() { throw null; }
}
public partial class JsonPatchDocument
{
public JsonPatchDocument(Azure.Quantum.Jobs.Models.JsonPatchOperation op, string path) { }
public string From { get { throw null; } set { } }
public Azure.Quantum.Jobs.Models.JsonPatchOperation Op { get { throw null; } }
public string Path { get { throw null; } }
public object Value { get { throw null; } set { } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct JsonPatchOperation : System.IEquatable<Azure.Quantum.Jobs.Models.JsonPatchOperation>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public JsonPatchOperation(string value) { throw null; }
public static Azure.Quantum.Jobs.Models.JsonPatchOperation Add { get { throw null; } }
public static Azure.Quantum.Jobs.Models.JsonPatchOperation Copy { get { throw null; } }
public static Azure.Quantum.Jobs.Models.JsonPatchOperation Move { get { throw null; } }
public static Azure.Quantum.Jobs.Models.JsonPatchOperation Remove { get { throw null; } }
public static Azure.Quantum.Jobs.Models.JsonPatchOperation Replace { get { throw null; } }
public static Azure.Quantum.Jobs.Models.JsonPatchOperation Test { get { throw null; } }
public bool Equals(Azure.Quantum.Jobs.Models.JsonPatchOperation other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Quantum.Jobs.Models.JsonPatchOperation left, Azure.Quantum.Jobs.Models.JsonPatchOperation right) { throw null; }
public static implicit operator Azure.Quantum.Jobs.Models.JsonPatchOperation (string value) { throw null; }
public static bool operator !=(Azure.Quantum.Jobs.Models.JsonPatchOperation left, Azure.Quantum.Jobs.Models.JsonPatchOperation right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct MeterPeriod : System.IEquatable<Azure.Quantum.Jobs.Models.MeterPeriod>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public MeterPeriod(string value) { throw null; }
public static Azure.Quantum.Jobs.Models.MeterPeriod Monthly { get { throw null; } }
public static Azure.Quantum.Jobs.Models.MeterPeriod None { get { throw null; } }
public bool Equals(Azure.Quantum.Jobs.Models.MeterPeriod other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Quantum.Jobs.Models.MeterPeriod left, Azure.Quantum.Jobs.Models.MeterPeriod right) { throw null; }
public static implicit operator Azure.Quantum.Jobs.Models.MeterPeriod (string value) { throw null; }
public static bool operator !=(Azure.Quantum.Jobs.Models.MeterPeriod left, Azure.Quantum.Jobs.Models.MeterPeriod right) { throw null; }
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct ProviderAvailability : System.IEquatable<Azure.Quantum.Jobs.Models.ProviderAvailability>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public ProviderAvailability(string value) { throw null; }
public static Azure.Quantum.Jobs.Models.ProviderAvailability Available { get { throw null; } }
public static Azure.Quantum.Jobs.Models.ProviderAvailability Degraded { get { throw null; } }
public static Azure.Quantum.Jobs.Models.ProviderAvailability Unavailable { get { throw null; } }
public bool Equals(Azure.Quantum.Jobs.Models.ProviderAvailability other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Quantum.Jobs.Models.ProviderAvailability left, Azure.Quantum.Jobs.Models.ProviderAvailability right) { throw null; }
public static implicit operator Azure.Quantum.Jobs.Models.ProviderAvailability (string value) { throw null; }
public static bool operator !=(Azure.Quantum.Jobs.Models.ProviderAvailability left, Azure.Quantum.Jobs.Models.ProviderAvailability right) { throw null; }
public override string ToString() { throw null; }
}
public partial class ProviderStatus
{
internal ProviderStatus() { }
public Azure.Quantum.Jobs.Models.ProviderAvailability? CurrentAvailability { get { throw null; } }
public string Id { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Quantum.Jobs.Models.TargetStatus> Targets { get { throw null; } }
}
public partial class QuantumJobQuota
{
internal QuantumJobQuota() { }
public string Dimension { get { throw null; } }
public float? Holds { get { throw null; } }
public float? Limit { get { throw null; } }
public Azure.Quantum.Jobs.Models.MeterPeriod? Period { get { throw null; } }
public string ProviderId { get { throw null; } }
public Azure.Quantum.Jobs.Models.DimensionScope? Scope { get { throw null; } }
public float? Utilization { get { throw null; } }
}
public partial class QuantumJobQuotaList
{
internal QuantumJobQuotaList() { }
public string NextLink { get { throw null; } }
public System.Collections.Generic.IReadOnlyList<Azure.Quantum.Jobs.Models.QuantumJobQuota> Value { get { throw null; } }
}
public static partial class QuantumModelFactory
{
public static Azure.Quantum.Jobs.Models.CostEstimate CostEstimate(string currencyCode = null, System.Collections.Generic.IEnumerable<Azure.Quantum.Jobs.Models.UsageEvent> events = null, float? estimatedTotal = default(float?)) { throw null; }
public static Azure.Quantum.Jobs.Models.ErrorData ErrorData(string code = null, string message = null) { throw null; }
public static Azure.Quantum.Jobs.Models.JobDetails JobDetails(string id = null, string name = null, string containerUri = null, string inputDataUri = null, string inputDataFormat = null, object inputParams = null, string providerId = null, string target = null, System.Collections.Generic.IDictionary<string, string> metadata = null, string outputDataUri = null, string outputDataFormat = null, Azure.Quantum.Jobs.Models.JobStatus? status = default(Azure.Quantum.Jobs.Models.JobStatus?), System.DateTimeOffset? creationTime = default(System.DateTimeOffset?), System.DateTimeOffset? beginExecutionTime = default(System.DateTimeOffset?), System.DateTimeOffset? endExecutionTime = default(System.DateTimeOffset?), System.DateTimeOffset? cancellationTime = default(System.DateTimeOffset?), Azure.Quantum.Jobs.Models.CostEstimate costEstimate = null, Azure.Quantum.Jobs.Models.ErrorData errorData = null, System.Collections.Generic.IEnumerable<string> tags = null) { throw null; }
public static Azure.Quantum.Jobs.Models.ProviderStatus ProviderStatus(string id = null, Azure.Quantum.Jobs.Models.ProviderAvailability? currentAvailability = default(Azure.Quantum.Jobs.Models.ProviderAvailability?), System.Collections.Generic.IEnumerable<Azure.Quantum.Jobs.Models.TargetStatus> targets = null) { throw null; }
public static Azure.Quantum.Jobs.Models.QuantumJobQuota QuantumJobQuota(string dimension = null, Azure.Quantum.Jobs.Models.DimensionScope? scope = default(Azure.Quantum.Jobs.Models.DimensionScope?), string providerId = null, float? utilization = default(float?), float? holds = default(float?), float? limit = default(float?), Azure.Quantum.Jobs.Models.MeterPeriod? period = default(Azure.Quantum.Jobs.Models.MeterPeriod?)) { throw null; }
public static Azure.Quantum.Jobs.Models.QuantumJobQuotaList QuantumJobQuotaList(System.Collections.Generic.IEnumerable<Azure.Quantum.Jobs.Models.QuantumJobQuota> value = null, string nextLink = null) { throw null; }
public static Azure.Quantum.Jobs.Models.SasUriResponse SasUriResponse(string sasUri = null) { throw null; }
public static Azure.Quantum.Jobs.Models.TargetStatus TargetStatus(string id = null, Azure.Quantum.Jobs.Models.TargetAvailability? currentAvailability = default(Azure.Quantum.Jobs.Models.TargetAvailability?), long? averageQueueTime = default(long?), string statusPage = null) { throw null; }
public static Azure.Quantum.Jobs.Models.UsageEvent UsageEvent(string dimensionId = null, string dimensionName = null, string measureUnit = null, float? amountBilled = default(float?), float? amountConsumed = default(float?), float? unitPrice = default(float?)) { throw null; }
}
public partial class SasUriResponse
{
internal SasUriResponse() { }
public string SasUri { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct TargetAvailability : System.IEquatable<Azure.Quantum.Jobs.Models.TargetAvailability>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public TargetAvailability(string value) { throw null; }
public static Azure.Quantum.Jobs.Models.TargetAvailability Available { get { throw null; } }
public static Azure.Quantum.Jobs.Models.TargetAvailability Degraded { get { throw null; } }
public static Azure.Quantum.Jobs.Models.TargetAvailability Unavailable { get { throw null; } }
public bool Equals(Azure.Quantum.Jobs.Models.TargetAvailability other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Quantum.Jobs.Models.TargetAvailability left, Azure.Quantum.Jobs.Models.TargetAvailability right) { throw null; }
public static implicit operator Azure.Quantum.Jobs.Models.TargetAvailability (string value) { throw null; }
public static bool operator !=(Azure.Quantum.Jobs.Models.TargetAvailability left, Azure.Quantum.Jobs.Models.TargetAvailability right) { throw null; }
public override string ToString() { throw null; }
}
public partial class TargetStatus
{
internal TargetStatus() { }
public long? AverageQueueTime { get { throw null; } }
public Azure.Quantum.Jobs.Models.TargetAvailability? CurrentAvailability { get { throw null; } }
public string Id { get { throw null; } }
public string StatusPage { get { throw null; } }
}
public partial class UsageEvent
{
internal UsageEvent() { }
public float? AmountBilled { get { throw null; } }
public float? AmountConsumed { get { throw null; } }
public string DimensionId { get { throw null; } }
public string DimensionName { get { throw null; } }
public string MeasureUnit { get { throw null; } }
public float? UnitPrice { get { throw null; } }
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
[ExportLanguageService(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared]
internal class CSharpSyntaxFactsService : ISyntaxFactsService
{
public bool IsAwaitKeyword(SyntaxToken token)
{
return token.IsKind(SyntaxKind.AwaitKeyword);
}
public bool IsIdentifier(SyntaxToken token)
{
return token.IsKind(SyntaxKind.IdentifierToken);
}
public bool IsGlobalNamespaceKeyword(SyntaxToken token)
{
return token.IsKind(SyntaxKind.GlobalKeyword);
}
public bool IsVerbatimIdentifier(SyntaxToken token)
{
return token.IsVerbatimIdentifier();
}
public bool IsOperator(SyntaxToken token)
{
var kind = token.Kind();
return
(SyntaxFacts.IsAnyUnaryExpression(kind) &&
(token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax)) ||
(SyntaxFacts.IsBinaryExpression(kind) && token.Parent is BinaryExpressionSyntax) ||
(SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax);
}
public bool IsKeyword(SyntaxToken token)
{
var kind = (SyntaxKind)token.RawKind;
return
SyntaxFacts.IsKeywordKind(kind); // both contextual and reserved keywords
}
public bool IsContextualKeyword(SyntaxToken token)
{
var kind = (SyntaxKind)token.RawKind;
return
SyntaxFacts.IsContextualKeyword(kind);
}
public bool IsPreprocessorKeyword(SyntaxToken token)
{
var kind = (SyntaxKind)token.RawKind;
return
SyntaxFacts.IsPreprocessorKeyword(kind);
}
public bool IsHashToken(SyntaxToken token)
{
return (SyntaxKind)token.RawKind == SyntaxKind.HashToken;
}
public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var csharpTree = syntaxTree as SyntaxTree;
if (csharpTree == null)
{
return false;
}
return csharpTree.IsInInactiveRegion(position, cancellationToken);
}
public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var csharpTree = syntaxTree as SyntaxTree;
if (csharpTree == null)
{
return false;
}
return csharpTree.IsInNonUserCode(position, cancellationToken);
}
public bool IsEntirelyWithinStringOrCharLiteral(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var csharpTree = syntaxTree as SyntaxTree;
if (csharpTree == null)
{
return false;
}
return csharpTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
}
public bool IsDirective(SyntaxNode node)
{
return node is DirectiveTriviaSyntax;
}
public bool TryGetExternalSourceInfo(SyntaxNode node, out ExternalSourceInfo info)
{
var lineDirective = node as LineDirectiveTriviaSyntax;
if (lineDirective != null)
{
if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
{
info = new ExternalSourceInfo(null, ends: true);
return true;
}
else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
lineDirective.Line.Value is int)
{
info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
return true;
}
}
info = default(ExternalSourceInfo);
return false;
}
public bool IsRightSideOfQualifiedName(SyntaxNode node)
{
var name = node as SimpleNameSyntax;
return name.IsRightSideOfQualifiedName();
}
public bool IsMemberAccessExpressionName(SyntaxNode node)
{
var name = node as SimpleNameSyntax;
return name.IsMemberAccessExpressionName();
}
public bool IsObjectCreationExpressionType(SyntaxNode node)
{
return node.IsParentKind(SyntaxKind.ObjectCreationExpression) &&
((ObjectCreationExpressionSyntax)node.Parent).Type == node;
}
public bool IsAttributeName(SyntaxNode node)
{
return SyntaxFacts.IsAttributeName(node);
}
public bool IsInvocationExpression(SyntaxNode node)
{
return node is InvocationExpressionSyntax;
}
public bool IsAnonymousFunction(SyntaxNode node)
{
return node is ParenthesizedLambdaExpressionSyntax ||
node is SimpleLambdaExpressionSyntax ||
node is AnonymousMethodExpressionSyntax;
}
public bool IsGenericName(SyntaxNode node)
{
return node is GenericNameSyntax;
}
public bool IsNamedParameter(SyntaxNode node)
{
return node.CheckParent<NameColonSyntax>(p => p.Name == node);
}
public bool IsSkippedTokensTrivia(SyntaxNode node)
{
return node is SkippedTokensTriviaSyntax;
}
public bool HasIncompleteParentMember(SyntaxNode node)
{
return node.IsParentKind(SyntaxKind.IncompleteMember);
}
public SyntaxToken GetIdentifierOfGenericName(SyntaxNode genericName)
{
var csharpGenericName = genericName as GenericNameSyntax;
return csharpGenericName != null
? csharpGenericName.Identifier
: default(SyntaxToken);
}
public bool IsCaseSensitive
{
get
{
return true;
}
}
public bool IsUsingDirectiveName(SyntaxNode node)
{
return
node.IsParentKind(SyntaxKind.UsingDirective) &&
((UsingDirectiveSyntax)node.Parent).Name == node;
}
public bool IsForEachStatement(SyntaxNode node)
{
return node is ForEachStatementSyntax;
}
public bool IsLockStatement(SyntaxNode node)
{
return node is LockStatementSyntax;
}
public bool IsUsingStatement(SyntaxNode node)
{
return node is UsingStatementSyntax;
}
public bool IsThisConstructorInitializer(SyntaxToken token)
{
return token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token;
}
public bool IsBaseConstructorInitializer(SyntaxToken token)
{
return token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) &&
((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token;
}
public bool IsQueryExpression(SyntaxNode node)
{
return node is QueryExpressionSyntax;
}
public bool IsPredefinedType(SyntaxToken token)
{
PredefinedType actualType;
return TryGetPredefinedType(token, out actualType) && actualType != PredefinedType.None;
}
public bool IsPredefinedType(SyntaxToken token, PredefinedType type)
{
PredefinedType actualType;
return TryGetPredefinedType(token, out actualType) && actualType == type;
}
public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
{
type = GetPredefinedType(token);
return type != PredefinedType.None;
}
private PredefinedType GetPredefinedType(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.BoolKeyword:
return PredefinedType.Boolean;
case SyntaxKind.ByteKeyword:
return PredefinedType.Byte;
case SyntaxKind.SByteKeyword:
return PredefinedType.SByte;
case SyntaxKind.IntKeyword:
return PredefinedType.Int32;
case SyntaxKind.UIntKeyword:
return PredefinedType.UInt32;
case SyntaxKind.ShortKeyword:
return PredefinedType.Int16;
case SyntaxKind.UShortKeyword:
return PredefinedType.UInt16;
case SyntaxKind.LongKeyword:
return PredefinedType.Int64;
case SyntaxKind.ULongKeyword:
return PredefinedType.UInt64;
case SyntaxKind.FloatKeyword:
return PredefinedType.Single;
case SyntaxKind.DoubleKeyword:
return PredefinedType.Double;
case SyntaxKind.DecimalKeyword:
return PredefinedType.Decimal;
case SyntaxKind.StringKeyword:
return PredefinedType.String;
case SyntaxKind.CharKeyword:
return PredefinedType.Char;
case SyntaxKind.ObjectKeyword:
return PredefinedType.Object;
case SyntaxKind.VoidKeyword:
return PredefinedType.Void;
default:
return PredefinedType.None;
}
}
public bool IsPredefinedOperator(SyntaxToken token)
{
PredefinedOperator actualOperator;
return TryGetPredefinedOperator(token, out actualOperator) && actualOperator != PredefinedOperator.None;
}
public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
{
PredefinedOperator actualOperator;
return TryGetPredefinedOperator(token, out actualOperator) && actualOperator == op;
}
public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
{
op = GetPredefinedOperator(token);
return op != PredefinedOperator.None;
}
private PredefinedOperator GetPredefinedOperator(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.PlusEqualsToken:
return PredefinedOperator.Addition;
case SyntaxKind.MinusToken:
case SyntaxKind.MinusEqualsToken:
return PredefinedOperator.Subtraction;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return PredefinedOperator.BitwiseAnd;
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return PredefinedOperator.BitwiseOr;
case SyntaxKind.MinusMinusToken:
return PredefinedOperator.Decrement;
case SyntaxKind.PlusPlusToken:
return PredefinedOperator.Increment;
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
return PredefinedOperator.Division;
case SyntaxKind.EqualsEqualsToken:
return PredefinedOperator.Equality;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return PredefinedOperator.ExclusiveOr;
case SyntaxKind.GreaterThanToken:
return PredefinedOperator.GreaterThan;
case SyntaxKind.GreaterThanEqualsToken:
return PredefinedOperator.GreaterThanOrEqual;
case SyntaxKind.ExclamationEqualsToken:
return PredefinedOperator.Inequality;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.LessThanLessThanEqualsToken:
return PredefinedOperator.LeftShift;
case SyntaxKind.LessThanEqualsToken:
return PredefinedOperator.LessThanOrEqual;
case SyntaxKind.AsteriskToken:
case SyntaxKind.AsteriskEqualsToken:
return PredefinedOperator.Multiplication;
case SyntaxKind.PercentToken:
case SyntaxKind.PercentEqualsToken:
return PredefinedOperator.Modulus;
case SyntaxKind.ExclamationToken:
case SyntaxKind.TildeToken:
return PredefinedOperator.Complement;
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return PredefinedOperator.RightShift;
}
return PredefinedOperator.None;
}
public string GetText(int kind)
{
return SyntaxFacts.GetText((SyntaxKind)kind);
}
public bool IsIdentifierStartCharacter(char c)
{
return SyntaxFacts.IsIdentifierStartCharacter(c);
}
public bool IsIdentifierPartCharacter(char c)
{
return SyntaxFacts.IsIdentifierPartCharacter(c);
}
public bool IsIdentifierEscapeCharacter(char c)
{
return c == '@';
}
public bool IsValidIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
}
public bool IsVerbatimIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
}
public bool IsTypeCharacter(char c)
{
return false;
}
public bool IsStartOfUnicodeEscapeSequence(char c)
{
return c == '\\';
}
public bool IsLiteral(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
return true;
}
return false;
}
public bool IsStringLiteral(SyntaxToken token)
{
return token.IsKind(SyntaxKind.StringLiteralToken);
}
public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, SyntaxNode parent)
{
var typedToken = token;
var typedParent = parent;
if (typedParent.IsKind(SyntaxKind.IdentifierName))
{
TypeSyntax declaredType = null;
if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration))
{
declaredType = ((VariableDeclarationSyntax)typedParent.Parent).Type;
}
else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration))
{
declaredType = ((FieldDeclarationSyntax)typedParent.Parent).Declaration.Type;
}
return declaredType == typedParent && typedToken.ValueText == "var";
}
return false;
}
public bool IsTypeNamedDynamic(SyntaxToken token, SyntaxNode parent)
{
var typedParent = parent as ExpressionSyntax;
if (typedParent != null)
{
if (SyntaxFacts.IsInTypeOnlyContext(typedParent) &&
typedParent.IsKind(SyntaxKind.IdentifierName) &&
token.ValueText == "dynamic")
{
return true;
}
}
return false;
}
public bool IsBindableToken(SyntaxToken token)
{
if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.DelegateKeyword:
case SyntaxKind.VoidKeyword:
return false;
}
return true;
}
return false;
}
public bool IsMemberAccessExpression(SyntaxNode node)
{
return node is MemberAccessExpressionSyntax &&
((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.SimpleMemberAccessExpression;
}
public bool IsConditionalMemberAccessExpression(SyntaxNode node)
{
return node is ConditionalAccessExpressionSyntax;
}
public bool IsPointerMemberAccessExpression(SyntaxNode node)
{
return node is MemberAccessExpressionSyntax &&
((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.PointerMemberAccessExpression;
}
public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity)
{
name = null;
arity = 0;
var simpleName = node as SimpleNameSyntax;
if (simpleName != null)
{
name = simpleName.Identifier.ValueText;
arity = simpleName.Arity;
}
}
public SyntaxNode GetExpressionOfMemberAccessExpression(SyntaxNode node)
{
if (node.IsKind(SyntaxKind.MemberBindingExpression))
{
if (node.IsParentKind(SyntaxKind.ConditionalAccessExpression))
{
return GetExpressionOfConditionalMemberAccessExpression(node.Parent);
}
if (node.IsParentKind(SyntaxKind.InvocationExpression) &&
node.Parent.IsParentKind(SyntaxKind.ConditionalAccessExpression))
{
return GetExpressionOfConditionalMemberAccessExpression(node.Parent.Parent);
}
}
return (node as MemberAccessExpressionSyntax)?.Expression;
}
public SyntaxNode GetExpressionOfConditionalMemberAccessExpression(SyntaxNode node)
{
return (node as ConditionalAccessExpressionSyntax)?.Expression;
}
public bool IsInStaticContext(SyntaxNode node)
{
return node.IsInStaticContext();
}
public bool IsInNamespaceOrTypeContext(SyntaxNode node)
{
return SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
}
public SyntaxNode GetExpressionOfArgument(SyntaxNode node)
{
return ((ArgumentSyntax)node).Expression;
}
public RefKind GetRefKindOfArgument(SyntaxNode node)
{
return (node as ArgumentSyntax).GetRefKind();
}
public bool IsInConstantContext(SyntaxNode node)
{
return (node as ExpressionSyntax).IsInConstantContext();
}
public bool IsInConstructor(SyntaxNode node)
{
return node.GetAncestor<ConstructorDeclarationSyntax>() != null;
}
public bool IsUnsafeContext(SyntaxNode node)
{
return node.IsUnsafeContext();
}
public SyntaxNode GetNameOfAttribute(SyntaxNode node)
{
return ((AttributeSyntax)node).Name;
}
public bool IsAttribute(SyntaxNode node)
{
return node is AttributeSyntax;
}
public bool IsAttributeNamedArgumentIdentifier(SyntaxNode node)
{
var identifier = node as IdentifierNameSyntax;
return
identifier != null &&
identifier.IsParentKind(SyntaxKind.NameEquals) &&
identifier.Parent.IsParentKind(SyntaxKind.AttributeArgument);
}
public SyntaxNode GetContainingTypeDeclaration(SyntaxNode root, int position)
{
if (root == null)
{
throw new ArgumentNullException("root");
}
if (position < 0 || position > root.Span.End)
{
throw new ArgumentOutOfRangeException("position");
}
return root
.FindToken(position)
.GetAncestors<SyntaxNode>()
.FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
}
public SyntaxNode GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode node)
{
throw ExceptionUtilities.Unreachable;
}
public SyntaxToken FindTokenOnLeftOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public SyntaxToken FindTokenOnRightOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public bool IsObjectCreationExpression(SyntaxNode node)
{
return node is ObjectCreationExpressionSyntax;
}
public bool IsObjectInitializerNamedAssignmentIdentifier(SyntaxNode node)
{
var identifier = node as IdentifierNameSyntax;
return
identifier != null &&
identifier.IsLeftSideOfAssignExpression() &&
identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression);
}
public bool IsElementAccessExpression(SyntaxNode node)
{
return node.Kind() == SyntaxKind.ElementAccessExpression;
}
public SyntaxNode ConvertToSingleLine(SyntaxNode node)
{
return node.ConvertToSingleLine();
}
public SyntaxToken ToIdentifierToken(string name)
{
return name.ToIdentifierToken();
}
public SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia)
{
return ((ExpressionSyntax)expression).Parenthesize(includeElasticTrivia);
}
public bool IsIndexerMemberCRef(SyntaxNode node)
{
return node.Kind() == SyntaxKind.IndexerMemberCref;
}
public SyntaxNode GetContainingMemberDeclaration(SyntaxNode root, int position)
{
Contract.ThrowIfNull(root, "root");
Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
var end = root.FullSpan.End;
if (end == 0)
{
// empty file
return null;
}
// make sure position doesn't touch end of root
position = Math.Min(position, end - 1);
var node = root.FindToken(position).Parent;
while (node != null)
{
if (node is MemberDeclarationSyntax)
{
return node;
}
node = node.Parent;
}
return null;
}
public bool IsMethodLevelMember(SyntaxNode node)
{
return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax;
}
public bool IsTopLevelNodeWithMembers(SyntaxNode node)
{
return node is NamespaceDeclarationSyntax ||
node is TypeDeclarationSyntax ||
node is EnumDeclarationSyntax;
}
public bool TryGetDeclaredSymbolInfo(SyntaxNode node, out DeclaredSymbolInfo declaredSymbolInfo)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
var classDecl = (ClassDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(classDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Class, classDecl.Identifier.Span);
return true;
case SyntaxKind.ConstructorDeclaration:
var ctorDecl = (ConstructorDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(
ctorDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Constructor,
ctorDecl.Identifier.Span,
parameterCount: (ushort)(ctorDecl.ParameterList?.Parameters.Count ?? 0));
return true;
case SyntaxKind.DelegateDeclaration:
var delegateDecl = (DelegateDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(delegateDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Delegate, delegateDecl.Identifier.Span);
return true;
case SyntaxKind.EnumDeclaration:
var enumDecl = (EnumDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(enumDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Enum, enumDecl.Identifier.Span);
return true;
case SyntaxKind.EnumMemberDeclaration:
var enumMember = (EnumMemberDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(enumMember.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.EnumMember, enumMember.Identifier.Span);
return true;
case SyntaxKind.EventDeclaration:
var eventDecl = (EventDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(eventDecl.Identifier.ValueText, eventDecl.ExplicitInterfaceSpecifier),
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Event, eventDecl.Identifier.Span);
return true;
case SyntaxKind.IndexerDeclaration:
var indexerDecl = (IndexerDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(WellKnownMemberNames.Indexer,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Indexer, indexerDecl.ThisKeyword.Span);
return true;
case SyntaxKind.InterfaceDeclaration:
var interfaceDecl = (InterfaceDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(interfaceDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Interface, interfaceDecl.Identifier.Span);
return true;
case SyntaxKind.MethodDeclaration:
var method = (MethodDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(
ExpandExplicitInterfaceName(method.Identifier.ValueText, method.ExplicitInterfaceSpecifier),
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Method,
method.Identifier.Span,
parameterCount: (ushort)(method.ParameterList?.Parameters.Count ?? 0),
typeParameterCount: (ushort)(method.TypeParameterList?.Parameters.Count ?? 0));
return true;
case SyntaxKind.PropertyDeclaration:
var property = (PropertyDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(property.Identifier.ValueText, property.ExplicitInterfaceSpecifier),
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Property, property.Identifier.Span);
return true;
case SyntaxKind.StructDeclaration:
var structDecl = (StructDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(structDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Struct, structDecl.Identifier.Span);
return true;
case SyntaxKind.VariableDeclarator:
// could either be part of a field declaration or an event field declaration
var variableDeclarator = (VariableDeclaratorSyntax)node;
var variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax;
var fieldDeclaration = variableDeclaration?.Parent as BaseFieldDeclarationSyntax;
if (fieldDeclaration != null)
{
var kind = fieldDeclaration is EventFieldDeclarationSyntax
? DeclaredSymbolInfoKind.Event
: fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword)
? DeclaredSymbolInfoKind.Constant
: DeclaredSymbolInfoKind.Field;
declaredSymbolInfo = new DeclaredSymbolInfo(variableDeclarator.Identifier.ValueText,
GetContainerDisplayName(fieldDeclaration.Parent),
GetFullyQualifiedContainerName(fieldDeclaration.Parent),
kind, variableDeclarator.Identifier.Span);
return true;
}
break;
}
declaredSymbolInfo = default(DeclaredSymbolInfo);
return false;
}
private static string ExpandExplicitInterfaceName(string identifier, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier)
{
if (explicitInterfaceSpecifier == null)
{
return identifier;
}
else
{
var builder = new StringBuilder();
ExpandTypeName(explicitInterfaceSpecifier.Name, builder);
builder.Append('.');
builder.Append(identifier);
return builder.ToString();
}
}
private static void ExpandTypeName(TypeSyntax type, StringBuilder builder)
{
switch (type.Kind())
{
case SyntaxKind.AliasQualifiedName:
var alias = (AliasQualifiedNameSyntax)type;
builder.Append(alias.Alias.Identifier.ValueText);
break;
case SyntaxKind.ArrayType:
var array = (ArrayTypeSyntax)type;
ExpandTypeName(array.ElementType, builder);
for (int i = 0; i < array.RankSpecifiers.Count; i++)
{
var rankSpecifier = array.RankSpecifiers[i];
builder.Append(rankSpecifier.OpenBracketToken.Text);
for (int j = 1; j < rankSpecifier.Sizes.Count; j++)
{
builder.Append(',');
}
builder.Append(rankSpecifier.CloseBracketToken.Text);
}
break;
case SyntaxKind.GenericName:
var generic = (GenericNameSyntax)type;
builder.Append(generic.Identifier.ValueText);
if (generic.TypeArgumentList != null)
{
var arguments = generic.TypeArgumentList.Arguments;
builder.Append(generic.TypeArgumentList.LessThanToken.Text);
for (int i = 0; i < arguments.Count; i++)
{
if (i != 0)
{
builder.Append(',');
}
ExpandTypeName(arguments[i], builder);
}
builder.Append(generic.TypeArgumentList.GreaterThanToken.Text);
}
break;
case SyntaxKind.IdentifierName:
var identifierName = (IdentifierNameSyntax)type;
builder.Append(identifierName.Identifier.ValueText);
break;
case SyntaxKind.NullableType:
var nullable = (NullableTypeSyntax)type;
ExpandTypeName(nullable.ElementType, builder);
builder.Append(nullable.QuestionToken.Text);
break;
case SyntaxKind.OmittedTypeArgument:
// do nothing since it was omitted, but don't reach the default block
break;
case SyntaxKind.PointerType:
var pointer = (PointerTypeSyntax)type;
ExpandTypeName(pointer.ElementType, builder);
builder.Append(pointer.AsteriskToken.Text);
break;
case SyntaxKind.PredefinedType:
var predefined = (PredefinedTypeSyntax)type;
builder.Append(predefined.Keyword.Text);
break;
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)type;
ExpandTypeName(qualified.Left, builder);
builder.Append(qualified.DotToken.Text);
ExpandTypeName(qualified.Right, builder);
break;
default:
Debug.Assert(false, "Unexpected type syntax " + type.Kind());
break;
}
}
private static string GetContainerDisplayName(SyntaxNode node)
{
return GetContainer(node, immediate: true);
}
private static string GetFullyQualifiedContainerName(SyntaxNode node)
{
return GetContainer(node, immediate: false);
}
private static string GetContainer(SyntaxNode node, bool immediate)
{
var name = GetNodeName(node, includeTypeParameters: immediate);
var names = new List<string> { name };
// check for nested classes and always add that to the container name.
var parent = node.Parent;
while (parent is TypeDeclarationSyntax)
{
var currentParent = (TypeDeclarationSyntax)parent;
names.Add(currentParent.Identifier.ValueText + (immediate ? ExpandTypeParameterList(currentParent.TypeParameterList) : ""));
parent = currentParent.Parent;
}
// If they're just asking for the immediate parent, then we're done. Otherwise keep
// walking all the way to the root, adding the names.
if (!immediate)
{
while (parent != null && parent.Kind() != SyntaxKind.CompilationUnit)
{
names.Add(GetNodeName(parent, includeTypeParameters: false));
parent = parent.Parent;
}
}
names.Reverse();
return string.Join(".", names);
}
private static string GetNodeName(SyntaxNode node, bool includeTypeParameters)
{
string name;
TypeParameterListSyntax typeParameterList;
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
var classDecl = (ClassDeclarationSyntax)node;
name = classDecl.Identifier.ValueText;
typeParameterList = classDecl.TypeParameterList;
break;
case SyntaxKind.CompilationUnit:
return string.Empty;
case SyntaxKind.DelegateDeclaration:
var delegateDecl = (DelegateDeclarationSyntax)node;
name = delegateDecl.Identifier.ValueText;
typeParameterList = delegateDecl.TypeParameterList;
break;
case SyntaxKind.EnumDeclaration:
return ((EnumDeclarationSyntax)node).Identifier.ValueText;
case SyntaxKind.IdentifierName:
return ((IdentifierNameSyntax)node).Identifier.ValueText;
case SyntaxKind.InterfaceDeclaration:
var interfaceDecl = (InterfaceDeclarationSyntax)node;
name = interfaceDecl.Identifier.ValueText;
typeParameterList = interfaceDecl.TypeParameterList;
break;
case SyntaxKind.MethodDeclaration:
var methodDecl = (MethodDeclarationSyntax)node;
name = methodDecl.Identifier.ValueText;
typeParameterList = methodDecl.TypeParameterList;
break;
case SyntaxKind.NamespaceDeclaration:
return GetNodeName(((NamespaceDeclarationSyntax)node).Name, includeTypeParameters: false);
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)node;
return GetNodeName(qualified.Left, includeTypeParameters: false) + "." + GetNodeName(qualified.Right, includeTypeParameters: false);
case SyntaxKind.StructDeclaration:
var structDecl = (StructDeclarationSyntax)node;
name = structDecl.Identifier.ValueText;
typeParameterList = structDecl.TypeParameterList;
break;
default:
Debug.Assert(false, "Unexpected node type " + node.Kind());
return null;
}
return name + (includeTypeParameters ? ExpandTypeParameterList(typeParameterList) : "");
}
private static string ExpandTypeParameterList(TypeParameterListSyntax typeParameterList)
{
if (typeParameterList != null && typeParameterList.Parameters.Count > 0)
{
var builder = new StringBuilder();
builder.Append('<');
builder.Append(typeParameterList.Parameters[0].Identifier.ValueText);
for (int i = 1; i < typeParameterList.Parameters.Count; i++)
{
builder.Append(',');
builder.Append(typeParameterList.Parameters[i].Identifier.ValueText);
}
builder.Append('>');
return builder.ToString();
}
else
{
return null;
}
}
public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode root)
{
var list = new List<SyntaxNode>();
AppendMethodLevelMembers(root, list);
return list;
}
private void AppendMethodLevelMembers(SyntaxNode node, List<SyntaxNode> list)
{
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
AppendMethodLevelMembers(member, list);
continue;
}
if (IsMethodLevelMember(member))
{
list.Add(member);
}
}
}
public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
{
if (node.Span.IsEmpty)
{
return default(TextSpan);
}
var member = GetContainingMemberDeclaration(node, node.SpanStart);
if (member == null)
{
return default(TextSpan);
}
// TODO: currently we only support method for now
var method = member as BaseMethodDeclarationSyntax;
if (method != null)
{
if (method.Body == null)
{
return default(TextSpan);
}
return GetBlockBodySpan(method.Body);
}
return default(TextSpan);
}
public bool ContainsInMemberBody(SyntaxNode node, TextSpan span)
{
var constructor = node as ConstructorDeclarationSyntax;
if (constructor != null)
{
return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
(constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
}
var method = node as BaseMethodDeclarationSyntax;
if (method != null)
{
return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
}
var property = node as BasePropertyDeclarationSyntax;
if (property != null)
{
return property.AccessorList != null && property.AccessorList.Span.Contains(span);
}
var @enum = node as EnumMemberDeclarationSyntax;
if (@enum != null)
{
return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
}
var field = node as BaseFieldDeclarationSyntax;
if (field != null)
{
return field.Declaration != null && field.Declaration.Span.Contains(span);
}
return false;
}
private TextSpan GetBlockBodySpan(BlockSyntax body)
{
return TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
}
public int GetMethodLevelMemberId(SyntaxNode root, SyntaxNode node)
{
Contract.Requires(root.SyntaxTree == node.SyntaxTree);
int currentId = 0;
SyntaxNode currentNode;
Contract.ThrowIfFalse(TryGetMethodLevelMember(root, (n, i) => n == node, ref currentId, out currentNode));
Contract.ThrowIfFalse(currentId >= 0);
CheckMemberId(root, node, currentId);
return currentId;
}
public SyntaxNode GetMethodLevelMember(SyntaxNode root, int memberId)
{
int currentId = 0;
SyntaxNode currentNode;
if (!TryGetMethodLevelMember(root, (n, i) => i == memberId, ref currentId, out currentNode))
{
return null;
}
Contract.ThrowIfNull(currentNode);
CheckMemberId(root, currentNode, memberId);
return currentNode;
}
private bool TryGetMethodLevelMember(
SyntaxNode node, Func<SyntaxNode, int, bool> predicate, ref int currentId, out SyntaxNode currentNode)
{
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
if (TryGetMethodLevelMember(member, predicate, ref currentId, out currentNode))
{
return true;
}
continue;
}
if (IsMethodLevelMember(member))
{
if (predicate(member, currentId))
{
currentNode = member;
return true;
}
currentId++;
}
}
currentNode = null;
return false;
}
[Conditional("DEBUG")]
private void CheckMemberId(SyntaxNode root, SyntaxNode node, int memberId)
{
var list = GetMethodLevelMembers(root);
var index = list.IndexOf(node);
Contract.ThrowIfFalse(index == memberId);
}
public SyntaxNode GetBindableParent(SyntaxToken token)
{
var node = token.Parent;
while (node != null)
{
var parent = node.Parent;
// If this node is on the left side of a member access expression, don't ascend
// further or we'll end up binding to something else.
var memberAccess = parent as MemberAccessExpressionSyntax;
if (memberAccess != null)
{
if (memberAccess.Expression == node)
{
break;
}
}
// If this node is on the left side of a qualified name, don't ascend
// further or we'll end up binding to something else.
var qualifiedName = parent as QualifiedNameSyntax;
if (qualifiedName != null)
{
if (qualifiedName.Left == node)
{
break;
}
}
// If this node is on the left side of a alias-qualified name, don't ascend
// further or we'll end up binding to something else.
var aliasQualifiedName = parent as AliasQualifiedNameSyntax;
if (aliasQualifiedName != null)
{
if (aliasQualifiedName.Alias == node)
{
break;
}
}
// If this node is the type of an object creation expression, return the
// object creation expression.
var objectCreation = parent as ObjectCreationExpressionSyntax;
if (objectCreation != null)
{
if (objectCreation.Type == node)
{
node = parent;
break;
}
}
// If this node is not parented by a name, we're done.
var name = parent as NameSyntax;
if (name == null)
{
break;
}
node = parent;
}
return node;
}
public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode root, CancellationToken cancellationToken)
{
var compilationUnit = root as CompilationUnitSyntax;
if (compilationUnit == null)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var constructors = new List<SyntaxNode>();
AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
return constructors;
}
private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
var constructor = member as ConstructorDeclarationSyntax;
if (constructor != null)
{
constructors.Add(constructor);
continue;
}
var @namespace = member as NamespaceDeclarationSyntax;
if (@namespace != null)
{
AppendConstructors(@namespace.Members, constructors, cancellationToken);
}
var @class = member as ClassDeclarationSyntax;
if (@class != null)
{
AppendConstructors(@class.Members, constructors, cancellationToken);
}
var @struct = member as StructDeclarationSyntax;
if (@struct != null)
{
AppendConstructors(@struct.Members, constructors, cancellationToken);
}
}
}
public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
{
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var tuple = token.Parent.GetBraces();
openBrace = tuple.Item1;
return openBrace.Kind() == SyntaxKind.OpenBraceToken;
}
openBrace = default(SyntaxToken);
return false;
}
}
}
| |
// Copyright 2019 Esri
// 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.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Core.Data;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Framework.Dialogs;
namespace AnimationFromPath
{
public static class CreateAnimationFromPath
{
#region Constants
//determines where intermediate keyframes are created along a segment
private const double LINE_CONSTRAINT_FACTOR = 0.15;
private const double ARC_CONSTRAINT_FACTOR = 0.15;
//minimum length of a straight line segment needed to create intermediate keyframes
//and use additional logic for ignoring rotation on end points. If a straight line segment
//is smaller than this threshold then intermediate keyframes are not created and ignore-rotation-at-end-points
//logic is not used
private const double STRAIGHT_SEGMENT_LENGTH_THRESHOLD = 30;
private const double ANIMATION_APPEND_TIME = 3; //seconds
#endregion
#region Fields/Properties
private static double _keyframeHeading = 0;
private static double _keyframePitch = 0;
private static double Z_CONVERSION_FACTOR = 1;
private static string _selectedMethod = "Keyframes along path";
public static string SelectedMethod
{
get { return _selectedMethod; }
set { _selectedMethod = value; }
}
private static string _selectedCameraView = "Top down";
public static string SelectedCameraView
{
get { return _selectedCameraView; }
set { _selectedCameraView = value; }
}
private static double _customPitch = -90;
public static double CustomPitch
{
get { return _customPitch; }
set { _customPitch = value; }
}
private static double _cameraZOffset = 1000;
public static double CameraZOffset
{
get { return _cameraZOffset; }
set { _cameraZOffset = value; }
}
private static double _totalDuration = 0;
public static double TotalDuration
{
get { return _totalDuration; }
set { _totalDuration = value; }
}
private static double _keyEveryNSecond = 1;
public static double KeyEveryNSecond
{
get { return _keyEveryNSecond; }
set { _keyEveryNSecond = value; }
}
private static MapPoint _targetPoint = null;
public static MapPoint TargetPoint
{
get { return _targetPoint; }
set { _targetPoint = value; }
}
#endregion
#region Functions
public static async Task CreateKeyframes()
{
FeatureLayer ftrLayer = null;
MapView mapView = MapView.Active;
if (mapView == null)
return;
var mapSelection = await QueuedTask.Run(() => MapView.Active.Map.GetSelection());
if (mapSelection.Count == 1)
{
var layer = mapSelection.First().Key;
if (layer is FeatureLayer)
{
ftrLayer = (FeatureLayer)layer;
if (ftrLayer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select a polyline feature.");
return;
}
int numFtrsSelected = await QueuedTask.Run(() => ftrLayer.GetSelection().GetCount());
if (numFtrsSelected != 1)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select only one polyline feature.");
return;
}
}
else
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select a polyline feature.");
return;
}
}
else
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select a polyline feature.");
return;
}
if (SelectedCameraView == "Face target" && TargetPoint == null)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Selected view type is - Face target - but a target point is not set.");
return;
}
string oid_fieldName = await QueuedTask.Run(() => ftrLayer.GetTable().GetDefinition().GetObjectIDField());
//get selected polyline
Polyline lineGeom = await QueuedTask.Run<Polyline>(() =>
{
var selectedFtrOID = MapView.Active.Map.GetSelection()[ftrLayer][0];
QueryFilter qf = new QueryFilter();
qf.WhereClause = oid_fieldName + " = " + selectedFtrOID.ToString();
RowCursor result = ftrLayer.GetFeatureClass().Search(qf);
if (result != null)
{
result.MoveNext();
Feature selectedFtr = result.Current as Feature;
return selectedFtr.GetShape() as Polyline;
}
return null;
});
//couldn't get the selected feature
if (lineGeom == null)
return;
ProjectionTransformation transformation = await QueuedTask.Run(() => ProjectionTransformation.Create(ftrLayer.GetSpatialReference(), mapView.Map.SpatialReference));
SpatialReference layerSpatRef = await QueuedTask.Run(() => ftrLayer.GetSpatialReference());
if (layerSpatRef.Unit.Name != "Degree")
Z_CONVERSION_FACTOR = layerSpatRef.Unit.ConversionFactor;
//Project target point if method is Face target
if (SelectedCameraView == "Face target")
{
if (TargetPoint != null && TargetPoint.SpatialReference != layerSpatRef)
{
ProjectionTransformation transf_forTarget = await QueuedTask.Run(() => ProjectionTransformation.Create(TargetPoint.SpatialReference, layerSpatRef));
MapPoint projected_targetPoint = (MapPoint)GeometryEngine.Instance.ProjectEx(TargetPoint, transf_forTarget);
TargetPoint = null;
TargetPoint = projected_targetPoint;
}
}
var animation = mapView.Map.Animation;
var cameraTrack = animation.Tracks.OfType<CameraTrack>().First();
var keyframes = cameraTrack.Keyframes;
//Get segment list for line
ReadOnlyPartCollection polylineParts = lineGeom.Parts;
//get total segment count and determine path length
double pathLength = 0;
int segmentCount = 0;
IEnumerator<ReadOnlySegmentCollection> segments = polylineParts.GetEnumerator();
while (segments.MoveNext())
{
ReadOnlySegmentCollection seg = segments.Current;
foreach (Segment s in seg)
{
//pathLength += s.Length;//s.Length returns 2D length
double length3D = Math.Sqrt((s.EndPoint.X - s.StartPoint.X) * (s.EndPoint.X - s.StartPoint.X) +
(s.EndPoint.Y - s.StartPoint.Y) * (s.EndPoint.Y - s.StartPoint.Y) +
(s.EndPoint.Z - s.StartPoint.Z) * (s.EndPoint.Z - s.StartPoint.Z));
pathLength += length3D;
segmentCount += 1;
}
}
//reset heading and pitch
_keyframeHeading = 0;
_keyframePitch = 0;
// Create keyframes based on chosen method
if (SelectedMethod == "Keyframes along path")
{
await CreateKeyframes_AlongPath(mapView, layerSpatRef, transformation, cameraTrack, segments, segmentCount, pathLength);
}
else if (SelectedMethod == "Keyframes every N seconds")
{
await CreateKeyframes_EveryNSeconds(mapView, layerSpatRef, transformation, cameraTrack, segments, segmentCount, pathLength, KeyEveryNSecond);
}
else if (SelectedMethod == "Keyframes only at vertices")
{
await CreateKeyframes_AtVertices(mapView, layerSpatRef, transformation, cameraTrack, lineGeom, segments, segmentCount, pathLength);
}
}
//Use this method for smoother turns at corners. Additionally this method processes straight line segments and arc segments separately
//For arc segments a keyframe is created at every second. However a minimum of 5 keyframes are created for arcs.
//So if arc segment length is less than 5 then we default to at least 5 keyframes. This is an attempt to stick to the path as much as possible.
//For straight line segments, rotation is ignored at end point of each segment except for the end point of the path itself. Two keyframes with rotation
//are created at certain distance (determined by LINE_CONSTRAINT_FACTOR) before and after the end point of each segment. This is an attempt to avoid
//sharp turns at corners along the path.
public static async Task CreateKeyframes_AlongPath(MapView mapView, SpatialReference layerSpatRef, ProjectionTransformation transformation,
CameraTrack cameraTrack, IEnumerator<ReadOnlySegmentCollection> segments,
int segmentCount, double pathLength)
{
double segmentLength = 0;
int num_iterations = 0;
segments.Reset();
//process each segment depending upon its type - straight line or arc
while (segments.MoveNext())
{
ReadOnlySegmentCollection seg = segments.Current;
double accumulatedDuration = mapView.Map.Animation.Duration.TotalSeconds + ((mapView.Map.Animation.Duration.TotalSeconds > 0) ? ANIMATION_APPEND_TIME : 0); // 0;
foreach (Segment s in seg)
{
double length3D = Math.Sqrt((s.EndPoint.X - s.StartPoint.X) * (s.EndPoint.X - s.StartPoint.X) +
(s.EndPoint.Y - s.StartPoint.Y) * (s.EndPoint.Y - s.StartPoint.Y) +
(s.EndPoint.Z - s.StartPoint.Z) * (s.EndPoint.Z - s.StartPoint.Z));
double segmentDuration = (TotalDuration / pathLength) * length3D;
segmentLength = length3D;
//straight line segments
if (s.SegmentType == SegmentType.Line)
{
MapPoint startPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z * Z_CONVERSION_FACTOR, layerSpatRef));
MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z * Z_CONVERSION_FACTOR, layerSpatRef));
//we will be creating three intermediate keyframes for staright segments only if segment length is more than a set threshold
//the threshold is just a guess and might have to be altered depending upon the path geometry. Should work for most cases though
MapPoint firstIntPoint = null;
MapPoint midIntPoint = null;
MapPoint lastIntPoint = null;
if (segmentLength >= STRAIGHT_SEGMENT_LENGTH_THRESHOLD)
{
//first intermediate point
firstIntPoint = await CreatePointAlongSegment(startPt, endPt, LINE_CONSTRAINT_FACTOR * segmentLength, layerSpatRef);
//mid point
midIntPoint = await CreatePointAlongSegment(startPt, endPt, 0.5 * segmentLength, layerSpatRef);
//last intermediate point
lastIntPoint = await CreatePointAlongSegment(startPt, endPt, (1 - LINE_CONSTRAINT_FACTOR) * segmentLength, layerSpatRef);
}
//create keyframe at start vertex of path in map space
double timeSpanValue = accumulatedDuration;
TimeSpan keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
if (segmentLength >= STRAIGHT_SEGMENT_LENGTH_THRESHOLD)
{
SetPitchAndHeadingForLine(startPt, firstIntPoint);
}
else
{
SetPitchAndHeadingForLine(startPt, endPt);
}
//ignore rotation for all start vertices (which would also be end vertices of previous segments) EXCEPT for the first vertex of path
if (num_iterations == 0 || segmentLength < STRAIGHT_SEGMENT_LENGTH_THRESHOLD)
{
await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
else
{
await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading, true, false);
}
if (segmentLength > STRAIGHT_SEGMENT_LENGTH_THRESHOLD)
{
//Create a keyframe at PATH_CONSTRAINT_FACTOR distance along the segment from start point
double distanceAlong = LINE_CONSTRAINT_FACTOR * segmentLength;
timeSpanValue = accumulatedDuration + LINE_CONSTRAINT_FACTOR * segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(firstIntPoint, midIntPoint);
await CreateCameraKeyframe(mapView, firstIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
//Create a keyframe at middle of segment
distanceAlong = 0.5 * segmentLength;
timeSpanValue = accumulatedDuration + 0.5 * segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(midIntPoint, lastIntPoint);
//await CreateCameraKeyframe(mapView, midIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
//Create a keyframe at (1 - PATH_CONSTRAINT_FACTOR) distance along the segment from start point
distanceAlong = (1 - LINE_CONSTRAINT_FACTOR) * segmentLength;
timeSpanValue = accumulatedDuration + (1 - LINE_CONSTRAINT_FACTOR) * segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(lastIntPoint, endPt);
await CreateCameraKeyframe(mapView, lastIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
//Create a keyframe at end point of segment only for the end point of last segment
//Otherwise we will get duplicate keyframes at end of one segment and start of the next one
if (num_iterations == segmentCount - 1)
{
timeSpanValue = accumulatedDuration + segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
if (SelectedCameraView == "Face target")
{
SetPitchAndHeadingForLine(endPt, TargetPoint);
}
await CreateCameraKeyframe(mapView, endPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
}
//processing for arcs - create a keyframe every second for arcs
//we will create a minimum of 5 keyframes along the arc
else if (s.SegmentType == SegmentType.EllipticArc && segmentDuration > 5)
{
EllipticArcSegment ellipArc = s as EllipticArcSegment;
MapPoint startPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z, layerSpatRef));
MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z, layerSpatRef));
double radius = Math.Sqrt((ellipArc.CenterPoint.X - startPt.X) * (ellipArc.CenterPoint.X - startPt.X) + (ellipArc.CenterPoint.Y - startPt.Y) * (ellipArc.CenterPoint.Y - startPt.Y));
double angle = ellipArc.CentralAngle;
MapPoint centerPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(ellipArc.CenterPoint.X, ellipArc.CenterPoint.Y, (s.StartPoint.Z + s.EndPoint.Z) / 2, layerSpatRef));
int num_keys = (int)segmentDuration;
MapPoint firstIntPoint = null;
//first intermediate keyframe for arc - needed for setting heading for start vertex
// >2 to account for start and end
if (num_keys > 2)
{
firstIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle / (num_keys - 1), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
}
//Create keyframe at start vertex of path in map space
double timeSpanValue = accumulatedDuration;
TimeSpan keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
if (firstIntPoint != null)
{
SetPitchAndHeadingForLine(startPt, firstIntPoint);
}
else
{
SetPitchAndHeadingForLine(startPt, endPt);
}
//Ignore rotation for all start vertices EXCEPT for the first vertex of path
if (num_iterations == 0)
{
await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
else
{
await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading, true, false);
}
//Loop to create intermediate keyframes at each second
for (int i = 0; i < num_keys - 2; i++)
{
MapPoint currentIntPoint = null;
MapPoint nextIntPoint = null;
currentIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, (angle / (num_keys - 1)) * (i + 1), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
if (i < num_keys - 3)
{
nextIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, (angle / (num_keys - 1)) * (i + 2), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
}
else //for the last intermediate keyframe, heading/pitch has to be determined relative to the end point fo segment
{
nextIntPoint = endPt;
}
//timeSpanValue = accumulatedDuration + (i + 1) * 1; //at each second
timeSpanValue = accumulatedDuration + (i + 1) * (segmentDuration / (num_keys - 1));
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(currentIntPoint, nextIntPoint);
await CreateCameraKeyframe(mapView, currentIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
//Create a keyframe at end point of segment only for the end point of last segment
if (num_iterations == segmentCount - 1)
{
timeSpanValue = accumulatedDuration + segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
if (SelectedCameraView == "Face target")
{
SetPitchAndHeadingForLine(endPt, TargetPoint);
}
await CreateCameraKeyframe(mapView, endPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
}
//create a minimum of 5 keyframes along the arc
else if (s.SegmentType == SegmentType.EllipticArc)
{
EllipticArcSegment ellipArc = s as EllipticArcSegment;
MapPoint startPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z, layerSpatRef));
MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z, layerSpatRef));
double radius = Math.Sqrt((ellipArc.CenterPoint.X - startPt.X) * (ellipArc.CenterPoint.X - startPt.X) + (ellipArc.CenterPoint.Y - startPt.Y) * (ellipArc.CenterPoint.Y - startPt.Y));
double angle = ellipArc.CentralAngle;
MapPoint centerPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(ellipArc.CenterPoint.X, ellipArc.CenterPoint.Y, (s.StartPoint.Z + s.EndPoint.Z) / 2, layerSpatRef));
//we are creating five intermediate keyframes for arcs
MapPoint firstIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle * ARC_CONSTRAINT_FACTOR, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
MapPoint secondIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle * ARC_CONSTRAINT_FACTOR * 2, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
MapPoint midIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle * 0.5, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
MapPoint secondLastIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle * (1 - ARC_CONSTRAINT_FACTOR * 2), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
MapPoint lastIntPoint = await CreatePointAlongArc(startPt, endPt, centerPt, angle * (1 - ARC_CONSTRAINT_FACTOR), radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
//Create keyframe at start vertex of path in map space
double timeSpanValue = accumulatedDuration;
TimeSpan keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(startPt, firstIntPoint);
//Ignore rotation for all start vertices EXCEPT for the first vertex of path
if (num_iterations == 0)
{
await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
else
{
await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading, true, false);
}
//await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
//Create a keyframe at PATH_CONSTRAINT_FACTOR distance along the segment from start point
timeSpanValue = accumulatedDuration + ARC_CONSTRAINT_FACTOR * segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(firstIntPoint, secondIntPoint);
await CreateCameraKeyframe(mapView, firstIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
//Create a keyframe at 2* PATH_CONSTRAINT_FACTOR distance along the segment from start point
timeSpanValue = accumulatedDuration + ARC_CONSTRAINT_FACTOR * 2 * segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(secondIntPoint, midIntPoint);
await CreateCameraKeyframe(mapView, secondIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
//Create a keyframe at middle of segment
timeSpanValue = accumulatedDuration + 0.5 * segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(midIntPoint, secondLastIntPoint);
await CreateCameraKeyframe(mapView, midIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
//Create a keyframe at (1 - PATH_CONSTRAINT_FACTOR * 2) distance along the segment from start point
timeSpanValue = accumulatedDuration + (1 - ARC_CONSTRAINT_FACTOR * 2) * segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(secondLastIntPoint, lastIntPoint);
await CreateCameraKeyframe(mapView, secondLastIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
//Create a keyframe at (1 - PATH_CONSTRAINT_FACTOR) distance along the segment from start point
timeSpanValue = accumulatedDuration + (1 - ARC_CONSTRAINT_FACTOR) * segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(lastIntPoint, endPt);
await CreateCameraKeyframe(mapView, lastIntPoint, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
//Create a keyframe at end point of segment only for the end point of last segment
if (num_iterations == segmentCount - 1)
{
timeSpanValue = accumulatedDuration + segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
if (SelectedCameraView == "Face target")
{
SetPitchAndHeadingForLine(endPt, TargetPoint);
}
await CreateCameraKeyframe(mapView, endPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
}
accumulatedDuration += segmentDuration;
num_iterations++;
}
}
}
//Use this method to create a keyframe at every n-second of the specified animation duration
public static async Task CreateKeyframes_EveryNSeconds(MapView mapView, SpatialReference layerSpatRef, ProjectionTransformation transformation,
CameraTrack cameraTrack, IEnumerator<ReadOnlySegmentCollection> segments,
int segmentCount, double pathLength, double keyEveryNSecond = 1)
{
double segmentLength = 0;
int numKeysToCreate = (int)(TotalDuration / keyEveryNSecond); //approximately
double createKeyAtDist = pathLength / numKeysToCreate;
double skippedDistance = 0;
double accumulatedDuration = mapView.Map.Animation.Duration.TotalSeconds + ((mapView.Map.Animation.Duration.TotalSeconds > 0) ? ANIMATION_APPEND_TIME : 0); // 0;
int num_iterations = 0;
segments.Reset();
List<MapPoint> pointsForKeyframes = new List<MapPoint>();
MapPoint pathEndPt = null;
//process each segment depending upon its type - straight line or arc
while (segments.MoveNext())
{
ReadOnlySegmentCollection seg = segments.Current;
foreach (Segment s in seg)
{
segmentLength = Math.Sqrt((s.EndPoint.X - s.StartPoint.X) * (s.EndPoint.X - s.StartPoint.X) +
(s.EndPoint.Y - s.StartPoint.Y) * (s.EndPoint.Y - s.StartPoint.Y) +
(s.EndPoint.Z - s.StartPoint.Z) * (s.EndPoint.Z - s.StartPoint.Z));
double segmentDuration = (TotalDuration / pathLength) * segmentLength;
//straight line segments
if (s.SegmentType == SegmentType.Line)
{
MapPoint startPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z, layerSpatRef));
MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z, layerSpatRef));
//add start of path to points collection
if (num_iterations == 0)
{
pointsForKeyframes.Add(startPt);
}
if (num_iterations == segmentCount - 1 || segmentCount == 1)
{
pathEndPt = endPt; //store path end pt. This will be the last keyframe.
}
double distCoveredAlongSeg = Math.Abs(createKeyAtDist - skippedDistance); //we are accouunting for skipped distances from previous segments
if (distCoveredAlongSeg < segmentLength)
{
MapPoint keyPt = await CreatePointAlongSegment(startPt, endPt, distCoveredAlongSeg, layerSpatRef);
//add point to collection
pointsForKeyframes.Add(keyPt);
//skipped distance is used now, reset to zero
skippedDistance = 0;
//are more keyframes possible for this segment
bool moreKeysPossible = ((segmentLength - distCoveredAlongSeg) >= createKeyAtDist);
while (moreKeysPossible)
{
double keyAtDistAlongSeg = distCoveredAlongSeg + createKeyAtDist;
keyPt = await CreatePointAlongSegment(startPt, endPt, keyAtDistAlongSeg, layerSpatRef);
//add point to collection
pointsForKeyframes.Add(keyPt);
distCoveredAlongSeg += createKeyAtDist;
moreKeysPossible = ((segmentLength - distCoveredAlongSeg) > createKeyAtDist);
}
//if any segment length left then add to skipped distance
skippedDistance += (segmentLength - distCoveredAlongSeg);
}
else
{
//add this segment's length to skipped distance as no keyframe could be created along it
skippedDistance += segmentLength;
}
}
else if (s.SegmentType == SegmentType.EllipticArc)
{
EllipticArcSegment ellipArc = s as EllipticArcSegment;
MapPoint startPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z, layerSpatRef));
MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z, layerSpatRef));
double radius = Math.Sqrt((ellipArc.CenterPoint.X - startPt.X) * (ellipArc.CenterPoint.X - startPt.X) + (ellipArc.CenterPoint.Y - startPt.Y) * (ellipArc.CenterPoint.Y - startPt.Y));
double angle = ellipArc.CentralAngle;
MapPoint centerPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(ellipArc.CenterPoint.X, ellipArc.CenterPoint.Y, (s.StartPoint.Z + s.EndPoint.Z) / 2, layerSpatRef));
//add start of path to points collection
if (num_iterations == 0)
{
pointsForKeyframes.Add(startPt);
}
if (num_iterations == segmentCount - 1 || segmentCount == 1)
{
pathEndPt = endPt; //store path end pt. This will be the last keyframe.
}
double distCoveredAlongSeg = Math.Abs(createKeyAtDist - skippedDistance); //we are accouunting for skipped distances from previous segments
if (distCoveredAlongSeg < segmentLength)
{
MapPoint keyPt = await CreatePointAlongArc(startPt, endPt, centerPt, angle * distCoveredAlongSeg / segmentLength, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
//add point to collection
pointsForKeyframes.Add(keyPt);
//skipped distance is used now, reset to zero
skippedDistance = 0;
//are more keyframes possible for this segment
bool moreKeysPossible = ((segmentLength - distCoveredAlongSeg) >= createKeyAtDist);
while (moreKeysPossible)
{
double keyAtDistAlongSeg = distCoveredAlongSeg + createKeyAtDist;
keyPt = await CreatePointAlongArc(startPt, endPt, centerPt, angle * keyAtDistAlongSeg / segmentLength, radius, layerSpatRef, ellipArc.IsMinor, ellipArc.IsCounterClockwise);
//add point to collection
pointsForKeyframes.Add(keyPt);
distCoveredAlongSeg += createKeyAtDist;
moreKeysPossible = ((segmentLength - distCoveredAlongSeg) > createKeyAtDist);
}
//if any segment length left then add to skipped distance
skippedDistance += (segmentLength - distCoveredAlongSeg);
}
else
{
//add this segment's length to skipped distance as no keyframe could be created along it
skippedDistance += segmentLength;
}
}
num_iterations++;
}
}
//now iterate over the points list and create keyframes
double timeSpanValue = accumulatedDuration;
TimeSpan keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
for (int i = 0; i < pointsForKeyframes.Count; i++)
{
MapPoint currentPt = pointsForKeyframes[i];
MapPoint nextPt = null;
if (i + 1 < pointsForKeyframes.Count)
{
nextPt = pointsForKeyframes[i + 1];
}
else
{
nextPt = pathEndPt;
}
timeSpanValue = i * keyEveryNSecond + accumulatedDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(currentPt, nextPt);
await CreateCameraKeyframe(mapView, currentPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
if (i == pointsForKeyframes.Count - 1 && skippedDistance > 0)
{
keyframeTimespan = TimeSpan.FromSeconds(TotalDuration + accumulatedDuration);
await CreateCameraKeyframe(mapView, pathEndPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
}
}
//Use this method if you want keyframes ONLY at line vertices. This is good if the line is highly densified.
//However, you will get sharp turns at corners because there is no attempt to smooth the animation
public static async Task CreateKeyframes_AtVertices(MapView mapView, SpatialReference layerSpatRef, ProjectionTransformation transformation,
CameraTrack cameraTrack, Polyline lineGeom, IEnumerator<ReadOnlySegmentCollection> segments,
int segmentCount, double pathLength)
{
double segmentLength = 0;
int num_iterations = 0;
segments.Reset();
//process each segment depending upon its type - straight line or arc
while (segments.MoveNext())
{
ReadOnlySegmentCollection seg = segments.Current;
double accumulatedDuration = mapView.Map.Animation.Duration.TotalSeconds + ((mapView.Map.Animation.Duration.TotalSeconds > 0) ? ANIMATION_APPEND_TIME : 0); // 0;
foreach (Segment s in seg)
{
segmentLength = Math.Sqrt((s.EndPoint.X - s.StartPoint.X) * (s.EndPoint.X - s.StartPoint.X) +
(s.EndPoint.Y - s.StartPoint.Y) * (s.EndPoint.Y - s.StartPoint.Y) +
(s.EndPoint.Z - s.StartPoint.Z) * (s.EndPoint.Z - s.StartPoint.Z));
double segmentDuration = (TotalDuration / pathLength) * segmentLength;
MapPoint startPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.StartPoint.X, s.StartPoint.Y, s.StartPoint.Z, layerSpatRef));
MapPoint endPt = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(s.EndPoint.X, s.EndPoint.Y, s.EndPoint.Z, layerSpatRef));
//create keyframe at start vertex of path in map space
double timeSpanValue = accumulatedDuration;
TimeSpan keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
SetPitchAndHeadingForLine(startPt, endPt);
await CreateCameraKeyframe(mapView, startPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
//Create a keyframe at end point of segment only for the end point of last segment
//Otherwise we will get duplicate keyframes at end of one segment and start of the next one
if (num_iterations == segmentCount - 1)
{
timeSpanValue = accumulatedDuration + segmentDuration;
keyframeTimespan = TimeSpan.FromSeconds(timeSpanValue);
if (SelectedCameraView == "Face target")
{
SetPitchAndHeadingForLine(endPt, TargetPoint);
}
await CreateCameraKeyframe(mapView, endPt, transformation, cameraTrack, keyframeTimespan, _keyframePitch, _keyframeHeading);
}
accumulatedDuration += segmentDuration;
num_iterations++;
}
}
}
private static async Task<MapPoint> CreatePointAlongSegment(MapPoint startPt, MapPoint endPt, double distanceFromStartPoint, SpatialReference spatRef)
{
System.Windows.Media.Media3D.Point3D fromPt = new System.Windows.Media.Media3D.Point3D(startPt.X, startPt.Y, startPt.Z);
System.Windows.Media.Media3D.Point3D toPt = new System.Windows.Media.Media3D.Point3D(endPt.X, endPt.Y, endPt.Z);
System.Windows.Media.Media3D.Vector3D lineVec = new System.Windows.Media.Media3D.Vector3D(toPt.X - fromPt.X, toPt.Y - fromPt.Y, toPt.Z - fromPt.Z);
lineVec.Normalize();
System.Windows.Media.Media3D.Point3D ptAlong = new System.Windows.Media.Media3D.Point3D(fromPt.X + distanceFromStartPoint * (lineVec.X),
fromPt.Y + distanceFromStartPoint * (lineVec.Y),
fromPt.Z + distanceFromStartPoint * (lineVec.Z));
MapPoint intermediateKeyframePoint = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(ptAlong.X, ptAlong.Y, ptAlong.Z, spatRef));
return intermediateKeyframePoint;
}
private static async Task<MapPoint> CreatePointAlongArc(MapPoint startPt, MapPoint endPt, MapPoint centerPt, double angle, double radius, SpatialReference spatRef, bool arcIsMinor, bool arcIsCounterClockwise)
{
System.Windows.Media.Media3D.Vector3D start = new System.Windows.Media.Media3D.Vector3D(startPt.X - centerPt.X, startPt.Y - centerPt.Y, startPt.Z - centerPt.Z);
System.Windows.Media.Media3D.Vector3D end = new System.Windows.Media.Media3D.Vector3D(endPt.X - centerPt.X, endPt.Y - centerPt.Y, endPt.Z - centerPt.Z);
System.Windows.Media.Media3D.Vector3D normalOfPlane = new System.Windows.Media.Media3D.Vector3D();
normalOfPlane = System.Windows.Media.Media3D.Vector3D.CrossProduct(start, end);
//Two ortho vectors: orthoVec and start
System.Windows.Media.Media3D.Vector3D orthoVec = new System.Windows.Media.Media3D.Vector3D();
orthoVec = System.Windows.Media.Media3D.Vector3D.CrossProduct(normalOfPlane, start);
//If this is not done then half of the keyframes for S-shaped curve are not on the curve
if (arcIsMinor && !arcIsCounterClockwise)
orthoVec.Negate();
//Normalize
start.Normalize();
orthoVec.Normalize();
System.Windows.Media.Media3D.Vector3D ptAlong = new System.Windows.Media.Media3D.Vector3D();
ptAlong = radius * Math.Cos(angle) * start + radius * Math.Sin(angle) * orthoVec;
MapPoint intermediateKeyframePoint = await QueuedTask.Run(() => MapPointBuilder.CreateMapPoint(ptAlong.X + centerPt.X, ptAlong.Y + centerPt.Y, ptAlong.Z + centerPt.Z, spatRef));
return intermediateKeyframePoint;
}
private static async Task CreateCameraKeyframe(MapView mapView, MapPoint orig_cameraPoint, ProjectionTransformation transformation,
CameraTrack cameraTrack, TimeSpan currentTimespanValue, double pitch, double heading, bool ignoreRotation = false, bool ignoreTranslation = false)
{
await QueuedTask.Run(() =>
{
Keyframe keyFrame = null;
MapPoint projected_cameraPoint = (MapPoint)GeometryEngine.Instance.ProjectEx(orig_cameraPoint, transformation);
if (mapView.ViewingMode == MapViewingMode.Map)
{
var camera = new Camera(projected_cameraPoint.X, projected_cameraPoint.Y, CameraZOffset, heading, null, CameraViewpoint.LookAt);
keyFrame = cameraTrack.CreateKeyframe(camera, currentTimespanValue, AnimationTransition.FixedArc, .5);
}
else
{
var camera = new Camera(projected_cameraPoint.X, projected_cameraPoint.Y, (projected_cameraPoint.Z + CameraZOffset), pitch, heading, null, CameraViewpoint.LookAt);
keyFrame = cameraTrack.CreateKeyframe(camera, currentTimespanValue, AnimationTransition.FixedArc, .5);
}
if (ignoreRotation)
{
CameraKeyframe camKey = keyFrame as CameraKeyframe;
camKey.HeadingTransition = AnimationTransition.None;
camKey.RollTransition = AnimationTransition.None;
camKey.PitchTransition = AnimationTransition.None;
}
if (ignoreTranslation)
{
CameraKeyframe camKey = keyFrame as CameraKeyframe;
camKey.XTransition = AnimationTransition.None;
camKey.YTransition = AnimationTransition.None;
camKey.ZTransition = AnimationTransition.None;
}
});
}
private static async void SetPitchAndHeadingForLine(MapPoint startPt, MapPoint endPt)
{
if (SelectedCameraView == "Top down")
{
_keyframeHeading = CalculateHeading(startPt, endPt);
_keyframePitch = -90;
}
else if (SelectedCameraView == "Top down - face north")
{
_keyframeHeading = 0;
_keyframePitch = -90;
}
else if (SelectedCameraView == "Custom pitch")
{
_keyframeHeading = CalculateHeading(startPt, endPt);
_keyframePitch = CustomPitch;
}
else if (SelectedCameraView == "View along" || SelectedCameraView == "Face backward")
{
_keyframeHeading = CalculateHeading(startPt, endPt);
_keyframePitch = CalculatePitch(startPt, endPt);
}
else if (SelectedCameraView == "Face target")
{
_keyframeHeading = CalculateHeading(startPt, TargetPoint);
_keyframePitch = CalculatePitch(startPt, TargetPoint);
}
}
private static double CalculateHeading(MapPoint startPt, MapPoint endPt)
{
double dx, dy, dz, angle, heading;
if (SelectedCameraView == "Top down - face north")
{
heading = 0;
}
else
{
dx = endPt.X - startPt.X;
dy = endPt.Y - startPt.Y;
//need to apply z-conversion factor to target Z
dz = (SelectedCameraView == "Face target") ? endPt.Z * Z_CONVERSION_FACTOR - startPt.Z : endPt.Z - startPt.Z;
angle = Math.Atan2(dy, dx);
heading = 180 + (90 + angle * 180 / Math.PI);
if (SelectedCameraView == "Face backward") { heading = heading - 180; }
}
return heading;
}
private static double CalculatePitch(MapPoint startPt, MapPoint endPt)
{
double dx, dy, dz, pitchForLookingAtTarget;
dx = startPt.X - endPt.X;
dy = startPt.Y - endPt.Y;
//dz = startPt.Z - endPt.Z;
//need to apply z-conversion factor to target Z
dz = (SelectedCameraView == "Face target") ? startPt.Z - endPt.Z * Z_CONVERSION_FACTOR : startPt.Z - endPt.Z;
//try dividing by 0.00017 unit conversion factor if units = degree
SpatialReference spatRef = startPt.SpatialReference;
if (spatRef.Unit.Name == "Degree")
{
dx = dx * 111000;
dy = dy * 111000;
}
double test = dz / Math.Sqrt(dx * dx + dy * dy + dz * dz);
pitchForLookingAtTarget = -(90 - Math.Acos(test) * 180 / Math.PI);
return pitchForLookingAtTarget;
}
#endregion
}
}
| |
namespace android.net
{
[global::MonoJavaBridge.JavaClass()]
public partial class ConnectivityManager : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected ConnectivityManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public static bool isNetworkTypeValid(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.net.ConnectivityManager._m0.native == global::System.IntPtr.Zero)
global::android.net.ConnectivityManager._m0 = @__env.GetStaticMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "isNetworkTypeValid", "(I)Z");
return @__env.CallStaticBooleanMethod(android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual void setNetworkPreference(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.net.ConnectivityManager.staticClass, "setNetworkPreference", "(I)V", ref global::android.net.ConnectivityManager._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new int NetworkPreference
{
get
{
return getNetworkPreference();
}
set
{
setNetworkPreference(value);
}
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual int getNetworkPreference()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.net.ConnectivityManager.staticClass, "getNetworkPreference", "()I", ref global::android.net.ConnectivityManager._m2);
}
public new global::android.net.NetworkInfo ActiveNetworkInfo
{
get
{
return getActiveNetworkInfo();
}
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual global::android.net.NetworkInfo getActiveNetworkInfo()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.net.ConnectivityManager.staticClass, "getActiveNetworkInfo", "()Landroid/net/NetworkInfo;", ref global::android.net.ConnectivityManager._m3) as android.net.NetworkInfo;
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual global::android.net.NetworkInfo getNetworkInfo(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.net.ConnectivityManager.staticClass, "getNetworkInfo", "(I)Landroid/net/NetworkInfo;", ref global::android.net.ConnectivityManager._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.net.NetworkInfo;
}
public new global::android.net.NetworkInfo[] AllNetworkInfo
{
get
{
return getAllNetworkInfo();
}
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual global::android.net.NetworkInfo[] getAllNetworkInfo()
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<android.net.NetworkInfo>(this, global::android.net.ConnectivityManager.staticClass, "getAllNetworkInfo", "()[Landroid/net/NetworkInfo;", ref global::android.net.ConnectivityManager._m5) as android.net.NetworkInfo[];
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual int startUsingNetworkFeature(int arg0, java.lang.String arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.net.ConnectivityManager.staticClass, "startUsingNetworkFeature", "(ILjava/lang/String;)I", ref global::android.net.ConnectivityManager._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual int stopUsingNetworkFeature(int arg0, java.lang.String arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.net.ConnectivityManager.staticClass, "stopUsingNetworkFeature", "(ILjava/lang/String;)I", ref global::android.net.ConnectivityManager._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual bool requestRouteToHost(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.net.ConnectivityManager.staticClass, "requestRouteToHost", "(II)Z", ref global::android.net.ConnectivityManager._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public new bool BackgroundDataSetting
{
get
{
return getBackgroundDataSetting();
}
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual bool getBackgroundDataSetting()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.net.ConnectivityManager.staticClass, "getBackgroundDataSetting", "()Z", ref global::android.net.ConnectivityManager._m9);
}
public static global::java.lang.String CONNECTIVITY_ACTION
{
get
{
return "android.net.conn.CONNECTIVITY_CHANGE";
}
}
public static global::java.lang.String EXTRA_NETWORK_INFO
{
get
{
return "networkInfo";
}
}
public static global::java.lang.String EXTRA_IS_FAILOVER
{
get
{
return "isFailover";
}
}
public static global::java.lang.String EXTRA_OTHER_NETWORK_INFO
{
get
{
return "otherNetwork";
}
}
public static global::java.lang.String EXTRA_NO_CONNECTIVITY
{
get
{
return "noConnectivity";
}
}
public static global::java.lang.String EXTRA_REASON
{
get
{
return "reason";
}
}
public static global::java.lang.String EXTRA_EXTRA_INFO
{
get
{
return "extraInfo";
}
}
public static global::java.lang.String ACTION_BACKGROUND_DATA_SETTING_CHANGED
{
get
{
return "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED";
}
}
public static int TYPE_MOBILE
{
get
{
return 0;
}
}
public static int TYPE_WIFI
{
get
{
return 1;
}
}
public static int TYPE_MOBILE_MMS
{
get
{
return 2;
}
}
public static int TYPE_MOBILE_SUPL
{
get
{
return 3;
}
}
public static int TYPE_MOBILE_DUN
{
get
{
return 4;
}
}
public static int TYPE_MOBILE_HIPRI
{
get
{
return 5;
}
}
public static int TYPE_WIMAX
{
get
{
return 6;
}
}
public static int DEFAULT_NETWORK_PREFERENCE
{
get
{
return 1;
}
}
static ConnectivityManager()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.net.ConnectivityManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/ConnectivityManager"));
}
}
}
| |
//
// 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 Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
namespace Microsoft.Azure.Management.Resources
{
public partial class ResourceManagementClient : ServiceClient<ResourceManagementClient>, IResourceManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IDeploymentOperationOperations _deploymentOperations;
/// <summary>
/// Operations for managing deployment operations.
/// </summary>
public virtual IDeploymentOperationOperations DeploymentOperations
{
get { return this._deploymentOperations; }
}
private IDeploymentOperations _deployments;
/// <summary>
/// Operations for managing deployments.
/// </summary>
public virtual IDeploymentOperations Deployments
{
get { return this._deployments; }
}
private IProviderOperations _providers;
/// <summary>
/// Operations for managing providers.
/// </summary>
public virtual IProviderOperations Providers
{
get { return this._providers; }
}
private IResourceGroupOperations _resourceGroups;
/// <summary>
/// Operations for managing resource groups.
/// </summary>
public virtual IResourceGroupOperations ResourceGroups
{
get { return this._resourceGroups; }
}
private IResourceOperations _resources;
/// <summary>
/// Operations for managing resources.
/// </summary>
public virtual IResourceOperations Resources
{
get { return this._resources; }
}
private ITagOperations _tags;
/// <summary>
/// Operations for managing tags.
/// </summary>
public virtual ITagOperations Tags
{
get { return this._tags; }
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
private ResourceManagementClient()
: base()
{
this._deploymentOperations = new DeploymentOperationOperations(this);
this._deployments = new DeploymentOperations(this);
this._providers = new ProviderOperations(this);
this._resourceGroups = new ResourceGroupOperations(this);
this._resources = new ResourceOperations(this);
this._tags = new TagOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private ResourceManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._deploymentOperations = new DeploymentOperationOperations(this);
this._deployments = new DeploymentOperations(this);
this._providers = new ProviderOperations(this);
this._resourceGroups = new ResourceGroupOperations(this);
this._resources = new ResourceOperations(this);
this._tags = new TagOperations(this);
this._apiVersion = "2014-04-01-preview";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the ResourceManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public ResourceManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// ResourceManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of ResourceManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<ResourceManagementClient> client)
{
base.Clone(client);
if (client is ResourceManagementClient)
{
ResourceManagementClient clonedClient = ((ResourceManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public async Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
{
// Validate
if (operationStatusLink == null)
{
throw new ArgumentNullException("operationStatusLink");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationStatusLink", operationStatusLink);
Tracing.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = operationStatusLink.Trim();
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-04-01-preview");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
LongRunningOperationResponse result = null;
result = new LongRunningOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (statusCode == HttpStatusCode.Conflict)
{
result.Status = OperationStatus.Failed;
}
if (statusCode == HttpStatusCode.OK)
{
result.Status = OperationStatus.Succeeded;
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/* 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 CanvassPositionEncoder
{
public const ushort BLOCK_LENGTH = 28;
public const ushort TEMPLATE_ID = 50;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private CanvassPositionEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public CanvassPositionEncoder()
{
_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 IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public CanvassPositionEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public CanvassPositionEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LogLeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LogLeadershipTermIdEncodingLength()
{
return 8;
}
public static long LogLeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LogLeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LogLeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public CanvassPositionEncoder LogLeadershipTermId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int LogPositionEncodingOffset()
{
return 8;
}
public static int LogPositionEncodingLength()
{
return 8;
}
public static long LogPositionNullValue()
{
return -9223372036854775808L;
}
public static long LogPositionMinValue()
{
return -9223372036854775807L;
}
public static long LogPositionMaxValue()
{
return 9223372036854775807L;
}
public CanvassPositionEncoder LogPosition(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int LeadershipTermIdEncodingOffset()
{
return 16;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public CanvassPositionEncoder LeadershipTermId(long value)
{
_buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public static int FollowerMemberIdEncodingOffset()
{
return 24;
}
public static int FollowerMemberIdEncodingLength()
{
return 4;
}
public static int FollowerMemberIdNullValue()
{
return -2147483648;
}
public static int FollowerMemberIdMinValue()
{
return -2147483647;
}
public static int FollowerMemberIdMaxValue()
{
return 2147483647;
}
public CanvassPositionEncoder FollowerMemberId(int value)
{
_buffer.PutInt(_offset + 24, value, ByteOrder.LittleEndian);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
CanvassPositionDecoder writer = new CanvassPositionDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
| |
using System.Collections.Immutable;
using System.Text.Json.Serialization;
using JetBrains.Annotations;
using JsonApiDotNetCore.AtomicOperations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Queries.Expressions;
using JsonApiDotNetCore.Queries.Internal;
using JsonApiDotNetCore.QueryStrings;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
using JsonApiDotNetCore.Resources.Internal;
using JsonApiDotNetCore.Serialization.Objects;
namespace JsonApiDotNetCore.Serialization.Response;
/// <inheritdoc />
[PublicAPI]
public class ResponseModelAdapter : IResponseModelAdapter
{
private static readonly CollectionConverter CollectionConverter = new();
private readonly IJsonApiRequest _request;
private readonly IJsonApiOptions _options;
private readonly ILinkBuilder _linkBuilder;
private readonly IMetaBuilder _metaBuilder;
private readonly IResourceDefinitionAccessor _resourceDefinitionAccessor;
private readonly IEvaluatedIncludeCache _evaluatedIncludeCache;
private readonly IRequestQueryStringAccessor _requestQueryStringAccessor;
private readonly ISparseFieldSetCache _sparseFieldSetCache;
// Ensures that at most one ResourceObject (and one tree node) is produced per resource instance.
private readonly Dictionary<IIdentifiable, ResourceObjectTreeNode> _resourceToTreeNodeCache = new(IdentifiableComparer.Instance);
public ResponseModelAdapter(IJsonApiRequest request, IJsonApiOptions options, ILinkBuilder linkBuilder, IMetaBuilder metaBuilder,
IResourceDefinitionAccessor resourceDefinitionAccessor, IEvaluatedIncludeCache evaluatedIncludeCache, ISparseFieldSetCache sparseFieldSetCache,
IRequestQueryStringAccessor requestQueryStringAccessor)
{
ArgumentGuard.NotNull(request, nameof(request));
ArgumentGuard.NotNull(options, nameof(options));
ArgumentGuard.NotNull(linkBuilder, nameof(linkBuilder));
ArgumentGuard.NotNull(metaBuilder, nameof(metaBuilder));
ArgumentGuard.NotNull(resourceDefinitionAccessor, nameof(resourceDefinitionAccessor));
ArgumentGuard.NotNull(evaluatedIncludeCache, nameof(evaluatedIncludeCache));
ArgumentGuard.NotNull(sparseFieldSetCache, nameof(sparseFieldSetCache));
ArgumentGuard.NotNull(requestQueryStringAccessor, nameof(requestQueryStringAccessor));
_request = request;
_options = options;
_linkBuilder = linkBuilder;
_metaBuilder = metaBuilder;
_resourceDefinitionAccessor = resourceDefinitionAccessor;
_evaluatedIncludeCache = evaluatedIncludeCache;
_sparseFieldSetCache = sparseFieldSetCache;
_requestQueryStringAccessor = requestQueryStringAccessor;
}
/// <inheritdoc />
public Document Convert(object? model)
{
_sparseFieldSetCache.Reset();
_resourceToTreeNodeCache.Clear();
var document = new Document();
IncludeExpression? include = _evaluatedIncludeCache.Get();
IImmutableSet<IncludeElementExpression> includeElements = include?.Elements ?? ImmutableHashSet<IncludeElementExpression>.Empty;
var rootNode = ResourceObjectTreeNode.CreateRoot();
if (model is IEnumerable<IIdentifiable> resources)
{
ResourceType resourceType = (_request.SecondaryResourceType ?? _request.PrimaryResourceType)!;
foreach (IIdentifiable resource in resources)
{
TraverseResource(resource, resourceType, _request.Kind, includeElements, rootNode, null);
}
PopulateRelationshipsInTree(rootNode, _request.Kind);
IEnumerable<ResourceObject> resourceObjects = rootNode.GetResponseData();
document.Data = new SingleOrManyData<ResourceObject>(resourceObjects);
}
else if (model is IIdentifiable resource)
{
ResourceType resourceType = (_request.SecondaryResourceType ?? _request.PrimaryResourceType)!;
TraverseResource(resource, resourceType, _request.Kind, includeElements, rootNode, null);
PopulateRelationshipsInTree(rootNode, _request.Kind);
ResourceObject resourceObject = rootNode.GetResponseData().Single();
document.Data = new SingleOrManyData<ResourceObject>(resourceObject);
}
else if (model == null)
{
document.Data = new SingleOrManyData<ResourceObject>(null);
}
else if (model is IEnumerable<OperationContainer?> operations)
{
using var _ = new RevertRequestStateOnDispose(_request, null);
document.Results = operations.Select(operation => ConvertOperation(operation, includeElements)).ToList();
}
else if (model is IEnumerable<ErrorObject> errorObjects)
{
document.Errors = errorObjects.ToArray();
}
else if (model is ErrorObject errorObject)
{
document.Errors = errorObject.AsArray();
}
else
{
throw new InvalidOperationException("Data being returned must be resources, operations, errors or null.");
}
document.JsonApi = GetApiObject();
document.Links = _linkBuilder.GetTopLevelLinks();
document.Meta = _metaBuilder.Build();
document.Included = GetIncluded(rootNode);
return document;
}
protected virtual AtomicResultObject ConvertOperation(OperationContainer? operation, IImmutableSet<IncludeElementExpression> includeElements)
{
ResourceObject? resourceObject = null;
if (operation != null)
{
_request.CopyFrom(operation.Request);
ResourceType resourceType = (operation.Request.SecondaryResourceType ?? operation.Request.PrimaryResourceType)!;
var rootNode = ResourceObjectTreeNode.CreateRoot();
TraverseResource(operation.Resource, resourceType, operation.Request.Kind, includeElements, rootNode, null);
PopulateRelationshipsInTree(rootNode, operation.Request.Kind);
resourceObject = rootNode.GetResponseData().Single();
_sparseFieldSetCache.Reset();
_resourceToTreeNodeCache.Clear();
}
return new AtomicResultObject
{
Data = resourceObject == null ? default : new SingleOrManyData<ResourceObject>(resourceObject)
};
}
private void TraverseResource(IIdentifiable resource, ResourceType resourceType, EndpointKind kind, IImmutableSet<IncludeElementExpression> includeElements,
ResourceObjectTreeNode parentTreeNode, RelationshipAttribute? parentRelationship)
{
ResourceObjectTreeNode treeNode = GetOrCreateTreeNode(resource, resourceType, kind);
if (parentRelationship != null)
{
parentTreeNode.AttachRelationshipChild(parentRelationship, treeNode);
}
else
{
parentTreeNode.AttachDirectChild(treeNode);
}
if (kind != EndpointKind.Relationship)
{
TraverseRelationships(resource, treeNode, includeElements, kind);
}
}
private ResourceObjectTreeNode GetOrCreateTreeNode(IIdentifiable resource, ResourceType resourceType, EndpointKind kind)
{
if (!_resourceToTreeNodeCache.TryGetValue(resource, out ResourceObjectTreeNode? treeNode))
{
ResourceObject resourceObject = ConvertResource(resource, resourceType, kind);
treeNode = new ResourceObjectTreeNode(resource, resourceType, resourceObject);
_resourceToTreeNodeCache.Add(resource, treeNode);
}
return treeNode;
}
protected virtual ResourceObject ConvertResource(IIdentifiable resource, ResourceType resourceType, EndpointKind kind)
{
bool isRelationship = kind == EndpointKind.Relationship;
if (!isRelationship)
{
_resourceDefinitionAccessor.OnSerialize(resource);
}
var resourceObject = new ResourceObject
{
Type = resourceType.PublicName,
Id = resource.StringId
};
if (!isRelationship)
{
IImmutableSet<ResourceFieldAttribute> fieldSet = _sparseFieldSetCache.GetSparseFieldSetForSerializer(resourceType);
resourceObject.Attributes = ConvertAttributes(resource, resourceType, fieldSet);
resourceObject.Links = _linkBuilder.GetResourceLinks(resourceType, resource);
resourceObject.Meta = _resourceDefinitionAccessor.GetMeta(resourceType, resource);
}
return resourceObject;
}
protected virtual IDictionary<string, object?>? ConvertAttributes(IIdentifiable resource, ResourceType resourceType,
IImmutableSet<ResourceFieldAttribute> fieldSet)
{
var attrMap = new Dictionary<string, object?>(resourceType.Attributes.Count);
foreach (AttrAttribute attr in resourceType.Attributes)
{
if (!fieldSet.Contains(attr) || attr.Property.Name == nameof(Identifiable<object>.Id))
{
continue;
}
object? value = attr.GetValue(resource);
if (_options.SerializerOptions.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingNull && value == null)
{
continue;
}
if (_options.SerializerOptions.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingDefault &&
Equals(value, RuntimeTypeConverter.GetDefaultValue(attr.Property.PropertyType)))
{
continue;
}
attrMap.Add(attr.PublicName, value);
}
return attrMap.Any() ? attrMap : null;
}
private void TraverseRelationships(IIdentifiable leftResource, ResourceObjectTreeNode leftTreeNode, IImmutableSet<IncludeElementExpression> includeElements,
EndpointKind kind)
{
foreach (IncludeElementExpression includeElement in includeElements)
{
TraverseRelationship(includeElement.Relationship, leftResource, leftTreeNode, includeElement, kind);
}
}
private void TraverseRelationship(RelationshipAttribute relationship, IIdentifiable leftResource, ResourceObjectTreeNode leftTreeNode,
IncludeElementExpression includeElement, EndpointKind kind)
{
object? rightValue = relationship.GetValue(leftResource);
ICollection<IIdentifiable> rightResources = CollectionConverter.ExtractResources(rightValue);
leftTreeNode.EnsureHasRelationship(relationship);
foreach (IIdentifiable rightResource in rightResources)
{
TraverseResource(rightResource, relationship.RightType, kind, includeElement.Children, leftTreeNode, relationship);
}
}
private void PopulateRelationshipsInTree(ResourceObjectTreeNode rootNode, EndpointKind kind)
{
if (kind != EndpointKind.Relationship)
{
foreach (ResourceObjectTreeNode treeNode in rootNode.GetUniqueNodes())
{
PopulateRelationshipsInResourceObject(treeNode);
}
}
}
private void PopulateRelationshipsInResourceObject(ResourceObjectTreeNode treeNode)
{
IImmutableSet<ResourceFieldAttribute> fieldSet = _sparseFieldSetCache.GetSparseFieldSetForSerializer(treeNode.ResourceType);
foreach (RelationshipAttribute relationship in treeNode.ResourceType.Relationships)
{
if (fieldSet.Contains(relationship))
{
PopulateRelationshipInResourceObject(treeNode, relationship);
}
}
}
private void PopulateRelationshipInResourceObject(ResourceObjectTreeNode treeNode, RelationshipAttribute relationship)
{
SingleOrManyData<ResourceIdentifierObject> data = GetRelationshipData(treeNode, relationship);
RelationshipLinks? links = _linkBuilder.GetRelationshipLinks(relationship, treeNode.Resource);
if (links != null || data.IsAssigned)
{
var relationshipObject = new RelationshipObject
{
Links = links,
Data = data
};
treeNode.ResourceObject.Relationships ??= new Dictionary<string, RelationshipObject?>();
treeNode.ResourceObject.Relationships.Add(relationship.PublicName, relationshipObject);
}
}
private static SingleOrManyData<ResourceIdentifierObject> GetRelationshipData(ResourceObjectTreeNode treeNode, RelationshipAttribute relationship)
{
ISet<ResourceObjectTreeNode>? rightNodes = treeNode.GetRightNodesInRelationship(relationship);
if (rightNodes != null)
{
IEnumerable<ResourceIdentifierObject> resourceIdentifierObjects = rightNodes.Select(rightNode => new ResourceIdentifierObject
{
Type = rightNode.ResourceType.PublicName,
Id = rightNode.ResourceObject.Id
});
return relationship is HasOneAttribute
? new SingleOrManyData<ResourceIdentifierObject>(resourceIdentifierObjects.SingleOrDefault())
: new SingleOrManyData<ResourceIdentifierObject>(resourceIdentifierObjects);
}
return default;
}
protected virtual JsonApiObject? GetApiObject()
{
if (!_options.IncludeJsonApiVersion)
{
return null;
}
var jsonApiObject = new JsonApiObject
{
Version = "1.1"
};
if (_request.Kind == EndpointKind.AtomicOperations)
{
jsonApiObject.Ext = new List<string>
{
"https://jsonapi.org/ext/atomic"
};
}
return jsonApiObject;
}
private IList<ResourceObject>? GetIncluded(ResourceObjectTreeNode rootNode)
{
IList<ResourceObject> resourceObjects = rootNode.GetResponseIncluded();
if (resourceObjects.Any())
{
return resourceObjects;
}
return _requestQueryStringAccessor.Query.ContainsKey("include") ? Array.Empty<ResourceObject>() : null;
}
}
| |
namespace Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs
{
/// <summary>
/// The Generic Field definition
/// </summary>
partial class GenericFieldDefinition
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GenericFieldDefinition));
this.label1 = new System.Windows.Forms.Label();
this.txtPrompt = new System.Windows.Forms.TextBox();
this.lblPrompt = new System.Windows.Forms.Label();
this.txtFieldName = new System.Windows.Forms.TextBox();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// btnOk
//
resources.ApplyResources(this.btnOk, "btnOk");
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
this.baseImageList.Images.SetKeyName(76, "");
this.baseImageList.Images.SetKeyName(77, "");
this.baseImageList.Images.SetKeyName(78, "");
this.baseImageList.Images.SetKeyName(79, "");
this.baseImageList.Images.SetKeyName(80, "");
this.baseImageList.Images.SetKeyName(81, "");
this.baseImageList.Images.SetKeyName(82, "");
this.baseImageList.Images.SetKeyName(83, "");
this.baseImageList.Images.SetKeyName(84, "");
this.baseImageList.Images.SetKeyName(85, "");
this.baseImageList.Images.SetKeyName(86, "");
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label1.Name = "label1";
//
// txtPrompt
//
resources.ApplyResources(this.txtPrompt, "txtPrompt");
this.txtPrompt.Name = "txtPrompt";
this.txtPrompt.DoubleClick += new System.EventHandler(this.txtPrompt_DoubleClick);
this.txtPrompt.Enter += new System.EventHandler(this.txtPrompt_Enter);
this.txtPrompt.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtPrompt_OnKeyDown);
this.txtPrompt.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtPrompt_OnKeyUp);
this.txtPrompt.Leave += new System.EventHandler(this.txtPrompt_Leave);
//
// lblPrompt
//
resources.ApplyResources(this.lblPrompt, "lblPrompt");
this.lblPrompt.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblPrompt.Name = "lblPrompt";
//
// txtFieldName
//
resources.ApplyResources(this.txtFieldName, "txtFieldName");
this.txtFieldName.Name = "txtFieldName";
this.txtFieldName.TextChanged += new System.EventHandler(this.txtFieldName_TextChanged);
this.txtFieldName.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtFieldName_KeyDown);
this.txtFieldName.Leave += new System.EventHandler(this.txtFieldName_Leave);
this.txtFieldName.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.txtFieldName_PreviewKeyDown);
//
// toolTip
//
this.toolTip.Active = false;
this.toolTip.AutomaticDelay = 50000;
this.toolTip.AutoPopDelay = 500000;
this.toolTip.InitialDelay = 1;
this.toolTip.ReshowDelay = 1;
this.toolTip.UseAnimation = false;
this.toolTip.UseFading = false;
//
// GenericFieldDefinition
//
this.AcceptButton = this.btnOk;
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.label1);
this.Controls.Add(this.txtPrompt);
this.Controls.Add(this.lblPrompt);
this.Controls.Add(this.txtFieldName);
this.Name = "GenericFieldDefinition";
this.Load += new System.EventHandler(this.GenericFieldDefinition_Load);
this.Controls.SetChildIndex(this.txtFieldName, 0);
this.Controls.SetChildIndex(this.lblPrompt, 0);
this.Controls.SetChildIndex(this.txtPrompt, 0);
this.Controls.SetChildIndex(this.label1, 0);
this.Controls.SetChildIndex(this.groupBox1, 0);
this.Controls.SetChildIndex(this.btnOk, 0);
this.Controls.SetChildIndex(this.btnCancel, 0);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// The field name label
/// </summary>
protected System.Windows.Forms.Label label1;
/// <summary>
/// The prompt textbox
/// </summary>
protected System.Windows.Forms.TextBox txtPrompt;
/// <summary>
/// The prompt label
/// </summary>
protected System.Windows.Forms.Label lblPrompt;
/// <summary>
/// The field name textbox
/// </summary>
protected System.Windows.Forms.TextBox txtFieldName;
private System.Windows.Forms.ToolTip toolTip;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
// The parts of a workspace that deal with open documents
public abstract partial class Workspace
{
// open documents
private readonly Dictionary<ProjectId, ISet<DocumentId>> _projectToOpenDocumentsMap = new Dictionary<ProjectId, ISet<DocumentId>>();
// text buffer maps
private readonly Dictionary<SourceTextContainer, DocumentId> _bufferToDocumentInCurrentContextMap = new Dictionary<SourceTextContainer, DocumentId>();
private readonly Dictionary<DocumentId, TextTracker> _textTrackers = new Dictionary<DocumentId, TextTracker>();
/// <summary>
/// True if this workspace supports manually opening and closing documents.
/// </summary>
public virtual bool CanOpenDocuments
{
get { return false; }
}
/// <summary>
/// True if this workspace supports manually changing the active context document of a text buffer.
/// </summary>
internal virtual bool CanChangeActiveContextDocument
{
get { return false; }
}
private static void RemoveIfEmpty<TKey, TValue>(IDictionary<TKey, ISet<TValue>> dictionary, TKey key)
{
if (dictionary.TryGetValue(key, out var values))
{
if (values.Count == 0)
{
dictionary.Remove(key);
}
}
}
private void ClearOpenDocuments()
{
List<DocumentId> docIds;
using (_stateLock.DisposableWait())
{
docIds = _projectToOpenDocumentsMap.Values.SelectMany(x => x).ToList();
}
foreach (var docId in docIds)
{
this.ClearOpenDocument(docId, isSolutionClosing: true);
}
}
private void ClearOpenDocuments(ProjectId projectId)
{
ISet<DocumentId> openDocs;
using (_stateLock.DisposableWait())
{
_projectToOpenDocumentsMap.TryGetValue(projectId, out openDocs);
}
if (openDocs != null)
{
// ClearOpenDocument will remove the document from the original set.
var copyOfOpenDocs = openDocs.ToList();
foreach (var docId in copyOfOpenDocs)
{
this.ClearOpenDocument(docId);
}
}
}
protected void ClearOpenDocument(DocumentId documentId, bool isSolutionClosing = false)
{
DocumentId currentContextDocumentId;
using (_stateLock.DisposableWait())
{
currentContextDocumentId = this.ClearOpenDocument_NoLock(documentId);
}
// If the solution is closing, then setting the updated document context can fail
// if the host documents are already closed.
if (!isSolutionClosing && this.CanChangeActiveContextDocument && currentContextDocumentId != null)
{
SetDocumentContext(currentContextDocumentId);
}
}
/// <returns>The DocumentId of the current context document for the buffer that was
/// previously attached to the given documentId, if any</returns>
private DocumentId ClearOpenDocument_NoLock(DocumentId documentId)
{
_stateLock.AssertHasLock();
if (_projectToOpenDocumentsMap.TryGetValue(documentId.ProjectId, out var openDocIds) && openDocIds != null)
{
openDocIds.Remove(documentId);
}
RemoveIfEmpty(_projectToOpenDocumentsMap, documentId.ProjectId);
// Stop tracking the buffer or update the documentId associated with the buffer.
if (_textTrackers.TryGetValue(documentId, out var tracker))
{
tracker.Disconnect();
_textTrackers.Remove(documentId);
var currentContextDocumentId = UpdateCurrentContextMapping_NoLock(tracker.TextContainer, documentId);
if (currentContextDocumentId != null)
{
return currentContextDocumentId;
}
else
{
// No documentIds are attached to this buffer, so stop tracking it.
this.UnregisterText(tracker.TextContainer);
}
}
return null;
}
/// <summary>
/// Open the specified document in the host environment.
/// </summary>
public virtual void OpenDocument(DocumentId documentId, bool activate = true)
{
this.CheckCanOpenDocuments();
}
/// <summary>
/// Close the specified document in the host environment.
/// </summary>
public virtual void CloseDocument(DocumentId documentId)
{
this.CheckCanOpenDocuments();
}
/// <summary>
/// Open the specified additional document in the host environment.
/// </summary>
public virtual void OpenAdditionalDocument(DocumentId documentId, bool activate = true)
{
this.CheckCanOpenDocuments();
}
/// <summary>
/// Close the specified additional document in the host environment.
/// </summary>
public virtual void CloseAdditionalDocument(DocumentId documentId)
{
this.CheckCanOpenDocuments();
}
protected void CheckCanOpenDocuments()
{
if (!this.CanOpenDocuments)
{
throw new NotSupportedException(WorkspacesResources.This_workspace_does_not_support_opening_and_closing_documents);
}
}
protected void CheckProjectDoesNotContainOpenDocuments(ProjectId projectId)
{
if (ProjectHasOpenDocuments(projectId))
{
throw new ArgumentException(string.Format(WorkspacesResources._0_still_contains_open_documents, this.GetProjectName(projectId)));
}
}
private bool ProjectHasOpenDocuments(ProjectId projectId)
{
using (_stateLock.DisposableWait())
{
return _projectToOpenDocumentsMap.ContainsKey(projectId);
}
}
/// <summary>
/// Determines if the document is currently open in the host environment.
/// </summary>
public virtual bool IsDocumentOpen(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
var openDocuments = this.GetProjectOpenDocuments_NoLock(documentId.ProjectId);
return openDocuments != null && openDocuments.Contains(documentId);
}
}
/// <summary>
/// Gets a list of the currently opened documents.
/// </summary>
public virtual IEnumerable<DocumentId> GetOpenDocumentIds(ProjectId projectId = null)
{
using (_stateLock.DisposableWait())
{
if (_projectToOpenDocumentsMap.Count == 0)
{
return SpecializedCollections.EmptyEnumerable<DocumentId>();
}
if (projectId != null)
{
if (_projectToOpenDocumentsMap.TryGetValue(projectId, out var documentIds))
{
return documentIds;
}
return SpecializedCollections.EmptyEnumerable<DocumentId>();
}
return _projectToOpenDocumentsMap.SelectMany(kvp => kvp.Value).ToImmutableArray();
}
}
/// <summary>
/// Gets the ids for documents associated with a text container.
/// Documents are normally associated with a text container when the documents are opened.
/// </summary>
public virtual IEnumerable<DocumentId> GetRelatedDocumentIds(SourceTextContainer container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
using (_stateLock.DisposableWait())
{
return GetRelatedDocumentIds_NoLock(container);
}
}
private ImmutableArray<DocumentId> GetRelatedDocumentIds_NoLock(SourceTextContainer container)
{
if (!_bufferToDocumentInCurrentContextMap.TryGetValue(container, out var documentId))
{
// it is not an opened file
return ImmutableArray<DocumentId>.Empty;
}
return this.CurrentSolution.GetRelatedDocumentIds(documentId);
}
/// <summary>
/// Gets the id for the document associated with the given text container in its current context.
/// Documents are normally associated with a text container when the documents are opened.
/// </summary>
public virtual DocumentId GetDocumentIdInCurrentContext(SourceTextContainer container)
{
if (container == null)
{
throw new ArgumentNullException(nameof(container));
}
using (_stateLock.DisposableWait())
{
return GetDocumentIdInCurrentContext_NoLock(container);
}
}
/// <summary>
/// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that
/// is in the current context. If the <see cref="DocumentId"/> is currently closed, then
/// it is returned directly. If it is open, then this returns the same result that
/// <see cref="GetDocumentIdInCurrentContext(SourceTextContainer)"/> would return for the
/// <see cref="SourceTextContainer"/>. Hosts can override this method to provide more
/// customized behaviors (e.g. special handling of documents in Shared Projects).
/// </summary>
internal virtual DocumentId GetDocumentIdInCurrentContext(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
using (_stateLock.DisposableWait())
{
var container = GetOpenDocumentSourceTextContainer_NoLock(documentId);
return container != null ? GetDocumentIdInCurrentContext_NoLock(container) : documentId;
}
}
private SourceTextContainer GetOpenDocumentSourceTextContainer_NoLock(DocumentId documentId)
{
SourceTextContainer container;
var documentIds = this.CurrentSolution.GetRelatedDocumentIds(documentId);
container = _bufferToDocumentInCurrentContextMap.Where(kvp => documentIds.Contains(kvp.Value)).Select(kvp => kvp.Key).FirstOrDefault();
return container;
}
private DocumentId GetDocumentIdInCurrentContext_NoLock(SourceTextContainer container)
{
bool foundValue = _bufferToDocumentInCurrentContextMap.TryGetValue(container, out var docId);
if (foundValue)
{
return docId;
}
else
{
return null;
}
}
/// <summary>
///
/// </summary>
internal virtual void SetDocumentContext(DocumentId documentId)
{
throw new NotSupportedException();
}
/// <summary>
///
/// </summary>
protected void OnDocumentContextUpdated(DocumentId documentId)
{
// TODO: remove linear search
SourceTextContainer container = null;
using (_stateLock.DisposableWait())
{
container = GetOpenDocumentSourceTextContainer_NoLock(documentId);
}
if (container != null)
{
OnDocumentContextUpdated(documentId, container);
}
}
/// <summary>
///
/// </summary>
internal void OnDocumentContextUpdated(DocumentId documentId, SourceTextContainer container)
{
using (_serializationLock.DisposableWait())
{
DocumentId oldActiveContextDocumentId;
using (_stateLock.DisposableWait())
{
oldActiveContextDocumentId = _bufferToDocumentInCurrentContextMap[container];
_bufferToDocumentInCurrentContextMap[container] = documentId;
}
// fire and forget
this.RaiseDocumentActiveContextChangedEventAsync(container, oldActiveContextDocumentId: oldActiveContextDocumentId, newActiveContextDocumentId: documentId);
}
}
protected void CheckDocumentIsClosed(DocumentId documentId)
{
if (this.IsDocumentOpen(documentId))
{
throw new ArgumentException(
string.Format(WorkspacesResources._0_is_still_open,
this.GetDocumentName(documentId)));
}
}
protected void CheckDocumentIsOpen(DocumentId documentId)
{
if (!this.IsDocumentOpen(documentId))
{
throw new ArgumentException(string.Format(
WorkspacesResources._0_is_not_open,
this.GetDocumentName(documentId)));
}
}
private ISet<DocumentId> GetProjectOpenDocuments_NoLock(ProjectId project)
{
_stateLock.AssertHasLock();
_projectToOpenDocumentsMap.TryGetValue(project, out var openDocs);
return openDocs;
}
protected internal void OnDocumentOpened(
DocumentId documentId, SourceTextContainer textContainer,
bool isCurrentContext = true)
{
CheckDocumentIsInCurrentSolution(documentId);
CheckDocumentIsClosed(documentId);
using (_serializationLock.DisposableWait())
{
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetDocument(documentId);
var oldDocumentState = oldDocument.State;
AddToOpenDocumentMap(documentId);
var newText = textContainer.CurrentText;
Solution currentSolution;
if (oldDocument.TryGetText(out var oldText) &&
oldDocument.TryGetTextVersion(out var version))
{
// Optimize the case where we've already got the previous text and version.
var newTextAndVersion = GetProperTextAndVersion(oldText, newText, version, oldDocumentState.FilePath);
// keep open document text alive by using PreserveIdentity
currentSolution = oldSolution.WithDocumentText(documentId, newTextAndVersion, PreservationMode.PreserveIdentity);
}
else
{
// We don't have the old text or version. And we don't want to retrieve them
// just yet (as that would cause blocking in this synchronous method). So just
// make a simple loader to do that for us later when requested.
//
// keep open document text alive by using PreserveIdentity
//
// Note: we pass along the newText here so that clients can easily get the text
// of an opened document just by calling TryGetText without any blocking.
currentSolution = oldSolution.WithDocumentTextLoader(documentId,
new ReuseVersionLoader((DocumentState)oldDocument.State, newText), newText, PreservationMode.PreserveIdentity);
}
var newSolution = this.SetCurrentSolution(currentSolution);
SignupForTextChanges(documentId, textContainer, isCurrentContext, (w, id, text, mode) => w.OnDocumentTextChanged(id, text, mode));
var newDoc = newSolution.GetDocument(documentId);
this.OnDocumentTextChanged(newDoc);
// Fire and forget that the workspace is changing.
RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId);
this.RaiseDocumentOpenedEventAsync(newDoc);
}
this.RegisterText(textContainer);
}
private class ReuseVersionLoader : TextLoader
{
// Capture DocumentState instead of Document so that we don't hold onto the old solution.
private readonly DocumentState _oldDocumentState;
private readonly SourceText _newText;
public ReuseVersionLoader(DocumentState oldDocumentState, SourceText newText)
{
_oldDocumentState = oldDocumentState;
_newText = newText;
}
public override async Task<TextAndVersion> LoadTextAndVersionAsync(
Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
var oldText = await _oldDocumentState.GetTextAsync(cancellationToken).ConfigureAwait(false);
var version = await _oldDocumentState.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
return GetProperTextAndVersion(oldText, _newText, version, _oldDocumentState.FilePath);
}
internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
{
var oldText = _oldDocumentState.GetTextSynchronously(cancellationToken);
var version = _oldDocumentState.GetVersionSynchronously(cancellationToken);
return GetProperTextAndVersion(oldText, _newText, version, _oldDocumentState.FilePath);
}
}
private static TextAndVersion GetProperTextAndVersion(SourceText oldText, SourceText newText, VersionStamp version, string filePath)
{
// if the supplied text is the same as the previous text, then also use same version
// otherwise use new version
return oldText.ContentEquals(newText)
? TextAndVersion.Create(newText, version, filePath)
: TextAndVersion.Create(newText, version.GetNewerVersion(), filePath);
}
private void SignupForTextChanges(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext, Action<Workspace, DocumentId, SourceText, PreservationMode> onChangedHandler)
{
var tracker = new TextTracker(this, documentId, textContainer, onChangedHandler);
_textTrackers.Add(documentId, tracker);
this.UpdateCurrentContextMapping_NoLock(textContainer, documentId, isCurrentContext);
tracker.Connect();
}
private void AddToOpenDocumentMap(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
var openDocuments = GetProjectOpenDocuments_NoLock(documentId.ProjectId);
if (openDocuments != null)
{
openDocuments.Add(documentId);
}
else
{
_projectToOpenDocumentsMap.Add(documentId.ProjectId, new HashSet<DocumentId> { documentId });
}
}
}
protected internal void OnAdditionalDocumentOpened(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true)
{
CheckAdditionalDocumentIsInCurrentSolution(documentId);
CheckDocumentIsClosed(documentId);
using (_serializationLock.DisposableWait())
{
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetAdditionalDocument(documentId);
var oldText = oldDocument.GetTextAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
// keep open document text alive by using PreserveIdentity
var newText = textContainer.CurrentText;
Solution currentSolution;
if (oldText == newText || oldText.ContentEquals(newText))
{
// if the supplied text is the same as the previous text, then also use same version
var version = oldDocument.GetTextVersionAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
var newTextAndVersion = TextAndVersion.Create(newText, version, oldDocument.FilePath);
currentSolution = oldSolution.WithAdditionalDocumentText(documentId, newTextAndVersion, PreservationMode.PreserveIdentity);
}
else
{
currentSolution = oldSolution.WithAdditionalDocumentText(documentId, newText, PreservationMode.PreserveIdentity);
}
var newSolution = this.SetCurrentSolution(currentSolution);
SignupForTextChanges(documentId, textContainer, isCurrentContext, (w, id, text, mode) => w.OnAdditionalDocumentTextChanged(id, text, mode));
// Fire and forget.
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.AdditionalDocumentChanged, oldSolution, newSolution, documentId: documentId);
}
this.RegisterText(textContainer);
}
protected internal void OnDocumentClosed(DocumentId documentId, TextLoader reloader, bool updateActiveContext = false)
{
this.CheckDocumentIsInCurrentSolution(documentId);
this.CheckDocumentIsOpen(documentId);
// When one file from a set of linked or shared documents is closed, we first update
// our data structures and then call SetDocumentContext to tell the project system
// what the new active context is. This can cause reentrancy, so we call
// SetDocumentContext after releasing the serializationLock.
DocumentId currentContextDocumentId;
using (_serializationLock.DisposableWait())
{
// forget any open document info
currentContextDocumentId = ForgetAnyOpenDocumentInfo(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetDocument(documentId);
this.OnDocumentClosing(documentId);
var newSolution = oldSolution.WithDocumentTextLoader(documentId, reloader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
var newDoc = newSolution.GetDocument(documentId);
this.OnDocumentTextChanged(newDoc);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this
this.RaiseDocumentClosedEventAsync(newDoc); // don't wait for this
}
if (updateActiveContext && currentContextDocumentId != null && this.CanChangeActiveContextDocument)
{
// Closing this document did not result in the buffer closing, so some
// document is now the current context of that buffer. Fire the appropriate
// events to set that document as the current context of that buffer.
SetDocumentContext(currentContextDocumentId);
}
}
private DocumentId ForgetAnyOpenDocumentInfo(DocumentId documentId)
{
using (_stateLock.DisposableWait())
{
return this.ClearOpenDocument_NoLock(documentId);
}
}
protected internal void OnAdditionalDocumentClosed(DocumentId documentId, TextLoader reloader)
{
this.CheckAdditionalDocumentIsInCurrentSolution(documentId);
using (_serializationLock.DisposableWait())
{
// forget any open document info
ForgetAnyOpenDocumentInfo(documentId);
var oldSolution = this.CurrentSolution;
var oldDocument = oldSolution.GetAdditionalDocument(documentId);
var newSolution = oldSolution.WithAdditionalDocumentTextLoader(documentId, reloader, PreservationMode.PreserveValue);
newSolution = this.SetCurrentSolution(newSolution);
this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.AdditionalDocumentChanged, oldSolution, newSolution, documentId: documentId); // don't wait for this
}
}
private void UpdateCurrentContextMapping_NoLock(SourceTextContainer textContainer, DocumentId id, bool isCurrentContext)
{
if (isCurrentContext || !_bufferToDocumentInCurrentContextMap.ContainsKey(textContainer))
{
_bufferToDocumentInCurrentContextMap[textContainer] = id;
}
}
/// <returns>The DocumentId of the current context document attached to the textContainer, if any.</returns>
private DocumentId UpdateCurrentContextMapping_NoLock(SourceTextContainer textContainer, DocumentId id)
{
var documentIds = this.CurrentSolution.GetRelatedDocumentIds(id);
if (documentIds.Length == 0)
{
// no related document. remove map and return no context
_bufferToDocumentInCurrentContextMap.Remove(textContainer);
return null;
}
if (documentIds.Length == 1 && documentIds[0] == id)
{
// only related document is myself. remove map and return no context
_bufferToDocumentInCurrentContextMap.Remove(textContainer);
return null;
}
if (documentIds[0] != id)
{
// there are related documents, set first one as new context.
_bufferToDocumentInCurrentContextMap[textContainer] = documentIds[0];
return documentIds[0];
}
// there are multiple related documents, and first one is myself. return next one.
_bufferToDocumentInCurrentContextMap[textContainer] = documentIds[1];
return documentIds[1];
}
private SourceText GetOpenDocumentText(Solution solution, DocumentId documentId)
{
CheckDocumentIsOpen(documentId);
var doc = solution.GetDocument(documentId);
// text should always be preserved, so TryGetText will succeed.
doc.TryGetText(out var text);
return text;
}
/// <summary>
/// This method is called during OnSolutionReload. Override this method if you want to manipulate
/// the reloaded solution.
/// </summary>
protected virtual Solution AdjustReloadedSolution(Solution oldSolution, Solution reloadedSolution)
{
var newSolution = reloadedSolution;
// keep open documents using same text
foreach (var docId in this.GetOpenDocumentIds())
{
if (newSolution.ContainsDocument(docId))
{
newSolution = newSolution.WithDocumentText(docId, this.GetOpenDocumentText(oldSolution, docId), PreservationMode.PreserveIdentity);
}
}
return newSolution;
}
protected virtual Project AdjustReloadedProject(Project oldProject, Project reloadedProject)
{
var oldSolution = oldProject.Solution;
var newSolution = reloadedProject.Solution;
// keep open documents open using same text
foreach (var docId in this.GetOpenDocumentIds(oldProject.Id))
{
if (newSolution.ContainsDocument(docId))
{
newSolution = newSolution.WithDocumentText(docId, this.GetOpenDocumentText(oldSolution, docId), PreservationMode.PreserveIdentity);
}
}
return newSolution.GetProject(oldProject.Id);
}
}
}
| |
namespace android.os
{
[global::MonoJavaBridge.JavaClass()]
public partial class Environment : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Environment(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
public static global::java.io.File RootDirectory
{
get
{
return getRootDirectory();
}
}
private static global::MonoJavaBridge.MethodId _m0;
public static global::java.io.File getRootDirectory()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Environment._m0.native == global::System.IntPtr.Zero)
global::android.os.Environment._m0 = @__env.GetStaticMethodIDNoThrow(global::android.os.Environment.staticClass, "getRootDirectory", "()Ljava/io/File;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.os.Environment.staticClass, global::android.os.Environment._m0)) as java.io.File;
}
public static global::java.io.File DataDirectory
{
get
{
return getDataDirectory();
}
}
private static global::MonoJavaBridge.MethodId _m1;
public static global::java.io.File getDataDirectory()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Environment._m1.native == global::System.IntPtr.Zero)
global::android.os.Environment._m1 = @__env.GetStaticMethodIDNoThrow(global::android.os.Environment.staticClass, "getDataDirectory", "()Ljava/io/File;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.os.Environment.staticClass, global::android.os.Environment._m1)) as java.io.File;
}
public static global::java.io.File ExternalStorageDirectory
{
get
{
return getExternalStorageDirectory();
}
}
private static global::MonoJavaBridge.MethodId _m2;
public static global::java.io.File getExternalStorageDirectory()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Environment._m2.native == global::System.IntPtr.Zero)
global::android.os.Environment._m2 = @__env.GetStaticMethodIDNoThrow(global::android.os.Environment.staticClass, "getExternalStorageDirectory", "()Ljava/io/File;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.os.Environment.staticClass, global::android.os.Environment._m2)) as java.io.File;
}
private static global::MonoJavaBridge.MethodId _m3;
public static global::java.io.File getExternalStoragePublicDirectory(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Environment._m3.native == global::System.IntPtr.Zero)
global::android.os.Environment._m3 = @__env.GetStaticMethodIDNoThrow(global::android.os.Environment.staticClass, "getExternalStoragePublicDirectory", "(Ljava/lang/String;)Ljava/io/File;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.os.Environment.staticClass, global::android.os.Environment._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.File;
}
public static global::java.io.File DownloadCacheDirectory
{
get
{
return getDownloadCacheDirectory();
}
}
private static global::MonoJavaBridge.MethodId _m4;
public static global::java.io.File getDownloadCacheDirectory()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Environment._m4.native == global::System.IntPtr.Zero)
global::android.os.Environment._m4 = @__env.GetStaticMethodIDNoThrow(global::android.os.Environment.staticClass, "getDownloadCacheDirectory", "()Ljava/io/File;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.os.Environment.staticClass, global::android.os.Environment._m4)) as java.io.File;
}
public static global::java.lang.String ExternalStorageState
{
get
{
return getExternalStorageState();
}
}
private static global::MonoJavaBridge.MethodId _m5;
public static global::java.lang.String getExternalStorageState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Environment._m5.native == global::System.IntPtr.Zero)
global::android.os.Environment._m5 = @__env.GetStaticMethodIDNoThrow(global::android.os.Environment.staticClass, "getExternalStorageState", "()Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.os.Environment.staticClass, global::android.os.Environment._m5)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m6;
public Environment() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Environment._m6.native == global::System.IntPtr.Zero)
global::android.os.Environment._m6 = @__env.GetMethodIDNoThrow(global::android.os.Environment.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Environment.staticClass, global::android.os.Environment._m6);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _DIRECTORY_MUSIC3966;
public static global::java.lang.String DIRECTORY_MUSIC
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetStaticObjectField(global::android.os.Environment.staticClass, _DIRECTORY_MUSIC3966)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _DIRECTORY_PODCASTS3967;
public static global::java.lang.String DIRECTORY_PODCASTS
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetStaticObjectField(global::android.os.Environment.staticClass, _DIRECTORY_PODCASTS3967)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _DIRECTORY_RINGTONES3968;
public static global::java.lang.String DIRECTORY_RINGTONES
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetStaticObjectField(global::android.os.Environment.staticClass, _DIRECTORY_RINGTONES3968)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _DIRECTORY_ALARMS3969;
public static global::java.lang.String DIRECTORY_ALARMS
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetStaticObjectField(global::android.os.Environment.staticClass, _DIRECTORY_ALARMS3969)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _DIRECTORY_NOTIFICATIONS3970;
public static global::java.lang.String DIRECTORY_NOTIFICATIONS
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetStaticObjectField(global::android.os.Environment.staticClass, _DIRECTORY_NOTIFICATIONS3970)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _DIRECTORY_PICTURES3971;
public static global::java.lang.String DIRECTORY_PICTURES
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetStaticObjectField(global::android.os.Environment.staticClass, _DIRECTORY_PICTURES3971)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _DIRECTORY_MOVIES3972;
public static global::java.lang.String DIRECTORY_MOVIES
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetStaticObjectField(global::android.os.Environment.staticClass, _DIRECTORY_MOVIES3972)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _DIRECTORY_DOWNLOADS3973;
public static global::java.lang.String DIRECTORY_DOWNLOADS
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetStaticObjectField(global::android.os.Environment.staticClass, _DIRECTORY_DOWNLOADS3973)) as java.lang.String;
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _DIRECTORY_DCIM3974;
public static global::java.lang.String DIRECTORY_DCIM
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetStaticObjectField(global::android.os.Environment.staticClass, _DIRECTORY_DCIM3974)) as java.lang.String;
}
set
{
}
}
public static global::java.lang.String MEDIA_REMOVED
{
get
{
return "removed";
}
}
public static global::java.lang.String MEDIA_UNMOUNTED
{
get
{
return "unmounted";
}
}
public static global::java.lang.String MEDIA_CHECKING
{
get
{
return "checking";
}
}
public static global::java.lang.String MEDIA_NOFS
{
get
{
return "nofs";
}
}
public static global::java.lang.String MEDIA_MOUNTED
{
get
{
return "mounted";
}
}
public static global::java.lang.String MEDIA_MOUNTED_READ_ONLY
{
get
{
return "mounted_ro";
}
}
public static global::java.lang.String MEDIA_SHARED
{
get
{
return "shared";
}
}
public static global::java.lang.String MEDIA_BAD_REMOVAL
{
get
{
return "bad_removal";
}
}
public static global::java.lang.String MEDIA_UNMOUNTABLE
{
get
{
return "unmountable";
}
}
static Environment()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.Environment.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/Environment"));
global::android.os.Environment._DIRECTORY_MUSIC3966 = @__env.GetStaticFieldIDNoThrow(global::android.os.Environment.staticClass, "DIRECTORY_MUSIC", "Ljava/lang/String;");
global::android.os.Environment._DIRECTORY_PODCASTS3967 = @__env.GetStaticFieldIDNoThrow(global::android.os.Environment.staticClass, "DIRECTORY_PODCASTS", "Ljava/lang/String;");
global::android.os.Environment._DIRECTORY_RINGTONES3968 = @__env.GetStaticFieldIDNoThrow(global::android.os.Environment.staticClass, "DIRECTORY_RINGTONES", "Ljava/lang/String;");
global::android.os.Environment._DIRECTORY_ALARMS3969 = @__env.GetStaticFieldIDNoThrow(global::android.os.Environment.staticClass, "DIRECTORY_ALARMS", "Ljava/lang/String;");
global::android.os.Environment._DIRECTORY_NOTIFICATIONS3970 = @__env.GetStaticFieldIDNoThrow(global::android.os.Environment.staticClass, "DIRECTORY_NOTIFICATIONS", "Ljava/lang/String;");
global::android.os.Environment._DIRECTORY_PICTURES3971 = @__env.GetStaticFieldIDNoThrow(global::android.os.Environment.staticClass, "DIRECTORY_PICTURES", "Ljava/lang/String;");
global::android.os.Environment._DIRECTORY_MOVIES3972 = @__env.GetStaticFieldIDNoThrow(global::android.os.Environment.staticClass, "DIRECTORY_MOVIES", "Ljava/lang/String;");
global::android.os.Environment._DIRECTORY_DOWNLOADS3973 = @__env.GetStaticFieldIDNoThrow(global::android.os.Environment.staticClass, "DIRECTORY_DOWNLOADS", "Ljava/lang/String;");
global::android.os.Environment._DIRECTORY_DCIM3974 = @__env.GetStaticFieldIDNoThrow(global::android.os.Environment.staticClass, "DIRECTORY_DCIM", "Ljava/lang/String;");
}
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
using Trinity.Network;
using System.Reflection;
using Trinity;
using Trinity.Core.Lib;
using Trinity.Utilities;
using Trinity.Diagnostics;
namespace Trinity
{
public static partial class Global
{
private static IPAddress my_ip_address = null;
private static List<IPAddress> my_ip_addresses = null;
private static IPEndPoint my_ip_endpoint = null;
private static long my_aggregation_ipe_value = -1;
static string tmp_dir = null;
static string app_dir = null;
/// <summary>
/// Safely exit current Trinity instance. Logs will be flushed before exiting.
/// </summary>
public static void Exit()
{
Global.Exit(0);
}
/// <summary>
/// Safely exit current Trinity instance. Logs will be flushed before exiting.
/// </summary>
/// <param name="exitCode">Exit code to be given to the operating system.</param>
public static void Exit(int exitCode)
{
Win32.NativeAPI.timeEndPeriod(1);
Diagnostics.Log.Flush();
Environment.Exit(exitCode);
}
internal static string TempDirectory
{
get
{
if (tmp_dir == null)
{
tmp_dir = FileUtility.CompletePath(FileUtility.CompletePath(Environment.GetEnvironmentVariable("TEMP")) + @"Trinity\", true);
}
return tmp_dir;
}
}
internal static string AppDataDirectory
{
get
{
if (app_dir == null)
{
app_dir = FileUtility.CompletePath(FileUtility.CompletePath(Environment.GetEnvironmentVariable("AppData")) + @"Trinity\", true);
}
return app_dir;
}
}
/// <summary>
/// Gets the path or UNC location of the running Trinity instance.
/// </summary>
public static string MyAssemblyPath
{
get
{
return AssemblyPath.MyAssemblyPath;
}
}
/// <summary>
/// Gets the IPAddress bound to current Trinity server.
/// </summary>
public static IPAddress MyIPAddress
{
get
{
if (my_ip_address == null)
{
IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
foreach (IPAddress ip in addressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
my_ip_address = ip;
break;
}
}
}
return my_ip_address;
}
internal set
{
my_ip_address = value;
my_ip_endpoint = null;
}
}
/// <summary>
/// Gets all the IPAddresses bound to current Trinity server.
/// </summary>
public static List<IPAddress> MyIPAddresses
{
get
{
if (my_ip_addresses == null)
{
my_ip_addresses = new List<IPAddress>();
IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;
foreach (IPAddress ip in addressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
my_ip_addresses.Add(ip);
}
}
}
return my_ip_addresses;
}
}
/// <summary>
/// Gets the IPEndPoint bound to current Trinity instance.
/// </summary>
public static IPEndPoint MyIPEndPoint
{
get
{
if (my_ip_endpoint == null)
{
my_ip_endpoint = new IPEndPoint(MyIPAddress, TrinityConfig.ListeningPort);
}
return my_ip_endpoint;
}
}
/// <summary>
/// Gets the total memory usage of all Trinity servers.
/// </summary>
/// <returns>Working set size in bytes.</returns>
public static long GetTotalMemoryUsage()
{
return CloudStorage.GetTotalMemoryUsage();
}
/// <summary>
/// Gets the IPEndPoint bound to current Trinity proxy.
/// </summary>
public unsafe static long MyProxyIPEndPoint
{
get
{
if (my_aggregation_ipe_value == -1)
{
byte[] bytes = new byte[8];
fixed (byte* byte_p = bytes)
{
byte* p = byte_p;
*(int*)p = BitHelper.ToInt32(MyIPAddress.GetAddressBytes(), 0);
p += 4;
*(int*)p = TrinityConfig.ProxyPort;
my_aggregation_ipe_value = *(long*)byte_p;
}
}
return my_aggregation_ipe_value;
}
}
internal unsafe static DateTime GetBuildTime()
{
byte[] PEBuffer = new byte[2048];
using (FileStream fs = new FileStream(Assembly.GetCallingAssembly().Location, FileMode.Open, FileAccess.Read))
{
fs.Read(PEBuffer, 0, 2048);
}
fixed (byte* p = PEBuffer)
{
DateTime t = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(*(int*)(p + *(int*)(p + 60) + 8));
return t.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(t).Hours);
}
}
}
}
| |
/*
* 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 System.Threading;
using System.Text;
using System.Timers;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Mono.Addins;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AvatarFactoryModule")]
public class AvatarFactoryModule : IAvatarFactoryModule, INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const string BAKED_TEXTURES_REPORT_FORMAT = "{0,-9} {1}";
private Scene m_scene = null;
private int m_savetime = 5; // seconds to wait before saving changed appearance
private int m_sendtime = 2; // seconds to wait before sending changed appearance
private bool m_reusetextures = false;
private int m_checkTime = 500; // milliseconds to wait between checks for appearance updates
private System.Timers.Timer m_updateTimer = new System.Timers.Timer();
private Dictionary<UUID,long> m_savequeue = new Dictionary<UUID,long>();
private Dictionary<UUID,long> m_sendqueue = new Dictionary<UUID,long>();
private object m_setAppearanceLock = new object();
#region Region Module interface
public void Initialise(IConfigSource config)
{
IConfig appearanceConfig = config.Configs["Appearance"];
if (appearanceConfig != null)
{
m_savetime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSave",Convert.ToString(m_savetime)));
m_sendtime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSend",Convert.ToString(m_sendtime)));
m_reusetextures = appearanceConfig.GetBoolean("ReuseTextures",m_reusetextures);
// m_log.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime);
}
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
m_scene = scene;
scene.RegisterModuleInterface<IAvatarFactoryModule>(this);
scene.EventManager.OnNewClient += SubscribeToClientEvents;
}
public void RemoveRegion(Scene scene)
{
if (scene == m_scene)
{
scene.UnregisterModuleInterface<IAvatarFactoryModule>(this);
scene.EventManager.OnNewClient -= SubscribeToClientEvents;
}
m_scene = null;
}
public void RegionLoaded(Scene scene)
{
m_updateTimer.Enabled = false;
m_updateTimer.AutoReset = true;
m_updateTimer.Interval = m_checkTime; // 500 milliseconds wait to start async ops
m_updateTimer.Elapsed += new ElapsedEventHandler(HandleAppearanceUpdateTimer);
}
public void Close()
{
}
public string Name
{
get { return "Default Avatar Factory"; }
}
public bool IsSharedModule
{
get { return false; }
}
public Type ReplaceableInterface
{
get { return null; }
}
private void SubscribeToClientEvents(IClientAPI client)
{
client.OnRequestWearables += Client_OnRequestWearables;
client.OnSetAppearance += Client_OnSetAppearance;
client.OnAvatarNowWearing += Client_OnAvatarNowWearing;
client.OnCachedTextureRequest += Client_OnCachedTextureRequest;
}
#endregion
#region IAvatarFactoryModule
/// </summary>
/// <param name="sp"></param>
/// <param name="texture"></param>
/// <param name="visualParam"></param>
public void SetAppearance(IScenePresence sp, AvatarAppearance appearance, WearableCacheItem[] cacheItems)
{
SetAppearance(sp, appearance.Texture, appearance.VisualParams, cacheItems);
}
public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems)
{
float oldoff = sp.Appearance.AvatarFeetOffset;
Vector3 oldbox = sp.Appearance.AvatarBoxSize;
SetAppearance(sp, textureEntry, visualParams, cacheItems);
sp.Appearance.SetSize(avSize);
float off = sp.Appearance.AvatarFeetOffset;
Vector3 box = sp.Appearance.AvatarBoxSize;
if (oldoff != off || oldbox != box)
((ScenePresence)sp).SetSize(box, off);
}
/// <summary>
/// Set appearance data (texture asset IDs and slider settings)
/// </summary>
/// <param name="sp"></param>
/// <param name="texture"></param>
/// <param name="visualParam"></param>
public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, WearableCacheItem[] cacheItems)
{
// m_log.DebugFormat(
// "[AVFACTORY]: start SetAppearance for {0}, te {1}, visualParams {2}",
// sp.Name, textureEntry, visualParams);
// TODO: This is probably not necessary any longer, just assume the
// textureEntry set implies that the appearance transaction is complete
bool changed = false;
// Process the texture entry transactionally, this doesn't guarantee that Appearance is
// going to be handled correctly but it does serialize the updates to the appearance
lock (m_setAppearanceLock)
{
// Process the visual params, this may change height as well
if (visualParams != null)
{
changed = sp.Appearance.SetVisualParams(visualParams);
}
// Process the baked texture array
if (textureEntry != null)
{
m_log.DebugFormat("[AVFACTORY]: Received texture update for {0} {1}", sp.Name, sp.UUID);
// WriteBakedTexturesReport(sp, m_log.DebugFormat);
changed = sp.Appearance.SetTextureEntries(textureEntry) || changed;
// WriteBakedTexturesReport(sp, m_log.DebugFormat);
UpdateBakedTextureCache(sp, cacheItems);
// This appears to be set only in the final stage of the appearance
// update transaction. In theory, we should be able to do an immediate
// appearance send and save here.
}
// NPC should send to clients immediately and skip saving appearance
if (((ScenePresence)sp).PresenceType == PresenceType.Npc)
{
SendAppearance((ScenePresence)sp);
return;
}
// save only if there were changes, send no matter what (doesn't hurt to send twice)
if (changed)
QueueAppearanceSave(sp.ControllingClient.AgentId);
QueueAppearanceSend(sp.ControllingClient.AgentId);
}
// m_log.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString());
}
private void SendAppearance(ScenePresence sp)
{
// Send the appearance to everyone in the scene
sp.SendAppearanceToAllOtherAgents();
// Send animations back to the avatar as well
sp.Animator.SendAnimPack();
}
public bool SendAppearance(UUID agentId)
{
// m_log.DebugFormat("[AVFACTORY]: Sending appearance for {0}", agentId);
ScenePresence sp = m_scene.GetScenePresence(agentId);
if (sp == null)
{
// This is expected if the user has gone away.
// m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentId);
return false;
}
SendAppearance(sp);
return true;
}
public Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId)
{
ScenePresence sp = m_scene.GetScenePresence(agentId);
if (sp == null)
return new Dictionary<BakeType, Primitive.TextureEntryFace>();
return GetBakedTextureFaces(sp);
}
public WearableCacheItem[] GetCachedItems(UUID agentId)
{
ScenePresence sp = m_scene.GetScenePresence(agentId);
WearableCacheItem[] items = sp.Appearance.WearableCacheItems;
//foreach (WearableCacheItem item in items)
//{
//}
return items;
}
public bool SaveBakedTextures(UUID agentId)
{
ScenePresence sp = m_scene.GetScenePresence(agentId);
if (sp == null)
return false;
m_log.DebugFormat(
"[AV FACTORY]: Permanently saving baked textures for {0} in {1}",
sp.Name, m_scene.RegionInfo.RegionName);
Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp);
if (bakedTextures.Count == 0)
return false;
IAssetCache cache = sp.Scene.RequestModuleInterface<IAssetCache>();
if(cache == null)
return true; // no baked local caching so nothing to do
foreach (BakeType bakeType in bakedTextures.Keys)
{
Primitive.TextureEntryFace bakedTextureFace = bakedTextures[bakeType];
if (bakedTextureFace == null)
continue;
AssetBase asset;
cache.Get(bakedTextureFace.TextureID.ToString(), out asset);
if (asset != null && asset.Local)
{
// cache does not update asset contents
cache.Expire(bakedTextureFace.TextureID.ToString());
// Replace an HG ID with the simple asset ID so that we can persist textures for foreign HG avatars
asset.ID = asset.FullID.ToString();
asset.Temporary = false;
asset.Local = false;
m_scene.AssetService.Store(asset);
}
if (asset == null)
{
m_log.WarnFormat(
"[AV FACTORY]: Baked texture id {0} not found for bake {1} for avatar {2} in {3} when trying to save permanently",
bakedTextureFace.TextureID, bakeType, sp.Name, m_scene.RegionInfo.RegionName);
}
}
return true;
}
/// <summary>
/// Queue up a request to send appearance.
/// </summary>
/// <remarks>
/// Makes it possible to accumulate changes without sending out each one separately.
/// </remarks>
/// <param name="agentId"></param>
public void QueueAppearanceSend(UUID agentid)
{
// m_log.DebugFormat("[AVFACTORY]: Queue appearance send for {0}", agentid);
// 10000 ticks per millisecond, 1000 milliseconds per second
long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_sendtime * 1000 * 10000);
lock (m_sendqueue)
{
m_sendqueue[agentid] = timestamp;
m_updateTimer.Start();
}
}
public void QueueAppearanceSave(UUID agentid)
{
// m_log.DebugFormat("[AVFACTORY]: Queueing appearance save for {0}", agentid);
// 10000 ticks per millisecond, 1000 milliseconds per second
long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_savetime * 1000 * 10000);
lock (m_savequeue)
{
m_savequeue[agentid] = timestamp;
m_updateTimer.Start();
}
}
// called on textures update
public bool UpdateBakedTextureCache(IScenePresence sp, WearableCacheItem[] cacheItems)
{
if(cacheItems == null)
return false;
// npcs dont have baked cache
if (((ScenePresence)sp).IsNPC)
return true;
// uploaded baked textures will be in assets local cache
IAssetCache cache = m_scene.RequestModuleInterface<IAssetCache>();
IBakedTextureModule m_BakedTextureModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
int validDirtyBakes = 0;
int hits = 0;
// our main cacheIDs mapper is p.Appearance.WearableCacheItems
WearableCacheItem[] wearableCache = sp.Appearance.WearableCacheItems;
if (wearableCache == null)
{
wearableCache = WearableCacheItem.GetDefaultCacheItem();
}
List<UUID> missing = new List<UUID>();
bool haveSkirt = (wearableCache[19].TextureID != UUID.Zero);
bool haveNewSkirt = false;
// Process received baked textures
for (int i = 0; i < cacheItems.Length; i++)
{
int idx = (int)cacheItems[i].TextureIndex;
Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
// No face
if (face == null)
{
// for some reason viewer is cleaning this
if(idx != 19) // skirt is optional
{
sp.Appearance.Texture.FaceTextures[idx] = sp.Appearance.Texture.CreateFace((uint) idx);
sp.Appearance.Texture.FaceTextures[idx].TextureID = AppearanceManager.DEFAULT_AVATAR_TEXTURE;
}
wearableCache[idx].CacheId = UUID.Zero;
wearableCache[idx].TextureID = UUID.Zero;
wearableCache[idx].TextureAsset = null;
continue;
}
else
{
if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
{
wearableCache[idx].CacheId = UUID.Zero;
wearableCache[idx].TextureID = UUID.Zero;
wearableCache[idx].TextureAsset = null;
continue;
}
if(idx == 19)
haveNewSkirt = true;
/*
if (face.TextureID == wearableCache[idx].TextureID && m_BakedTextureModule != null)
{
if (wearableCache[idx].CacheId != cacheItems[i].CacheId)
{
wearableCache[idx].CacheId = cacheItems[i].CacheId;
validDirtyBakes++;
//assuming this can only happen if asset is in cache
}
hits++;
continue;
}
*/
wearableCache[idx].TextureAsset = null;
if (cache != null)
{
AssetBase asb = null;
cache.Get(face.TextureID.ToString(), out asb);
wearableCache[idx].TextureAsset = asb;
}
if (wearableCache[idx].TextureAsset != null)
{
if ( wearableCache[idx].TextureID != face.TextureID ||
wearableCache[idx].CacheId != cacheItems[i].CacheId)
validDirtyBakes++;
wearableCache[idx].TextureID = face.TextureID;
wearableCache[idx].CacheId = cacheItems[i].CacheId;
hits++;
}
else
{
wearableCache[idx].CacheId = UUID.Zero;
wearableCache[idx].TextureID = UUID.Zero;
wearableCache[idx].TextureAsset = null;
missing.Add(face.TextureID);
continue;
}
}
}
// handle optional skirt case
if(!haveNewSkirt && haveSkirt)
{
wearableCache[19].CacheId = UUID.Zero;
wearableCache[19].TextureID = UUID.Zero;
wearableCache[19].TextureAsset = null;
validDirtyBakes++;
}
sp.Appearance.WearableCacheItems = wearableCache;
if (missing.Count > 0)
{
foreach (UUID id in missing)
sp.ControllingClient.SendRebakeAvatarTextures(id);
}
if (validDirtyBakes > 0 && hits == cacheItems.Length)
{
// if we got a full set of baked textures save all in BakedTextureModule
if (m_BakedTextureModule != null)
{
m_log.DebugFormat("[UpdateBakedCache] Uploading to Bakes Server: cache hits: {0} changed entries: {1} rebakes {2}",
hits.ToString(), validDirtyBakes.ToString(), missing.Count);
m_BakedTextureModule.Store(sp.UUID, wearableCache);
}
}
else
m_log.DebugFormat("[UpdateBakedCache] cache hits: {0} changed entries: {1} rebakes {2}",
hits.ToString(), validDirtyBakes.ToString(), missing.Count);
for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++)
{
int j = AvatarAppearance.BAKE_INDICES[iter];
sp.Appearance.WearableCacheItems[j].TextureAsset = null;
// m_log.Debug("[UpdateBCache] {" + iter + "/" +
// sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" +
// sp.Appearance.WearableCacheItems[j].CacheId + ", t-" +
// sp.Appearance.WearableCacheItems[j].TextureID);
}
return (hits == cacheItems.Length);
}
// called when we get a new root avatar
public bool ValidateBakedTextureCache(IScenePresence sp)
{
int hits = 0;
if (((ScenePresence)sp).IsNPC)
return true;
lock (m_setAppearanceLock)
{
IAssetCache cache = m_scene.RequestModuleInterface<IAssetCache>();
IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
WearableCacheItem[] bakedModuleCache = null;
if (cache == null)
return false;
WearableCacheItem[] wearableCache = sp.Appearance.WearableCacheItems;
// big debug
// m_log.DebugFormat("[AVFACTORY]: ValidateBakedTextureCache start for {0} {1}", sp.Name, sp.UUID);
/*
for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++)
{
int j = AvatarAppearance.BAKE_INDICES[iter];
Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[j];
if (wearableCache == null)
{
if (face != null)
m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t- " + face.TextureID);
else
m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t- No texture");
}
else
{
if (face != null)
m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " ft- " + face.TextureID +
"}: cc-" +
wearableCache[j].CacheId + ", ct-" +
wearableCache[j].TextureID
);
else
m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t - No texture" +
"}: cc-" +
wearableCache[j].CacheId + ", ct-" +
wearableCache[j].TextureID
);
}
}
*/
bool wearableCacheValid = false;
if (wearableCache == null)
{
wearableCache = WearableCacheItem.GetDefaultCacheItem();
}
else
{
// we may have received a full cache
// check same coerence and store
wearableCacheValid = true;
for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
{
int idx = AvatarAppearance.BAKE_INDICES[i];
Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
if (face != null)
{
if (face.TextureID == wearableCache[idx].TextureID &&
face.TextureID != UUID.Zero)
{
if (wearableCache[idx].TextureAsset != null)
{
hits++;
wearableCache[idx].TextureAsset.Temporary = true;
wearableCache[idx].TextureAsset.Local = true;
cache.Cache(wearableCache[idx].TextureAsset);
wearableCache[idx].TextureAsset = null;
continue;
}
if (cache.Check((wearableCache[idx].TextureID).ToString()))
{
hits++;
continue;
}
}
wearableCacheValid = false;
}
}
wearableCacheValid = (wearableCacheValid && (hits >= AvatarAppearance.BAKE_INDICES.Length - 1));
if (wearableCacheValid)
{
// m_log.Debug("[ValidateBakedCache] have valid local cache");
}
else
wearableCache[19].TextureAsset = null; // clear optional skirt
}
bool checkExternal = false;
if (!wearableCacheValid)
{
hits = 0;
// only use external bake module on login condition check
// ScenePresence ssp = null;
// if (sp is ScenePresence)
{
// ssp = (ScenePresence)sp;
// checkExternal = (((uint)ssp.TeleportFlags & (uint)TeleportFlags.ViaLogin) != 0) &&
// bakedModule != null;
// or do it anytime we dont have the cache
checkExternal = bakedModule != null;
}
}
if (checkExternal)
{
bool gotbacked = false;
// m_log.Debug("[ValidateBakedCache] local cache invalid, checking bakedModule");
try
{
bakedModuleCache = bakedModule.Get(sp.UUID);
}
catch (Exception e)
{
m_log.ErrorFormat(e.ToString());
bakedModuleCache = null;
}
if (bakedModuleCache != null)
{
m_log.Debug("[ValidateBakedCache] got bakedModule " + bakedModuleCache.Length + " cached textures");
for (int i = 0; i < bakedModuleCache.Length; i++)
{
int j = (int)bakedModuleCache[i].TextureIndex;
if (bakedModuleCache[i].TextureAsset != null)
{
wearableCache[j].TextureID = bakedModuleCache[i].TextureID;
wearableCache[j].CacheId = bakedModuleCache[i].CacheId;
wearableCache[j].TextureAsset = bakedModuleCache[i].TextureAsset;
bakedModuleCache[i].TextureAsset.Temporary = true;
bakedModuleCache[i].TextureAsset.Local = true;
cache.Cache(bakedModuleCache[i].TextureAsset);
}
}
gotbacked = true;
}
if (gotbacked)
{
// force the ones we got
for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
{
int idx = AvatarAppearance.BAKE_INDICES[i];
if(wearableCache[idx].TextureAsset == null)
{
if(idx == 19)
{
sp.Appearance.Texture.FaceTextures[idx] = null;
hits++;
}
continue;
}
Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
if (face == null)
{
face = sp.Appearance.Texture.CreateFace((uint)idx);
sp.Appearance.Texture.FaceTextures[idx] = face;
}
face.TextureID = wearableCache[idx].TextureID;
hits++;
wearableCache[idx].TextureAsset = null;
}
}
}
sp.Appearance.WearableCacheItems = wearableCache;
}
// debug
// m_log.DebugFormat("[ValidateBakedCache]: Completed texture check for {0} {1} with {2} hits", sp.Name, sp.UUID, hits);
/*
for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++)
{
int j = AvatarAppearance.BAKE_INDICES[iter];
m_log.Debug("[ValidateBakedCache] {" + iter + "/" +
sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" +
sp.Appearance.WearableCacheItems[j].CacheId + ", t-" +
sp.Appearance.WearableCacheItems[j].TextureID);
}
*/
return (hits >= AvatarAppearance.BAKE_INDICES.Length - 1); // skirt is optional
}
public int RequestRebake(IScenePresence sp, bool missingTexturesOnly)
{
if (((ScenePresence)sp).IsNPC)
return 0;
int texturesRebaked = 0;
IAssetCache cache = m_scene.RequestModuleInterface<IAssetCache>();
for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
{
int idx = AvatarAppearance.BAKE_INDICES[i];
Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
// if there is no texture entry, skip it
if (face == null)
continue;
if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
continue;
if (missingTexturesOnly)
{
if (cache != null && cache.Check(face.TextureID.ToString()))
{
continue;
}
else
{
m_log.DebugFormat(
"[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.",
face.TextureID, idx, sp.Name);
}
}
else
{
m_log.DebugFormat(
"[AVFACTORY]: Requesting rebake of {0} ({1}) for {2}.",
face.TextureID, idx, sp.Name);
}
texturesRebaked++;
sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID);
}
return texturesRebaked;
}
#endregion
#region AvatarFactoryModule private methods
private Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(ScenePresence sp)
{
if (sp.IsChildAgent)
return new Dictionary<BakeType, Primitive.TextureEntryFace>();
Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures
= new Dictionary<BakeType, Primitive.TextureEntryFace>();
AvatarAppearance appearance = sp.Appearance;
Primitive.TextureEntryFace[] faceTextures = appearance.Texture.FaceTextures;
foreach (int i in Enum.GetValues(typeof(BakeType)))
{
BakeType bakeType = (BakeType)i;
if (bakeType == BakeType.Unknown)
continue;
// m_log.DebugFormat(
// "[AVFACTORY]: NPC avatar {0} has texture id {1} : {2}",
// acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]);
int ftIndex = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType);
Primitive.TextureEntryFace texture = faceTextures[ftIndex]; // this will be null if there's no such baked texture
bakedTextures[bakeType] = texture;
}
return bakedTextures;
}
private void HandleAppearanceUpdateTimer(object sender, EventArgs ea)
{
long now = DateTime.Now.Ticks;
lock (m_sendqueue)
{
Dictionary<UUID, long> sends = new Dictionary<UUID, long>(m_sendqueue);
foreach (KeyValuePair<UUID, long> kvp in sends)
{
// We have to load the key and value into local parameters to avoid a race condition if we loop
// around and load kvp with a different value before FireAndForget has launched its thread.
UUID avatarID = kvp.Key;
long sendTime = kvp.Value;
// m_log.DebugFormat("[AVFACTORY]: Handling queued appearance updates for {0}, update delta to now is {1}", avatarID, sendTime - now);
if (sendTime < now)
{
Util.FireAndForget(o => SendAppearance(avatarID), null, "AvatarFactoryModule.SendAppearance");
m_sendqueue.Remove(avatarID);
}
}
}
lock (m_savequeue)
{
Dictionary<UUID, long> saves = new Dictionary<UUID, long>(m_savequeue);
foreach (KeyValuePair<UUID, long> kvp in saves)
{
// We have to load the key and value into local parameters to avoid a race condition if we loop
// around and load kvp with a different value before FireAndForget has launched its thread.
UUID avatarID = kvp.Key;
long sendTime = kvp.Value;
if (sendTime < now)
{
Util.FireAndForget(o => SaveAppearance(avatarID), null, "AvatarFactoryModule.SaveAppearance");
m_savequeue.Remove(avatarID);
}
}
// We must lock both queues here so that QueueAppearanceSave() or *Send() don't m_updateTimer.Start() on
// another thread inbetween the first count calls and m_updateTimer.Stop() on this thread.
lock (m_sendqueue)
if (m_savequeue.Count == 0 && m_sendqueue.Count == 0)
m_updateTimer.Stop();
}
}
private void SaveAppearance(UUID agentid)
{
// We must set appearance parameters in the en_US culture in order to avoid issues where values are saved
// in a culture where decimal points are commas and then reloaded in a culture which just treats them as
// number seperators.
Culture.SetCurrentCulture();
ScenePresence sp = m_scene.GetScenePresence(agentid);
if (sp == null)
{
// This is expected if the user has gone away.
// m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentid);
return;
}
// m_log.DebugFormat("[AVFACTORY]: Saving appearance for avatar {0}", agentid);
// This could take awhile since it needs to pull inventory
// We need to do it at the point of save so that there is a sufficient delay for any upload of new body part/shape
// assets and item asset id changes to complete.
// I don't think we need to worry about doing this within m_setAppearanceLock since the queueing avoids
// multiple save requests.
SetAppearanceAssets(sp.UUID, sp.Appearance);
// List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
// foreach (AvatarAttachment att in attachments)
// {
// m_log.DebugFormat(
// "[AVFACTORY]: For {0} saving attachment {1} at point {2}",
// sp.Name, att.ItemID, att.AttachPoint);
// }
m_scene.AvatarService.SetAppearance(agentid, sp.Appearance);
// Trigger this here because it's the final step in the set/queue/save process for appearance setting.
// Everything has been updated and stored. Ensures bakes have been persisted (if option is set to persist bakes).
m_scene.EventManager.TriggerAvatarAppearanceChanged(sp);
}
/// <summary>
/// For a given set of appearance items, check whether the items are valid and add their asset IDs to
/// appearance data.
/// </summary>
/// <param name='userID'></param>
/// <param name='appearance'></param>
private void SetAppearanceAssets(UUID userID, AvatarAppearance appearance)
{
IInventoryService invService = m_scene.InventoryService;
if (invService.GetRootFolder(userID) != null)
{
for (int i = 0; i < appearance.Wearables.Length; i++)
{
for (int j = 0; j < appearance.Wearables[i].Count; j++)
{
if (appearance.Wearables[i][j].ItemID == UUID.Zero)
{
m_log.WarnFormat(
"[AVFACTORY]: Wearable item {0}:{1} for user {2} unexpectedly UUID.Zero. Ignoring.",
i, j, userID);
continue;
}
// Ignore ruth's assets
if (i < AvatarWearable.DefaultWearables.Length)
{
if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID)
continue;
}
InventoryItemBase baseItem = invService.GetItem(userID, appearance.Wearables[i][j].ItemID);
if (baseItem != null)
{
appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID);
}
else
{
m_log.WarnFormat(
"[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default",
appearance.Wearables[i][j].ItemID, (WearableType)i);
appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID);
}
}
}
}
else
{
m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID);
}
// IInventoryService invService = m_scene.InventoryService;
// bool resetwearable = false;
// if (invService.GetRootFolder(userID) != null)
// {
// for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++)
// {
// for (int j = 0; j < appearance.Wearables[i].Count; j++)
// {
// // Check if the default wearables are not set
// if (appearance.Wearables[i][j].ItemID == UUID.Zero)
// {
// switch ((WearableType) i)
// {
// case WearableType.Eyes:
// case WearableType.Hair:
// case WearableType.Shape:
// case WearableType.Skin:
// //case WearableType.Underpants:
// TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance);
// resetwearable = true;
// m_log.Warn("[AVFACTORY]: UUID.Zero Wearables, passing fake values.");
// resetwearable = true;
// break;
//
// }
// continue;
// }
//
// // Ignore ruth's assets except for the body parts! missing body parts fail avatar appearance on V1
// if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID)
// {
// switch ((WearableType)i)
// {
// case WearableType.Eyes:
// case WearableType.Hair:
// case WearableType.Shape:
// case WearableType.Skin:
// //case WearableType.Underpants:
// TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance);
//
// m_log.WarnFormat("[AVFACTORY]: {0} Default Wearables, passing existing values.", (WearableType)i);
// resetwearable = true;
// break;
//
// }
// continue;
// }
//
// InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID);
// baseItem = invService.GetItem(baseItem);
//
// if (baseItem != null)
// {
// appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID);
// int unmodifiedWearableIndexForClosure = i;
// m_scene.AssetService.Get(baseItem.AssetID.ToString(), this,
// delegate(string x, object y, AssetBase z)
// {
// if (z == null)
// {
// TryAndRepairBrokenWearable(
// (WearableType)unmodifiedWearableIndexForClosure, invService,
// userID, appearance);
// }
// });
// }
// else
// {
// m_log.ErrorFormat(
// "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default",
// appearance.Wearables[i][j].ItemID, (WearableType)i);
//
// TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance);
// resetwearable = true;
//
// }
// }
// }
//
// // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
// if (appearance.Wearables[(int) WearableType.Eyes] == null)
// {
// m_log.WarnFormat("[AVFACTORY]: {0} Eyes are Null, passing existing values.", (WearableType.Eyes));
//
// TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance);
// resetwearable = true;
// }
// else
// {
// if (appearance.Wearables[(int) WearableType.Eyes][0].ItemID == UUID.Zero)
// {
// m_log.WarnFormat("[AVFACTORY]: Eyes are UUID.Zero are broken, {0} {1}",
// appearance.Wearables[(int) WearableType.Eyes][0].ItemID,
// appearance.Wearables[(int) WearableType.Eyes][0].AssetID);
// TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance);
// resetwearable = true;
//
// }
//
// }
// // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
// if (appearance.Wearables[(int)WearableType.Shape] == null)
// {
// m_log.WarnFormat("[AVFACTORY]: {0} shape is Null, passing existing values.", (WearableType.Shape));
//
// TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance);
// resetwearable = true;
// }
// else
// {
// if (appearance.Wearables[(int)WearableType.Shape][0].ItemID == UUID.Zero)
// {
// m_log.WarnFormat("[AVFACTORY]: Shape is UUID.Zero and broken, {0} {1}",
// appearance.Wearables[(int)WearableType.Shape][0].ItemID,
// appearance.Wearables[(int)WearableType.Shape][0].AssetID);
// TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance);
// resetwearable = true;
//
// }
//
// }
// // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
// if (appearance.Wearables[(int)WearableType.Hair] == null)
// {
// m_log.WarnFormat("[AVFACTORY]: {0} Hair is Null, passing existing values.", (WearableType.Hair));
//
// TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance);
// resetwearable = true;
// }
// else
// {
// if (appearance.Wearables[(int)WearableType.Hair][0].ItemID == UUID.Zero)
// {
// m_log.WarnFormat("[AVFACTORY]: Hair is UUID.Zero and broken, {0} {1}",
// appearance.Wearables[(int)WearableType.Hair][0].ItemID,
// appearance.Wearables[(int)WearableType.Hair][0].AssetID);
// TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance);
// resetwearable = true;
//
// }
//
// }
// // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
// if (appearance.Wearables[(int)WearableType.Skin] == null)
// {
// m_log.WarnFormat("[AVFACTORY]: {0} Skin is Null, passing existing values.", (WearableType.Skin));
//
// TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance);
// resetwearable = true;
// }
// else
// {
// if (appearance.Wearables[(int)WearableType.Skin][0].ItemID == UUID.Zero)
// {
// m_log.WarnFormat("[AVFACTORY]: Skin is UUID.Zero and broken, {0} {1}",
// appearance.Wearables[(int)WearableType.Skin][0].ItemID,
// appearance.Wearables[(int)WearableType.Skin][0].AssetID);
// TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance);
// resetwearable = true;
//
// }
//
// }
// if (resetwearable)
// {
// ScenePresence presence = null;
// if (m_scene.TryGetScenePresence(userID, out presence))
// {
// presence.ControllingClient.SendWearables(presence.Appearance.Wearables,
// presence.Appearance.Serial++);
// }
// }
//
// }
// else
// {
// m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID);
// }
}
private void TryAndRepairBrokenWearable(WearableType type, IInventoryService invService, UUID userID,AvatarAppearance appearance)
{
UUID defaultwearable = GetDefaultItem(type);
if (defaultwearable != UUID.Zero)
{
UUID newInvItem = UUID.Random();
InventoryItemBase itembase = new InventoryItemBase(newInvItem, userID)
{
AssetID = defaultwearable,
AssetType = (int)FolderType.BodyPart,
CreatorId = userID.ToString(),
//InvType = (int)InventoryType.Wearable,
Description = "Failed Wearable Replacement",
Folder = invService.GetFolderForType(userID, FolderType.BodyPart).ID,
Flags = (uint) type, Name = Enum.GetName(typeof (WearableType), type),
BasePermissions = (uint) PermissionMask.Copy,
CurrentPermissions = (uint) PermissionMask.Copy,
EveryOnePermissions = (uint) PermissionMask.Copy,
GroupPermissions = (uint) PermissionMask.Copy,
NextPermissions = (uint) PermissionMask.Copy
};
invService.AddItem(itembase);
UUID LinkInvItem = UUID.Random();
itembase = new InventoryItemBase(LinkInvItem, userID)
{
AssetID = newInvItem,
AssetType = (int)AssetType.Link,
CreatorId = userID.ToString(),
InvType = (int) InventoryType.Wearable,
Description = "Failed Wearable Replacement",
Folder = invService.GetFolderForType(userID, FolderType.CurrentOutfit).ID,
Flags = (uint) type,
Name = Enum.GetName(typeof (WearableType), type),
BasePermissions = (uint) PermissionMask.Copy,
CurrentPermissions = (uint) PermissionMask.Copy,
EveryOnePermissions = (uint) PermissionMask.Copy,
GroupPermissions = (uint) PermissionMask.Copy,
NextPermissions = (uint) PermissionMask.Copy
};
invService.AddItem(itembase);
appearance.Wearables[(int)type] = new AvatarWearable(newInvItem, GetDefaultItem(type));
ScenePresence presence = null;
if (m_scene.TryGetScenePresence(userID, out presence))
{
m_scene.SendInventoryUpdate(presence.ControllingClient,
invService.GetFolderForType(userID, FolderType.CurrentOutfit), false, true);
}
}
}
private UUID GetDefaultItem(WearableType wearable)
{
// These are ruth
UUID ret = UUID.Zero;
switch (wearable)
{
case WearableType.Eyes:
ret = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7");
break;
case WearableType.Hair:
ret = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66");
break;
case WearableType.Pants:
ret = new UUID("00000000-38f9-1111-024e-222222111120");
break;
case WearableType.Shape:
ret = new UUID("66c41e39-38f9-f75a-024e-585989bfab73");
break;
case WearableType.Shirt:
ret = new UUID("00000000-38f9-1111-024e-222222111110");
break;
case WearableType.Skin:
ret = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb");
break;
case WearableType.Undershirt:
ret = new UUID("16499ebb-3208-ec27-2def-481881728f47");
break;
case WearableType.Underpants:
ret = new UUID("4ac2e9c7-3671-d229-316a-67717730841d");
break;
}
return ret;
}
#endregion
#region Client Event Handlers
/// <summary>
/// Tell the client for this scene presence what items it should be wearing now
/// </summary>
/// <param name="client"></param>
private void Client_OnRequestWearables(IClientAPI client)
{
Util.FireAndForget(delegate(object x)
{
Thread.Sleep(4000);
// m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId);
ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
if (sp != null)
client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial++);
else
m_log.WarnFormat("[AVFACTORY]: Client_OnRequestWearables unable to find presence for {0}", client.AgentId);
}, null, "AvatarFactoryModule.OnClientRequestWearables");
}
/// <summary>
/// Set appearance data (texture asset IDs and slider settings) received from a client
/// </summary>
/// <param name="client"></param>
/// <param name="texture"></param>
/// <param name="visualParam"></param>
private void Client_OnSetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems)
{
// m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance called for {0} ({1})", client.Name, client.AgentId);
ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
if (sp != null)
SetAppearance(sp, textureEntry, visualParams,avSize, cacheItems);
else
m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance unable to find presence for {0}", client.AgentId);
}
/// <summary>
/// Update what the avatar is wearing using an item from their inventory.
/// </summary>
/// <param name="client"></param>
/// <param name="e"></param>
private void Client_OnAvatarNowWearing(IClientAPI client, AvatarWearingArgs e)
{
// m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing called for {0} ({1})", client.Name, client.AgentId);
ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
if (sp == null)
{
m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing unable to find presence for {0}", client.AgentId);
return;
}
// we need to clean out the existing textures
sp.Appearance.ResetAppearance();
// operate on a copy of the appearance so we don't have to lock anything yet
AvatarAppearance avatAppearance = new AvatarAppearance(sp.Appearance, false);
foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
{
// If the wearable type is larger than the current array, expand it
if (avatAppearance.Wearables.Length <= wear.Type)
{
int currentLength = avatAppearance.Wearables.Length;
AvatarWearable[] wears = avatAppearance.Wearables;
Array.Resize(ref wears, wear.Type + 1);
for (int i = currentLength ; i <= wear.Type ; i++)
wears[i] = new AvatarWearable();
avatAppearance.Wearables = wears;
}
avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero);
}
avatAppearance.GetAssetsFrom(sp.Appearance);
lock (m_setAppearanceLock)
{
// Update only those fields that we have changed. This is important because the viewer
// often sends AvatarIsWearing and SetAppearance packets at once, and AvatarIsWearing
// shouldn't overwrite the changes made in SetAppearance.
sp.Appearance.Wearables = avatAppearance.Wearables;
sp.Appearance.Texture = avatAppearance.Texture;
// We don't need to send the appearance here since the "iswearing" will trigger a new set
// of visual param and baked texture changes. When those complete, the new appearance will be sent
QueueAppearanceSave(client.AgentId);
}
}
/// <summary>
/// Respond to the cached textures request from the client
/// </summary>
/// <param name="client"></param>
/// <param name="serial"></param>
/// <param name="cachedTextureRequest"></param>
private void Client_OnCachedTextureRequest(IClientAPI client, int serial, List<CachedTextureRequestArg> cachedTextureRequest)
{
// m_log.WarnFormat("[AVFACTORY]: Client_OnCachedTextureRequest called for {0} ({1})", client.Name, client.AgentId);
ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
List<CachedTextureResponseArg> cachedTextureResponse = new List<CachedTextureResponseArg>();
foreach (CachedTextureRequestArg request in cachedTextureRequest)
{
UUID texture = UUID.Zero;
int index = request.BakedTextureIndex;
if (m_reusetextures)
{
// this is the most insanely dumb way to do this... however it seems to
// actually work. if the appearance has been reset because wearables have
// changed then the texture entries are zero'd out until the bakes are
// uploaded. on login, if the textures exist in the cache (eg if you logged
// into the simulator recently, then the appearance will pull those and send
// them back in the packet and you won't have to rebake. if the textures aren't
// in the cache then the intial makeroot() call in scenepresence will zero
// them out.
//
// a better solution (though how much better is an open question) is to
// store the hashes in the appearance and compare them. Thats's coming.
Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[index];
if (face != null)
texture = face.TextureID;
// m_log.WarnFormat("[AVFACTORY]: reuse texture {0} for index {1}",texture,index);
}
CachedTextureResponseArg response = new CachedTextureResponseArg();
response.BakedTextureIndex = index;
response.BakedTextureID = texture;
response.HostName = null;
cachedTextureResponse.Add(response);
}
// m_log.WarnFormat("[AVFACTORY]: serial is {0}",serial);
// The serial number appears to be used to match requests and responses
// in the texture transaction. We just send back the serial number
// that was provided in the request. The viewer bumps this for us.
client.SendCachedTextureResponse(sp, serial, cachedTextureResponse);
}
#endregion
public void WriteBakedTexturesReport(IScenePresence sp, ReportOutputAction outputAction)
{
outputAction("For {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName);
outputAction(BAKED_TEXTURES_REPORT_FORMAT, "Bake Type", "UUID");
Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp.UUID);
foreach (BakeType bt in bakedTextures.Keys)
{
string rawTextureID;
if (bakedTextures[bt] == null)
{
rawTextureID = "not set";
}
else
{
rawTextureID = bakedTextures[bt].TextureID.ToString();
if (m_scene.AssetService.Get(rawTextureID) == null)
rawTextureID += " (not found)";
else
rawTextureID += " (uploaded)";
}
outputAction(BAKED_TEXTURES_REPORT_FORMAT, bt, rawTextureID);
}
bool bakedTextureValid = m_scene.AvatarFactory.ValidateBakedTextureCache(sp);
outputAction("{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete");
}
}
}
| |
//This file has been modified based on forum user suggestions.
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.VisualBasic;
using System.Text;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
namespace fyiReporting.RDL
{
///<summary>
/// Code represents the Code report element.
///</summary>
[Serializable]
internal class Code : ReportLink
{
string _Source; // The source code
string _Classname; // Class name of generated class
Assembly _Assembly; // the compiled assembly
internal Code(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
_Source=xNode.InnerText;
_Assembly = GetAssembly();
}
override internal void FinalPass()
{
return;
}
private Assembly GetAssembly()
{
// Generate the proxy source code
List<string> lines = new List<string>(); // hold lines in array in case of error
VBCodeProvider vbcp = new VBCodeProvider();
StringBuilder sb = new StringBuilder();
// Generate code with the following general form
//Imports System
//Imports Microsoft.VisualBasic
//Imports System.Convert
//Imports System.Math
//Namespace fyiReporting.vbgen
//Public Class MyClassn // where n is a uniquely generated integer
//Sub New()
//End Sub
// ' this is the code in the <Code> tag
//End Class
//End Namespace
string unique = Interlocked.Increment(ref Parser.Counter).ToString();
lines.Add("Imports System");
lines.Add("Imports Microsoft.VisualBasic");
lines.Add("Imports System.Convert");
lines.Add("Imports System.Math");
lines.Add("Imports fyiReporting.RDL");
lines.Add("Namespace fyiReporting.vbgen");
_Classname = "MyClass" + unique;
lines.Add("Public Class " + _Classname);
lines.Add("Private Shared _report As CodeReport");
lines.Add("Sub New()");
lines.Add("End Sub");
lines.Add("Sub New(byVal def As Report)");
lines.Add(_Classname + "._report = New CodeReport(def)");
lines.Add("End Sub");
lines.Add("Public Shared ReadOnly Property Report As CodeReport");
lines.Add("Get");
lines.Add("Return " + _Classname + "._report");
lines.Add("End Get");
lines.Add("End Property");
// Read and write code as lines
StringReader tr = new StringReader(_Source);
while (tr.Peek() >= 0)
{
string line = tr.ReadLine();
lines.Add(line);
}
tr.Close();
lines.Add("End Class");
lines.Add("End Namespace");
foreach (string l in lines)
{
sb.Append(l);
sb.Append("\r\n");
}
string vbcode = sb.ToString();
// debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// StreamWriter tsw = File.CreateText(@"c:\temp\vbcode.txt");
// tsw.Write(vbcode);
// tsw.Close();
// debug code !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Create Assembly
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
string re;
//AJM GJL 250608 - Try the Bin Directory too, for websites
if (RdlEngineConfig.DirectoryLoadedFrom == null) {
if (System.IO.File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RdlEngine.dll"))) {
re = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "RdlEngine.dll"); // this can fail especially in web scenarios
}
else
{
re = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Bin"); // this can work especially in web scenarios
re = Path.Combine(re, "RdlEngine.dll");
}
}
else
re = Path.Combine(RdlEngineConfig.DirectoryLoadedFrom, "RdlEngine.dll"); // use RdlEngineConfig.xml directory when available
cp.ReferencedAssemblies.Add(re);
// also allow access to classes that have been added to report
if (this.OwnerReport.CodeModules != null)
{
foreach(CodeModule cm in this.OwnerReport.CodeModules.Items)
{
//Changed from Forum, User: solidstate http://www.fyireporting.com/forum/viewtopic.php?t=905
string modulePath = Path.Combine(Path.GetDirectoryName(re), cm.CdModule);
cp.ReferencedAssemblies.Add(modulePath);
}
}
cp.GenerateExecutable = false;
cp.GenerateInMemory = false; // just loading into memory causes problems when instantiating
cp.IncludeDebugInformation = false;
CompilerResults cr = vbcp.CompileAssemblyFromSource(cp, vbcode);
if(cr.Errors.Count > 0)
{
StringBuilder err = new StringBuilder(string.Format("Code element has {0} error(s). Line numbers are relative to Code element.", cr.Errors.Count));
foreach (CompilerError ce in cr.Errors)
{
string l;
if (ce.Line >= 1 && ce.Line <= lines.Count)
l = lines[ce.Line - 1] as string;
else
l = "Unknown";
err.AppendFormat("\r\nLine {0} '{1}' : {2} {3}", ce.Line - 5, l, ce.ErrorNumber, ce.ErrorText);
}
this.OwnerReport.rl.LogError(4, err.ToString());
return null;
}
return Assembly.LoadFrom(cr.PathToAssembly); // We need an assembly loaded from the file system
// or instantiation of object complains
}
internal Type CodeType()
{
if (_Assembly == null)
return null;
Type t=null;
try
{
object instance = _Assembly.CreateInstance("fyiReporting.vbgen." + this._Classname, false);
t = instance.GetType();
}
catch (Exception e)
{
OwnerReport.rl.LogError(4,
string.Format("Unable to load instance of Code\r\n{0}", e.Message));
}
return t;
}
internal object Load(Report rpt)
{
WorkClass wc = GetWC(rpt);
if (wc.bCreateFailed) // We only try to create once.
return wc.Instance;
if (wc.Instance != null) // Already loaded
return wc.Instance;
if (_Assembly == null)
{
wc.bCreateFailed = true; // we don't have an assembly
return null;
}
// Load an instance of the object
string err="";
try
{
object[] args = new object[1];
args[0] = rpt;
wc.Instance = _Assembly.CreateInstance("fyiReporting.vbgen." + this._Classname, false, BindingFlags.CreateInstance, null, args, null, null);
}
catch (Exception e)
{
wc.Instance = null;
err = e.Message;
}
if (wc.Instance == null)
{
string e = String.Format("Unable to create instance of local code class.\r\n{0}", err);
if (rpt == null)
OwnerReport.rl.LogError(4, e);
else
rpt.rl.LogError(4, e);
wc.bCreateFailed = true;
}
return wc.Instance;
}
internal string Source
{
get { return _Source; }
}
internal object Instance(Report rpt)
{
return Load(rpt); // load if necessary
}
private WorkClass GetWC(Report rpt)
{
if (rpt == null)
return new WorkClass();
WorkClass wc = rpt.Cache.Get(this, "wc") as WorkClass;
if (wc == null)
{
wc = new WorkClass();
rpt.Cache.Add(this, "wc", wc);
}
return wc;
}
private void RemoveWC(Report rpt)
{
rpt.Cache.Remove(this, "wc");
}
class WorkClass
{
internal object Instance;
internal bool bCreateFailed;
internal WorkClass()
{
Instance=null; //
bCreateFailed=false;
}
}
}
// The CodeReport code was donated to the RDL Project by "solidstore" of the forum.
// The classes defined below are for use by the VB code runtime.
/// <summary>
/// This class is only for use with the VB code generation.
/// </summary>
public class CodeReport
{
private readonly CodeGlobals globals;
private readonly CodeParameters parameters;
private readonly CodeUser user;
public CodeReport(Report report)
{
this.globals = new CodeGlobals(report);
this.parameters = new CodeParameters(report);
this.user = new CodeUser(report);
}
public CodeGlobals Globals
{
get
{
return this.globals;
}
}
public CodeParameters Parameters
{
get
{
return this.parameters;
}
}
public CodeUser User
{
get
{
return this.user;
}
}
}
/// <summary>
/// This class is only for use with the VB code generation.
/// </summary>
public class CodeParameters
{
private readonly Report report;
public CodeParameters(Report report)
{
this.report = report;
}
public object this[string key]
{
get
{
foreach (UserReportParameter p in report.UserReportParameters)
{
if (p.Name.Equals(key))
{
return p;
}
}
return null;
}
}
}
/// <summary>
/// This class is only for use with the VB code generation.
/// </summary>
public class CodeUser
{
private readonly Report report;
public CodeUser(Report report)
{
this.report = report;
}
public object this[string key]
{
get
{
switch (key.ToLower())
{
case "userid":
return report.UserID;
case "language":
return report.ClientLanguage;
}
return null;
}
}
public string Language
{
get
{
return report.ClientLanguage;
}
}
public string UserID
{
get
{
return report.UserID;
}
}
}
/// <summary>
/// This class is only for use with the VB code generation.
/// </summary>
public class CodeGlobals
{
private readonly Report report;
public CodeGlobals(Report report)
{
this.report = report;
}
public object this[string key]
{
get
{
switch (key.ToLower())
{
case "pagenumber":
return report.PageNumber;
case "totalpages":
return report.TotalPages;
case "executiontime":
return report.ExecutionTime;
case "reportfolder":
return report.Folder;
case "reportname":
return report.Name;
}
return null;
}
}
public DateTime ExecutionTime
{
get
{
return report.ExecutionTime;
}
}
public int PageNumber
{
get
{
return report.PageNumber;
}
}
public string ReportFolder
{
get
{
return report.Folder;
}
}
public string ReportName
{
get
{
return report.Name;
}
}
public int TotalPages
{
get
{
return report.TotalPages;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Grauenwolf.TravellerTools.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Apache.Geode.Client.FwkLib
{
using Apache.Geode.Client.Tests;
using Apache.Geode.DUnitFramework;
public class Security : PerfTests
{
#region Protected constants
protected const string EntryCount = "entryCount";
protected const string WorkTime = "workTime";
protected const string ObjectType = "objectType";
protected const string EntryOps = "entryOps";
protected const string LargeSetQuery = "largeSetQuery";
protected const string UnsupportedPRQuery = "unsupportedPRQuery";
#endregion
#region Utility methods
private CacheableKey GetKey(int max)
{
ResetKey(ObjectType);
string objectType = GetStringValue(ObjectType);
QueryHelper qh = QueryHelper.GetHelper();
int numSet = 0;
int setSize = 0;
if (objectType != null && objectType == "Portfolio")
{
setSize = qh.PortfolioSetSize;
numSet = max / setSize;
return new CacheableString(String.Format("port{0}-{1}",
Util.Rand(numSet), Util.Rand(setSize)));
}
else if (objectType != null && objectType == "Position")
{
setSize = qh.PositionSetSize;
numSet = max / setSize;
return new CacheableString(String.Format("pos{0}-{1}",
Util.Rand(numSet), Util.Rand(setSize)));
}
else
{
return m_keysA[Util.Rand(m_maxKeys)];
}
}
private IGeodeSerializable GetUserObject(string objType)
{
IGeodeSerializable usrObj = null;
ResetKey(EntryCount);
int numOfKeys = GetUIntValue(EntryCount);
ResetKey(ValueSizes);
int objSize = GetUIntValue(ValueSizes);
QueryHelper qh = QueryHelper.GetHelper();
int numSet = 0;
int setSize = 0;
if (objType != null && objType == "Portfolio")
{
setSize = qh.PortfolioSetSize;
numSet = numOfKeys / setSize;
usrObj = new Portfolio(Util.Rand(setSize), objSize);
}
else if (objType != null && objType == "Position")
{
setSize = qh.PositionSetSize;
numSet = numOfKeys / setSize;
int numSecIds = Portfolio.SecIds.Length;
usrObj = new Position(Portfolio.SecIds[setSize % numSecIds], setSize * 100);
}
return usrObj;
}
private bool AllowQuery(QueryCategory category, bool haveLargeResultset,
bool islargeSetQuery, bool isUnsupportedPRQuery)
{
if (category == QueryCategory.Unsupported)
{
return false;
}
else if (haveLargeResultset != islargeSetQuery)
{
return false;
}
else if (isUnsupportedPRQuery &&
((category == QueryCategory.MultiRegion) ||
(category == QueryCategory.NestedQueries)))
{
return false;
}
else
{
return true;
}
}
private void RunQuery(ref int queryCnt)
{
FwkInfo("In Security.RunQuery");
try
{
ResetKey(EntryCount);
int numOfKeys = GetUIntValue(EntryCount);
QueryHelper qh = QueryHelper.GetHelper();
int setSize = qh.PortfolioSetSize;
if (numOfKeys < setSize)
{
setSize = numOfKeys;
}
int index = Util.Rand(QueryStrings.RSsize);
DateTime startTime;
DateTime endTime;
TimeSpan elapsedTime;
QueryService qs = CacheHelper.DCache.GetQueryService();
ResetKey(LargeSetQuery);
ResetKey(UnsupportedPRQuery);
bool isLargeSetQuery = GetBoolValue(LargeSetQuery);
bool isUnsupportedPRQuery = GetBoolValue(UnsupportedPRQuery);
QueryStrings currentQuery = QueryStatics.ResultSetQueries[index];
if (AllowQuery(currentQuery.Category, currentQuery.IsLargeResultset,
isLargeSetQuery, isUnsupportedPRQuery))
{
string query = currentQuery.Query;
FwkInfo("Security.RunQuery: ResultSet Query Category [{0}], " +
"String [{1}].", currentQuery.Category, query);
Query qry = qs.NewQuery(query);
startTime = DateTime.Now;
ISelectResults results = qry.Execute(600);
endTime = DateTime.Now;
elapsedTime = endTime - startTime;
FwkInfo("Security.RunQuery: Time Taken to execute" +
" the query [{0}]: {1}ms", query, elapsedTime.TotalMilliseconds);
++queryCnt;
}
index = Util.Rand(QueryStrings.SSsize);
currentQuery = QueryStatics.StructSetQueries[index];
if (AllowQuery(currentQuery.Category, currentQuery.IsLargeResultset,
isLargeSetQuery, isUnsupportedPRQuery))
{
string query = currentQuery.Query;
FwkInfo("Security.RunQuery: StructSet Query Category [{0}], " +
"String [{1}].", currentQuery.Category, query);
Query qry = qs.NewQuery(query);
startTime = DateTime.Now;
ISelectResults results = qry.Execute(600);
endTime = DateTime.Now;
elapsedTime = endTime - startTime;
FwkInfo("Security.RunQuery: Time Taken to execute" +
" the query [{0}]: {1}ms", query, elapsedTime.TotalMilliseconds);
++queryCnt;
}
}
catch (Exception ex)
{
FwkException("Security.RunQuery: Caught Exception: {0}", ex);
}
FwkInfo("Security.RunQuery complete.");
}
#endregion
#region Public methods
public new void DoRegisterInterestList()
{
FwkInfo("In DoRegisterInterestList()");
try
{
Region region = GetRegion();
int numKeys = GetUIntValue(DistinctKeys); // check distince keys first
if (numKeys <= 0)
{
FwkSevere("DoRegisterInterestList() Failed to initialize keys " +
"with numKeys: {0}", numKeys);
return;
}
int low = GetUIntValue(KeyIndexBegin);
low = (low > 0) ? low : 0;
int numOfRegisterKeys = GetUIntValue(RegisterKeys);
int high = numOfRegisterKeys + low;
ClearKeys();
m_maxKeys = numOfRegisterKeys;
m_keyIndexBegin = low;
int keySize = GetUIntValue(KeySize);
keySize = (keySize > 0) ? keySize : 10;
string keyBase = new string('A', keySize);
InitStrKeys(low, high, keyBase);
FwkInfo("DoRegisterInterestList() registering interest for {0} to {1}",
low, high);
CacheableKey[] registerKeyList = new CacheableKey[high - low];
for (int j = low; j < high; j++)
{
if (m_keysA[j - low] != null)
{
registerKeyList[j - low] = m_keysA[j - low];
}
else
{
FwkInfo("DoRegisterInterestList() key[{0}] is null.", (j - low));
}
}
FwkInfo("DoRegisterInterestList() region name is {0}", region.Name);
region.RegisterKeys(registerKeyList);
}
catch (Exception ex)
{
FwkException("DoRegisterInterestList() Caught Exception: {0}", ex);
}
FwkInfo("DoRegisterInterestList() complete.");
}
public void DoEntryOperations()
{
FwkInfo("DoEntryOperations called.");
int opsSec = GetUIntValue(OpsSecond);
opsSec = (opsSec < 1) ? 0 : opsSec;
int entryCount = GetUIntValue(EntryCount);
entryCount = (entryCount < 1) ? 10000 : entryCount;
int secondsToRun = GetTimeValue(WorkTime);
secondsToRun = (secondsToRun < 1) ? 30 : secondsToRun;
int valSize = GetUIntValue(ValueSizes);
valSize = ((valSize < 0) ? 32 : valSize);
DateTime now = DateTime.Now;
DateTime end = now + TimeSpan.FromSeconds(secondsToRun);
byte[] valBuf = Encoding.ASCII.GetBytes(new string('A', valSize));
string opcode = null;
int creates = 0, puts = 0, gets = 0, dests = 0, invals = 0, queries = 0;
Region region = GetRegion();
if (region == null)
{
FwkSevere("Security.DoEntryOperations: No region to perform operations on.");
now = end; // Do not do the loop
}
FwkInfo("DoEntryOperations will work for {0} secs using {1} byte values.", secondsToRun, valSize);
CacheableKey key;
IGeodeSerializable value;
IGeodeSerializable tmpValue;
PaceMeter meter = new PaceMeter(opsSec);
string objectType = GetStringValue(ObjectType);
while (now < end)
{
try
{
opcode = GetStringValue(EntryOps);
if (opcode == null || opcode.Length == 0) opcode = "no-op";
if (opcode == "add")
{
key = GetKey(entryCount);
if (objectType != null && objectType.Length > 0)
{
tmpValue = GetUserObject(objectType);
}
else
{
tmpValue = CacheableBytes.Create(valBuf);
}
region.Create(key, tmpValue);
creates++;
}
else
{
key = GetKey(entryCount);
if (opcode == "update")
{
if (objectType != null && objectType.Length > 0)
{
tmpValue = GetUserObject(objectType);
}
else
{
int keyVal = int.Parse(key.ToString());
int val = BitConverter.ToInt32(valBuf, 0);
val = (val == keyVal) ? keyVal + 1 : keyVal; // alternate the value so that it can be validated later.
BitConverter.GetBytes(val).CopyTo(valBuf, 0);
BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(valBuf, 4);
tmpValue = CacheableBytes.Create(valBuf);
}
region.Put(key, tmpValue);
puts++;
}
else if (opcode == "invalidate")
{
region.Invalidate(key);
invals++;
}
else if (opcode == "destroy")
{
region.Destroy(key);
dests++;
}
else if (opcode == "read")
{
value = region.Get(key);
gets++;
}
else if (opcode == "read+localdestroy")
{
value = region.Get(key);
gets++;
region.LocalDestroy(key);
dests++;
}
else if (opcode == "query")
{
RunQuery(ref queries);
}
else
{
FwkSevere("Invalid operation specified: {0}", opcode);
}
}
}
catch (TimeoutException ex)
{
FwkSevere("Security: Caught unexpected timeout exception during entry " +
"{0} operation; continuing with the test: {1}", opcode, ex);
}
catch (EntryExistsException)
{
}
catch (EntryNotFoundException)
{
}
catch (EntryDestroyedException)
{
}
catch (Exception ex)
{
end = DateTime.Now;
FwkException("Security: Caught unexpected exception during entry " +
"{0} operation; exiting task: {1}", opcode, ex);
}
meter.CheckPace();
now = DateTime.Now;
}
FwkInfo("DoEntryOperations did {0} creates, {1} puts, {2} gets, " +
"{3} invalidates, {4} destroys, {5} queries.", creates, puts, gets,
invals, dests, queries);
}
public void DoEntryOperationsMU()
{
FwkInfo("DoEntryOperations called.");
int opsSec = GetUIntValue(OpsSecond);
opsSec = (opsSec < 1) ? 0 : opsSec;
int entryCount = GetUIntValue(EntryCount);
entryCount = (entryCount < 1) ? 10000 : entryCount;
int secondsToRun = GetTimeValue(WorkTime);
secondsToRun = (secondsToRun < 1) ? 30 : secondsToRun;
int valSize = GetUIntValue(ValueSizes);
valSize = ((valSize < 0) ? 32 : valSize);
DateTime now = DateTime.Now;
DateTime end = now + TimeSpan.FromSeconds(secondsToRun);
byte[] valBuf = Encoding.ASCII.GetBytes(new string('A', valSize));
string opcode = null;
int creates = 0, puts = 0, gets = 0, dests = 0, invals = 0, queries = 0;
Region region = GetRegion();
if (region == null)
{
FwkSevere("Security.DoEntryOperations: No region to perform operations on.");
now = end; // Do not do the loop
}
FwkInfo("DoEntryOperations will work for {0} secs using {1} byte values.", secondsToRun, valSize);
CacheableKey key;
IGeodeSerializable value;
IGeodeSerializable tmpValue;
PaceMeter meter = new PaceMeter(opsSec);
string objectType = GetStringValue(ObjectType);
while (now < end)
{
try
{
opcode = GetStringValue(EntryOps);
if (opcode == null || opcode.Length == 0) opcode = "no-op";
if (opcode == "add")
{
key = GetKey(entryCount);
if (objectType != null && objectType.Length > 0)
{
tmpValue = GetUserObject(objectType);
}
else
{
tmpValue = CacheableBytes.Create(valBuf);
}
region.Create(key, tmpValue);
creates++;
}
else
{
key = GetKey(entryCount);
if (opcode == "update")
{
if (objectType != null && objectType.Length > 0)
{
tmpValue = GetUserObject(objectType);
}
else
{
int keyVal = int.Parse(key.ToString());
int val = BitConverter.ToInt32(valBuf, 0);
val = (val == keyVal) ? keyVal + 1 : keyVal; // alternate the value so that it can be validated later.
BitConverter.GetBytes(val).CopyTo(valBuf, 0);
BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(valBuf, 4);
tmpValue = CacheableBytes.Create(valBuf);
}
region.Put(key, tmpValue);
puts++;
}
else if (opcode == "invalidate")
{
region.Invalidate(key);
invals++;
}
else if (opcode == "destroy")
{
region.Destroy(key);
dests++;
}
else if (opcode == "read")
{
value = region.Get(key);
gets++;
}
else if (opcode == "read+localdestroy")
{
value = region.Get(key);
gets++;
region.LocalDestroy(key);
dests++;
}
else if (opcode == "query")
{
RunQuery(ref queries);
}
else
{
FwkSevere("Invalid operation specified: {0}", opcode);
}
}
}
catch (TimeoutException ex)
{
FwkSevere("Security: Caught unexpected timeout exception during entry " +
"{0} operation; continuing with the test: {1}", opcode, ex);
}
catch (EntryExistsException)
{
}
catch (EntryNotFoundException)
{
}
catch (EntryDestroyedException)
{
}
catch (Exception ex)
{
end = DateTime.Now;
FwkException("Security: Caught unexpected exception during entry " +
"{0} operation; exiting task: {1}", opcode, ex);
}
meter.CheckPace();
now = DateTime.Now;
}
FwkInfo("DoEntryOperations did {0} creates, {1} puts, {2} gets, " +
"{3} invalidates, {4} destroys, {5} queries.", creates, puts, gets,
invals, dests, queries);
}
#endregion
}
}
| |
/*
Copyright 2019 Esri
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.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
namespace Symbology
{
internal class SymbologyPaneViewModel : DockPane
{
private const string _dockPaneID = "Symbology_SymbologyPane";
private static readonly object LockStyleItems = new object();
protected SymbologyPaneViewModel()
{
BindingOperations.EnableCollectionSynchronization(MyCustomStyleItems, LockStyleItems);
lock (LockStyleItems)
{
MyCustomStyleItems.Clear();
}
SelectedGeometry = SymbolGeometries.FirstOrDefault();
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
CreateStyleProjectItem();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
}
#region Public properties
/// <summary>
/// Text shown near the top of the DockPane.
/// </summary>
private string _heading = "Custom Symbols";
public string Heading
{
get { return _heading; }
set
{
SetProperty(ref _heading, value, () => Heading);
}
}
private ObservableCollection<CustomSymbolStyleItem> _myCustomStyleItems = new ObservableCollection<CustomSymbolStyleItem>();
/// <summary>
/// Collection of Symbol Items.
/// </summary>
public ObservableCollection<CustomSymbolStyleItem> MyCustomStyleItems
{
get
{
return _myCustomStyleItems;
}
set
{
SetProperty(ref _myCustomStyleItems, value, () => MyCustomStyleItems);
}
}
private ObservableCollection<string> _symbolGeometries = new ObservableCollection<string>
{
"Point",
"Line",
"Polygon",
"Mesh"
};
/// <summary>
/// Collection of available symbol geometries
/// </summary>
public ObservableCollection<string> SymbolGeometries
{
get
{
return _symbolGeometries;
}
set { SetProperty(ref _symbolGeometries, value, () => SymbolGeometries); }
}
private string _selectedGeometry;
/// <summary>
/// The selected symbol geometry type
/// </summary>
public string SelectedGeometry
{
get
{
//Initialize(); This crashes
return _selectedGeometry;
}
set
{
SetProperty(ref _selectedGeometry, value, () => SelectedGeometry);
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Initialize();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
}
public StyleItemType styleItemType = StyleItemType.PointSymbol;
#endregion
#region private methods and properties
private IDictionary<GeometryType, string> _geometriesDictionary = new Dictionary<GeometryType, string>
{
{ GeometryType.Point, "Point" },
{ GeometryType.Polyline, "Line"},
{GeometryType.Polygon, "Polygon" },
{GeometryType.Multipatch, "Mesh" }
};
private static string _styleFilePath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\AppData\Roaming\ESRI\ArcGISPro\MyCustomSymbols.stylx";
private static StyleProjectItem _styleProjectItem = null;
/// <summary>
/// Initialize the list box with the symbol items
/// </summary>
/// <returns></returns>
private async Task Initialize()
{
lock (LockStyleItems)
{
MyCustomStyleItems.Clear();
}
var myGeometryTypeKey = _geometriesDictionary.FirstOrDefault(x => x.Value == SelectedGeometry).Key;
var symbolsMapping = await GetSymbolDataMapping(myGeometryTypeKey);
foreach (var symbol in symbolsMapping)
{
var symbolStyleItem = await CreateSymbolStyleItem(symbol.Key, symbol.Value); //define the symbol
lock (LockStyleItems)
{
MyCustomStyleItems.Add(new CustomSymbolStyleItem(symbolStyleItem, symbol.Value));
}
//Add styleItem to StyleProject Item
bool styleItemExists = await DoesStyleItemExists(symbolStyleItem.ItemType, symbol.Value);
if ((styleItemExists == false) && (_styleProjectItem != null))
await AddStyleItemToStyle(_styleProjectItem, symbolStyleItem);
}
}
/// <summary>
/// Creates a SymbolStyleItem from a symbol
/// </summary>
/// <param name="symbol"></param>
/// <param name="data"></param>
/// <returns></returns>
private Task<SymbolStyleItem> CreateSymbolStyleItem(CIMSymbol symbol, string data)
{
var symbolStyleItem = QueuedTask.Run(() =>
{
SymbolStyleItem sItem = null;
try
{
sItem = new SymbolStyleItem() //define the symbol
{
Symbol = symbol,
ItemType = styleItemType,
//Category = "Shapes",
Name = data,
Key = data,
Tags = data,
};
}
catch (Exception )
{
}
return sItem;
});
return symbolStyleItem;
}
/// <summary>
/// Gets all the symbols available for a particular geometry
/// </summary>
/// <param name="geometry"></param>
/// <returns></returns>
private async Task<Dictionary<CIMSymbol, string>> GetSymbolDataMapping(GeometryType geometry)
{
var myDictionary = new Dictionary<CIMSymbol, string>();
switch (geometry)
{
case GeometryType.Point:
styleItemType = StyleItemType.PointSymbol;
myDictionary = await MyPointSymbology.GetAllPointSymbolsAsync();
break;
case GeometryType.Polygon:
styleItemType = StyleItemType.PolygonSymbol;
myDictionary = await MyPolygonSymbology.GetAllPolygonSymbolsAsync();
break;
case GeometryType.Polyline:
styleItemType = StyleItemType.LineSymbol;
myDictionary = await MyLineSymbology.GetAllLineSymbolsAsync();
break;
case GeometryType.Multipatch:
styleItemType = StyleItemType.MeshSymbol;
myDictionary = await MeshSymbology.GetAll3DSymbolsAsync();
break;
}
return myDictionary;
}
/// <summary>
/// Create a styleProject item.
/// </summary>
/// <returns></returns>
private static async Task CreateStyleProjectItem()
{
if (_styleProjectItem?.PhysicalPath == null)
{
await QueuedTask.Run(() =>
{
if (File.Exists(_styleFilePath)) //check if the file is on disc. Add it to the project if it is.
Project.Current.AddStyle(_styleFilePath);
else //else create the style item
{
if (_styleProjectItem != null)
Project.Current.RemoveStyle(_styleProjectItem.Name); //remove style from project
Project.Current.CreateStyle($@"{_styleFilePath}");
}
});
var styleItemsContainer = Project.Current.GetItems<StyleProjectItem>(); //gets all Style Project Items in the current project
_styleProjectItem = styleItemsContainer.FirstOrDefault(s => s.Name.Contains("MyCustomSymbols"));
}
}
/// <summary>
/// Adds a styleitem to a style.
/// </summary>
/// <param name="styleProjectItem"></param>
/// <param name="cimSymbolStyleItem"></param>
/// <returns></returns>
private Task AddStyleItemToStyle(StyleProjectItem styleProjectItem, SymbolStyleItem cimSymbolStyleItem)
{
return QueuedTask.Run(() =>
{
if (styleProjectItem == null || cimSymbolStyleItem == null)
{
return;
}
try
{
styleProjectItem.AddItem(cimSymbolStyleItem);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine($@"Error in AddStyleItemToStyle: {ex.ToString()}");
}
});
}
public Task<bool> DoesStyleItemExists(StyleItemType styleItemType, string key)
{
var styleItemExists = QueuedTask.Run(() =>
{
bool styleItem = false;
//Search for a specific point symbol in style
SymbolStyleItem item = (SymbolStyleItem)_styleProjectItem?.LookupItem(styleItemType, key);
if (item == null)
styleItem = false;
else
styleItem = true;
return styleItem;
});
return styleItemExists;
}
#endregion
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class SymbologyPane_ShowButton : Button
{
protected override void OnClick()
{
SymbologyPaneViewModel.Show();
}
}
}
| |
using System;
using System.Text;
using Xunit;
namespace System.Text.EncodingTests
{
//System.Test.UnicodeEncoding.GetBytes(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32)
public class UnicodeEncodingGetBytes1
{
#region Positive Tests
// PosTest1:Invoke the method
[Fact]
public void PosTest1()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
actualValue = uEncoding.GetBytes(chars, 0, 10, bytes, 5);
Assert.Equal(20, actualValue);
}
// PosTest2:Invoke the method and set charCount as 1 and byteIndex as 0
[Fact]
public void PosTest2()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
actualValue = uEncoding.GetBytes(chars, 0, 1, bytes, 0);
Assert.Equal(2, actualValue);
}
// PosTest3:Invoke the method and set charIndex as 20
[Fact]
public void PosTest3()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 20);
Assert.Equal(0, actualValue);
}
#endregion
#region Negative Tests
// NegTest1:Invoke the method and set chars as null
[Fact]
public void NegTest1()
{
Char[] chars = null;
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentNullException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 0);
});
}
// NegTest2:Invoke the method and set bytes as null
[Fact]
public void NegTest2()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = null;
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentNullException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 0);
});
}
// NegTest3:Invoke the method and the destination buffer is not enough
[Fact]
public void NegTest3()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 10, bytes, 15);
});
}
// NegTest4:Invoke the method and the destination buffer is not enough
[Fact]
public void NegTest4()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[10];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 10, bytes, 0);
});
}
// NegTest5:Invoke the method and set charIndex as -1
[Fact]
public void NegTest5()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, -1, 1, bytes, 0);
});
}
// NegTest6:Invoke the method and set charIndex as 15
[Fact]
public void NegTest6()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 15, 1, bytes, 0);
});
}
// NegTest7:Invoke the method and set charCount as -1
[Fact]
public void NegTest7()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, -1, bytes, 0);
});
}
// NegTest8:Invoke the method and set charCount as 12
[Fact]
public void NegTest8()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 12, bytes, 0);
});
}
// NegTest9:Invoke the method and set byteIndex as -1
[Fact]
public void NegTest9()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[30];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 1, bytes, -1);
});
}
// NegTest10:Invoke the method and set charIndex as 21
[Fact]
public void NegTest10()
{
Char[] chars = GetCharArray(10);
Byte[] bytes = new Byte[20];
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
actualValue = uEncoding.GetBytes(chars, 0, 0, bytes, 21);
});
}
#endregion
#region Helper Methods
//Create a None-Surrogate-Char Array.
public Char[] GetCharArray(int length)
{
if (length <= 0) return new Char[] { };
Char[] charArray = new Char[length];
int i = 0;
while (i < length)
{
Char temp = TestLibrary.Generator.GetChar(-55);
if (!Char.IsSurrogate(temp))
{
charArray[i] = temp;
i++;
}
}
return charArray;
}
//Convert Char Array to String
public String ToString(Char[] chars)
{
String str = "{";
for (int i = 0; i < chars.Length; i++)
{
str = str + @"\u" + String.Format("{0:X04}", (int)chars[i]);
if (i != chars.Length - 1) str = str + ",";
}
str = str + "}";
return str;
}
#endregion
}
}
| |
using System.Collections.Generic;
using FarseerPhysics.Samples.DrawingSystem;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
namespace FarseerPhysics.Samples.ScreenSystem
{
/// <summary>
/// The screen manager is a component which manages one or more GameScreen
/// instances. It maintains a stack of screens, calls their Update and Draw
/// methods at the appropriate times, and automatically routes input to the
/// topmost active screen.
/// </summary>
public class ScreenManager : DrawableGameComponent
{
private InputHelper _input;
private bool _isInitialized;
private List<GameScreen> _screens;
private List<GameScreen> _screensToUpdate;
private List<RenderTarget2D> _transitions;
/// <summary>
/// Constructs a new screen manager component.
/// </summary>
public ScreenManager(Game game)
: base(game)
{
// we must set EnabledGestures before we can query for them, but
// we don't assume the game wants to read them.
TouchPanel.EnabledGestures = GestureType.None;
Content = game.Content;
Content.RootDirectory = "Content";
_input = new InputHelper(this);
_screens = new List<GameScreen>();
_screensToUpdate = new List<GameScreen>();
_transitions = new List<RenderTarget2D>();
}
/// <summary>
/// A default SpriteBatch shared by all the screens. This saves
/// each screen having to bother creating their own local instance.
/// </summary>
public SpriteBatch SpriteBatch { get; private set; }
public LineBatch LineBatch { get; private set; }
public ContentManager Content { get; private set; }
public SpriteFonts Fonts { get; private set; }
public AssetCreator Assets { get; private set; }
/// <summary>
/// Initializes the screen manager component.
/// </summary>
public override void Initialize()
{
Fonts = new SpriteFonts(Content);
base.Initialize();
_isInitialized = true;
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
SpriteBatch = new SpriteBatch(GraphicsDevice);
LineBatch = new LineBatch(GraphicsDevice);
Assets = new AssetCreator(GraphicsDevice);
Assets.LoadContent(Content);
_input.LoadContent();
// Tell each of the screens to load their content.
foreach (GameScreen screen in _screens)
{
screen.LoadContent();
}
}
/// <summary>
/// Unload your graphics content.
/// </summary>
protected override void UnloadContent()
{
// Tell each of the screens to unload their content.
foreach (GameScreen screen in _screens)
{
screen.UnloadContent();
}
}
/// <summary>
/// Allows each screen to run logic.
/// </summary>
public override void Update(GameTime gameTime)
{
// Read the keyboard and gamepad.
_input.Update(gameTime);
// Make a copy of the master screen list, to avoid confusion if
// the process of updating one screen adds or removes others.
_screensToUpdate.Clear();
foreach (GameScreen screen in _screens)
{
_screensToUpdate.Add(screen);
}
bool otherScreenHasFocus = !Game.IsActive;
bool coveredByOtherScreen = false;
// Loop as long as there are screens waiting to be updated.
while (_screensToUpdate.Count > 0)
{
// Pop the topmost screen off the waiting list.
GameScreen screen = _screensToUpdate[_screensToUpdate.Count - 1];
_screensToUpdate.RemoveAt(_screensToUpdate.Count - 1);
// Update the screen.
screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
if (screen.ScreenState == ScreenState.TransitionOn || screen.ScreenState == ScreenState.Active)
{
// If this is the first active screen we came across,
// give it a chance to handle input.
if (!otherScreenHasFocus)
{
_input.ShowCursor = screen.HasCursor;
_input.EnableVirtualStick = screen.HasVirtualStick;
screen.HandleInput(_input, gameTime);
otherScreenHasFocus = true;
}
// If this is an active non-popup, inform any subsequent
// screens that they are covered by it.
if (!screen.IsPopup)
coveredByOtherScreen = true;
}
}
}
/// <summary>
/// Tells each screen to draw itself.
/// </summary>
public override void Draw(GameTime gameTime)
{
int transitionCount = 0;
foreach (GameScreen screen in _screens)
{
if (screen.ScreenState == ScreenState.TransitionOn ||
screen.ScreenState == ScreenState.TransitionOff)
{
++transitionCount;
if (_transitions.Count < transitionCount)
{
PresentationParameters _pp = GraphicsDevice.PresentationParameters;
_transitions.Add(new RenderTarget2D(GraphicsDevice, _pp.BackBufferWidth, _pp.BackBufferHeight, false, SurfaceFormat.Color, _pp.DepthStencilFormat, _pp.MultiSampleCount, RenderTargetUsage.DiscardContents));
}
GraphicsDevice.SetRenderTarget(_transitions[transitionCount - 1]);
GraphicsDevice.Clear(Color.Transparent);
screen.Draw(gameTime);
GraphicsDevice.SetRenderTarget(null);
}
}
GraphicsDevice.Clear(Color.Black);
transitionCount = 0;
foreach (GameScreen screen in _screens)
{
if (screen.ScreenState == ScreenState.Hidden)
continue;
if (screen.ScreenState == ScreenState.TransitionOn || screen.ScreenState == ScreenState.TransitionOff)
{
SpriteBatch.Begin(0, BlendState.AlphaBlend);
SpriteBatch.Draw(_transitions[transitionCount], Vector2.Zero, Color.White * screen.TransitionAlpha);
SpriteBatch.End();
++transitionCount;
}
else
screen.Draw(gameTime);
}
_input.Draw();
}
/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public void AddScreen(GameScreen screen)
{
screen.ScreenManager = this;
screen.IsExiting = false;
// If we have a graphics device, tell the screen to load content.
if (_isInitialized)
screen.LoadContent();
_screens.Add(screen);
// update the TouchPanel to respond to gestures this screen is interested in
TouchPanel.EnabledGestures = screen.EnabledGestures;
}
/// <summary>
/// Removes a screen from the screen manager. You should normally
/// use GameScreen.ExitScreen instead of calling this directly, so
/// the screen can gradually transition off rather than just being
/// instantly removed.
/// </summary>
public void RemoveScreen(GameScreen screen)
{
// If we have a graphics device, tell the screen to unload content.
if (_isInitialized)
screen.UnloadContent();
_screens.Remove(screen);
_screensToUpdate.Remove(screen);
// if there is a screen still in the manager, update TouchPanel
// to respond to gestures that screen is interested in.
if (_screens.Count > 0)
TouchPanel.EnabledGestures = _screens[_screens.Count - 1].EnabledGestures;
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Models;
using System;
using System.Collections.Generic;
namespace IdentityServer4
{
internal static class Constants
{
public const string IdentityServerName = "IdentityServer4";
public const string IdentityServerAuthenticationType = IdentityServerName;
public const string ExternalAuthenticationMethod = "external";
public const string DefaultHashAlgorithm = "SHA256";
public static readonly TimeSpan DefaultCookieTimeSpan = TimeSpan.FromHours(10);
public static readonly TimeSpan DefaultCacheDuration = TimeSpan.FromMinutes(60);
public static readonly List<string> SupportedResponseTypes = new List<string>
{
OidcConstants.ResponseTypes.Code,
OidcConstants.ResponseTypes.Token,
OidcConstants.ResponseTypes.IdToken,
OidcConstants.ResponseTypes.IdTokenToken,
OidcConstants.ResponseTypes.CodeIdToken,
OidcConstants.ResponseTypes.CodeToken,
OidcConstants.ResponseTypes.CodeIdTokenToken
};
public static readonly Dictionary<string, string> ResponseTypeToGrantTypeMapping = new Dictionary<string, string>
{
{ OidcConstants.ResponseTypes.Code, GrantType.AuthorizationCode },
{ OidcConstants.ResponseTypes.Token, GrantType.Implicit },
{ OidcConstants.ResponseTypes.IdToken, GrantType.Implicit },
{ OidcConstants.ResponseTypes.IdTokenToken, GrantType.Implicit },
{ OidcConstants.ResponseTypes.CodeIdToken, GrantType.Hybrid },
{ OidcConstants.ResponseTypes.CodeToken, GrantType.Hybrid },
{ OidcConstants.ResponseTypes.CodeIdTokenToken, GrantType.Hybrid }
};
public static readonly List<string> AllowedGrantTypesForAuthorizeEndpoint = new List<string>
{
GrantType.AuthorizationCode,
GrantType.Implicit,
GrantType.Hybrid
};
public static readonly List<string> SupportedCodeChallengeMethods = new List<string>
{
OidcConstants.CodeChallengeMethods.Plain,
OidcConstants.CodeChallengeMethods.Sha256
};
public enum ScopeRequirement
{
None,
ResourceOnly,
IdentityOnly,
Identity
}
public static readonly Dictionary<string, ScopeRequirement> ResponseTypeToScopeRequirement = new Dictionary<string, ScopeRequirement>
{
{ OidcConstants.ResponseTypes.Code, ScopeRequirement.None },
{ OidcConstants.ResponseTypes.Token, ScopeRequirement.ResourceOnly },
{ OidcConstants.ResponseTypes.IdToken, ScopeRequirement.IdentityOnly },
{ OidcConstants.ResponseTypes.IdTokenToken, ScopeRequirement.Identity },
{ OidcConstants.ResponseTypes.CodeIdToken, ScopeRequirement.Identity },
{ OidcConstants.ResponseTypes.CodeToken, ScopeRequirement.Identity },
{ OidcConstants.ResponseTypes.CodeIdTokenToken, ScopeRequirement.Identity }
};
public static readonly Dictionary<string, IEnumerable<string>> AllowedResponseModesForGrantType = new Dictionary<string, IEnumerable<string>>
{
{ GrantType.AuthorizationCode, new[] { OidcConstants.ResponseModes.Query, OidcConstants.ResponseModes.FormPost, OidcConstants.ResponseModes.Fragment } },
{ GrantType.Hybrid, new[] { OidcConstants.ResponseModes.Fragment, OidcConstants.ResponseModes.FormPost }},
{ GrantType.Implicit, new[] { OidcConstants.ResponseModes.Fragment, OidcConstants.ResponseModes.FormPost }}
};
public static readonly List<string> SupportedResponseModes = new List<string>
{
OidcConstants.ResponseModes.FormPost,
OidcConstants.ResponseModes.Query,
OidcConstants.ResponseModes.Fragment
};
public static string[] SupportedSubjectTypes =
{
"pairwise", "public"
};
public static class SigningAlgorithms
{
public const string RSA_SHA_256 = "RS256";
}
public static readonly List<string> SupportedDisplayModes = new List<string>
{
OidcConstants.DisplayModes.Page,
OidcConstants.DisplayModes.Popup,
OidcConstants.DisplayModes.Touch,
OidcConstants.DisplayModes.Wap
};
public static readonly List<string> SupportedPromptModes = new List<string>
{
OidcConstants.PromptModes.None,
OidcConstants.PromptModes.Login,
OidcConstants.PromptModes.Consent,
OidcConstants.PromptModes.SelectAccount
};
public static class KnownAcrValues
{
public const string HomeRealm = "idp:";
public const string Tenant = "tenant:";
public static readonly string[] All = { HomeRealm, Tenant };
}
public static Dictionary<string, int> ProtectedResourceErrorStatusCodes = new Dictionary<string, int>
{
{ OidcConstants.ProtectedResourceErrors.InvalidToken, 401 },
{ OidcConstants.ProtectedResourceErrors.ExpiredToken, 401 },
{ OidcConstants.ProtectedResourceErrors.InvalidRequest, 400 },
{ OidcConstants.ProtectedResourceErrors.InsufficientScope, 403 }
};
public static readonly Dictionary<string, IEnumerable<string>> ScopeToClaimsMapping = new Dictionary<string, IEnumerable<string>>
{
{ IdentityServerConstants.StandardScopes.Profile, new[]
{
JwtClaimTypes.Name,
JwtClaimTypes.FamilyName,
JwtClaimTypes.GivenName,
JwtClaimTypes.MiddleName,
JwtClaimTypes.NickName,
JwtClaimTypes.PreferredUserName,
JwtClaimTypes.Profile,
JwtClaimTypes.Picture,
JwtClaimTypes.WebSite,
JwtClaimTypes.Gender,
JwtClaimTypes.BirthDate,
JwtClaimTypes.ZoneInfo,
JwtClaimTypes.Locale,
JwtClaimTypes.UpdatedAt
}},
{ IdentityServerConstants.StandardScopes.Email, new[]
{
JwtClaimTypes.Email,
JwtClaimTypes.EmailVerified
}},
{ IdentityServerConstants.StandardScopes.Address, new[]
{
JwtClaimTypes.Address
}},
{ IdentityServerConstants.StandardScopes.Phone, new[]
{
JwtClaimTypes.PhoneNumber,
JwtClaimTypes.PhoneNumberVerified
}},
{ IdentityServerConstants.StandardScopes.OpenId, new[]
{
JwtClaimTypes.Subject
}}
};
public static class UIConstants
{
// the limit after which old messages are purged
public const int CookieMessageThreshold = 2;
public static class DefaultRoutePathParams
{
public const string Error = "errorId";
public const string Login = "returnUrl";
public const string Consent = "returnUrl";
public const string Logout = "logoutId";
public const string EndSessionCallback = "endSessionId";
public const string Custom = "returnUrl";
public const string UserCode = "userCode";
}
public static class DefaultRoutePaths
{
public const string Login = "/account/login";
public const string Logout = "/account/logout";
public const string Consent = "/consent";
public const string Error = "/home/error";
public const string DeviceVerification = "/device";
}
}
public static class EndpointNames
{
public const string Authorize = "Authorize";
public const string Token = "Token";
public const string DeviceAuthorization = "DeviceAuthorization";
public const string Discovery = "Discovery";
public const string Introspection = "Introspection";
public const string Revocation = "Revocation";
public const string EndSession = "Endsession";
public const string CheckSession = "Checksession";
public const string UserInfo = "Userinfo";
}
public static class ProtocolRoutePaths
{
public const string ConnectPathPrefix = "connect";
public const string Authorize = ConnectPathPrefix + "/authorize";
public const string AuthorizeCallback = Authorize + "/callback";
public const string DiscoveryConfiguration = ".well-known/openid-configuration";
public const string DiscoveryWebKeys = DiscoveryConfiguration + "/jwks";
public const string Token = ConnectPathPrefix + "/token";
public const string Revocation = ConnectPathPrefix + "/revocation";
public const string UserInfo = ConnectPathPrefix + "/userinfo";
public const string Introspection = ConnectPathPrefix + "/introspect";
public const string EndSession = ConnectPathPrefix + "/endsession";
public const string EndSessionCallback = EndSession + "/callback";
public const string CheckSession = ConnectPathPrefix + "/checksession";
public const string DeviceAuthorization = ConnectPathPrefix + "/deviceauthorization";
public const string MtlsPathPrefix = ConnectPathPrefix + "/mtls";
public const string MtlsToken = MtlsPathPrefix + "/token";
public const string MtlsRevocation = MtlsPathPrefix + "/revocation";
public const string MtlsIntrospection = MtlsPathPrefix + "/introspect";
public const string MtlsDeviceAuthorization = MtlsPathPrefix + "/deviceauthorization";
public static readonly string[] CorsPaths =
{
DiscoveryConfiguration,
DiscoveryWebKeys,
Token,
UserInfo,
Revocation
};
}
public static class EnvironmentKeys
{
public const string IdentityServerBasePath = "idsvr:IdentityServerBasePath";
[Obsolete("The IdentityServerOrigin constant is obsolete.")]
public const string IdentityServerOrigin = "idsvr:IdentityServerOrigin"; // todo: deprecate
public const string SignOutCalled = "idsvr:IdentityServerSignOutCalled";
}
public static class TokenTypeHints
{
public const string RefreshToken = "refresh_token";
public const string AccessToken = "access_token";
}
public static List<string> SupportedTokenTypeHints = new List<string>
{
TokenTypeHints.RefreshToken,
TokenTypeHints.AccessToken
};
public static class RevocationErrors
{
public const string UnsupportedTokenType = "unsupported_token_type";
}
public class Filters
{
// filter for claims from an incoming access token (e.g. used at the user profile endpoint)
public static readonly string[] ProtocolClaimsFilter = {
JwtClaimTypes.AccessTokenHash,
JwtClaimTypes.Audience,
JwtClaimTypes.AuthorizedParty,
JwtClaimTypes.AuthorizationCodeHash,
JwtClaimTypes.ClientId,
JwtClaimTypes.Expiration,
JwtClaimTypes.IssuedAt,
JwtClaimTypes.Issuer,
JwtClaimTypes.JwtId,
JwtClaimTypes.Nonce,
JwtClaimTypes.NotBefore,
JwtClaimTypes.ReferenceTokenId,
JwtClaimTypes.SessionId,
JwtClaimTypes.Scope
};
// filter list for claims returned from profile service prior to creating tokens
public static readonly string[] ClaimsServiceFilterClaimTypes = {
// TODO: consider JwtClaimTypes.AuthenticationContextClassReference,
JwtClaimTypes.AccessTokenHash,
JwtClaimTypes.Audience,
JwtClaimTypes.AuthenticationMethod,
JwtClaimTypes.AuthenticationTime,
JwtClaimTypes.AuthorizedParty,
JwtClaimTypes.AuthorizationCodeHash,
JwtClaimTypes.ClientId,
JwtClaimTypes.Expiration,
JwtClaimTypes.IdentityProvider,
JwtClaimTypes.IssuedAt,
JwtClaimTypes.Issuer,
JwtClaimTypes.JwtId,
JwtClaimTypes.Nonce,
JwtClaimTypes.NotBefore,
JwtClaimTypes.ReferenceTokenId,
JwtClaimTypes.SessionId,
JwtClaimTypes.Subject,
JwtClaimTypes.Scope,
JwtClaimTypes.Confirmation
};
public static readonly string[] JwtRequestClaimTypesFilter = {
JwtClaimTypes.Audience,
JwtClaimTypes.Expiration,
JwtClaimTypes.IssuedAt,
JwtClaimTypes.Issuer,
JwtClaimTypes.NotBefore,
JwtClaimTypes.JwtId
};
}
public static class WsFedSignOut
{
public const string LogoutUriParameterName = "wa";
public const string LogoutUriParameterValue = "wsignoutcleanup1.0";
}
public static class AuthorizationParamsStore
{
public const string MessageStoreIdParameterName = "authzId";
}
public static class CurveOids
{
public const string P256 = "1.2.840.10045.3.1.7";
public const string P384 = "1.3.132.0.34";
public const string P521 = "1.3.132.0.35";
}
}
}
| |
// 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.Globalization;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetFramework.Analyzers.TypesShouldNotExtendCertainBaseTypesAnalyzer,
Microsoft.NetFramework.CSharp.Analyzers.CSharpTypesShouldNotExtendCertainBaseTypesFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetFramework.Analyzers.TypesShouldNotExtendCertainBaseTypesAnalyzer,
Microsoft.NetFramework.VisualBasic.Analyzers.BasicTypesShouldNotExtendCertainBaseTypesFixer>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public class TypesShouldNotExtendCertainBaseTypesTests
{
[Fact]
public async Task TypesShouldNotExtendCertainBaseTypes_CSharp_NoDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class C : Attribute
{
}
");
}
[Fact]
public async Task TypesShouldNotExtendCertainBaseTypes_CSharp_ApplicationException()
{
var source = @"
using System;
public class C1 : ApplicationException
{
}
";
DiagnosticResult[] expected = new[]
{
GetCSharpApplicationExceptionResultAt(4, 14, "C1", "System.ApplicationException")
};
await VerifyCS.VerifyAnalyzerAsync(source, expected);
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task TypesShouldNotExtendCertainBaseTypes_CSharp_ApplicationException_Internal()
{
var source = @"
using System;
class C1 : ApplicationException
{
}
";
await VerifyCS.VerifyAnalyzerAsync(source);
}
[Fact]
public async Task TypesShouldNotExtendCertainBaseTypes_CSharp_XmlDocument()
{
var source = @"
using System.Xml;
public class C1 : XmlDocument
{
}
";
DiagnosticResult[] expected = new[]
{
GetCSharpXmlDocumentResultAt(4, 14, "C1", "System.Xml.XmlDocument")
};
await VerifyCS.VerifyAnalyzerAsync(source, expected);
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task TypesShouldNotExtendCertainBaseTypes_CSharp_XmlDocument_Internal()
{
var source = @"
using System.Xml;
class C1 : XmlDocument
{
}
";
await VerifyCS.VerifyAnalyzerAsync(source);
}
[Fact]
public async Task TypesShouldNotExtendCertainBaseTypes_CSharp_Collection()
{
var source = @"
using System.Collections;
public class C1 : CollectionBase
{
}
public class C2 : DictionaryBase
{
}
public class C3 : Queue
{
}
public class C4 : ReadOnlyCollectionBase
{
}
public class C5 : SortedList
{
}
public class C6 : Stack
{
}";
DiagnosticResult[] expected = new[]
{
GetCSharpCollectionBaseResultAt(4, 14, "C1", "System.Collections.CollectionBase"),
GetCSharpDictionaryBaseResultAt(8, 14, "C2", "System.Collections.DictionaryBase"),
GetCSharpQueueResultAt(12, 14, "C3", "System.Collections.Queue"),
GetCSharpReadOnlyCollectionResultAt(16, 14, "C4", "System.Collections.ReadOnlyCollectionBase"),
GetCSharpSortedListResultAt(20, 14, "C5", "System.Collections.SortedList"),
GetCSharpStackResultAt(24, 14, "C6", "System.Collections.Stack")
};
await VerifyCS.VerifyAnalyzerAsync(source, expected);
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task TypesShouldNotExtendCertainBaseTypes_CSharp_Collection_Internal()
{
var source = @"
using System.Collections;
class C1 : CollectionBase
{
}
class C2 : DictionaryBase
{
}
class C3 : Queue
{
}
class C4 : ReadOnlyCollectionBase
{
}
internal class C5 : SortedList
{
}
public class C6
{
private class Inner : Stack
{
}
}";
await VerifyCS.VerifyAnalyzerAsync(source);
}
[Fact]
public async Task TypesShouldNotExtendCertainBaseTypes_Basic_NoDiagnostic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class Class2
Inherits Attribute
End Class
");
}
[Fact]
public async Task TypesShouldNotExtendCertainBaseTypes_Basic_ApplicationException()
{
var source = @"
Imports System
Public Class C1
Inherits ApplicationException
End Class
";
DiagnosticResult[] expected = new[]
{
GetBasicApplicationExceptionResultAt(4, 14, "C1", "System.ApplicationException")
};
await VerifyVB.VerifyAnalyzerAsync(source, expected);
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task TypesShouldNotExtendCertainBaseTypes_Basic_ApplicationException_Internal()
{
var source = @"
Imports System
Friend Class C1
Inherits ApplicationException
End Class
";
await VerifyVB.VerifyAnalyzerAsync(source);
}
[Fact]
public async Task TypesShouldNotExtendCertainBaseTypes_Basic_XmlDocument()
{
var source = @"
Imports System.Xml
Public Class C1
Inherits XmlDocument
End Class
";
DiagnosticResult[] expected = new[]
{
GetBasicXmlDocumentResultAt(4, 14, "C1", "System.Xml.XmlDocument")
};
await VerifyVB.VerifyAnalyzerAsync(source, expected);
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task TypesShouldNotExtendCertainBaseTypes_Basic_XmlDocument_Internal()
{
var source = @"
Imports System.Xml
Friend Class C1
Inherits XmlDocument
End Class
";
await VerifyVB.VerifyAnalyzerAsync(source);
}
[Fact]
public async Task TypesShouldNotExtendCertainBaseTypes_Basic_Collection()
{
var source = @"
Imports System.Collections
Public Class C1
Inherits CollectionBase
End Class
Public Class C2
Inherits DictionaryBase
End Class
Public Class C3
Inherits Queue
End Class
Public Class C4
Inherits ReadOnlyCollectionBase
End Class
Public Class C5
Inherits SortedList
End Class
Public Class C6
Inherits Stack
End Class
";
DiagnosticResult[] expected = new[]
{
GetBasicCollectionBaseResultAt(4, 14, "C1", "System.Collections.CollectionBase"),
GetBasicDictionaryBaseResultAt(9, 14, "C2", "System.Collections.DictionaryBase"),
GetBasicQueueResultAt(14, 14, "C3", "System.Collections.Queue"),
GetBasicReadOnlyCollectionBaseResultAt(19, 14, "C4", "System.Collections.ReadOnlyCollectionBase"),
GetBasicSortedListResultAt(24, 14, "C5", "System.Collections.SortedList"),
GetBasicStackResultAt(29, 14, "C6", "System.Collections.Stack")
};
await VerifyVB.VerifyAnalyzerAsync(source, expected);
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task TypesShouldNotExtendCertainBaseTypes_Basic_Collection_Internal()
{
var source = @"
Imports System.Collections
Class C1
Inherits CollectionBase
End Class
Class C2
Inherits DictionaryBase
End Class
Class C3
Inherits Queue
End Class
Class C4
Inherits ReadOnlyCollectionBase
End Class
Friend Class C5
Inherits SortedList
End Class
Public Class C6
Private Class InnerClass
Inherits Stack
End Class
End Class
";
await VerifyVB.VerifyAnalyzerAsync(source);
}
private static DiagnosticResult GetCSharpCollectionBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsCollectionBase, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetBasicCollectionBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsCollectionBase, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetCSharpDictionaryBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsDictionaryBase, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetBasicDictionaryBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsDictionaryBase, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetCSharpQueueResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsQueue, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetBasicQueueResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsQueue, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetCSharpReadOnlyCollectionResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsReadOnlyCollectionBase, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetBasicReadOnlyCollectionBaseResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsReadOnlyCollectionBase, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetCSharpSortedListResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsSortedList, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetBasicSortedListResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsSortedList, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetCSharpStackResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsStack, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetBasicStackResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemCollectionsStack, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetCSharpApplicationExceptionResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemApplicationException, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetBasicApplicationExceptionResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemApplicationException, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetCSharpXmlDocumentResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemXmlXmlDocument, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
private static DiagnosticResult GetBasicXmlDocumentResultAt(int line, int column, string declaredTypeName, string badBaseTypeName)
{
string message = string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.TypesShouldNotExtendCertainBaseTypesMessageSystemXmlXmlDocument, declaredTypeName, badBaseTypeName);
#pragma warning disable RS0030 // Do not used banned APIs
return VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(message);
#pragma warning restore RS0030 // Do not used banned APIs
}
}
}
| |
using System;
using NUnit.Framework;
using SharpVectors.Dom;
using SharpVectors.Dom.Svg;
namespace SharpVectors.UnitTests.Svg.BasicTypesAndInterfaces
{
public class SvgNumberListTests : SvgListTests
{
#region Fields
private static int counter = 0;
#endregion
#region Additional SvgStringList-specific tests
[Test]
public void TestFromStringEmpty()
{
((SvgNumberList) list).FromString("");
Assert.AreEqual(0, list.NumberOfItems);
}
[Test]
public void TestFromStringNull()
{
((SvgNumberList) list).FromString(null);
Assert.AreEqual(0, list.NumberOfItems);
}
[Test]
public void TestFromStringLeadingWhitespace()
{
((SvgNumberList) list).FromString(" 1 2 3 4");
Assert.AreEqual(1, ((SvgNumberList) list).GetItem(0).Value);
Assert.AreEqual(2, ((SvgNumberList) list).GetItem(1).Value);
Assert.AreEqual(3, ((SvgNumberList) list).GetItem(2).Value);
Assert.AreEqual(4, ((SvgNumberList) list).GetItem(3).Value);
}
[Test]
public void TestFromStringTrailingWhitespace()
{
((SvgNumberList) list).FromString("1 2 3 4 ");
Assert.AreEqual(1, ((SvgNumberList) list).GetItem(0).Value);
Assert.AreEqual(2, ((SvgNumberList) list).GetItem(1).Value);
Assert.AreEqual(3, ((SvgNumberList) list).GetItem(2).Value);
Assert.AreEqual(4, ((SvgNumberList) list).GetItem(3).Value);
}
[Test]
public void TestFromStringOneValue()
{
((SvgNumberList) list).FromString("1");
Assert.AreEqual(1, ((SvgNumberList) list).GetItem(0).Value);
}
[Test]
public void TestFromStringSpaceDelimited()
{
((SvgNumberList) list).FromString("1 2 3 4");
Assert.AreEqual(1, ((SvgNumberList) list).GetItem(0).Value);
Assert.AreEqual(2, ((SvgNumberList) list).GetItem(1).Value);
Assert.AreEqual(3, ((SvgNumberList) list).GetItem(2).Value);
Assert.AreEqual(4, ((SvgNumberList) list).GetItem(3).Value);
}
[Test]
public void TestFromStringCommaDelimited()
{
((SvgNumberList) list).FromString("1,2, 3 ,4 , 5");
Assert.AreEqual(1, ((SvgNumberList) list).GetItem(0).Value);
Assert.AreEqual(2, ((SvgNumberList) list).GetItem(1).Value);
Assert.AreEqual(3, ((SvgNumberList) list).GetItem(2).Value);
Assert.AreEqual(4, ((SvgNumberList) list).GetItem(3).Value);
Assert.AreEqual(5, ((SvgNumberList) list).GetItem(4).Value);
}
[Test]
[ExpectedException(typeof(DomException))]
public void TestFromStringMultipleCommas()
{
((SvgNumberList) list).FromString("1,,2");
}
[Test]
[ExpectedException(typeof(DomException))]
public void TestFromStringMultipleCommas2()
{
((SvgNumberList) list).FromString("1, ,2");
}
[Test]
[ExpectedException(typeof(DomException))]
public void TestFromStringMultipleCommas3()
{
((SvgNumberList) list).FromString("1 , ,2");
}
[Test]
[ExpectedException(typeof(DomException))]
public void TestFromStringMultipleCommas4()
{
((SvgNumberList) list).FromString("1 , , 2");
}
[Test]
public void TestFromStringMixed()
{
((SvgNumberList) list).FromString("1 2 3,4 ,5 , 6");
Assert.AreEqual(1, ((SvgNumberList) list).GetItem(0).Value);
Assert.AreEqual(2, ((SvgNumberList) list).GetItem(1).Value);
Assert.AreEqual(3, ((SvgNumberList) list).GetItem(2).Value);
Assert.AreEqual(4, ((SvgNumberList) list).GetItem(3).Value);
Assert.AreEqual(5, ((SvgNumberList) list).GetItem(4).Value);
Assert.AreEqual(6, ((SvgNumberList) list).GetItem(5).Value);
}
#endregion
#region Support Methods
protected override SvgList makeList()
{
return new SvgNumberList();
}
protected new SvgNumber makeItem()
{
return new SvgNumber(counter++);
}
#endregion
}
}
| |
using Sandbox.Common.ObjectBuilders;
using Sandbox.ModAPI;
using VRage.Game.Components;
using VRage.ModAPI;
using VRage.ObjectBuilders;
using VRageMath;
using VRage.Game.Entity;
using VRage.Voxels;
using Draygo.API;
using Sandbox.Game;
using Sandbox.Game.Entities.Blocks;
using System;
using Entities.Blocks;
using Sandbox.ModAPI.Interfaces.Terminal;
using System.Collections.Generic;
using Sandbox.Game.Gui;
using System.Text;
using System.Linq;
using Sandbox.Game.Localization;
using System.Globalization;
using System.Text.RegularExpressions;
using SpaceEngineers.Game.ModAPI;
using VRage.Game;
using VRage.Utils;
namespace DockingAssist
{
[MyEntityComponentDescriptor(typeof(MyObjectBuilder_MergeBlock), true)]
public class MergeAssist : MyGameLogicComponent
{
private MyObjectBuilder_EntityBase objectBuilder;
IMyShipMergeBlock mergeblock;
static Dictionary<Vector3I, EntityCache> BlockCache = new Dictionary<Vector3I, EntityCache>();
static double scale = 100;
static bool isdirty = false;
static IMyShipMergeBlock dirtyblock;
IMyFunctionalBlock target;
Vector3I lastpos = new Vector3I(0, 0, 0);
bool alive = true;
bool updating = false;
int index = 0;
public override void Init(MyObjectBuilder_EntityBase objectBuilder)
{
this.objectBuilder = objectBuilder;
this.NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;
mergeblock = Entity as IMyShipMergeBlock;
}
public override void UpdateBeforeSimulation100()
{
if (DockCore.instance?.TextAPI == null)
return;
if (DockCore.instance.isDedicated)
return;
//not init
if (mergeblock == null || mergeblock.MarkedForClose || mergeblock.Closed)
return;
if (dirtyblock == null || dirtyblock.MarkedForClose || dirtyblock.Closed)
isdirty = false;
if (MyAPIGateway.Session?.Player?.Controller?.ControlledEntity?.Entity == null)
return;
if (!alive)
return;
if (updating)
{
DockCore.OnDraw -= Draw;
updating = false;
}
if (MyAPIGateway.Session.Player.Controller.ControlledEntity.Entity.GetTopMostParent() == mergeblock.GetTopMostParent())
{
index = DockCore.instance.indexer.Add((mergeblock));
}
if (!mergeblock.IsWorking)
return;
//add to cache
string debug = "";
Vector3D Coordinate = mergeblock.WorldMatrix.Translation / scale;
if ( Coordinate.AbsMax() >= Vector3I.MaxValue.AbsMax())
{
scale = (Coordinate.AbsMax() * 2) / Vector3I.MaxValue.AbsMax();
isdirty = true;
dirtyblock = mergeblock;
BlockCache.Clear(); //BOOM
//return;
}
debug += scale.ToString() + '\n';
EntityCache Cache;
BlockCache.TryGetValue(lastpos, out Cache);
if(Cache != null)
{
Cache.Remove(mergeblock);
}
lastpos = new Vector3I(Coordinate);
EntityCache Search = new EntityCache();
BlockCache.TryGetValue(lastpos, out Cache);
if (Cache != null)
{
Search.Copy(Cache);
Cache.Add(mergeblock);
}
else
{
Cache = new EntityCache();
Cache.Add(mergeblock);
BlockCache.Add(lastpos, Cache);
}
IMyFunctionalBlock Closest;
if(TryGetClosestMergeblock(mergeblock, ref Search, out Closest))
{
debug += Closest.EntityId.ToString() + '\n';
if(MyAPIGateway.Session.Player.Controller.ControlledEntity.Entity.GetTopMostParent() == mergeblock.GetTopMostParent() )
{
DockCore.instance.CanDraw = true;
if(DockCore.instance.idx % DockCore.instance.indexer.Count() == index)
{
target = Closest;
DockCore.OnDraw += Draw;
updating = true;
}
}
}
debug += Search.Count().ToString();
}
private void Draw()
{
if (target == null)
return;
if (mergeblock == null)
return;
if (MyAPIGateway.Session?.Player?.Controller?.ControlledEntity?.Entity == null)
return;
if (MyAPIGateway.Session.Player.Controller.ControlledEntity.Entity.GetTopMostParent() != mergeblock.GetTopMostParent())
return;
if (DockCore.instance.DrawHud != true) return;
DockCore.instance.DrawCenterDot();//draw the center dot
MatrixD mergepoint = new MatrixD(mergeblock.WorldMatrix);
mergepoint.Translation = target.WorldMatrix.Translation + (MathHelper.Clamp(Vector3D.Distance(mergeblock.WorldMatrix.Translation, target.WorldMatrix.Translation), 5d, double.MaxValue) * target.WorldMatrix.Right);
MyTransparentGeometry.AddPointBillboard(MyStringId.GetOrCompute("WhiteDot"), Color.Green.ToVector4(), mergeblock.WorldMatrix.Translation + mergeblock.WorldMatrix.Right * mergeblock.CubeGrid.GridSize / 2, 1, 0.0f);
Vector2D dotpos = DockCore.instance.DrawOtherDot(CorrectRot(mergepoint), target.WorldAABB.Center, DockCore.DotObject.Rotate);
MatrixD targetpoint = new MatrixD(target.WorldMatrix);
targetpoint.Translation += targetpoint.Right * mergeblock.CubeGrid.GridSize / 2;
MyTransparentGeometry.AddPointBillboard(MyStringId.GetOrCompute("WhiteDot"), Color.Purple.ToVector4(), targetpoint.Translation, 1, 0.0f);
Vector2D anglepos = DockCore.instance.DrawOtherDot(CorrectRot(targetpoint), mergeblock.WorldAABB.Center, DockCore.DotObject.Translate);
var roll = Vector3D.Dot(-target.WorldMatrix.Forward, mergeblock.WorldMatrix.Forward) - 1;
roll *= -180;
int i_roll = (int)roll;
i_roll %= 90;
if (i_roll > 45)
i_roll = 90 - i_roll;
DockCore.instance.SetDistanceMessage(string.Format(" <color=teal>Distance: {0:N}\n <color=teal>Roll Alignment:{1:N0}", Vector3D.Distance(target.WorldMatrix.Translation, mergeblock.WorldMatrix.Translation), i_roll));
if (dotpos.Length() > 0.05)
{
DockCore.instance.DrawArrow(dotpos);
DockCore.instance.SetAngleMessage();
}
else
{
if (anglepos.Length() > 0.05)
{
DockCore.instance.DrawArrow(anglepos);
DockCore.instance.SetTranslationMessage();
}
else
{
DockCore.instance.HideArrow();
DockCore.instance.SetApproachMessage();
}
}
//DockCore.instance.TextAPI.Send(new HUDTextNI.HUDMessage(4, 20, new Vector2D(-0.4,-0.4),1,true, true, Color.Black, string.Format("{0}<color=teal>Roll Alignment:{1:N0}", instruction, i_roll)));
}
private MatrixD CorrectRot(MatrixD _Matrix)
{
var Up = _Matrix.Up;
var Forward = _Matrix.Forward;
var Right = _Matrix.Right;
_Matrix.Forward = Right;
_Matrix.Up = Forward;
_Matrix.Left = Up;
return _Matrix;
}
private bool TryGetClosestMergeblock(IMyShipMergeBlock mergeblock, ref EntityCache search, out IMyFunctionalBlock closest)
{
int x = 0;
int y = 0;
int z = 0;
for(x = -1; x < 2; x++)
{
for(y=-1; y < 2; y++)
{
for (z = -1; z < 2; z++)
{
if (x == 0 && y == 0 && z == 0)
continue;
EntityCache Cache;
BlockCache.TryGetValue(lastpos + new Vector3I(x, y, z), out Cache);
if(Cache != null)
{
search.Copy(Cache);
}
}
}
}
double dist = double.MaxValue;
closest = null;
foreach(var block in search)
{
if (block == null || block.MarkedForClose || block.Closed)
continue;
if (block.CubeGrid == mergeblock.CubeGrid)
continue;
if(Vector3D.Distance(block.WorldMatrix.Translation, mergeblock.WorldMatrix.Translation) < dist)
{
dist = Vector3D.Distance(block.WorldMatrix.Translation, mergeblock.WorldMatrix.Translation);
closest = block;
}
}
if (closest != null)
return true;
return false;
}
public override void MarkForClose()
{
if (DockCore.instance == null || DockCore.instance.isDedicated) return;
EntityCache Cache;
BlockCache.TryGetValue(lastpos, out Cache);
if (Cache != null)
{
Cache.Remove(mergeblock);
}
alive = false;
DockCore.instance.indexer.Remove(mergeblock);
base.MarkForClose();
}
public override MyObjectBuilder_EntityBase GetObjectBuilder(bool copy = false)
{
return copy ? (MyObjectBuilder_EntityBase)objectBuilder.Clone() : objectBuilder;
}
}
}
| |
// 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.Linq;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
public sealed class SignerInfo
{
public int Version { get; }
public SubjectIdentifier SignerIdentifier { get; }
private readonly Oid _digestAlgorithm;
private readonly AttributeAsn[] _signedAttributes;
private readonly ReadOnlyMemory<byte>? _signedAttributesMemory;
private readonly Oid _signatureAlgorithm;
private readonly ReadOnlyMemory<byte>? _signatureAlgorithmParameters;
private readonly ReadOnlyMemory<byte> _signature;
private readonly AttributeAsn[] _unsignedAttributes;
private readonly SignedCms _document;
private X509Certificate2 _signerCertificate;
private SignerInfo _parentSignerInfo;
private CryptographicAttributeObjectCollection _parsedSignedAttrs;
private CryptographicAttributeObjectCollection _parsedUnsignedAttrs;
internal SignerInfo(ref SignerInfoAsn parsedData, SignedCms ownerDocument)
{
Version = parsedData.Version;
SignerIdentifier = new SubjectIdentifier(parsedData.Sid);
_digestAlgorithm = parsedData.DigestAlgorithm.Algorithm;
_signedAttributesMemory = parsedData.SignedAttributes;
_signatureAlgorithm = parsedData.SignatureAlgorithm.Algorithm;
_signatureAlgorithmParameters = parsedData.SignatureAlgorithm.Parameters;
_signature = parsedData.SignatureValue;
_unsignedAttributes = parsedData.UnsignedAttributes;
if (_signedAttributesMemory.HasValue)
{
SignedAttributesSet signedSet = SignedAttributesSet.Decode(
_signedAttributesMemory.Value,
AsnEncodingRules.BER);
_signedAttributes = signedSet.SignedAttributes;
Debug.Assert(_signedAttributes != null);
}
_document = ownerDocument;
}
public CryptographicAttributeObjectCollection SignedAttributes
{
get
{
if (_parsedSignedAttrs == null)
{
_parsedSignedAttrs = MakeAttributeCollection(_signedAttributes);
}
return _parsedSignedAttrs;
}
}
public CryptographicAttributeObjectCollection UnsignedAttributes
{
get
{
if (_parsedUnsignedAttrs == null)
{
_parsedUnsignedAttrs = MakeAttributeCollection(_unsignedAttributes);
}
return _parsedUnsignedAttrs;
}
}
internal ReadOnlyMemory<byte> GetSignatureMemory() => _signature;
public byte[] GetSignature() => _signature.ToArray();
public X509Certificate2 Certificate
{
get
{
if (_signerCertificate == null)
{
_signerCertificate = FindSignerCertificate();
}
return _signerCertificate;
}
}
public SignerInfoCollection CounterSignerInfos
{
get
{
// We only support one level of counter signing.
if (_parentSignerInfo != null ||
_unsignedAttributes == null ||
_unsignedAttributes.Length == 0)
{
return new SignerInfoCollection();
}
return GetCounterSigners(_unsignedAttributes);
}
}
public Oid DigestAlgorithm => new Oid(_digestAlgorithm);
public Oid SignatureAlgorithm => new Oid(_signatureAlgorithm);
public void AddUnsignedAttribute(AsnEncodedData unsignedAttribute)
{
int myIdx = _document.SignerInfos.FindIndexForSigner(this);
if (myIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
ref SignedDataAsn signedData = ref _document.GetRawData();
ref SignerInfoAsn mySigner = ref signedData.SignerInfos[myIdx];
int existingAttribute = mySigner.UnsignedAttributes == null ? -1 : FindAttributeIndexByOid(mySigner.UnsignedAttributes, unsignedAttribute.Oid);
if (existingAttribute == -1)
{
// create a new attribute
AttributeAsn newUnsignedAttr = new AttributeAsn(unsignedAttribute);
int newAttributeIdx;
if (mySigner.UnsignedAttributes == null)
{
newAttributeIdx = 0;
mySigner.UnsignedAttributes = new AttributeAsn[1];
}
else
{
newAttributeIdx = mySigner.UnsignedAttributes.Length;
Array.Resize(ref mySigner.UnsignedAttributes, newAttributeIdx + 1);
}
mySigner.UnsignedAttributes[newAttributeIdx] = newUnsignedAttr;
}
else
{
// merge with existing attribute
ref AttributeAsn modifiedAttr = ref mySigner.UnsignedAttributes[existingAttribute];
int newIndex = modifiedAttr.AttrValues.Length;
Array.Resize(ref modifiedAttr.AttrValues, newIndex + 1);
modifiedAttr.AttrValues[newIndex] = unsignedAttribute.RawData;
}
// Re-normalize the document
_document.Reencode();
}
public void RemoveUnsignedAttribute(AsnEncodedData unsignedAttribute)
{
int myIdx = _document.SignerInfos.FindIndexForSigner(this);
if (myIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
ref SignedDataAsn signedData = ref _document.GetRawData();
ref SignerInfoAsn mySigner = ref signedData.SignerInfos[myIdx];
(int outerIndex, int innerIndex) = FindAttributeLocation(mySigner.UnsignedAttributes, unsignedAttribute, out bool isOnlyValue);
if (outerIndex == -1 || innerIndex == -1)
{
throw new CryptographicException(SR.Cryptography_Cms_NoAttributeFound);
}
if (isOnlyValue)
{
PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes, outerIndex);
}
else
{
PkcsHelpers.RemoveAt(ref mySigner.UnsignedAttributes[outerIndex].AttrValues, innerIndex);
}
// Re-normalize the document
_document.Reencode();
}
private SignerInfoCollection GetCounterSigners(AttributeAsn[] unsignedAttrs)
{
// Since each "attribute" can have multiple "attribute values" there's no real
// correlation to a predictive size here.
List<SignerInfo> signerInfos = new List<SignerInfo>();
foreach (AttributeAsn attributeAsn in unsignedAttrs)
{
if (attributeAsn.AttrType.Value == Oids.CounterSigner)
{
foreach (ReadOnlyMemory<byte> attrValue in attributeAsn.AttrValues)
{
SignerInfoAsn parsedData = SignerInfoAsn.Decode(attrValue, AsnEncodingRules.BER);
SignerInfo signerInfo = new SignerInfo(ref parsedData, _document)
{
_parentSignerInfo = this
};
signerInfos.Add(signerInfo);
}
}
}
return new SignerInfoCollection(signerInfos.ToArray());
}
public void ComputeCounterSignature()
{
throw new PlatformNotSupportedException(SR.Cryptography_Cms_NoSignerCert);
}
public void ComputeCounterSignature(CmsSigner signer)
{
if (_parentSignerInfo != null)
throw new CryptographicException(SR.Cryptography_Cms_NoCounterCounterSigner);
if (signer == null)
throw new ArgumentNullException(nameof(signer));
signer.CheckCertificateValue();
int myIdx = _document.SignerInfos.FindIndexForSigner(this);
if (myIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
// Make sure that we're using the most up-to-date version of this that we can.
SignerInfo effectiveThis = _document.SignerInfos[myIdx];
X509Certificate2Collection chain;
SignerInfoAsn newSignerInfo = signer.Sign(effectiveThis._signature, null, false, out chain);
AttributeAsn newUnsignedAttr;
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
newSignerInfo.Encode(writer);
newUnsignedAttr = new AttributeAsn
{
AttrType = new Oid(Oids.CounterSigner, Oids.CounterSigner),
AttrValues = new[] { new ReadOnlyMemory<byte>(writer.Encode()) },
};
}
ref SignedDataAsn signedData = ref _document.GetRawData();
ref SignerInfoAsn mySigner = ref signedData.SignerInfos[myIdx];
int newExtensionIdx;
if (mySigner.UnsignedAttributes == null)
{
mySigner.UnsignedAttributes = new AttributeAsn[1];
newExtensionIdx = 0;
}
else
{
newExtensionIdx = mySigner.UnsignedAttributes.Length;
Array.Resize(ref mySigner.UnsignedAttributes, newExtensionIdx + 1);
}
mySigner.UnsignedAttributes[newExtensionIdx] = newUnsignedAttr;
_document.UpdateCertificatesFromAddition(chain);
// Re-normalize the document
_document.Reencode();
}
public void RemoveCounterSignature(int index)
{
if (index < 0)
{
// In NetFx RemoveCounterSignature doesn't bounds check, but the helper it calls does.
// In the helper the argument is called "childIndex".
throw new ArgumentOutOfRangeException("childIndex");
}
// The SignerInfo class is a projection of data contained within the SignedCms.
// The projection is applied at construction time, and is not live.
// So RemoveCounterSignature modifies _document, not this.
// (Because that's what NetFx does)
int myIdx = _document.SignerInfos.FindIndexForSigner(this);
// We've been removed.
if (myIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
ref SignedDataAsn parentData = ref _document.GetRawData();
ref SignerInfoAsn myData = ref parentData.SignerInfos[myIdx];
if (myData.UnsignedAttributes == null)
{
throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex);
}
int removeAttrIdx = -1;
int removeValueIndex = -1;
bool removeWholeAttr = false;
int csIndex = 0;
AttributeAsn[] unsignedAttrs = myData.UnsignedAttributes;
for (var i = 0; i < unsignedAttrs.Length; i++)
{
AttributeAsn attributeAsn = unsignedAttrs[i];
if (attributeAsn.AttrType.Value == Oids.CounterSigner)
{
if (index < csIndex + attributeAsn.AttrValues.Length)
{
removeAttrIdx = i;
removeValueIndex = index - csIndex;
if (removeValueIndex == 0 && attributeAsn.AttrValues.Length == 1)
{
removeWholeAttr = true;
}
break;
}
csIndex += attributeAsn.AttrValues.Length;
}
}
if (removeAttrIdx < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_NoSignerAtIndex);
}
// The easy path:
if (removeWholeAttr)
{
// Empty needs to normalize to null.
if (unsignedAttrs.Length == 1)
{
myData.UnsignedAttributes = null;
}
else
{
PkcsHelpers.RemoveAt(ref myData.UnsignedAttributes, removeAttrIdx);
}
}
else
{
PkcsHelpers.RemoveAt(ref unsignedAttrs[removeAttrIdx].AttrValues, removeValueIndex);
}
}
public void RemoveCounterSignature(SignerInfo counterSignerInfo)
{
if (counterSignerInfo == null)
throw new ArgumentNullException(nameof(counterSignerInfo));
SignerInfoCollection docSigners = _document.SignerInfos;
int index = docSigners.FindIndexForSigner(this);
if (index < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
SignerInfo liveThis = docSigners[index];
index = liveThis.CounterSignerInfos.FindIndexForSigner(counterSignerInfo);
if (index < 0)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
RemoveCounterSignature(index);
}
public void CheckSignature(bool verifySignatureOnly) =>
CheckSignature(new X509Certificate2Collection(), verifySignatureOnly);
public void CheckSignature(X509Certificate2Collection extraStore, bool verifySignatureOnly)
{
if (extraStore == null)
throw new ArgumentNullException(nameof(extraStore));
X509Certificate2 certificate = Certificate;
if (certificate == null)
{
certificate = FindSignerCertificate(SignerIdentifier, extraStore);
if (certificate == null)
{
throw new CryptographicException(SR.Cryptography_Cms_SignerNotFound);
}
}
Verify(extraStore, certificate, verifySignatureOnly);
}
public void CheckHash()
{
if (_signatureAlgorithm.Value != Oids.NoSignature)
{
throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters);
}
if (!CheckHash(compatMode: false) && !CheckHash(compatMode: true))
{
throw new CryptographicException(SR.Cryptography_BadSignature);
}
}
private bool CheckHash(bool compatMode)
{
using (IncrementalHash hasher = PrepareDigest(compatMode))
{
if (hasher == null)
{
Debug.Assert(compatMode, $"{nameof(PrepareDigest)} returned null for the primary check");
return false;
}
byte[] expectedSignature = hasher.GetHashAndReset();
return _signature.Span.SequenceEqual(expectedSignature);
}
}
private X509Certificate2 FindSignerCertificate()
{
return FindSignerCertificate(SignerIdentifier, _document.Certificates);
}
private static X509Certificate2 FindSignerCertificate(
SubjectIdentifier signerIdentifier,
X509Certificate2Collection extraStore)
{
if (extraStore == null || extraStore.Count == 0)
{
return null;
}
X509Certificate2Collection filtered = null;
X509Certificate2 match = null;
switch (signerIdentifier.Type)
{
case SubjectIdentifierType.IssuerAndSerialNumber:
{
X509IssuerSerial issuerSerial = (X509IssuerSerial)signerIdentifier.Value;
filtered = extraStore.Find(X509FindType.FindBySerialNumber, issuerSerial.SerialNumber, false);
foreach (X509Certificate2 cert in filtered)
{
if (cert.IssuerName.Name == issuerSerial.IssuerName)
{
match = cert;
break;
}
}
break;
}
case SubjectIdentifierType.SubjectKeyIdentifier:
{
filtered = extraStore.Find(X509FindType.FindBySubjectKeyIdentifier, signerIdentifier.Value, false);
if (filtered.Count > 0)
{
match = filtered[0];
}
break;
}
}
if (filtered != null)
{
foreach (X509Certificate2 cert in filtered)
{
if (!ReferenceEquals(cert, match))
{
cert.Dispose();
}
}
}
return match;
}
private IncrementalHash PrepareDigest(bool compatMode)
{
HashAlgorithmName hashAlgorithmName = GetDigestAlgorithm();
IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithmName);
if (_parentSignerInfo == null)
{
// Windows compatibility: If a document was loaded in detached mode,
// but had content, hash both parts of the content.
if (_document.Detached)
{
ref SignedDataAsn documentData = ref _document.GetRawData();
ReadOnlyMemory<byte>? embeddedContent = documentData.EncapContentInfo.Content;
if (embeddedContent != null)
{
// Unwrap the OCTET STRING manually, because of PKCS#7 compatibility.
// https://tools.ietf.org/html/rfc5652#section-5.2.1
ReadOnlyMemory<byte> hashableContent = SignedCms.GetContent(
embeddedContent.Value,
documentData.EncapContentInfo.ContentType);
hasher.AppendData(hashableContent.Span);
}
}
hasher.AppendData(_document.GetHashableContentSpan());
}
else
{
hasher.AppendData(_parentSignerInfo._signature.Span);
}
// A Counter-Signer always requires signed attributes.
// If any signed attributes are present, message-digest is required.
bool invalid = _parentSignerInfo != null || _signedAttributes != null;
if (_signedAttributes != null)
{
byte[] contentDigest = hasher.GetHashAndReset();
using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER))
{
// Some CMS implementations exist which do not sort the attributes prior to
// generating the signature. While they are not, technically, validly signed,
// Windows and OpenSSL both support trying in the document order rather than
// a sorted order. To accomplish this we will build as a SEQUENCE OF, but feed
// the SET OF into the hasher.
if (compatMode)
{
writer.PushSequence();
}
else
{
writer.PushSetOf();
}
foreach (AttributeAsn attr in _signedAttributes)
{
attr.Encode(writer);
// .NET Framework doesn't seem to validate the content type attribute,
// so we won't, either.
if (attr.AttrType.Value == Oids.MessageDigest)
{
CryptographicAttributeObject obj = MakeAttribute(attr);
if (obj.Values.Count != 1)
{
throw new CryptographicException(SR.Cryptography_BadHashValue);
}
var digestAttr = (Pkcs9MessageDigest)obj.Values[0];
if (!contentDigest.AsSpan().SequenceEqual(digestAttr.MessageDigest))
{
throw new CryptographicException(SR.Cryptography_BadHashValue);
}
invalid = false;
}
}
if (compatMode)
{
writer.PopSequence();
#if netcoreapp || netcoreapp30 || netstandard21
Span<byte> setOfTag = stackalloc byte[1];
setOfTag[0] = 0x31;
hasher.AppendData(setOfTag);
hasher.AppendData(writer.EncodeAsSpan().Slice(1));
#else
byte[] encoded = writer.Encode();
encoded[0] = 0x31;
hasher.AppendData(encoded);
#endif
}
else
{
writer.PopSetOf();
#if netcoreapp || netcoreapp30 || netstandard21
hasher.AppendData(writer.EncodeAsSpan());
#else
hasher.AppendData(writer.Encode());
#endif
}
}
}
else if (compatMode)
{
// If there were no signed attributes there's nothing to be compatible about.
return null;
}
if (invalid)
{
throw new CryptographicException(SR.Cryptography_Cms_MissingAuthenticatedAttribute);
}
return hasher;
}
private void Verify(
X509Certificate2Collection extraStore,
X509Certificate2 certificate,
bool verifySignatureOnly)
{
CmsSignature signatureProcessor = CmsSignature.ResolveAndVerifyKeyType(SignatureAlgorithm.Value, key: null);
if (signatureProcessor == null)
{
throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, SignatureAlgorithm.Value);
}
bool signatureValid =
VerifySignature(signatureProcessor, certificate, compatMode: false) ||
VerifySignature(signatureProcessor, certificate, compatMode: true);
if (!signatureValid)
{
throw new CryptographicException(SR.Cryptography_BadSignature);
}
if (!verifySignatureOnly)
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.ExtraStore.AddRange(extraStore);
chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
if (!chain.Build(certificate))
{
X509ChainStatus status = chain.ChainStatus.FirstOrDefault();
throw new CryptographicException(SR.Cryptography_Cms_TrustFailure, status.StatusInformation);
}
// NetFx checks for either of these
const X509KeyUsageFlags SufficientFlags =
X509KeyUsageFlags.DigitalSignature |
X509KeyUsageFlags.NonRepudiation;
foreach (X509Extension ext in certificate.Extensions)
{
if (ext.Oid.Value == Oids.KeyUsage)
{
if (!(ext is X509KeyUsageExtension keyUsage))
{
keyUsage = new X509KeyUsageExtension();
keyUsage.CopyFrom(ext);
}
if ((keyUsage.KeyUsages & SufficientFlags) == 0)
{
throw new CryptographicException(SR.Cryptography_Cms_WrongKeyUsage);
}
}
}
}
}
private bool VerifySignature(
CmsSignature signatureProcessor,
X509Certificate2 certificate,
bool compatMode)
{
using (IncrementalHash hasher = PrepareDigest(compatMode))
{
if (hasher == null)
{
Debug.Assert(compatMode, $"{nameof(PrepareDigest)} returned null for the primary check");
return false;
}
#if netcoreapp || netcoreapp30 || netstandard21
// SHA-2-512 is the biggest digest type we know about.
Span<byte> digestValue = stackalloc byte[512 / 8];
ReadOnlySpan<byte> digest = digestValue;
ReadOnlyMemory<byte> signature = _signature;
if (hasher.TryGetHashAndReset(digestValue, out int bytesWritten))
{
digest = digestValue.Slice(0, bytesWritten);
}
else
{
digest = hasher.GetHashAndReset();
}
#else
byte[] digest = hasher.GetHashAndReset();
byte[] signature = _signature.ToArray();
#endif
return signatureProcessor.VerifySignature(
digest,
signature,
DigestAlgorithm.Value,
hasher.AlgorithmName,
_signatureAlgorithmParameters,
certificate);
}
}
private HashAlgorithmName GetDigestAlgorithm()
{
return PkcsHelpers.GetDigestAlgorithm(DigestAlgorithm.Value, forVerification: true);
}
internal static CryptographicAttributeObjectCollection MakeAttributeCollection(AttributeAsn[] attributes)
{
var coll = new CryptographicAttributeObjectCollection();
if (attributes == null)
return coll;
foreach (AttributeAsn attribute in attributes)
{
coll.AddWithoutMerge(MakeAttribute(attribute));
}
return coll;
}
private static CryptographicAttributeObject MakeAttribute(AttributeAsn attribute)
{
Oid type = new Oid(attribute.AttrType);
AsnEncodedDataCollection valueColl = new AsnEncodedDataCollection();
foreach (ReadOnlyMemory<byte> attrValue in attribute.AttrValues)
{
valueColl.Add(PkcsHelpers.CreateBestPkcs9AttributeObjectAvailable(type, attrValue.ToArray()));
}
return new CryptographicAttributeObject(type, valueColl);
}
private static int FindAttributeIndexByOid(AttributeAsn[] attributes, Oid oid, int startIndex = 0)
{
for (int i = startIndex; i < attributes.Length; i++)
{
if (attributes[i].AttrType.Value == oid.Value)
{
return i;
}
}
return -1;
}
private static int FindAttributeValueIndexByEncodedData(ReadOnlyMemory<byte>[] attributeValues, ReadOnlySpan<byte> asnEncodedData, out bool isOnlyValue)
{
for (int i = 0; i < attributeValues.Length; i++)
{
ReadOnlySpan<byte> data = attributeValues[i].Span;
if (data.SequenceEqual(asnEncodedData))
{
isOnlyValue = attributeValues.Length == 1;
return i;
}
}
isOnlyValue = false;
return -1;
}
private static (int, int) FindAttributeLocation(AttributeAsn[] attributes, AsnEncodedData attribute, out bool isOnlyValue)
{
for (int outerIndex = 0; ; outerIndex++)
{
outerIndex = FindAttributeIndexByOid(attributes, attribute.Oid, outerIndex);
if (outerIndex == -1)
{
break;
}
int innerIndex = FindAttributeValueIndexByEncodedData(attributes[outerIndex].AttrValues, attribute.RawData, out isOnlyValue);
if (innerIndex != -1)
{
return (outerIndex, innerIndex);
}
}
isOnlyValue = false;
return (-1, -1);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public class HttpClient : HttpMessageInvoker
{
#region Fields
private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(100);
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private static readonly TimeSpan s_infiniteTimeout = Threading.Timeout.InfiniteTimeSpan;
private const HttpCompletionOption defaultCompletionOption = HttpCompletionOption.ResponseContentRead;
private volatile bool _operationStarted;
private volatile bool _disposed;
private CancellationTokenSource _pendingRequestsCts;
private HttpRequestHeaders _defaultRequestHeaders;
private Uri _baseAddress;
private TimeSpan _timeout;
private long _maxResponseContentBufferSize;
#endregion Fields
#region Properties
public HttpRequestHeaders DefaultRequestHeaders
{
get
{
if (_defaultRequestHeaders == null)
{
_defaultRequestHeaders = new HttpRequestHeaders();
}
return _defaultRequestHeaders;
}
}
public Uri BaseAddress
{
get { return _baseAddress; }
set
{
CheckBaseAddress(value, "value");
CheckDisposedOrStarted();
if (HttpEventSource.Log.IsEnabled()) HttpEventSource.UriBaseAddress(this, _baseAddress.ToString());
_baseAddress = value;
}
}
public TimeSpan Timeout
{
get { return _timeout; }
set
{
if (value != s_infiniteTimeout && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposedOrStarted();
_timeout = value;
}
}
public long MaxResponseContentBufferSize
{
get { return _maxResponseContentBufferSize; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException("value");
}
if (value > HttpContent.MaxBufferSize)
{
throw new ArgumentOutOfRangeException("value", value,
string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
CheckDisposedOrStarted();
_maxResponseContentBufferSize = value;
}
}
#endregion Properties
#region Constructors
public HttpClient()
: this(new HttpClientHandler())
{
}
public HttpClient(HttpMessageHandler handler)
: this(handler, true)
{
}
public HttpClient(HttpMessageHandler handler, bool disposeHandler)
: base(handler, disposeHandler)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", handler);
_timeout = s_defaultTimeout;
_maxResponseContentBufferSize = HttpContent.MaxBufferSize;
_pendingRequestsCts = new CancellationTokenSource();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
}
#endregion Constructors
#region Public Send
#region Simple Get Overloads
public Task<string> GetStringAsync(string requestUri)
{
return GetStringAsync(CreateUri(requestUri));
}
public Task<string> GetStringAsync(Uri requestUri)
{
return GetContentAsync(requestUri, HttpCompletionOption.ResponseContentRead, string.Empty,
content => content.ReadAsStringAsync());
}
public Task<byte[]> GetByteArrayAsync(string requestUri)
{
return GetByteArrayAsync(CreateUri(requestUri));
}
public Task<byte[]> GetByteArrayAsync(Uri requestUri)
{
return GetContentAsync(requestUri, HttpCompletionOption.ResponseContentRead, Array.Empty<byte>(),
content => content.ReadAsByteArrayAsync());
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(string requestUri)
{
return GetStreamAsync(CreateUri(requestUri));
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(Uri requestUri)
{
return GetContentAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, Stream.Null,
content => content.ReadAsStreamAsync());
}
private Task<T> GetContentAsync<T>(Uri requestUri, HttpCompletionOption completionOption, T defaultValue,
Func<HttpContent, Task<T>> readAs)
{
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
GetAsync(requestUri, completionOption).ContinueWithStandard(requestTask =>
{
if (HandleRequestFaultsAndCancelation(requestTask, tcs))
{
return;
}
HttpResponseMessage response = requestTask.Result;
if (response.Content == null)
{
tcs.TrySetResult(defaultValue);
return;
}
try
{
readAs(response.Content).ContinueWithStandard(contentTask =>
{
if (!HttpUtilities.HandleFaultsAndCancelation(contentTask, tcs))
{
tcs.TrySetResult(contentTask.Result);
}
});
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
});
return tcs.Task;
}
#endregion Simple Get Overloads
#region REST Send Overloads
public Task<HttpResponseMessage> GetAsync(string requestUri)
{
return GetAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri)
{
return GetAsync(requestUri, defaultCompletionOption);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption)
{
return GetAsync(CreateUri(requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption)
{
return GetAsync(requestUri, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken)
{
return GetAsync(requestUri, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
{
return PostAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content)
{
return PostAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PostAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)
{
return PutAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content)
{
return PutAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PutAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri)
{
return DeleteAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri)
{
return DeleteAsync(requestUri, CancellationToken.None);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken)
{
return DeleteAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
}
#endregion REST Send Overloads
#region Advanced Send Overloads
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
{
return SendAsync(request, defaultCompletionOption, CancellationToken.None);
}
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
return SendAsync(request, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
{
return SendAsync(request, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
CheckDisposed();
CheckRequestMessage(request);
SetOperationStarted();
PrepareRequestMessage(request);
// PrepareRequestMessage will resolve the request address against the base address.
CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken,
_pendingRequestsCts.Token);
SetTimeout(linkedCts);
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
base.SendAsync(request, linkedCts.Token).ContinueWithStandard(task =>
{
try
{
// The request is completed. Dispose the request content.
DisposeRequestContent(request);
if (task.IsFaulted)
{
SetTaskFaulted(request, linkedCts, tcs, task.Exception.GetBaseException());
return;
}
if (task.IsCanceled)
{
SetTaskCanceled(request, linkedCts, tcs);
return;
}
HttpResponseMessage response = task.Result;
if (response == null)
{
SetTaskFaulted(request, linkedCts, tcs,
new InvalidOperationException(SR.net_http_handler_noresponse));
return;
}
// If we don't have a response content, just return the response message.
if ((response.Content == null) || (completionOption == HttpCompletionOption.ResponseHeadersRead))
{
SetTaskCompleted(request, linkedCts, tcs, response);
return;
}
Debug.Assert(completionOption == HttpCompletionOption.ResponseContentRead,
"Unknown completion option.");
// We have an assigned content. Start loading it into a buffer and return response message once
// the whole content is buffered.
StartContentBuffering(request, linkedCts, tcs, response);
}
catch (Exception e)
{
// Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer.
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "SendAsync", e);
tcs.TrySetException(e);
}
});
return tcs.Task;
}
public void CancelPendingRequests()
{
CheckDisposed();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", "");
// With every request we link this cancellation token source.
CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts,
new CancellationTokenSource());
currentCts.Cancel();
currentCts.Dispose();
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, "CancelPendingRequests", "");
}
#endregion Advanced Send Overloads
#endregion Public Send
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
// Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
// the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
// a new CTS. We don't want a new CTS in this case.
_pendingRequestsCts.Cancel();
_pendingRequestsCts.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Private Helpers
private void DisposeRequestContent(HttpRequestMessage request)
{
Contract.Requires(request != null);
// When a request completes, HttpClient disposes the request content so the user doesn't have to. This also
// ensures that a HttpContent object is only sent once using HttpClient (similar to HttpRequestMessages
// that can also be sent only once).
HttpContent content = request.Content;
if (content != null)
{
content.Dispose();
}
}
private void StartContentBuffering(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
TaskCompletionSource<HttpResponseMessage> tcs, HttpResponseMessage response)
{
response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize).ContinueWithStandard(contentTask =>
{
try
{
// Make sure to dispose the CTS _before_ setting TaskCompletionSource. Otherwise the task will be
// completed and the user may dispose the user CTS on the continuation task leading to a race cond.
bool isCancellationRequested = cancellationTokenSource.Token.IsCancellationRequested;
// contentTask.Exception is always != null if IsFaulted is true. However, we need to access the
// Exception property, otherwise the Task considers the excpetion as "unhandled" and will throw in
// its finalizer.
if (contentTask.IsFaulted)
{
response.Dispose();
// If the cancellation token was canceled, we consider the exception to be caused by the
// cancellation (e.g. WebException when reading from canceled response stream).
if (isCancellationRequested && (contentTask.Exception.GetBaseException() is HttpRequestException))
{
SetTaskCanceled(request, cancellationTokenSource, tcs);
}
else
{
SetTaskFaulted(request, cancellationTokenSource, tcs, contentTask.Exception.GetBaseException());
}
return;
}
if (contentTask.IsCanceled)
{
response.Dispose();
SetTaskCanceled(request, cancellationTokenSource, tcs);
return;
}
// When buffering content is completed, set the Task as completed.
SetTaskCompleted(request, cancellationTokenSource, tcs, response);
}
catch (Exception e)
{
// Make sure we catch any exception, otherwise the task will catch it and throw in the finalizer.
response.Dispose();
tcs.TrySetException(e);
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, "SendAsync", e);
}
});
}
private void SetOperationStarted()
{
// This method flags the HttpClient instances as "active". I.e. we executed at least one request (or are
// in the process of doing so). This information is used to lock-down all property setters. Once a
// Send/SendAsync operation started, no property can be changed.
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
private static void CheckRequestMessage(HttpRequestMessage request)
{
if (!request.MarkAsSent())
{
throw new InvalidOperationException(SR.net_http_client_request_already_sent);
}
}
private void PrepareRequestMessage(HttpRequestMessage request)
{
Uri requestUri = null;
if ((request.RequestUri == null) && (_baseAddress == null))
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
if (request.RequestUri == null)
{
requestUri = _baseAddress;
}
else
{
// If the request Uri is an absolute Uri, just use it. Otherwise try to combine it with the base Uri.
if (!request.RequestUri.IsAbsoluteUri)
{
if (_baseAddress == null)
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
else
{
requestUri = new Uri(_baseAddress, request.RequestUri);
}
}
}
// We modified the original request Uri. Assign the new Uri to the request message.
if (requestUri != null)
{
request.RequestUri = requestUri;
}
// Add default headers
if (_defaultRequestHeaders != null)
{
request.Headers.AddHeaders(_defaultRequestHeaders);
}
}
private static void CheckBaseAddress(Uri baseAddress, string parameterName)
{
if (baseAddress == null)
{
return; // It's OK to not have a base address specified.
}
if (!baseAddress.IsAbsoluteUri)
{
throw new ArgumentException(SR.net_http_client_absolute_baseaddress_required, parameterName);
}
if (!HttpUtilities.IsHttpUri(baseAddress))
{
throw new ArgumentException(SR.net_http_client_http_baseaddress_required, parameterName);
}
}
private void SetTaskFaulted(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
TaskCompletionSource<HttpResponseMessage> tcs, Exception e)
{
LogSendError(request, cancellationTokenSource, "SendAsync", e);
tcs.TrySetException(e);
cancellationTokenSource.Dispose();
}
private void SetTaskCanceled(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
TaskCompletionSource<HttpResponseMessage> tcs)
{
LogSendError(request, cancellationTokenSource, "SendAsync", null);
tcs.TrySetCanceled(cancellationTokenSource.Token);
cancellationTokenSource.Dispose();
}
private void SetTaskCompleted(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
TaskCompletionSource<HttpResponseMessage> tcs, HttpResponseMessage response)
{
if (HttpEventSource.Log.IsEnabled()) HttpEventSource.ClientSendCompleted(this, response, request);
tcs.TrySetResult(response);
cancellationTokenSource.Dispose();
}
private void SetTimeout(CancellationTokenSource cancellationTokenSource)
{
Contract.Requires(cancellationTokenSource != null);
if (_timeout != s_infiniteTimeout)
{
cancellationTokenSource.CancelAfter(_timeout);
}
}
private void LogSendError(HttpRequestMessage request, CancellationTokenSource cancellationTokenSource,
string method, Exception e)
{
Contract.Requires(request != null);
if (cancellationTokenSource.IsCancellationRequested)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_canceled, LoggingHash.GetObjectLogHash(request)));
}
else
{
Debug.Assert(e != null);
if (NetEventSource.Log.IsEnabled()) NetEventSource.PrintError(NetEventSource.ComponentType.Http, this, method, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_client_send_error, LoggingHash.GetObjectLogHash(request), e));
}
}
private Uri CreateUri(String uri)
{
if (string.IsNullOrEmpty(uri))
{
return null;
}
return new Uri(uri, UriKind.RelativeOrAbsolute);
}
// Returns true if the task was faulted or canceled and sets tcs accordingly. Non-success status codes count as
// faults in cases where the HttpResponseMessage object will not be returned to the developer.
private static bool HandleRequestFaultsAndCancelation<T>(Task<HttpResponseMessage> task,
TaskCompletionSource<T> tcs)
{
if (HttpUtilities.HandleFaultsAndCancelation(task, tcs))
{
return true;
}
HttpResponseMessage response = task.Result;
if (!response.IsSuccessStatusCode)
{
if (response.Content != null)
{
response.Content.Dispose();
}
tcs.TrySetException(new HttpRequestException(
string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_message_not_success_statuscode, (int)response.StatusCode,
response.ReasonPhrase)));
return true;
}
return false;
}
#endregion Private Helpers
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Mdb;
using Mono.Cecil.Pdb;
using NUnit.Framework;
namespace Mono.Cecil.Tests {
[TestFixture]
public class ILProcessorTests : BaseTestFixture {
[Test]
public void Append ()
{
var method = CreateTestMethod ();
var il = method.GetILProcessor ();
var ret = il.Create (OpCodes.Ret);
il.Append (ret);
AssertOpCodeSequence (new [] { OpCodes.Ret }, method);
}
[Test]
public void InsertBefore ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
var ldloc_2 = method.Instructions.Where (i => i.OpCode == OpCodes.Ldloc_2).First ();
il.InsertBefore (
ldloc_2,
il.Create (OpCodes.Ldloc_1));
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
}
[Test]
public void InsertBeforeIssue697 ()
{
var parameters = new ReaderParameters { SymbolReaderProvider = new MdbReaderProvider () };
using (var module = GetResourceModule ("Issue697.dll", parameters))
{
var pathGetterDef = module.GetTypes ()
.SelectMany (t => t.Methods)
.First (m => m.Name.Equals ("get_Defer"));
var body = pathGetterDef.Body;
var worker = body.GetILProcessor ();
var initialBody = body.Instructions.ToList ();
var head = initialBody.First ();
var opcode = worker.Create (OpCodes.Ldc_I4_1);
worker.InsertBefore (head, opcode);
worker.InsertBefore (head, worker.Create (OpCodes.Ret));
initialBody.ForEach (worker.Remove);
AssertOpCodeSequence (new [] { OpCodes.Ldc_I4_1, OpCodes.Ret }, pathGetterDef.body);
}
}
[Test]
public void InsertBeforeIssue697bis ()
{
var parameters = new ReaderParameters { SymbolReaderProvider = new MdbReaderProvider () };
using (var module = GetResourceModule ("Issue697.dll", parameters)) {
var pathGetterDef = module.GetTypes ()
.SelectMany (t => t.Methods)
.First (m => m.Name.Equals ("get_Defer"));
var body = pathGetterDef.Body;
var worker = body.GetILProcessor ();
var initialBody = body.Instructions.ToList ();
Console.WriteLine (initialBody.Sum (i => i.GetSize ()));
var head = initialBody.First ();
var opcode = worker.Create (OpCodes.Ldc_I4_1);
worker.InsertBefore (head, opcode);
Assert.That (pathGetterDef.DebugInformation.Scope.Start.IsEndOfMethod, Is.False);
foreach (var subscope in pathGetterDef.DebugInformation.Scope.Scopes)
Assert.That (subscope.Start.IsEndOfMethod, Is.False);
// big test -- we can write w/o crashing
var unique = Guid.NewGuid ().ToString ();
var output = Path.GetTempFileName ();
var outputdll = output + ".dll";
var writer = new WriterParameters () {
SymbolWriterProvider = new MdbWriterProvider (),
WriteSymbols = true
};
using (var sink = File.Open (outputdll, FileMode.Create, FileAccess.ReadWrite)) {
module.Write (sink, writer);
}
Assert.Pass ();
}
}
[Test]
public void InsertAfter ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
var ldloc_0 = method.Instructions.First ();
il.InsertAfter (
ldloc_0,
il.Create (OpCodes.Ldloc_1));
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
}
[Test]
public void InsertAfterUsingIndex ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
il.InsertAfter (
0,
il.Create (OpCodes.Ldloc_1));
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Ldloc_1, OpCodes.Ldloc_2, OpCodes.Ldloc_3 }, method);
}
[Test]
public void ReplaceUsingIndex ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
il.Replace (1, il.Create (OpCodes.Nop));
AssertOpCodeSequence (new [] { OpCodes.Ldloc_0, OpCodes.Nop, OpCodes.Ldloc_3 }, method);
}
[Test]
public void Clear ()
{
var method = CreateTestMethod (OpCodes.Ldloc_0, OpCodes.Ldloc_2, OpCodes.Ldloc_3);
var il = method.GetILProcessor ();
il.Clear ();
AssertOpCodeSequence (new OpCode[] { }, method);
}
[TestCase (RoundtripType.None, false, false, false)]
[TestCase (RoundtripType.Pdb, false, false, false)]
[TestCase (RoundtripType.Pdb, true, false, false)]
[TestCase (RoundtripType.Pdb, true, false, true)]
[TestCase (RoundtripType.Pdb, true, true, false)]
[TestCase (RoundtripType.PortablePdb, false, false, false)]
[TestCase (RoundtripType.PortablePdb, true, false, false)]
[TestCase (RoundtripType.PortablePdb, true, false, true)]
[TestCase (RoundtripType.PortablePdb, true, true, false)]
public void InsertAfterWithSymbolRoundtrip (RoundtripType roundtripType, bool forceUnresolved, bool reverseScopes, bool padIL)
{
var methodBody = CreateTestMethodWithLocalScopes (padIL);
methodBody = RoundtripMethodBody (methodBody, roundtripType, forceUnresolved, reverseScopes);
var il = methodBody.GetILProcessor ();
il.InsertAfter (1, il.Create (OpCodes.Ldstr, "Test"));
methodBody = RoundtripMethodBody (methodBody, roundtripType, false, reverseScopes);
var wholeBodyScope = VerifyWholeBodyScope (methodBody);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [0], 1, 3);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [1], 4, null);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [0], 5, 6);
methodBody.Method.Module.Dispose ();
}
[TestCase (RoundtripType.None, false, false, false)]
[TestCase (RoundtripType.Pdb, false, false, false)]
[TestCase (RoundtripType.Pdb, true, false, false)]
[TestCase (RoundtripType.Pdb, true, false, true)]
[TestCase (RoundtripType.Pdb, true, true, false)]
[TestCase (RoundtripType.PortablePdb, false, false, false)]
[TestCase (RoundtripType.PortablePdb, true, false, false)]
[TestCase (RoundtripType.PortablePdb, true, false, true)]
[TestCase (RoundtripType.PortablePdb, true, true, false)]
public void RemoveWithSymbolRoundtrip (RoundtripType roundtripType, bool forceUnresolved, bool reverseScopes, bool padIL)
{
var methodBody = CreateTestMethodWithLocalScopes (padIL);
methodBody = RoundtripMethodBody (methodBody, roundtripType, forceUnresolved, reverseScopes);
var il = methodBody.GetILProcessor ();
il.RemoveAt (1);
methodBody = RoundtripMethodBody (methodBody, roundtripType, false, reverseScopes);
var wholeBodyScope = VerifyWholeBodyScope (methodBody);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [0], 1, 1);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [1], 2, null);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [0], 3, 4);
methodBody.Method.Module.Dispose ();
}
[TestCase (RoundtripType.None, false, false, false)]
[TestCase (RoundtripType.Pdb, false, false, false)]
[TestCase (RoundtripType.Pdb, true, false, false)]
[TestCase (RoundtripType.Pdb, true, false, true)]
[TestCase (RoundtripType.Pdb, true, true, false)]
[TestCase (RoundtripType.PortablePdb, false, false, false)]
[TestCase (RoundtripType.PortablePdb, true, false, false)]
[TestCase (RoundtripType.PortablePdb, true, false, true)]
[TestCase (RoundtripType.PortablePdb, true, true, false)]
public void ReplaceWithSymbolRoundtrip (RoundtripType roundtripType, bool forceUnresolved, bool reverseScopes, bool padIL)
{
var methodBody = CreateTestMethodWithLocalScopes (padIL);
methodBody = RoundtripMethodBody (methodBody, roundtripType, forceUnresolved, reverseScopes);
var il = methodBody.GetILProcessor ();
il.Replace (1, il.Create (OpCodes.Ldstr, "Test"));
methodBody = RoundtripMethodBody (methodBody, roundtripType, false, reverseScopes);
var wholeBodyScope = VerifyWholeBodyScope (methodBody);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [0], 1, 2);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [1], 3, null);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [0], 4, 5);
methodBody.Method.Module.Dispose ();
}
[TestCase (RoundtripType.None, false, false, false)]
[TestCase (RoundtripType.Pdb, false, false, false)]
[TestCase (RoundtripType.Pdb, true, false, false)]
[TestCase (RoundtripType.Pdb, true, false, true)]
[TestCase (RoundtripType.Pdb, true, true, false)]
[TestCase (RoundtripType.PortablePdb, false, false, false)]
[TestCase (RoundtripType.PortablePdb, true, false, false)]
[TestCase (RoundtripType.PortablePdb, true, false, true)]
[TestCase (RoundtripType.PortablePdb, true, true, false)]
public void EditBodyWithScopesAndSymbolRoundtrip (RoundtripType roundtripType, bool forceUnresolved, bool reverseScopes, bool padIL)
{
var methodBody = CreateTestMethodWithLocalScopes (padIL);
methodBody = RoundtripMethodBody (methodBody, roundtripType, forceUnresolved, reverseScopes);
var il = methodBody.GetILProcessor ();
il.Replace (4, il.Create (OpCodes.Ldstr, "Test"));
il.InsertAfter (5, il.Create (OpCodes.Ldloc_3));
var tempVar3 = new VariableDefinition (methodBody.Method.Module.ImportReference (typeof (string)));
methodBody.Variables.Add (tempVar3);
methodBody.Method.DebugInformation.Scope.Scopes [reverseScopes ? 0 : 1].Scopes.Insert (reverseScopes ? 0 : 1,
new ScopeDebugInformation (methodBody.Instructions [5], methodBody.Instructions [6]) {
Variables = { new VariableDebugInformation (tempVar3, "tempVar3") }
});
methodBody = RoundtripMethodBody (methodBody, roundtripType, false, reverseScopes);
var wholeBodyScope = VerifyWholeBodyScope (methodBody);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [0], 1, 2);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [1], 3, null);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [0], 4, 5);
AssertLocalScope (methodBody, wholeBodyScope.Scopes [1].Scopes [1], 5, 6);
methodBody.Method.Module.Dispose ();
}
[Test]
public void EditWithDebugInfoButNoLocalScopes()
{
var methodBody = CreateTestMethod (OpCodes.Ret);
methodBody.Method.DebugInformation = new MethodDebugInformation (methodBody.Method);
var il = methodBody.GetILProcessor ();
il.Replace (methodBody.Instructions [0], il.Create (OpCodes.Nop));
Assert.AreEqual (1, methodBody.Instructions.Count);
Assert.AreEqual (Code.Nop, methodBody.Instructions [0].OpCode.Code);
Assert.Null (methodBody.Method.DebugInformation.Scope);
}
static void AssertOpCodeSequence (OpCode [] expected, MethodBody body)
{
var opcodes = body.Instructions.Select (i => i.OpCode).ToArray ();
Assert.AreEqual (expected.Length, opcodes.Length);
for (int i = 0; i < opcodes.Length; i++)
Assert.AreEqual (expected [i], opcodes [i]);
}
static MethodBody CreateTestMethod (params OpCode [] opcodes)
{
var method = new MethodDefinition {
Name = "function",
Attributes = MethodAttributes.Public | MethodAttributes.Static
};
var il = method.Body.GetILProcessor ();
foreach (var opcode in opcodes)
il.Emit (opcode);
var instructions = method.Body.Instructions;
int size = 0;
for (int i = 0; i < instructions.Count; i++) {
var instruction = instructions [i];
instruction.Offset = size;
size += instruction.GetSize ();
}
return method.Body;
}
static ScopeDebugInformation VerifyWholeBodyScope (MethodBody body)
{
var debug_info = body.Method.DebugInformation;
Assert.IsNotNull (debug_info);
AssertLocalScope (body, debug_info.Scope, 0, null);
return debug_info.Scope;
}
static void AssertLocalScope (MethodBody methodBody, ScopeDebugInformation scope, int startIndex, int? endIndex)
{
Assert.IsNotNull (scope);
Assert.AreEqual (methodBody.Instructions [startIndex], scope.Start.ResolvedInstruction);
if (endIndex.HasValue)
Assert.AreEqual (methodBody.Instructions [endIndex.Value], scope.End.ResolvedInstruction);
else
Assert.IsTrue (scope.End.IsEndOfMethod);
}
static MethodBody CreateTestMethodWithLocalScopes (bool padILWithNulls)
{
var module = ModuleDefinition.CreateModule ("TestILProcessor", ModuleKind.Dll);
var type = new TypeDefinition ("NS", "TestType", TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.Sealed, module.ImportReference (typeof (object)));
module.Types.Add (type);
var methodBody = CreateTestMethod (OpCodes.Nop, OpCodes.Ldloc_0, OpCodes.Nop, OpCodes.Ldloc_1, OpCodes.Nop, OpCodes.Ldloc_2, OpCodes.Nop);
if (padILWithNulls)
methodBody.Instructions.Capacity += 10;
var method = methodBody.Method;
method.ReturnType = module.ImportReference (typeof (void));
type.Methods.Add (method);
methodBody.InitLocals = true;
var tempVar1 = new VariableDefinition (module.ImportReference (typeof (string)));
methodBody.Variables.Add (tempVar1);
var tempVar2 = new VariableDefinition (module.ImportReference (typeof (string)));
methodBody.Variables.Add (tempVar2);
var debug_info = method.DebugInformation;
// Must add a sequence point, otherwise the native PDB writer will not actually write the method's debug info
// into the PDB.
foreach (var instr in methodBody.Instructions) {
var sequence_point = new SequencePoint (instr, new Document (@"C:\test.cs")) {
StartLine = 0,
StartColumn = 0,
EndLine = 0,
EndColumn = 4,
};
debug_info.SequencePoints.Add (sequence_point);
}
// The method looks like this:
// | Scope | Scope.Scopes[0] | Scope.Scopes[1] | Scope.Scopes[1].Scopes[0]
// #0 Nop | > | | |
// #1 Ldloc_0 | . | > | |
// #2 Nop | . | < | |
// #3 Ldloc_1 | . | | > |
// #4 Nop | . | | . | >
// #5 Ldloc_2 | . | | . | <
// #6 Nop | . | | . |
// <end of m> | < | | < |
var instructions = methodBody.Instructions;
debug_info.Scope = new ScopeDebugInformation (instructions[0], null) {
Scopes = {
new ScopeDebugInformation (instructions[1], instructions[2]) {
Variables = { new VariableDebugInformation(tempVar1, "tempVar1") }
},
new ScopeDebugInformation (instructions[3], null) {
Scopes = {
new ScopeDebugInformation (instructions[4], instructions[5]) {
Variables = { new VariableDebugInformation(tempVar2, "tempVar2") }
}
}
}
}
};
return methodBody;
}
public enum RoundtripType {
None,
Pdb,
PortablePdb
}
static MethodBody RoundtripMethodBody(MethodBody methodBody, RoundtripType roundtripType, bool forceUnresolvedScopes = false, bool reverseScopeOrder = false)
{
var newModule = RoundtripModule (methodBody.Method.Module, roundtripType);
var newMethodBody = newModule.GetType ("NS.TestType").GetMethod ("function").Body;
if (forceUnresolvedScopes)
UnresolveScopes (newMethodBody.Method.DebugInformation.Scope);
if (reverseScopeOrder)
ReverseScopeOrder (newMethodBody.Method.DebugInformation.Scope);
return newMethodBody;
}
static void UnresolveScopes(ScopeDebugInformation scope)
{
scope.Start = new InstructionOffset (scope.Start.Offset);
if (!scope.End.IsEndOfMethod)
scope.End = new InstructionOffset (scope.End.Offset);
foreach (var subScope in scope.Scopes)
UnresolveScopes (subScope);
}
static void ReverseScopeOrder(ScopeDebugInformation scope)
{
List<ScopeDebugInformation> subScopes = scope.Scopes.ToList ();
subScopes.Reverse ();
scope.Scopes.Clear ();
foreach (var subScope in subScopes)
scope.Scopes.Add (subScope);
foreach (var subScope in scope.Scopes)
ReverseScopeOrder (subScope);
}
static ModuleDefinition RoundtripModule(ModuleDefinition module, RoundtripType roundtripType)
{
if (roundtripType == RoundtripType.None)
return module;
var file = Path.Combine (Path.GetTempPath (), "TestILProcessor.dll");
if (File.Exists (file))
File.Delete (file);
ISymbolWriterProvider symbolWriterProvider;
switch (roundtripType) {
case RoundtripType.Pdb when Platform.HasNativePdbSupport:
symbolWriterProvider = new PdbWriterProvider ();
break;
case RoundtripType.PortablePdb:
default:
symbolWriterProvider = new PortablePdbWriterProvider ();
break;
}
module.Write (file, new WriterParameters {
SymbolWriterProvider = symbolWriterProvider,
});
module.Dispose ();
ISymbolReaderProvider symbolReaderProvider;
switch (roundtripType) {
case RoundtripType.Pdb when Platform.HasNativePdbSupport:
symbolReaderProvider = new PdbReaderProvider ();
break;
case RoundtripType.PortablePdb:
default:
symbolReaderProvider = new PortablePdbReaderProvider ();
break;
}
return ModuleDefinition.ReadModule (file, new ReaderParameters {
SymbolReaderProvider = symbolReaderProvider,
InMemory = true
});
}
}
}
| |
using System;
using System.Linq;
using Buildron.Domain;
using Buildron.Domain.Builds;
using Buildron.Domain.CIServers;
using Buildron.Domain.Users;
using Buildron.Domain.Versions;
using Buildron.Infrastructure.BuildsProviders.Filter;
using Buildron.Infrastructure.BuildsProvider.Hudson;
using Buildron.Infrastructure.BuildsProvider.Jenkins;
using Buildron.Infrastructure.BuildsProvider.TeamCity;
using Skahal.Threading;
using UnityEngine;
using UnityEngine.UI;
using Zenject;
using Buildron.Domain.RemoteControls;
using Buildron.Domain.Servers;
using Buildron.Domain.Mods;
/// <summary>
/// Controller for configuration panel.
/// </summary>
[AddComponentMenu ("Buildron/Controllers/ConfigPanelController")]
public class ConfigPanelController : MonoBehaviour, IInitializable
{
#region Fields
private ICIServer m_ciServer;
private IBuildsProvider m_buildsProvider;
private Animator m_animator;
[Inject]
private IUserService m_userService;
[Inject]
private IVersionService m_versionService;
[Inject]
private IBuildService m_buildService;
[Inject]
private ICIServerService m_ciServerService;
[Inject]
private IRemoteControlService m_remoteControlService;
[Inject]
private IServerService m_serverService;
[Inject]
private IModLoader m_modLoader;
#endregion
#region Editor properties
public Toggle CIServerTypeHudsonToggle;
public Toggle CIServerTypeJenkinsToggle;
public Toggle CIServerTypeTeamCityToggle;
// CI Server.
public Text CIServerIPLabel;
public InputField CIServerIPInputField;
// CI Username.
public InputField CIServerUserNameInputField;
// CI Password.
public InputField CIServerPasswordInputField;
// CI tip and status.
public Text CIServerAuthenticationTipLabel;
public Text CIServerStatusLabel;
// Options.
public Button ModsButton;
public Text ModsLabel;
public Text RefreshSecondsLabel;
public Slider RefreshSecondsSlider;
public Text InstallationNumberLabel;
public Button UpdateButton;
public Text UpdateButtonLabel;
public Text VersionNumberButtonLabel;
public Button StartButton;
public bool AutoStart;
#endregion
#region Life cycle
public void Initialize ()
{
m_ciServer = m_ciServerService.GetCIServer ();
Debug.LogFormat ("Server type: {0}", m_ciServer.ServerType);
Debug.LogFormat ("IP: {0}", m_ciServer.IP);
PrepareCIServerTypesRadioButtons ();
CIServerIPInputField.text = m_ciServer.IP;
CIServerUserNameInputField.text = m_ciServer.DomainAndUserName;
CIServerPasswordInputField.text = m_ciServer.Password;
RefreshSecondsSlider.value = m_ciServer.RefreshSeconds;
UpdateRefreshSecondsLabel ();
UpdateBuildsProvider ();
if (AutoStart || HasAutoStartArgument ())
{
StartBuildron ();
}
m_userService.UserAuthenticationCompleted += HandleUserAuthenticationCompleted;
InitializeVersion ();
}
void Start()
{
var modsCount = m_modLoader.LoadedMods.Count;
ModsLabel.text = "{0} mods".With (modsCount);
ModsButton.enabled = modsCount > 0;
}
private bool HasAutoStartArgument ()
{
return System.Environment.GetCommandLineArgs ().Contains ("autostart");
}
void PrepareCIServerTypesRadioButtons ()
{
switch (m_ciServer.ServerType)
{
case CIServerType.Hudson:
Debug.Log ("CIServerTypeHudsonToggle.isOn");
CIServerTypeHudsonToggle.isOn = true;
break;
case CIServerType.Jenkins:
Debug.Log ("CIServerTypeJenkinsToggle.isOn");
CIServerTypeJenkinsToggle.isOn = true;
break;
default:
Debug.Log ("CIServerTypeTeamCityToggle.isOn");
CIServerTypeTeamCityToggle.isOn = true;
break;
}
}
void InitializeVersion ()
{
InstallationNumberLabel.text = string.Empty;
m_versionService.ClientRegistered += (object sender, ClientRegisteredEventArgs e) =>
{
InstallationNumberLabel.text = string.Format ("Installation number: {0}", e.ClientInstance);
};
m_versionService.Register (ClientKind.Buildron, SHDevice.Family);
if (!SHGameInfo.IsBetaVersion)
{
m_versionService.UpdateInfoReceived += delegate(object sender, UpdateInfoReceivedEventArgs e)
{
UpdateButtonLabel.text = e.UpdateInfo.Description;
if (!string.IsNullOrEmpty (e.UpdateInfo.Url))
{
UpdateButton.onClick.AddListener (() =>
{
Application.OpenURL (e.UpdateInfo.Url);
});
}
};
m_versionService.CheckUpdates (ClientKind.Buildron, SHDevice.Family);
}
VersionNumberButtonLabel.text = string.Format ("Version:{0}", SHGameInfo.Version);
}
private bool CanStart
{
get
{
return !string.IsNullOrEmpty (CIServerIPInputField.text)
&& (m_buildsProvider != null && m_buildsProvider.AuthenticationRequirement != AuthenticationRequirement.Always
|| (!string.IsNullOrEmpty (CIServerUserNameInputField.text)
&& !string.IsNullOrEmpty (CIServerPasswordInputField.text)));
}
}
private void HandleUserAuthenticationCompleted (object sender, UserAuthenticationCompletedEventArgs e)
{
if (e.Success)
{
CIServerStatusLabel.text = "Authenticated. Loading...";
m_userService.UserAuthenticationCompleted -= HandleUserAuthenticationCompleted;
//m_animator.enabled = true;
PanelTransitionController.Instance.ShowMainPanel ();
}
else
{
CIServerStatusLabel.text = "IP, Username or Password invalid!";
if (HasAutoStartArgument ())
{
SHCoroutine.Start (10f, StartBuildron);
}
}
}
public void UpdateBuildsProvider ()
{
if (CIServerTypeHudsonToggle.isOn)
{
m_buildsProvider = new HudsonBuildsProvider (m_ciServer);
m_ciServer.ServerType = CIServerType.Hudson;
}
else if (CIServerTypeJenkinsToggle.isOn)
{
m_buildsProvider = new JenkinsBuildsProvider (m_ciServer);
m_ciServer.ServerType = CIServerType.Jenkins;
}
else
{
m_buildsProvider = new TeamCityBuildsProvider (m_ciServer);
m_ciServer.ServerType = CIServerType.TeamCity;
}
CIServerIPLabel.text = string.Format ("{0} IP", m_buildsProvider.Name);
CIServerAuthenticationTipLabel.text = m_buildsProvider.AuthenticationTip;
}
public void DestroyPanel ()
{
Destroy (gameObject);
}
public void UpdateRefreshSecondsLabel ()
{
RefreshSecondsLabel.text = String.Format ("Refresh seconds: {0}", RefreshSecondsSlider.value);
}
#endregion
#region Panel commands
public void StartBuildron ()
{
Debug.Log ("Starting...");
m_ciServer.IP = CIServerIPInputField.text;
m_ciServer.UserName = CIServerUserNameInputField.text;
m_ciServer.Password = CIServerPasswordInputField.text;
m_ciServer.RefreshSeconds = Convert.ToInt32 (RefreshSecondsSlider.value);
m_ciServerService.SaveCIServer (m_ciServer);
UpdateBuildsProvider ();
if (!m_ciServerService.Initialized)
{
if (m_ciServer.IP.Equals ("#TEST_MODE#"))
{
m_buildsProvider = new TestBuildsProvider ();
}
// Inject the FilterBuildsProvider.
m_buildsProvider = new FilterBuildsProvider (m_buildsProvider, m_remoteControlService, m_serverService);
m_userService.Initialize (m_buildsProvider);
CIServerStatusLabel.text = string.Format ("Trying to connect to {0}...", m_buildsProvider.Name);
m_buildService.Initialize (m_buildsProvider);
m_ciServerService.Initialize (m_buildsProvider);
m_ciServerService.AuthenticateUser (m_ciServer);
}
}
#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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.CSharp.RuntimeBinder.Semantics;
namespace Microsoft.CSharp.RuntimeBinder
{
internal sealed class ExpressionTreeCallRewriter : ExprVisitorBase
{
/////////////////////////////////////////////////////////////////////////////////
// Members
private sealed class ExpressionExpr : Expr
{
public readonly Expression Expression;
public ExpressionExpr(Expression e)
: base(0)
{
Expression = e;
}
}
private readonly Dictionary<ExprCall, Expression> _DictionaryOfParameters;
private readonly Expression[] _ListOfParameters;
// Counts how many EXPRSAVEs we've encountered so we know which index into the
// parameter list we should be taking.
private int _currentParameterIndex;
/////////////////////////////////////////////////////////////////////////////////
private ExpressionTreeCallRewriter(Expression[] listOfParameters)
{
_DictionaryOfParameters = new Dictionary<ExprCall, Expression>();
_ListOfParameters = listOfParameters;
}
/////////////////////////////////////////////////////////////////////////////////
public static Expression Rewrite(ExprBinOp binOp, Expression[] listOfParameters)
{
ExpressionTreeCallRewriter rewriter = new ExpressionTreeCallRewriter(listOfParameters);
// We should have a ExprBinOp that's an EK_SEQUENCE. The RHS of our sequence
// should be a call to PM_EXPRESSION_LAMBDA. The LHS of our sequence is the
// set of declarations for the parameters that we'll need.
// Assert all of these first, and then unwrap them.
Debug.Assert(binOp != null);
Debug.Assert(binOp.Kind == ExpressionKind.Sequence);
Debug.Assert(binOp.OptionalRightChild is ExprCall);
Debug.Assert(((ExprCall)binOp.OptionalRightChild).PredefinedMethod == PREDEFMETH.PM_EXPRESSION_LAMBDA);
Debug.Assert(binOp.OptionalLeftChild != null);
// Visit the left to generate the parameter construction.
rewriter.Visit(binOp.OptionalLeftChild);
ExprCall call = (ExprCall)binOp.OptionalRightChild;
ExpressionExpr e = rewriter.Visit(call) as ExpressionExpr;
return e.Expression;
}
/////////////////////////////////////////////////////////////////////////////////
protected override Expr VisitSAVE(ExprBinOp pExpr)
{
// Saves should have a LHS that is a CALL to PM_EXPRESSION_PARAMETER
// and a RHS that is a WRAP of that call.
ExprCall call = (ExprCall)pExpr.OptionalLeftChild;
Debug.Assert(call?.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_PARAMETER);
Debug.Assert(pExpr.OptionalRightChild is ExprWrap);
Expression parameter = _ListOfParameters[_currentParameterIndex++];
_DictionaryOfParameters.Add(call, parameter);
return null;
}
/////////////////////////////////////////////////////////////////////////////////
protected override Expr VisitCALL(ExprCall pExpr)
{
if (pExpr.PredefinedMethod == PREDEFMETH.PM_COUNT)
{
return pExpr;
}
Expression exp;
switch (pExpr.PredefinedMethod)
{
case PREDEFMETH.PM_EXPRESSION_LAMBDA:
return GenerateLambda(pExpr);
case PREDEFMETH.PM_EXPRESSION_CALL:
exp = GenerateCall(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX:
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2:
exp = GenerateArrayIndex(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_CONVERT:
case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED:
case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED:
exp = GenerateConvert(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_PROPERTY:
exp = GenerateProperty(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_FIELD:
exp = GenerateField(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_INVOKE:
exp = GenerateInvoke(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_NEW:
exp = GenerateNew(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_ADD:
case PREDEFMETH.PM_EXPRESSION_AND:
case PREDEFMETH.PM_EXPRESSION_DIVIDE:
case PREDEFMETH.PM_EXPRESSION_EQUAL:
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR:
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN:
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL:
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT:
case PREDEFMETH.PM_EXPRESSION_LESSTHAN:
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL:
case PREDEFMETH.PM_EXPRESSION_MODULO:
case PREDEFMETH.PM_EXPRESSION_MULTIPLY:
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL:
case PREDEFMETH.PM_EXPRESSION_OR:
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT:
case PREDEFMETH.PM_EXPRESSION_SUBTRACT:
case PREDEFMETH.PM_EXPRESSION_ORELSE:
case PREDEFMETH.PM_EXPRESSION_ANDALSO:
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED:
exp = GenerateBinaryOperator(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED:
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED:
exp = GenerateUserDefinedBinaryOperator(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_NEGATE:
case PREDEFMETH.PM_EXPRESSION_NOT:
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED:
exp = GenerateUnaryOperator(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED:
exp = GenerateUserDefinedUnaryOperator(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE:
exp = GenerateConstantType(pExpr);
break;
case PREDEFMETH.PM_EXPRESSION_ASSIGN:
exp = GenerateAssignment(pExpr);
break;
default:
Debug.Assert(false, "Invalid Predefined Method in VisitCALL");
throw Error.InternalCompilerError();
}
return new ExpressionExpr(exp);
}
// ExpressionTreeRewriter has optimized away identity or up-cast conversions, leaving us with a bare parameter
// access. Just get the expression for that parameter so the lambda produced can be p0 => p0
protected override Expr VisitWRAP(ExprWrap pExpr) => new ExpressionExpr(GetExpression(pExpr));
#region Generators
/////////////////////////////////////////////////////////////////////////////////
private Expr GenerateLambda(ExprCall pExpr)
{
// We always call Lambda(body, arrayinit) where the arrayinit
// is the initialization of the parameters.
return Visit(((ExprList)pExpr.OptionalArguments).OptionalElement);
/*
* // Do we need to do this?
Expression e = (body as ExpressionExpr).Expression;
if (e.Type.IsValueType)
{
// If we have a value type, convert it to object so that boxing
// can happen.
e = Expression.Convert(body.Expression, typeof(object));
}
* */
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateCall(ExprCall pExpr)
{
// Our arguments are: object, methodinfo, parameters.
// The object is either an EXPRWRAP of a CALL, or a CALL that is a PM_CONVERT, whose
// argument is the WRAP of a CALL. Deal with that first.
ExprMethodInfo methinfo;
ExprArrayInit arrinit;
ExprList list = (ExprList)pExpr.OptionalArguments;
if (list.OptionalNextListNode is ExprList next)
{
methinfo = (ExprMethodInfo)next.OptionalElement;
arrinit = (ExprArrayInit)next.OptionalNextListNode;
}
else
{
methinfo = (ExprMethodInfo)list.OptionalNextListNode;
arrinit = null;
}
Expression obj = null;
MethodInfo m = methinfo.MethodInfo;
Expression[] arguments = GetArgumentsFromArrayInit(arrinit);
if (m == null)
{
Debug.Assert(false, "How did we get a call that doesn't have a methodinfo?");
throw Error.InternalCompilerError();
}
// The DLR is expecting the instance for a static invocation to be null. If we have
// an instance method, fetch the object.
if (!m.IsStatic)
{
obj = GetExpression(((ExprList)pExpr.OptionalArguments).OptionalElement);
}
return Expression.Call(obj, m, arguments);
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateArrayIndex(ExprCall pExpr)
{
// We have two possibilities here - we're either a single index array, in which
// case we'll be PM_EXPRESSION_ARRAYINDEX, or we have multiple dimensions,
// in which case we are PM_EXPRESSION_ARRAYINDEX2.
//
// Our arguments then, are: object, index or object, indices.
ExprList list = (ExprList)pExpr.OptionalArguments;
Debug.Assert(list != null);
Expression obj = GetExpression(list.OptionalElement);
Expression[] indices;
if (pExpr.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX)
{
indices = new[] { GetExpression(list.OptionalNextListNode) };
}
else
{
Debug.Assert(pExpr.PredefinedMethod == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2);
indices = GetArgumentsFromArrayInit((ExprArrayInit)list.OptionalNextListNode);
}
return Expression.ArrayAccess(obj, indices);
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateConvert(ExprCall pExpr)
{
PREDEFMETH pm = pExpr.PredefinedMethod;
Expression e;
Type t;
if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED)
{
// If we have a user defined conversion, then we'll have the object
// as the first element, and another list as a second element. This list
// contains a TYPEOF as the first element, and the METHODINFO for the call
// as the second.
ExprList list = (ExprList)pExpr.OptionalArguments;
ExprList list2 = (ExprList)list.OptionalNextListNode;
e = GetExpression(list.OptionalElement);
t = ((ExprTypeOf)list2.OptionalElement).SourceType.AssociatedSystemType;
if (e.Type.MakeByRefType() == t)
{
// We're trying to convert from a type to its by ref type. Don't do that.
return e;
}
Debug.Assert((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) == 0);
MethodInfo m = ((ExprMethodInfo)list2.OptionalNextListNode).MethodInfo;
if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED)
{
return Expression.Convert(e, t, m);
}
return Expression.ConvertChecked(e, t, m);
}
else
{
Debug.Assert(pm == PREDEFMETH.PM_EXPRESSION_CONVERT ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED);
// If we have a standard conversion, then we'll have some object as
// the first list element (ie a WRAP or a CALL), and then a TYPEOF
// as the second list element.
ExprList list = (ExprList)pExpr.OptionalArguments;
e = GetExpression(list.OptionalElement);
t = ((ExprTypeOf)list.OptionalNextListNode).SourceType.AssociatedSystemType;
if (e.Type.MakeByRefType() == t)
{
// We're trying to convert from a type to its by ref type. Don't do that.
return e;
}
if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0)
{
// If we want to unbox this thing, return that instead of the convert.
return Expression.Unbox(e, t);
}
if (pm == PREDEFMETH.PM_EXPRESSION_CONVERT)
{
return Expression.Convert(e, t);
}
return Expression.ConvertChecked(e, t);
}
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateProperty(ExprCall pExpr)
{
ExprList list = (ExprList)pExpr.OptionalArguments;
Expr instance = list.OptionalElement;
Expr nextNode = list.OptionalNextListNode;
ExprPropertyInfo propinfo;
ExprArrayInit arguments;
if (nextNode is ExprList nextList)
{
propinfo = nextList.OptionalElement as ExprPropertyInfo;
arguments = nextList.OptionalNextListNode as ExprArrayInit;
}
else
{
propinfo = nextNode as ExprPropertyInfo;
arguments = null;
}
PropertyInfo p = propinfo.PropertyInfo;
if (p == null)
{
Debug.Assert(false, "How did we get a prop that doesn't have a propinfo?");
throw Error.InternalCompilerError();
}
if (arguments == null)
{
return Expression.Property(GetExpression(instance), p);
}
return Expression.Property(GetExpression(instance), p, GetArgumentsFromArrayInit(arguments));
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateField(ExprCall pExpr)
{
ExprList list = (ExprList)pExpr.OptionalArguments;
ExprFieldInfo fieldInfo = (ExprFieldInfo)list.OptionalNextListNode;
Debug.Assert(fieldInfo != null);
Type t = fieldInfo.FieldType.AssociatedSystemType;
FieldInfo f = fieldInfo.Field.AssociatedFieldInfo;
// This is to ensure that for embedded nopia types, we have the
// appropriate local type from the member itself; this is possible
// because nopia types are not generic or nested.
if (!t.IsGenericType && !t.IsNested)
{
t = f.DeclaringType;
}
// Now find the generic'ed one if we're generic.
if (t.IsGenericType)
{
f = t.GetField(f.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
}
return Expression.Field(GetExpression(list.OptionalElement), f);
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateInvoke(ExprCall pExpr)
{
ExprList list = (ExprList)pExpr.OptionalArguments;
return Expression.Invoke(
GetExpression(list.OptionalElement),
GetArgumentsFromArrayInit(list.OptionalNextListNode as ExprArrayInit));
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateNew(ExprCall pExpr)
{
ExprList list = (ExprList)pExpr.OptionalArguments;
ConstructorInfo constructor = ((ExprMethodInfo)list.OptionalElement).ConstructorInfo;
Expression[] arguments = GetArgumentsFromArrayInit(list.OptionalNextListNode as ExprArrayInit);
return Expression.New(constructor, arguments);
}
/////////////////////////////////////////////////////////////////////////////////
private static Expression GenerateConstantType(ExprCall pExpr)
{
ExprList list = (ExprList)pExpr.OptionalArguments;
return Expression.Constant(
list.OptionalElement.Object, ((ExprTypeOf)list.OptionalNextListNode).SourceType.AssociatedSystemType);
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateAssignment(ExprCall pExpr)
{
ExprList list = (ExprList)pExpr.OptionalArguments;
return Expression.Assign(
GetExpression(list.OptionalElement),
GetExpression(list.OptionalNextListNode));
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateBinaryOperator(ExprCall pExpr)
{
ExprList list = (ExprList)pExpr.OptionalArguments;
Debug.Assert(list != null);
Expression arg1 = GetExpression(list.OptionalElement);
Expression arg2 = GetExpression(list.OptionalNextListNode);
switch (pExpr.PredefinedMethod)
{
case PREDEFMETH.PM_EXPRESSION_ADD:
return Expression.Add(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_AND:
return Expression.And(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_DIVIDE:
return Expression.Divide(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_EQUAL:
return Expression.Equal(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR:
return Expression.ExclusiveOr(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN:
return Expression.GreaterThan(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL:
return Expression.GreaterThanOrEqual(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT:
return Expression.LeftShift(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_LESSTHAN:
return Expression.LessThan(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL:
return Expression.LessThanOrEqual(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_MODULO:
return Expression.Modulo(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_MULTIPLY:
return Expression.Multiply(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL:
return Expression.NotEqual(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_OR:
return Expression.Or(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT:
return Expression.RightShift(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_SUBTRACT:
return Expression.Subtract(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_ORELSE:
return Expression.OrElse(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_ANDALSO:
return Expression.AndAlso(arg1, arg2);
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED:
return Expression.AddChecked(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED:
return Expression.MultiplyChecked(arg1, arg2);
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED:
return Expression.SubtractChecked(arg1, arg2);
default:
Debug.Assert(false, "Invalid Predefined Method in GenerateBinaryOperator");
throw Error.InternalCompilerError();
}
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateUserDefinedBinaryOperator(ExprCall pExpr)
{
ExprList list = (ExprList)pExpr.OptionalArguments;
Expression arg1 = GetExpression(list.OptionalElement);
Expression arg2 = GetExpression(((ExprList)list.OptionalNextListNode).OptionalElement);
list = (ExprList)list.OptionalNextListNode;
MethodInfo methodInfo;
bool bIsLifted = false;
if (list.OptionalNextListNode is ExprList next)
{
ExprConstant isLifted = (ExprConstant)next.OptionalElement;
Debug.Assert(isLifted != null);
bIsLifted = isLifted.Val.Int32Val == 1;
methodInfo = ((ExprMethodInfo)next.OptionalNextListNode).MethodInfo;
}
else
{
methodInfo = ((ExprMethodInfo)list.OptionalNextListNode).MethodInfo;
}
switch (pExpr.PredefinedMethod)
{
case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED:
return Expression.Add(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED:
return Expression.And(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED:
return Expression.Divide(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED:
return Expression.Equal(arg1, arg2, bIsLifted, methodInfo);
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED:
return Expression.ExclusiveOr(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED:
return Expression.GreaterThan(arg1, arg2, bIsLifted, methodInfo);
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED:
return Expression.GreaterThanOrEqual(arg1, arg2, bIsLifted, methodInfo);
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED:
return Expression.LeftShift(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED:
return Expression.LessThan(arg1, arg2, bIsLifted, methodInfo);
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED:
return Expression.LessThanOrEqual(arg1, arg2, bIsLifted, methodInfo);
case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED:
return Expression.Modulo(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED:
return Expression.Multiply(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED:
return Expression.NotEqual(arg1, arg2, bIsLifted, methodInfo);
case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED:
return Expression.Or(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED:
return Expression.RightShift(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED:
return Expression.Subtract(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED:
return Expression.OrElse(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED:
return Expression.AndAlso(arg1, arg2, methodInfo);
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED:
return Expression.AddChecked(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED:
return Expression.MultiplyChecked(arg1, arg2, methodInfo);
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED:
return Expression.SubtractChecked(arg1, arg2, methodInfo);
default:
Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedBinaryOperator");
throw Error.InternalCompilerError();
}
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateUnaryOperator(ExprCall pExpr)
{
PREDEFMETH pm = pExpr.PredefinedMethod;
Expression arg = GetExpression(pExpr.OptionalArguments);
switch (pm)
{
case PREDEFMETH.PM_EXPRESSION_NOT:
return Expression.Not(arg);
case PREDEFMETH.PM_EXPRESSION_NEGATE:
return Expression.Negate(arg);
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED:
return Expression.NegateChecked(arg);
default:
Debug.Assert(false, "Invalid Predefined Method in GenerateUnaryOperator");
throw Error.InternalCompilerError();
}
}
/////////////////////////////////////////////////////////////////////////////////
private Expression GenerateUserDefinedUnaryOperator(ExprCall pExpr)
{
PREDEFMETH pm = pExpr.PredefinedMethod;
ExprList list = (ExprList)pExpr.OptionalArguments;
Expression arg = GetExpression(list.OptionalElement);
MethodInfo methodInfo = ((ExprMethodInfo)list.OptionalNextListNode).MethodInfo;
switch (pm)
{
case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED:
return Expression.Not(arg, methodInfo);
case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED:
return Expression.Negate(arg, methodInfo);
case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED:
return Expression.UnaryPlus(arg, methodInfo);
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED:
return Expression.NegateChecked(arg, methodInfo);
default:
Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedUnaryOperator");
throw Error.InternalCompilerError();
}
}
#endregion
#region Helpers
/////////////////////////////////////////////////////////////////////////////////
private Expression GetExpression(Expr pExpr)
{
if (pExpr is ExprWrap wrap)
{
return _DictionaryOfParameters[(ExprCall)wrap.OptionalExpression];
}
else if (pExpr is ExprConstant)
{
Debug.Assert(pExpr.Type is NullType);
return null;
}
else
{
// We can have a convert node or a call of a user defined conversion.
ExprCall call = (ExprCall)pExpr;
Debug.Assert(call != null);
PREDEFMETH pm = call.PredefinedMethod;
Debug.Assert(pm == PREDEFMETH.PM_EXPRESSION_CONVERT ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT ||
pm == PREDEFMETH.PM_EXPRESSION_CALL ||
pm == PREDEFMETH.PM_EXPRESSION_PROPERTY ||
pm == PREDEFMETH.PM_EXPRESSION_FIELD ||
pm == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX ||
pm == PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2 ||
pm == PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE ||
pm == PREDEFMETH.PM_EXPRESSION_NEW ||
// Binary operators.
pm == PREDEFMETH.PM_EXPRESSION_ASSIGN ||
pm == PREDEFMETH.PM_EXPRESSION_ADD ||
pm == PREDEFMETH.PM_EXPRESSION_AND ||
pm == PREDEFMETH.PM_EXPRESSION_DIVIDE ||
pm == PREDEFMETH.PM_EXPRESSION_EQUAL ||
pm == PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR ||
pm == PREDEFMETH.PM_EXPRESSION_GREATERTHAN ||
pm == PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL ||
pm == PREDEFMETH.PM_EXPRESSION_LEFTSHIFT ||
pm == PREDEFMETH.PM_EXPRESSION_LESSTHAN ||
pm == PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL ||
pm == PREDEFMETH.PM_EXPRESSION_MODULO ||
pm == PREDEFMETH.PM_EXPRESSION_MULTIPLY ||
pm == PREDEFMETH.PM_EXPRESSION_NOTEQUAL ||
pm == PREDEFMETH.PM_EXPRESSION_OR ||
pm == PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT ||
pm == PREDEFMETH.PM_EXPRESSION_SUBTRACT ||
pm == PREDEFMETH.PM_EXPRESSION_ORELSE ||
pm == PREDEFMETH.PM_EXPRESSION_ANDALSO ||
pm == PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED ||
// Checked binary
pm == PREDEFMETH.PM_EXPRESSION_ADDCHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED ||
// Unary operators.
pm == PREDEFMETH.PM_EXPRESSION_NOT ||
pm == PREDEFMETH.PM_EXPRESSION_NEGATE ||
pm == PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED ||
// Checked unary
pm == PREDEFMETH.PM_EXPRESSION_NEGATECHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED ||
pm == PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED ||
pm == PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED
);
switch (pm)
{
case PREDEFMETH.PM_EXPRESSION_CALL:
return GenerateCall(call);
case PREDEFMETH.PM_EXPRESSION_CONVERT:
case PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED:
case PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED:
return GenerateConvert(call);
case PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT:
{
ExprList list = (ExprList)call.OptionalArguments;
return
Expression.NewArrayInit(
((ExprTypeOf)list.OptionalElement).SourceType.AssociatedSystemType,
GetArgumentsFromArrayInit((ExprArrayInit)list.OptionalNextListNode));
}
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX:
case PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2:
return GenerateArrayIndex(call);
case PREDEFMETH.PM_EXPRESSION_NEW:
return GenerateNew(call);
case PREDEFMETH.PM_EXPRESSION_PROPERTY:
return GenerateProperty(call);
case PREDEFMETH.PM_EXPRESSION_FIELD:
return GenerateField(call);
case PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE:
return GenerateConstantType(call);
case PREDEFMETH.PM_EXPRESSION_ASSIGN:
return GenerateAssignment(call);
case PREDEFMETH.PM_EXPRESSION_ADD:
case PREDEFMETH.PM_EXPRESSION_AND:
case PREDEFMETH.PM_EXPRESSION_DIVIDE:
case PREDEFMETH.PM_EXPRESSION_EQUAL:
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR:
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN:
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL:
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT:
case PREDEFMETH.PM_EXPRESSION_LESSTHAN:
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL:
case PREDEFMETH.PM_EXPRESSION_MODULO:
case PREDEFMETH.PM_EXPRESSION_MULTIPLY:
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL:
case PREDEFMETH.PM_EXPRESSION_OR:
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT:
case PREDEFMETH.PM_EXPRESSION_SUBTRACT:
case PREDEFMETH.PM_EXPRESSION_ORELSE:
case PREDEFMETH.PM_EXPRESSION_ANDALSO:
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED:
return GenerateBinaryOperator(call);
case PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED:
// Checked
case PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED:
return GenerateUserDefinedBinaryOperator(call);
case PREDEFMETH.PM_EXPRESSION_NOT:
case PREDEFMETH.PM_EXPRESSION_NEGATE:
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED:
return GenerateUnaryOperator(call);
case PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED:
case PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED:
return GenerateUserDefinedUnaryOperator(call);
default:
Debug.Assert(false, "Invalid Predefined Method in GetExpression");
throw Error.InternalCompilerError();
}
}
}
private Expression[] GetArgumentsFromArrayInit(ExprArrayInit arrinit)
{
List<Expression> expressions = new List<Expression>();
if (arrinit != null)
{
Expr list = arrinit.OptionalArguments;
while (list != null)
{
Expr p;
if (list is ExprList pList)
{
p = pList.OptionalElement;
list = pList.OptionalNextListNode;
}
else
{
p = list;
list = null;
}
expressions.Add(GetExpression(p));
}
Debug.Assert(expressions.Count == arrinit.DimensionSizes[0]);
}
return expressions.ToArray();
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
namespace System.Interop.Intermediate
{
/// <summary>
/// Represents an instruction in an instruction tree.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay}")]
class TreeInstruction
{
private TreeInstruction _left;
private TreeInstruction _right;
private IrOpCode _opcode;
private object _operand;
private int _offset = -1;
private StackTypeDescription _stackType;
public TreeInstruction(IrOpCode opcode)
{
_opcode = opcode;
}
public TreeInstruction(IrOpCode opcode, StackTypeDescription stackType, object operand, int offset)
{
_opcode = opcode;
_operand = operand;
_offset = offset;
_stackType = stackType;
}
public TreeInstruction(IrOpCode opcode, StackTypeDescription stackType, object operand, int offset, TreeInstruction left)
{
_left = left;
_opcode = opcode;
_operand = operand;
_offset = offset;
_stackType = stackType;
}
public TreeInstruction(IrOpCode opcode, StackTypeDescription stackType, object operand, int offset, TreeInstruction left, TreeInstruction right)
{
_left = left;
_opcode = opcode;
_operand = operand;
_offset = offset;
_stackType = stackType;
_right = right;
}
public TreeInstruction Left
{
get { return _left; }
set { _left = value; }
}
/// <summary>
/// Returns left and right if they are non-null.
/// <para>Overridden implementations may return more - as does <see cref="MethodCallInstruction"/>.</para>
/// </summary>
/// <returns></returns>
public virtual TreeInstruction[] GetChildInstructions()
{
//Utilities.PretendVariableIsUsed(DebuggerDisplay);
//Utilities.PretendVariableIsUsed(SubTreeText);
if (Right != null)
return new TreeInstruction[] { Left, Right };
else if (Left != null)
return new TreeInstruction[] { Left };
else
return new TreeInstruction[0];
}
/// <summary>
/// Replaces the specified child with <paramref name="newchild"/>.
/// </summary>
/// <param name="childIndex"></param>
/// <param name="newchild"></param>
public virtual void ReplaceChild(int childIndex, TreeInstruction newchild)
{
switch (childIndex)
{
case 0:
if (Left == null)
throw new NullReferenceException("Left");
Left = newchild;
break;
case 1:
if (Right == null)
throw new NullReferenceException("Right");
Right = newchild;
break;
default:
throw new ArgumentOutOfRangeException("childIndex");
}
}
private string DebuggerDisplay
{
get
{
if ((Operand is string) || (Operand is int))
return "" + Opcode.IrCode + " " + Operand;
else if (Operand is LocalVariableInfo)
{
LocalVariableInfo r = (LocalVariableInfo)Operand;
return string.Format("{0} V_{1} ({2})", Opcode, r.LocalIndex, r.LocalType.Name);
}
else if (Operand is FieldInfo)
{
FieldInfo f = (FieldInfo)Operand;
return string.Format("{0} {1} ({2})", Opcode, f.Name, f.FieldType.Name);
}
else
return Opcode.IrCode.ToString();
}
}
public string DebuggerTreeDisplay()
{
string leftString = (_left != null ? _left.DebuggerTreeDisplay() : string.Empty);
string rightString = (_right != null ? _right.DebuggerTreeDisplay() : string.Empty);
return ((_left == null) && (_right == null) ? string.Format("{0} {1}", DebuggerDisplay, _offset) : string.Format("{0} {1} [{2}, {3}]", DebuggerDisplay, _offset, leftString, rightString));
}
private string SubTreeText
{
get { return new TreeDrawer().DrawSubTree(this); }
}
public TreeInstruction Right
{
get { return _right; }
set { _right = value; }
}
public IrOpCode Opcode
{
get { return _opcode; }
set { _opcode = value; }
}
#region Operand
public object Operand
{
get { return _operand; }
set { _operand = value; }
}
public MethodBase OperandAsMethod
{
get { return _operand as MethodBase; }
}
//public MethodCompiler OperandAsMethodCompiler
//{
// get { return _operand as MethodCompiler; }
//}
//public PpeMethod OperandAsPpeMethod
//{
// get { return _operand as PpeMethod; }
//}
public IrBasicBlock OperandAsBasicBlock
{
get { return _operand as IrBasicBlock; }
}
public int OperandAsInt32
{
get { return (int)_operand; }
}
public MethodVariable OperandAsVariable
{
get { return _operand as MethodVariable; }
}
public FieldInfo OperandAsField
{
get { return _operand as FieldInfo; }
}
#endregion
/// <summary>
/// Offset in the IL stream, where applicable; otherwise -1. Used for branching.
/// </summary>
public int Offset
{
get { return _offset; }
set { _offset = value; }
}
public StackTypeDescription StackType
{
get { return _stackType; }
set { _stackType = value; }
}
#region Tree iteration / checking.
/// <summary>
/// Applies <paramref name="converter"/> to each node in the tree; when the converter return non-null, the current
/// node is replaced with the return value.
/// </summary>
/// <param name="root"></param>
/// <param name="converter"></param>
/// <returns></returns>
public static TreeInstruction ForeachTreeInstruction(TreeInstruction root, Converter<TreeInstruction, TreeInstruction> converter)
{
if (root == null)
return null;
TreeInstruction newRoot = null;
var parentlist = new Stack<TreeInstruction>();
var childIndexList = new Stack<int>();
TreeInstruction parent = null;
int childIndex = 0;
TreeInstruction inst = root;
do
{
var newInst = converter(inst);
if (newInst != null)
{
inst = newInst;
if (parent != null)
parent.ReplaceChild(childIndex, newInst);
else
newRoot = newInst;
}
// Go to the nest instruction.
if (inst.GetChildInstructions().Length > 0)
{
parentlist.Push(parent);
childIndexList.Push(childIndex);
parent = inst;
childIndex = 0;
inst = inst.GetChildInstructions()[0];
}
else if (parent != null && childIndex + 1 < parent.GetChildInstructions().Length)
inst = parent.GetChildInstructions()[++childIndex];
else if (parent != null)
{
while (parent != null && childIndex + 1 >= parent.GetChildInstructions().Length)
{
parent = parentlist.Pop();
childIndex = childIndexList.Pop();
}
if (parent != null)
inst = parent.GetChildInstructions()[++childIndex];
//parent = parentlist.Peek();
//childIndex = childIndexList.Peek();
}
} while (parent != null);
return newRoot;
}
/// <summary>
/// For checking tree construction.
/// </summary>
/// <returns></returns>
public IEnumerable<TreeInstruction> IterateSubtree()
{
var list = new List<TreeInstruction>();
BuildPreorder(list);
return list;
}
/// <summary>
/// For checking tree construction.
/// </summary>
/// <param name="list"></param>
internal virtual void BuildPreorder(List<TreeInstruction> list)
{
list.Add(this);
if (Left != null)
Left.BuildPreorder(list);
if (Right != null)
Right.BuildPreorder(list);
}
#endregion
/// <summary>
/// Returns the first instruction in the tree; that is, the instruction in the far left side.
/// </summary>
/// <returns></returns>
public TreeInstruction GetFirstInstruction()
{
TreeInstruction parent = this;
TreeInstruction child = null;
do
{
if (child != null)
parent = child;
child = parent.GetChildInstructions().FirstOrDefault();
} while (child != null);
return parent;
}
/// <summary>
/// Returns the first instruction in the tree that has an address.
/// Instructions that were not in the IL do not have an offset and therefore
/// cannot be targets for branches.
/// </summary>
/// <returns></returns>
public TreeInstruction GetFirstInstructionWithOffset()
{
TreeInstruction parent = this;
TreeInstruction child = null;
do
{
if (child != null)
parent = child;
child = parent.GetChildInstructions().FirstOrDefault();
} while ((child != null) && (child.Offset >= 0));
//if (parent.Offset < 0)
// throw new ILSemanticErrorException("Can't find first instruction with offset.");
return parent;
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace Dynastream.Fit
{
/// <summary>
/// Implements the Monitoring profile message.
/// </summary>
public class MonitoringMesg : Mesg
{
#region Fields
static class CyclesSubfield
{
public static ushort Steps = 0;
public static ushort Strokes = 1;
public static ushort Subfields = 2;
public static ushort Active = Fit.SubfieldIndexActiveSubfield;
public static ushort MainField = Fit.SubfieldIndexMainField;
}
#endregion
#region Constructors
public MonitoringMesg() : base(Profile.mesgs[Profile.MonitoringIndex])
{
}
public MonitoringMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the Timestamp field
/// Units: s
/// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field
/// Units: s
/// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DeviceIndex field
/// Comment: Associates this data to device_info message. Not required for file with single device (sensor).</summary>
/// <returns>Returns nullable byte representing the DeviceIndex field</returns>
public byte? GetDeviceIndex()
{
return (byte?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DeviceIndex field
/// Comment: Associates this data to device_info message. Not required for file with single device (sensor).</summary>
/// <param name="deviceIndex_">Nullable field value to be set</param>
public void SetDeviceIndex(byte? deviceIndex_)
{
SetFieldValue(0, 0, deviceIndex_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Calories field
/// Units: kcal
/// Comment: Accumulated total calories. Maintained by MonitoringReader for each activity_type. See SDK documentation</summary>
/// <returns>Returns nullable ushort representing the Calories field</returns>
public ushort? GetCalories()
{
return (ushort?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Calories field
/// Units: kcal
/// Comment: Accumulated total calories. Maintained by MonitoringReader for each activity_type. See SDK documentation</summary>
/// <param name="calories_">Nullable field value to be set</param>
public void SetCalories(ushort? calories_)
{
SetFieldValue(1, 0, calories_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Distance field
/// Units: m
/// Comment: Accumulated distance. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary>
/// <returns>Returns nullable float representing the Distance field</returns>
public float? GetDistance()
{
return (float?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Distance field
/// Units: m
/// Comment: Accumulated distance. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary>
/// <param name="distance_">Nullable field value to be set</param>
public void SetDistance(float? distance_)
{
SetFieldValue(2, 0, distance_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Cycles field
/// Units: cycles
/// Comment: Accumulated cycles. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary>
/// <returns>Returns nullable float representing the Cycles field</returns>
public float? GetCycles()
{
return (float?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Cycles field
/// Units: cycles
/// Comment: Accumulated cycles. Maintained by MonitoringReader for each activity_type. See SDK documentation.</summary>
/// <param name="cycles_">Nullable field value to be set</param>
public void SetCycles(float? cycles_)
{
SetFieldValue(3, 0, cycles_, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Retrieves the Steps subfield
/// Units: steps</summary>
/// <returns>Nullable uint representing the Steps subfield</returns>
public uint? GetSteps()
{
return (uint?)GetFieldValue(3, 0, CyclesSubfield.Steps);
}
/// <summary>
///
/// Set Steps subfield
/// Units: steps</summary>
/// <param name="steps">Subfield value to be set</param>
public void SetSteps(uint? steps)
{
SetFieldValue(3, 0, steps, CyclesSubfield.Steps);
}
/// <summary>
/// Retrieves the Strokes subfield
/// Units: strokes</summary>
/// <returns>Nullable float representing the Strokes subfield</returns>
public float? GetStrokes()
{
return (float?)GetFieldValue(3, 0, CyclesSubfield.Strokes);
}
/// <summary>
///
/// Set Strokes subfield
/// Units: strokes</summary>
/// <param name="strokes">Subfield value to be set</param>
public void SetStrokes(float? strokes)
{
SetFieldValue(3, 0, strokes, CyclesSubfield.Strokes);
}
///<summary>
/// Retrieves the ActiveTime field
/// Units: s</summary>
/// <returns>Returns nullable float representing the ActiveTime field</returns>
public float? GetActiveTime()
{
return (float?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActiveTime field
/// Units: s</summary>
/// <param name="activeTime_">Nullable field value to be set</param>
public void SetActiveTime(float? activeTime_)
{
SetFieldValue(4, 0, activeTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityType field</summary>
/// <returns>Returns nullable ActivityType enum representing the ActivityType field</returns>
public ActivityType? GetActivityType()
{
object obj = GetFieldValue(5, 0, Fit.SubfieldIndexMainField);
ActivityType? value = obj == null ? (ActivityType?)null : (ActivityType)obj;
return value;
}
/// <summary>
/// Set ActivityType field</summary>
/// <param name="activityType_">Nullable field value to be set</param>
public void SetActivityType(ActivityType? activityType_)
{
SetFieldValue(5, 0, activityType_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivitySubtype field</summary>
/// <returns>Returns nullable ActivitySubtype enum representing the ActivitySubtype field</returns>
public ActivitySubtype? GetActivitySubtype()
{
object obj = GetFieldValue(6, 0, Fit.SubfieldIndexMainField);
ActivitySubtype? value = obj == null ? (ActivitySubtype?)null : (ActivitySubtype)obj;
return value;
}
/// <summary>
/// Set ActivitySubtype field</summary>
/// <param name="activitySubtype_">Nullable field value to be set</param>
public void SetActivitySubtype(ActivitySubtype? activitySubtype_)
{
SetFieldValue(6, 0, activitySubtype_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityLevel field</summary>
/// <returns>Returns nullable ActivityLevel enum representing the ActivityLevel field</returns>
public ActivityLevel? GetActivityLevel()
{
object obj = GetFieldValue(7, 0, Fit.SubfieldIndexMainField);
ActivityLevel? value = obj == null ? (ActivityLevel?)null : (ActivityLevel)obj;
return value;
}
/// <summary>
/// Set ActivityLevel field</summary>
/// <param name="activityLevel_">Nullable field value to be set</param>
public void SetActivityLevel(ActivityLevel? activityLevel_)
{
SetFieldValue(7, 0, activityLevel_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Distance16 field
/// Units: 100 * m</summary>
/// <returns>Returns nullable ushort representing the Distance16 field</returns>
public ushort? GetDistance16()
{
return (ushort?)GetFieldValue(8, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Distance16 field
/// Units: 100 * m</summary>
/// <param name="distance16_">Nullable field value to be set</param>
public void SetDistance16(ushort? distance16_)
{
SetFieldValue(8, 0, distance16_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Cycles16 field
/// Units: 2 * cycles (steps)</summary>
/// <returns>Returns nullable ushort representing the Cycles16 field</returns>
public ushort? GetCycles16()
{
return (ushort?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Cycles16 field
/// Units: 2 * cycles (steps)</summary>
/// <param name="cycles16_">Nullable field value to be set</param>
public void SetCycles16(ushort? cycles16_)
{
SetFieldValue(9, 0, cycles16_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActiveTime16 field
/// Units: s</summary>
/// <returns>Returns nullable ushort representing the ActiveTime16 field</returns>
public ushort? GetActiveTime16()
{
return (ushort?)GetFieldValue(10, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActiveTime16 field
/// Units: s</summary>
/// <param name="activeTime16_">Nullable field value to be set</param>
public void SetActiveTime16(ushort? activeTime16_)
{
SetFieldValue(10, 0, activeTime16_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the LocalTimestamp field
/// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary>
/// <returns>Returns nullable uint representing the LocalTimestamp field</returns>
public uint? GetLocalTimestamp()
{
return (uint?)GetFieldValue(11, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set LocalTimestamp field
/// Comment: Must align to logging interval, for example, time must be 00:00:00 for daily log.</summary>
/// <param name="localTimestamp_">Nullable field value to be set</param>
public void SetLocalTimestamp(uint? localTimestamp_)
{
SetFieldValue(11, 0, localTimestamp_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Temperature field
/// Units: C
/// Comment: Avg temperature during the logging interval ended at timestamp</summary>
/// <returns>Returns nullable float representing the Temperature field</returns>
public float? GetTemperature()
{
return (float?)GetFieldValue(12, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Temperature field
/// Units: C
/// Comment: Avg temperature during the logging interval ended at timestamp</summary>
/// <param name="temperature_">Nullable field value to be set</param>
public void SetTemperature(float? temperature_)
{
SetFieldValue(12, 0, temperature_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TemperatureMin field
/// Units: C
/// Comment: Min temperature during the logging interval ended at timestamp</summary>
/// <returns>Returns nullable float representing the TemperatureMin field</returns>
public float? GetTemperatureMin()
{
return (float?)GetFieldValue(14, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TemperatureMin field
/// Units: C
/// Comment: Min temperature during the logging interval ended at timestamp</summary>
/// <param name="temperatureMin_">Nullable field value to be set</param>
public void SetTemperatureMin(float? temperatureMin_)
{
SetFieldValue(14, 0, temperatureMin_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TemperatureMax field
/// Units: C
/// Comment: Max temperature during the logging interval ended at timestamp</summary>
/// <returns>Returns nullable float representing the TemperatureMax field</returns>
public float? GetTemperatureMax()
{
return (float?)GetFieldValue(15, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TemperatureMax field
/// Units: C
/// Comment: Max temperature during the logging interval ended at timestamp</summary>
/// <param name="temperatureMax_">Nullable field value to be set</param>
public void SetTemperatureMax(float? temperatureMax_)
{
SetFieldValue(15, 0, temperatureMax_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field ActivityTime</returns>
public int GetNumActivityTime()
{
return GetNumFieldValues(16, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActivityTime field
/// Units: minutes
/// Comment: Indexed using minute_activity_level enum</summary>
/// <param name="index">0 based index of ActivityTime element to retrieve</param>
/// <returns>Returns nullable ushort representing the ActivityTime field</returns>
public ushort? GetActivityTime(int index)
{
return (ushort?)GetFieldValue(16, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActivityTime field
/// Units: minutes
/// Comment: Indexed using minute_activity_level enum</summary>
/// <param name="index">0 based index of activity_time</param>
/// <param name="activityTime_">Nullable field value to be set</param>
public void SetActivityTime(int index, ushort? activityTime_)
{
SetFieldValue(16, index, activityTime_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the ActiveCalories field
/// Units: kcal</summary>
/// <returns>Returns nullable ushort representing the ActiveCalories field</returns>
public ushort? GetActiveCalories()
{
return (ushort?)GetFieldValue(19, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set ActiveCalories field
/// Units: kcal</summary>
/// <param name="activeCalories_">Nullable field value to be set</param>
public void SetActiveCalories(ushort? activeCalories_)
{
SetFieldValue(19, 0, activeCalories_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CurrentActivityTypeIntensity field
/// Comment: Indicates single type / intensity for duration since last monitoring message.</summary>
/// <returns>Returns nullable byte representing the CurrentActivityTypeIntensity field</returns>
public byte? GetCurrentActivityTypeIntensity()
{
return (byte?)GetFieldValue(24, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CurrentActivityTypeIntensity field
/// Comment: Indicates single type / intensity for duration since last monitoring message.</summary>
/// <param name="currentActivityTypeIntensity_">Nullable field value to be set</param>
public void SetCurrentActivityTypeIntensity(byte? currentActivityTypeIntensity_)
{
SetFieldValue(24, 0, currentActivityTypeIntensity_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TimestampMin8 field
/// Units: min</summary>
/// <returns>Returns nullable byte representing the TimestampMin8 field</returns>
public byte? GetTimestampMin8()
{
return (byte?)GetFieldValue(25, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TimestampMin8 field
/// Units: min</summary>
/// <param name="timestampMin8_">Nullable field value to be set</param>
public void SetTimestampMin8(byte? timestampMin8_)
{
SetFieldValue(25, 0, timestampMin8_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Timestamp16 field
/// Units: s</summary>
/// <returns>Returns nullable ushort representing the Timestamp16 field</returns>
public ushort? GetTimestamp16()
{
return (ushort?)GetFieldValue(26, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Timestamp16 field
/// Units: s</summary>
/// <param name="timestamp16_">Nullable field value to be set</param>
public void SetTimestamp16(ushort? timestamp16_)
{
SetFieldValue(26, 0, timestamp16_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the HeartRate field
/// Units: bpm</summary>
/// <returns>Returns nullable byte representing the HeartRate field</returns>
public byte? GetHeartRate()
{
return (byte?)GetFieldValue(27, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set HeartRate field
/// Units: bpm</summary>
/// <param name="heartRate_">Nullable field value to be set</param>
public void SetHeartRate(byte? heartRate_)
{
SetFieldValue(27, 0, heartRate_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Intensity field</summary>
/// <returns>Returns nullable float representing the Intensity field</returns>
public float? GetIntensity()
{
return (float?)GetFieldValue(28, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Intensity field</summary>
/// <param name="intensity_">Nullable field value to be set</param>
public void SetIntensity(float? intensity_)
{
SetFieldValue(28, 0, intensity_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the DurationMin field
/// Units: min</summary>
/// <returns>Returns nullable ushort representing the DurationMin field</returns>
public ushort? GetDurationMin()
{
return (ushort?)GetFieldValue(29, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set DurationMin field
/// Units: min</summary>
/// <param name="durationMin_">Nullable field value to be set</param>
public void SetDurationMin(ushort? durationMin_)
{
SetFieldValue(29, 0, durationMin_, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the Duration field
/// Units: s</summary>
/// <returns>Returns nullable uint representing the Duration field</returns>
public uint? GetDuration()
{
return (uint?)GetFieldValue(30, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set Duration field
/// Units: s</summary>
/// <param name="duration_">Nullable field value to be set</param>
public void SetDuration(uint? duration_)
{
SetFieldValue(30, 0, duration_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
//-----------------------------------------------------------------------
// <copyright file="ActorMaterializer.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Runtime.Serialization;
using Akka.Actor;
using Akka.Configuration;
using Akka.Dispatch;
using Akka.Event;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Dsl.Internal;
using Akka.Streams.Implementation;
using Akka.Streams.Supervision;
using Akka.Util;
using Reactive.Streams;
using Decider = Akka.Streams.Supervision.Decider;
namespace Akka.Streams
{
/// <summary>
/// A ActorMaterializer takes the list of transformations comprising a
/// <see cref="IFlow{TOut,TMat}"/> and materializes them in the form of
/// <see cref="IProcessor{T1,T2}"/> instances. How transformation
/// steps are split up into asynchronous regions is implementation
/// dependent.
/// </summary>
public abstract class ActorMaterializer : IMaterializer, IDisposable
{
public static Config DefaultConfig()
=> ConfigurationFactory.FromResource<ActorMaterializer>("Akka.Streams.reference.conf");
#region static
/// <summary>
/// <para>
/// Creates a ActorMaterializer which will execute every step of a transformation
/// pipeline within its own <see cref="ActorBase"/>. The required <see cref="IActorRefFactory"/>
/// (which can be either an <see cref="ActorSystem"/> or an <see cref="IActorContext"/>)
/// will be used to create one actor that in turn creates actors for the transformation steps.
/// </para>
/// <para>
/// The materializer's <see cref="ActorMaterializerSettings"/> will be obtained from the
/// configuration of the <paramref name="context"/>'s underlying <see cref="ActorSystem"/>.
/// </para>
/// <para>
/// The <paramref name="namePrefix"/> is used as the first part of the names of the actors running
/// the processing steps. The default <paramref name="namePrefix"/> is "flow". The actor names are built up of
/// `namePrefix-flowNumber-flowStepNumber-stepName`.
/// </para>
/// </summary>
public static ActorMaterializer Create(IActorRefFactory context, ActorMaterializerSettings settings = null, string namePrefix = null)
{
var haveShutDown = new AtomicBoolean();
var system = ActorSystemOf(context);
system.Settings.InjectTopLevelFallback(DefaultConfig());
settings = settings ?? ActorMaterializerSettings.Create(system);
return new ActorMaterializerImpl(
system: system,
settings: settings,
dispatchers: system.Dispatchers,
supervisor: context.ActorOf(StreamSupervisor.Props(settings, haveShutDown).WithDispatcher(settings.Dispatcher), StreamSupervisor.NextName()),
haveShutDown: haveShutDown,
flowNames: EnumerableActorName.Create(namePrefix ?? "Flow"));
}
internal static ActorMaterializer Downcast(IMaterializer materializer)
{
//FIXME this method is going to cause trouble for other Materializer implementations
if (materializer is ActorMaterializer)
return (ActorMaterializer)materializer;
throw new ArgumentException($"Expected {typeof(ActorMaterializer)} but got {materializer.GetType()}");
}
private static ActorSystem ActorSystemOf(IActorRefFactory context)
{
if (context is ExtendedActorSystem)
return (ActorSystem)context;
if (context is IActorContext)
return ((IActorContext)context).System;
if (context == null)
throw new ArgumentNullException(nameof(context), "IActorRefFactory must be defined");
throw new ArgumentException($"ActorRefFactory context must be a ActorSystem or ActorContext, got [{context.GetType()}]");
}
#endregion
public abstract ActorMaterializerSettings Settings { get; }
/// <summary>
/// Indicates if the materializer has been shut down.
/// </summary>
public abstract bool IsShutdown { get; }
public abstract MessageDispatcher ExecutionContext { get; }
public abstract ActorSystem System { get; }
public abstract ILoggingAdapter Logger { get; }
public abstract IActorRef Supervisor { get; }
public abstract IMaterializer WithNamePrefix(string namePrefix);
public abstract TMat Materialize<TMat>(IGraph<ClosedShape, TMat> runnable);
public abstract ICancelable ScheduleOnce(TimeSpan delay, Action action);
public abstract ICancelable ScheduleRepeatedly(TimeSpan initialDelay, TimeSpan interval, Action action);
public abstract ActorMaterializerSettings EffectiveSettings(Attributes attributes);
/// <summary>
/// Shuts down this materializer and all the stages that have been materialized through this materializer. After
/// having shut down, this materializer cannot be used again. Any attempt to materialize stages after having
/// shut down will result in an <see cref="IllegalStateException"/> being thrown at materialization time.
/// </summary>
public abstract void Shutdown();
protected internal abstract IActorRef ActorOf(MaterializationContext context, Props props);
public void Dispose() => Shutdown();
}
/// <summary>
/// This exception signals that an actor implementing a Reactive Streams Subscriber, Publisher or Processor
/// has been terminated without being notified by an onError, onComplete or cancel signal. This usually happens
/// when an ActorSystem is shut down while stream processing actors are still running.
/// </summary>
[Serializable]
public class AbruptTerminationException : Exception
{
public readonly IActorRef Actor;
public AbruptTerminationException(IActorRef actor)
: base($"Processor actor [{actor}] terminated abruptly")
{
Actor = actor;
}
protected AbruptTerminationException(SerializationInfo info, StreamingContext context) : base(info, context)
{
Actor = (IActorRef)info.GetValue("Actor", typeof(IActorRef));
}
}
/// <summary>
/// This exception or subtypes thereof should be used to signal materialization failures.
/// </summary>
public class MaterializationException : Exception
{
public MaterializationException(string message, Exception innerException) : base(message, innerException) { }
protected MaterializationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
/// <summary>
/// This class describes the configurable properties of the <see cref="ActorMaterializer"/>.
/// Please refer to the withX methods for descriptions of the individual settings.
/// </summary>
public sealed class ActorMaterializerSettings
{
public static ActorMaterializerSettings Create(ActorSystem system)
{
var config = system.Settings.Config.GetConfig("akka.stream.materializer");
if(config == null)
throw new ArgumentException("Couldn't build an actor materializer settings. `akka.stream.materializer` config path is not defined.");
return Create(config);
}
private static ActorMaterializerSettings Create(Config config)
{
return new ActorMaterializerSettings(
initialInputBufferSize: config.GetInt("initial-input-buffer-size"),
maxInputBufferSize: config.GetInt("max-input-buffer-size"),
dispatcher: config.GetString("dispatcher"),
supervisionDecider: Deciders.StoppingDecider,
subscriptionTimeoutSettings: StreamSubscriptionTimeoutSettings.Create(config),
isDebugLogging: config.GetBoolean("debug-logging"),
outputBurstLimit: config.GetInt("output-burst-limit"),
isFuzzingMode: config.GetBoolean("debug.fuzzing-mode"),
isAutoFusing: config.GetBoolean("auto-fusing"),
maxFixedBufferSize: config.GetInt("max-fixed-buffer-size"),
syncProcessingLimit: config.GetInt("sync-processing-limit"));
}
private const int DefaultlMaxFixedbufferSize = 1000;
public readonly int InitialInputBufferSize;
public readonly int MaxInputBufferSize;
public readonly string Dispatcher;
public readonly Decider SupervisionDecider;
public readonly StreamSubscriptionTimeoutSettings SubscriptionTimeoutSettings;
public readonly bool IsDebugLogging;
public readonly int OutputBurstLimit;
public readonly bool IsFuzzingMode;
public readonly bool IsAutoFusing;
public readonly int MaxFixedBufferSize;
public readonly int SyncProcessingLimit;
public ActorMaterializerSettings(int initialInputBufferSize, int maxInputBufferSize, string dispatcher, Decider supervisionDecider, StreamSubscriptionTimeoutSettings subscriptionTimeoutSettings, bool isDebugLogging, int outputBurstLimit, bool isFuzzingMode, bool isAutoFusing, int maxFixedBufferSize, int syncProcessingLimit = DefaultlMaxFixedbufferSize)
{
InitialInputBufferSize = initialInputBufferSize;
MaxInputBufferSize = maxInputBufferSize;
Dispatcher = dispatcher;
SupervisionDecider = supervisionDecider;
SubscriptionTimeoutSettings = subscriptionTimeoutSettings;
IsDebugLogging = isDebugLogging;
OutputBurstLimit = outputBurstLimit;
IsFuzzingMode = isFuzzingMode;
IsAutoFusing = isAutoFusing;
MaxFixedBufferSize = maxFixedBufferSize;
SyncProcessingLimit = syncProcessingLimit;
}
public ActorMaterializerSettings WithInputBuffer(int initialSize, int maxSize)
{
return new ActorMaterializerSettings(initialSize, maxSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
public ActorMaterializerSettings WithDispatcher(string dispatcher)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
public ActorMaterializerSettings WithSupervisionStrategy(Decider decider)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, decider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
public ActorMaterializerSettings WithDebugLogging(bool isEnabled)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, isEnabled, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
public ActorMaterializerSettings WithFuzzingMode(bool isFuzzingMode)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, isFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
public ActorMaterializerSettings WithAutoFusing(bool isAutoFusing)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, isAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
public ActorMaterializerSettings WithMaxFixedBufferSize(int maxFixedBufferSize)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, maxFixedBufferSize, SyncProcessingLimit);
}
public ActorMaterializerSettings WithSyncProcessingLimit(int limit)
{
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, SubscriptionTimeoutSettings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, limit);
}
public ActorMaterializerSettings WithSubscriptionTimeoutSettings(StreamSubscriptionTimeoutSettings settings)
{
if (Equals(settings, SubscriptionTimeoutSettings))
return this;
return new ActorMaterializerSettings(InitialInputBufferSize, MaxInputBufferSize, Dispatcher, SupervisionDecider, settings, IsDebugLogging, OutputBurstLimit, IsFuzzingMode, IsAutoFusing, MaxFixedBufferSize, SyncProcessingLimit);
}
}
/// <summary>
/// Leaked publishers and subscribers are cleaned up when they are not used within a given deadline, configured by <see cref="StreamSubscriptionTimeoutSettings"/>.
/// </summary>
public sealed class StreamSubscriptionTimeoutSettings : IEquatable<StreamSubscriptionTimeoutSettings>
{
public static StreamSubscriptionTimeoutSettings Create(Config config)
{
var c = config.GetConfig("subscription-timeout");
var configMode = c.GetString("mode").ToLowerInvariant();
StreamSubscriptionTimeoutTerminationMode mode;
switch (configMode)
{
case "no": case "off": case "false": case "noop": mode = StreamSubscriptionTimeoutTerminationMode.NoopTermination; break;
case "warn": mode = StreamSubscriptionTimeoutTerminationMode.WarnTermination; break;
case "cancel": mode = StreamSubscriptionTimeoutTerminationMode.CancelTermination; break;
default: throw new ArgumentException("akka.stream.materializer.subscribtion-timeout.mode was not defined or has invalid value. Valid values are: no, off, false, noop, warn, cancel");
}
return new StreamSubscriptionTimeoutSettings(
mode: mode,
timeout: c.GetTimeSpan("timeout"));
}
public readonly StreamSubscriptionTimeoutTerminationMode Mode;
public readonly TimeSpan Timeout;
public StreamSubscriptionTimeoutSettings(StreamSubscriptionTimeoutTerminationMode mode, TimeSpan timeout)
{
Mode = mode;
Timeout = timeout;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, null))
return false;
if (ReferenceEquals(obj, this))
return true;
if (obj is StreamSubscriptionTimeoutSettings)
return Equals((StreamSubscriptionTimeoutSettings) obj);
return false;
}
public bool Equals(StreamSubscriptionTimeoutSettings other)
=> Mode == other.Mode && Timeout.Equals(other.Timeout);
public override int GetHashCode()
{
unchecked
{
return ((int)Mode * 397) ^ Timeout.GetHashCode();
}
}
public override string ToString() => $"StreamSubscriptionTimeoutSettings<{Mode}, {Timeout}>";
}
/// <summary>
/// This mode describes what shall happen when the subscription timeout expires
/// for substream Publishers created by operations like <see cref="InternalFlowOperations.PrefixAndTail{T,TMat}"/>.
/// </summary>
public enum StreamSubscriptionTimeoutTerminationMode
{
/// <summary>
/// Do not do anything when timeout expires.
/// </summary>
NoopTermination,
/// <summary>
/// Log a warning when the timeout expires.
/// </summary>
WarnTermination,
/// <summary>
/// When the timeout expires attach a Subscriber that will immediately cancel its subscription.
/// </summary>
CancelTermination
}
public static class ActorMaterializerExtensions
{
/// <summary>
/// <para>
/// Creates a ActorMaterializer which will execute every step of a transformation
/// pipeline within its own <see cref="ActorBase"/>. The required <see cref="IActorRefFactory"/>
/// (which can be either an <see cref="ActorSystem"/> or an <see cref="IActorContext"/>)
/// will be used to create one actor that in turn creates actors for the transformation steps.
/// </para>
/// <para>
/// The materializer's <see cref="ActorMaterializerSettings"/> will be obtained from the
/// configuration of the <paramref name="context"/>'s underlying <see cref="ActorSystem"/>.
/// </para>
/// <para>
/// The <paramref name="namePrefix"/> is used as the first part of the names of the actors running
/// the processing steps. The default <paramref name="namePrefix"/> is "flow". The actor names are built up of
/// namePrefix-flowNumber-flowStepNumber-stepName.
/// </para>
/// </summary>
public static ActorMaterializer Materializer(this IActorRefFactory context, ActorMaterializerSettings settings = null, string namePrefix = null)
=> ActorMaterializer.Create(context, settings, namePrefix);
}
}
| |
namespace FakeItEasy.IntegrationTests
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
#if FEATURE_NETCORE_REFLECTION
using System.Reflection;
#endif
using FakeItEasy.Configuration;
using FakeItEasy.Core;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xunit;
public class GeneralTests
{
public interface ITypeWithFakeableProperties
{
IEnumerable<object> Collection { get; }
IFoo Foo { get; }
}
[SuppressMessage("Microsoft.Design", "CA1040:AvoidEmptyInterfaces", Justification = "Required for testing.")]
public interface IEmpty
{
}
[Fact]
public void Faked_object_with_fakeable_properties_should_have_fake_as_default_value()
{
// Arrange
// Act
var fake = A.Fake<ITypeWithFakeableProperties>();
// Assert
fake.Collection.Should().NotBeNull();
fake.Foo.Should().NotBeNull();
}
[Fact]
public void Faked_object_with_method_that_returns_fakeable_type_should_return_fake_by_default()
{
// Arrange
var fake = A.Fake<IEnumerable<string>>();
// Act
var enumerator = fake.GetEnumerator();
// Assert
enumerator.Should().NotBeNull();
Fake.GetFakeManager(enumerator).Should().NotBeNull();
}
[Fact]
public void Faked_object_with_additional_attributes_should_create_a_type_with_those_attributes()
{
// Arrange
// Act
var fake = A.Fake<IEmpty>(a => a.WithAttributes(() => new ForTestAttribute()));
// Assert
fake.GetType().GetTypeInfo().GetCustomAttributes(typeof(ForTestAttribute), true).Should().HaveCount(1);
}
[Fact]
public void Additional_attributes_should_not_be_added_to_the_next_fake()
{
// Arrange
A.Fake<IEmpty>(a => a.WithAttributes(() => new ForTestAttribute()));
// Act
var secondFake = A.Fake<IFormattable>();
// Assert
secondFake.GetType().GetTypeInfo().GetCustomAttributes(typeof(ForTestAttribute), true).Should().BeEmpty();
}
[Fact]
public void ErrorMessage_when_type_cannot_be_faked_should_specify_non_resolvable_constructor_arguments()
{
// Arrange
// Act
var exception = Record.Exception(() => A.Fake<NonResolvableType>());
// Assert
const string ExpectedMessage = @"
The constructors with the following signatures were not tried:
(FakeItEasy.IntegrationTests.IFoo, *FakeItEasy.IntegrationTests.GeneralTests+NoInstanceType)
(*FakeItEasy.IntegrationTests.GeneralTests+NoInstanceType)
Types marked with * could not be resolved. Please provide a Dummy Factory to enable these constructors.
";
exception.Should()
.BeAnExceptionOfType<FakeCreationException>().And
.Message.Should().ContainModuloLineEndings(ExpectedMessage);
}
[Fact]
public void ErrorMessage_when_configuring_void_call_that_cannot_be_configured_should_be_correct()
{
// Arrange
var fake = A.Fake<TypeWithNonConfigurableMethod>();
// Act
var exception = Record.Exception(() =>
A.CallTo(() => fake.NonVirtualVoidMethod(string.Empty, 1)).DoesNothing());
// Assert
exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And
.Message.Should().Contain("Non-virtual");
}
[Fact]
public void ErrorMessage_when_configuring_function_call_that_cannot_be_configured_should_be_correct()
{
// Arrange
var fake = A.Fake<TypeWithNonConfigurableMethod>();
// Act
var exception = Record.Exception(() =>
A.CallTo(() => fake.NonVirtualFunction(string.Empty, 1)).Returns(10));
// Assert
exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And
.Message.Should().Contain("Non-virtual");
}
[Fact]
public void ErrorMessage_when_configuring_generic_function_call_that_cannot_be_configured_should_be_correct()
{
// Arrange
var fake = A.Fake<TypeWithNonConfigurableMethod>();
// Act
var exception = Record.Exception(() =>
A.CallTo(() => fake.GenericNonVirtualFunction<int>()).Returns(10));
// Assert
exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And
.Message.Should().Contain("Non-virtual");
}
[Fact]
public void Should_be_able_to_generate_class_fake_that_implements_additional_interface()
{
// Arrange
var fake = A.Fake<FakeableClass>(x => x.Implements(typeof(IFoo)).Implements(typeof(IFormattable)));
// Act
// Assert
fake.Should()
.BeAssignableTo<IFoo>().And
.BeAssignableTo<IFormattable>().And
.BeAssignableTo<FakeableClass>();
}
[Fact]
public void Should_be_able_to_generate_class_fake_that_implements_additional_interface_using_generic()
{
// Arrange
var fake = A.Fake<FakeableClass>(x => x.Implements<IFoo>().Implements<IFormattable>());
// Act
// Assert
fake.Should()
.BeAssignableTo<IFoo>().And
.BeAssignableTo<IFormattable>().And
.BeAssignableTo<FakeableClass>();
}
[Fact]
public void Should_be_able_to_generate_interface_fake_that_implements_additional_interface()
{
// Arrange
var fake = A.Fake<IFoo>(x => x.Implements(typeof(IFormatProvider)).Implements(typeof(IFormattable)));
// Act
// Assert
fake.Should()
.BeAssignableTo<IFoo>().And
.BeAssignableTo<IFormattable>().And
.BeAssignableTo<IFormatProvider>();
}
[Fact]
public void Should_be_able_to_generate_interface_fake_that_implements_additional_interface_using_generic()
{
// Arrange
var fake = A.Fake<IFoo>(x => x.Implements<IFormatProvider>().Implements<IFormattable>());
// Act
// Assert
fake.Should()
.BeAssignableTo<IFoo>().And
.BeAssignableTo<IFormattable>().And
.BeAssignableTo<IFormatProvider>();
}
[Fact]
public void FakeCollection_should_return_list_where_all_objects_are_fakes()
{
// Arrange
// Act
var result = A.CollectionOfFake<IFoo>(10);
// Assert
result.Should().BeAssignableTo<IList<IFoo>>().And
.OnlyContain(foo => foo is object && Fake.GetFakeManager(foo) is object);
}
[Fact]
public void DummyCollection_should_return_correct_number_of_dummies()
{
// Arrange
// Act
var result = A.CollectionOfDummy<IFoo>(10);
// Assert
result.Should().HaveCount(10);
}
[Fact]
public void Returns_from_sequence_only_applies_the_number_as_many_times_as_the_number_of_specified_values()
{
// Arrange
var foo = A.Fake<IFoo>();
A.CallTo(() => foo.Baz()).Throws(new InvalidOperationException());
A.CallTo(() => foo.Baz()).ReturnsNextFromSequence(1, 2);
foo.Baz();
foo.Baz();
// Act
var exception = Record.Exception(() => foo.Baz());
// Assert
exception.Should().BeAnExceptionOfType<InvalidOperationException>();
}
public class NonResolvableType
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "foo", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "bar", Justification = "Required for testing.")]
public NonResolvableType(IFoo foo, NoInstanceType bar)
{
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "bar", Justification = "Required for testing.")]
protected NonResolvableType(NoInstanceType bar)
{
}
}
public class NoInstanceType
{
private NoInstanceType()
{
}
}
public class FakeableClass
{
public virtual void Foo()
{
}
}
public class TypeWithNonConfigurableMethod
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "otherArgument", Justification = "Required for testing.")]
public void NonVirtualVoidMethod(string argument, int otherArgument)
{
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "otherArgument", Justification = "Required for testing.")]
public int NonVirtualFunction(string argument, int otherArgument)
{
return 1;
}
public T GenericNonVirtualFunction<T>() where T : struct => default;
}
}
}
| |
using Facebook;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public sealed class FB : ScriptableObject
{
public static InitDelegate OnInitComplete;
public static HideUnityDelegate OnHideUnity;
private static IFacebook facebook;
private static string authResponse;
private static bool isInitCalled = false;
private static string appId;
private static bool cookie;
private static bool logging;
private static bool status;
private static bool xfbml;
private static bool frictionlessRequests;
static IFacebook FacebookImpl
{
get
{
if (facebook == null)
{
throw new NullReferenceException("Facebook object is not yet loaded. Did you call FB.Init()?");
}
return facebook;
}
}
public static string AppId
{
get
{
// appId might be different from FBSettings.AppId
// if using the programmatic version of FB.Init()
return appId;
}
}
public static string UserId
{
get
{
return (facebook != null) ? facebook.UserId : "";
}
}
public static string AccessToken
{
get
{
return (facebook != null) ? facebook.AccessToken : "";
}
}
public static DateTime AccessTokenExpiresAt
{
get
{
return (facebook != null) ? facebook.AccessTokenExpiresAt : DateTime.MinValue;
}
}
public static bool IsLoggedIn
{
get
{
return (facebook != null) && facebook.IsLoggedIn;
}
}
public static bool IsInitialized
{
get
{
return (facebook != null) && facebook.IsInitialized;
}
}
#region Init
/**
* This is the preferred way to call FB.Init(). It will take the facebook app id specified in your
* "Facebook" => "Edit Settings" menu when it is called.
*
* onInitComplete - Delegate is called when FB.Init() finished initializing everything.
* By passing in a delegate you can find out when you can safely call the other methods.
*/
public static void Init(InitDelegate onInitComplete, HideUnityDelegate onHideUnity = null, string authResponse = null)
{
Init(
onInitComplete,
FBSettings.AppId,
FBSettings.Cookie,
FBSettings.Logging,
FBSettings.Status,
FBSettings.Xfbml,
FBSettings.FrictionlessRequests,
onHideUnity,
authResponse);
}
/**
* If you need a more programmatic way to set the facebook app id and other setting call this function.
* Useful for a build pipeline that requires no human input.
*/
public static void Init(
InitDelegate onInitComplete,
string appId,
bool cookie = true,
bool logging = true,
bool status = true,
bool xfbml = false,
bool frictionlessRequests = true,
HideUnityDelegate onHideUnity = null,
string authResponse = null)
{
FB.appId = appId;
FB.cookie = cookie;
FB.logging = logging;
FB.status = status;
FB.xfbml = xfbml;
FB.frictionlessRequests = frictionlessRequests;
FB.authResponse = authResponse;
FB.OnInitComplete = onInitComplete;
FB.OnHideUnity = onHideUnity;
if (!isInitCalled)
{
var versionInfo = FBBuildVersionAttribute.GetVersionAttributeOfType(typeof (IFacebook));
if (versionInfo == null)
{
FbDebug.Warn("Cannot find Facebook SDK Version");
}
else
{
FbDebug.Info(String.Format("Using SDK {0}, Build {1}", versionInfo.SdkVersion, versionInfo.BuildVersion));
}
#if UNITY_EDITOR
FBComponentFactory.GetComponent<EditorFacebookLoader>();
#elif UNITY_WEBPLAYER
FBComponentFactory.GetComponent<CanvasFacebookLoader>();
#elif UNITY_IOS
FBComponentFactory.GetComponent<IOSFacebookLoader>();
#elif UNITY_ANDROID
FBComponentFactory.GetComponent<AndroidFacebookLoader>();
#else
throw new NotImplementedException("Facebook API does not yet support this platform");
#endif
isInitCalled = true;
return;
}
FbDebug.Warn("FB.Init() has already been called. You only need to call this once and only once.");
// Init again if possible just in case something bad actually happened.
if (FacebookImpl != null)
{
OnDllLoaded();
}
}
private static void OnDllLoaded()
{
var versionInfo = FBBuildVersionAttribute.GetVersionAttributeOfType(FacebookImpl.GetType());
if (versionInfo != null)
{
FbDebug.Log(string.Format("Finished loading Facebook dll. Version {0} Build {1}", versionInfo.SdkVersion, versionInfo.BuildVersion));
}
FacebookImpl.Init(
OnInitComplete,
appId,
cookie,
logging,
status,
xfbml,
FBSettings.ChannelUrl,
authResponse,
frictionlessRequests,
OnHideUnity
);
}
#endregion
public static void Login(string scope = "", FacebookDelegate callback = null)
{
FacebookImpl.Login(scope, callback);
}
public static void Logout()
{
FacebookImpl.Logout();
}
public static void AppRequest(
string message,
OGActionType actionType,
string objectId,
string[] to,
string data = "",
string title = "",
FacebookDelegate callback = null)
{
FacebookImpl.AppRequest(message, actionType, objectId, to, null, null, null, data, title, callback);
}
public static void AppRequest(
string message,
OGActionType actionType,
string objectId,
List<object> filters = null,
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null)
{
FacebookImpl.AppRequest(message, actionType, objectId, null, filters, excludeIds, maxRecipients, data, title, callback);
}
public static void AppRequest(
string message,
string[] to = null,
List<object> filters = null,
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null)
{
FacebookImpl.AppRequest(message, null, null, to, filters, excludeIds, maxRecipients, data, title, callback);
}
public static void Feed(
string toId = "",
string link = "",
string linkName = "",
string linkCaption = "",
string linkDescription = "",
string picture = "",
string mediaSource = "",
string actionName = "",
string actionLink = "",
string reference = "",
Dictionary<string, string[]> properties = null,
FacebookDelegate callback = null)
{
FacebookImpl.FeedRequest(toId, link, linkName, linkCaption, linkDescription, picture, mediaSource, actionName, actionLink, reference, properties, callback);
}
public static void API(string query, HttpMethod method, FacebookDelegate callback = null, Dictionary<string, string> formData = null)
{
FacebookImpl.API(query, method, formData, callback);
}
public static void API(string query, HttpMethod method, FacebookDelegate callback, WWWForm formData)
{
FacebookImpl.API(query, method, formData, callback);
}
[Obsolete("use FB.ActivateApp()")]
public static void PublishInstall(FacebookDelegate callback = null)
{
FacebookImpl.PublishInstall(AppId, callback);
}
public static void ActivateApp()
{
FacebookImpl.ActivateApp(AppId);
}
public static void GetDeepLink(FacebookDelegate callback)
{
FacebookImpl.GetDeepLink(callback);
}
public static void GameGroupCreate(
string name,
string description,
string privacy = "CLOSED",
FacebookDelegate callback = null)
{
FacebookImpl.GameGroupCreate(name, description, privacy, callback);
}
public static void GameGroupJoin(
string id,
FacebookDelegate callback = null)
{
FacebookImpl.GameGroupJoin(id, callback);
}
#region App Events
public sealed class AppEvents
{
// If the player has set the limitEventUsage flag to YES, your app will continue
// to send this data to Facebook, but Facebook will not use the data to serve
// targeted ads. Facebook may continue to use the information for other purposes,
// including frequency capping, conversion events, estimating the number of unique
// users, security and fraud detection, and debugging.
public static bool LimitEventUsage
{
get
{
return (facebook != null) && facebook.LimitEventUsage;
}
set
{
facebook.LimitEventUsage = value;
}
}
public static void LogEvent(
string logEvent,
float? valueToSum = null,
Dictionary<string, object> parameters = null)
{
FacebookImpl.AppEventsLogEvent(logEvent, valueToSum, parameters);
}
public static void LogPurchase(
float logPurchase,
string currency = "USD",
Dictionary<string, object> parameters = null)
{
FacebookImpl.AppEventsLogPurchase(logPurchase, currency, parameters);
}
}
#endregion
#region Canvas-Only Implemented Methods
public sealed class Canvas
{
public static void Pay(
string product,
string action = "purchaseitem",
int quantity = 1,
int? quantityMin = null,
int? quantityMax = null,
string requestId = null,
string pricepointId = null,
string testCurrency = null,
FacebookDelegate callback = null)
{
FacebookImpl.Pay(product, action, quantity, quantityMin, quantityMax, requestId, pricepointId, testCurrency, callback);
}
public static void SetResolution(int width, int height, bool fullscreen, int preferredRefreshRate = 0, params FBScreen.Layout[] layoutParams)
{
FBScreen.SetResolution(width, height, fullscreen, preferredRefreshRate, layoutParams);
}
public static void SetAspectRatio(int width, int height, params FBScreen.Layout[] layoutParams)
{
FBScreen.SetAspectRatio(width, height, layoutParams);
}
}
#endregion
#region Android-Only Implemented Methods
public sealed class Android
{
public static string KeyHash
{
get
{
var androidFacebook = facebook as AndroidFacebook;
return (androidFacebook != null) ? androidFacebook.KeyHash : "";
}
}
}
#endregion
#region Facebook Loader Class
public abstract class RemoteFacebookLoader : MonoBehaviour
{
public delegate void LoadedDllCallback(IFacebook fb);
private const string facebookNamespace = "Facebook.";
private const int maxRetryLoadCount = 3;
private static int retryLoadCount = 0;
public static IEnumerator LoadFacebookClass(string className, LoadedDllCallback callback)
{
var url = string.Format(IntegratedPluginCanvasLocation.DllUrl, className);
var www = new WWW(url);
FbDebug.Log("loading dll: " + url);
yield return www;
if (www.error != null)
{
FbDebug.Error(www.error);
if (retryLoadCount < maxRetryLoadCount)
{
++retryLoadCount;
#if UNITY_WEBPLAYER
FBComponentFactory.AddComponent<CanvasFacebookLoader>();
#endif
}
www.Dispose();
yield break;
}
#if !UNITY_WINRT
#if UNITY_4_5
var authTokenWww = new WWW(IntegratedPluginCanvasLocation.KeyUrl);
yield return authTokenWww;
if (authTokenWww.error != null)
{
FbDebug.Error("Cannot load from " + IntegratedPluginCanvasLocation.KeyUrl + ": " + authTokenWww.error);
authTokenWww.Dispose();
yield break;
}
var assembly = Security.LoadAndVerifyAssembly(www.bytes, authTokenWww.text);
#else
var assembly = Security.LoadAndVerifyAssembly(www.bytes);
#endif
if (assembly == null)
{
FbDebug.Error("Could not securely load assembly from " + url);
www.Dispose();
yield break;
}
var facebookClass = assembly.GetType(facebookNamespace + className);
if (facebookClass == null)
{
FbDebug.Error(className + " not found in assembly!");
www.Dispose();
yield break;
}
// load the Facebook component into the gameobject
// using the "as" cast so it'll null if it fails to cast, instead of exception
var fb = typeof(FBComponentFactory)
.GetMethod("GetComponent")
.MakeGenericMethod(facebookClass)
.Invoke(null, new object[] { IfNotExist.AddNew }) as IFacebook;
if (fb == null)
{
FbDebug.Error(className + " couldn't be created.");
www.Dispose();
yield break;
}
callback(fb);
#endif
www.Dispose();
}
protected abstract string className { get; }
IEnumerator Start()
{
var loader = LoadFacebookClass(className, OnDllLoaded);
while (loader.MoveNext())
{
yield return loader.Current;
}
Destroy(this);
}
private void OnDllLoaded(IFacebook fb)
{
FB.facebook = fb;
FB.OnDllLoaded();
}
}
public abstract class CompiledFacebookLoader : MonoBehaviour
{
protected abstract IFacebook fb { get; }
void Start()
{
FB.facebook = fb;
FB.OnDllLoaded();
Destroy(this);
}
}
#endregion
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Database;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input;
using osu.Game.Input.Bindings;
using osuTK;
using osuTK.Graphics;
using osuTK.Input;
namespace osu.Game.Overlays.KeyBinding
{
public class KeyBindingRow : Container, IFilterable
{
private readonly object action;
private readonly IEnumerable<RealmKeyBinding> bindings;
private const float transition_time = 150;
private const float height = 20;
private const float padding = 5;
private bool matchingFilter;
public bool MatchingFilter
{
get => matchingFilter;
set
{
matchingFilter = value;
this.FadeTo(!matchingFilter ? 0 : 1);
}
}
private Container content;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) =>
content.ReceivePositionalInputAt(screenSpacePos);
public bool FilteringActive { get; set; }
private OsuSpriteText text;
private FillFlowContainer cancelAndClearButtons;
private FillFlowContainer<KeyButton> buttons;
private Bindable<bool> isDefault { get; } = new BindableBool(true);
public IEnumerable<string> FilterTerms => bindings.Select(b => b.KeyCombination.ReadableString()).Prepend(text.Text.ToString());
public KeyBindingRow(object action, List<RealmKeyBinding> bindings)
{
this.action = action;
this.bindings = bindings;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
}
[Resolved]
private RealmContextFactory realmFactory { get; set; }
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Padding = new MarginPadding { Horizontal = SettingsPanel.CONTENT_MARGINS };
InternalChildren = new Drawable[]
{
new RestoreDefaultValueButton<bool>
{
Current = isDefault,
Action = RestoreDefaults,
Origin = Anchor.TopRight,
},
content = new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Masking = true,
CornerRadius = padding,
EdgeEffect = new EdgeEffectParameters
{
Radius = 2,
Colour = colours.YellowDark.Opacity(0),
Type = EdgeEffectType.Shadow,
Hollow = true,
},
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
Alpha = 0.6f,
},
text = new OsuSpriteText
{
Text = action.GetDescription(),
Margin = new MarginPadding(padding),
},
buttons = new FillFlowContainer<KeyButton>
{
AutoSizeAxes = Axes.Both,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight
},
cancelAndClearButtons = new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Padding = new MarginPadding(padding) { Top = height + padding * 2 },
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Alpha = 0,
Spacing = new Vector2(5),
Children = new Drawable[]
{
new CancelButton { Action = finalise },
new ClearButton { Action = clear },
},
}
}
}
};
foreach (var b in bindings)
buttons.Add(new KeyButton(b));
updateIsDefaultValue();
}
public void RestoreDefaults()
{
int i = 0;
foreach (var d in Defaults)
{
var button = buttons[i++];
button.UpdateKeyCombination(d);
updateStoreFromButton(button);
}
isDefault.Value = true;
}
protected override bool OnHover(HoverEvent e)
{
content.FadeEdgeEffectTo(1, transition_time, Easing.OutQuint);
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
content.FadeEdgeEffectTo(0, transition_time, Easing.OutQuint);
base.OnHoverLost(e);
}
public override bool AcceptsFocus => bindTarget == null;
private KeyButton bindTarget;
public bool AllowMainMouseButtons;
public IEnumerable<KeyCombination> Defaults;
private bool isModifier(Key k) => k < Key.F1;
protected override bool OnClick(ClickEvent e) => true;
protected override bool OnMouseDown(MouseDownEvent e)
{
if (!HasFocus || !bindTarget.IsHovered)
return base.OnMouseDown(e);
if (!AllowMainMouseButtons)
{
switch (e.Button)
{
case MouseButton.Left:
case MouseButton.Right:
return true;
}
}
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState));
return true;
}
protected override void OnMouseUp(MouseUpEvent e)
{
// don't do anything until the last button is released.
if (!HasFocus || e.HasAnyButtonPressed)
{
base.OnMouseUp(e);
return;
}
if (bindTarget.IsHovered)
finalise();
// prevent updating bind target before clear button's action
else if (!cancelAndClearButtons.Any(b => b.IsHovered))
updateBindTarget();
}
protected override bool OnScroll(ScrollEvent e)
{
if (HasFocus)
{
if (bindTarget.IsHovered)
{
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState, e.ScrollDelta));
finalise();
return true;
}
}
return base.OnScroll(e);
}
protected override bool OnKeyDown(KeyDownEvent e)
{
if (!HasFocus)
return false;
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState));
if (!isModifier(e.Key)) finalise();
return true;
}
protected override void OnKeyUp(KeyUpEvent e)
{
if (!HasFocus)
{
base.OnKeyUp(e);
return;
}
finalise();
}
protected override bool OnJoystickPress(JoystickPressEvent e)
{
if (!HasFocus)
return false;
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState));
finalise();
return true;
}
protected override void OnJoystickRelease(JoystickReleaseEvent e)
{
if (!HasFocus)
{
base.OnJoystickRelease(e);
return;
}
finalise();
}
protected override bool OnMidiDown(MidiDownEvent e)
{
if (!HasFocus)
return false;
bindTarget.UpdateKeyCombination(KeyCombination.FromInputState(e.CurrentState));
finalise();
return true;
}
protected override void OnMidiUp(MidiUpEvent e)
{
if (!HasFocus)
{
base.OnMidiUp(e);
return;
}
finalise();
}
private void clear()
{
if (bindTarget == null)
return;
bindTarget.UpdateKeyCombination(InputKey.None);
finalise();
}
private void finalise()
{
if (bindTarget != null)
{
updateStoreFromButton(bindTarget);
updateIsDefaultValue();
bindTarget.IsBinding = false;
Schedule(() =>
{
// schedule to ensure we don't instantly get focus back on next OnMouseClick (see AcceptFocus impl.)
bindTarget = null;
});
}
if (HasFocus)
GetContainingInputManager().ChangeFocus(null);
cancelAndClearButtons.FadeOut(300, Easing.OutQuint);
cancelAndClearButtons.BypassAutoSizeAxes |= Axes.Y;
}
protected override void OnFocus(FocusEvent e)
{
content.AutoSizeDuration = 500;
content.AutoSizeEasing = Easing.OutQuint;
cancelAndClearButtons.FadeIn(300, Easing.OutQuint);
cancelAndClearButtons.BypassAutoSizeAxes &= ~Axes.Y;
updateBindTarget();
base.OnFocus(e);
}
protected override void OnFocusLost(FocusLostEvent e)
{
finalise();
base.OnFocusLost(e);
}
/// <summary>
/// Updates the bind target to the currently hovered key button or the first if clicked anywhere else.
/// </summary>
private void updateBindTarget()
{
if (bindTarget != null) bindTarget.IsBinding = false;
bindTarget = buttons.FirstOrDefault(b => b.IsHovered) ?? buttons.FirstOrDefault();
if (bindTarget != null) bindTarget.IsBinding = true;
}
private void updateStoreFromButton(KeyButton button)
{
using (var usage = realmFactory.GetForWrite())
{
var binding = usage.Realm.Find<RealmKeyBinding>(((IHasGuidPrimaryKey)button.KeyBinding).ID);
binding.KeyCombinationString = button.KeyBinding.KeyCombinationString;
usage.Commit();
}
}
private void updateIsDefaultValue()
{
isDefault.Value = bindings.Select(b => b.KeyCombination).SequenceEqual(Defaults);
}
private class CancelButton : TriangleButton
{
public CancelButton()
{
Text = "Cancel";
Size = new Vector2(80, 20);
}
}
public class ClearButton : DangerousTriangleButton
{
public ClearButton()
{
Text = "Clear";
Size = new Vector2(80, 20);
}
}
public class KeyButton : Container
{
public readonly RealmKeyBinding KeyBinding;
private readonly Box box;
public readonly OsuSpriteText Text;
private Color4 hoverColour;
private bool isBinding;
public bool IsBinding
{
get => isBinding;
set
{
if (value == isBinding) return;
isBinding = value;
updateHoverState();
}
}
public KeyButton(RealmKeyBinding keyBinding)
{
if (keyBinding.IsManaged)
throw new ArgumentException("Key binding should not be attached as we make temporary changes", nameof(keyBinding));
KeyBinding = keyBinding;
Margin = new MarginPadding(padding);
Masking = true;
CornerRadius = padding;
Height = height;
AutoSizeAxes = Axes.X;
Children = new Drawable[]
{
new Container
{
AlwaysPresent = true,
Width = 80,
Height = height,
},
box = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black
},
Text = new OsuSpriteText
{
Font = OsuFont.Numeric.With(size: 10),
Margin = new MarginPadding(5),
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Text = keyBinding.KeyCombination.ReadableString(),
},
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
hoverColour = colours.YellowDark;
}
protected override bool OnHover(HoverEvent e)
{
updateHoverState();
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
updateHoverState();
base.OnHoverLost(e);
}
private void updateHoverState()
{
if (isBinding)
{
box.FadeColour(Color4.White, transition_time, Easing.OutQuint);
Text.FadeColour(Color4.Black, transition_time, Easing.OutQuint);
}
else
{
box.FadeColour(IsHovered ? hoverColour : Color4.Black, transition_time, Easing.OutQuint);
Text.FadeColour(IsHovered ? Color4.Black : Color4.White, transition_time, Easing.OutQuint);
}
}
public void UpdateKeyCombination(KeyCombination newCombination)
{
if (KeyBinding.RulesetID != null && !RealmKeyBindingStore.CheckValidForGameplay(newCombination))
return;
KeyBinding.KeyCombination = newCombination;
Text.Text = KeyBinding.KeyCombination.ReadableString();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal partial class SolutionCrawlerRegistrationService
{
private partial class WorkCoordinator
{
private abstract class AsyncWorkItemQueue<TKey> : IDisposable
where TKey : class
{
private readonly object _gate;
private readonly AsyncSemaphore _semaphore;
private readonly SolutionCrawlerProgressReporter _progressReporter;
// map containing cancellation source for the item given out.
private readonly Dictionary<object, CancellationTokenSource> _cancellationMap;
public AsyncWorkItemQueue(SolutionCrawlerProgressReporter progressReporter)
{
_gate = new object();
_semaphore = new AsyncSemaphore(initialCount: 0);
_cancellationMap = new Dictionary<object, CancellationTokenSource>();
_progressReporter = progressReporter;
}
protected abstract int WorkItemCount_NoLock { get; }
protected abstract void Dispose_NoLock();
protected abstract bool AddOrReplace_NoLock(WorkItem item);
protected abstract bool TryTake_NoLock(TKey key, out WorkItem workInfo);
protected abstract bool TryTakeAnyWork_NoLock(ProjectId preferableProjectId, out WorkItem workItem);
public bool HasAnyWork
{
get
{
lock (_gate)
{
return HasAnyWork_NoLock;
}
}
}
public int WorkItemCount
{
get
{
lock (_gate)
{
return WorkItemCount_NoLock;
}
}
}
public void RemoveCancellationSource(object key)
{
lock (_gate)
{
// just remove cancellation token from the map.
// the cancellation token might be passed out to other service
// so don't call cancel on the source only because we are done using it.
_cancellationMap.Remove(key);
}
}
public virtual Task WaitAsync(CancellationToken cancellationToken)
{
return _semaphore.WaitAsync(cancellationToken);
}
public bool AddOrReplace(WorkItem item)
{
if (!HasAnyWork)
{
// first work is added.
_progressReporter.Start();
}
lock (_gate)
{
if (AddOrReplace_NoLock(item))
{
// increase count
_semaphore.Release();
return true;
}
return false;
}
}
public void RequestCancellationOnRunningTasks()
{
List<CancellationTokenSource> cancellations;
lock (_gate)
{
// request to cancel all running works
cancellations = CancelAll_NoLock();
}
RaiseCancellation_NoLock(cancellations);
}
public void Dispose()
{
List<CancellationTokenSource> cancellations;
lock (_gate)
{
// here we don't need to care about progress reporter since
// it will be only called when host is shutting down.
// we do the below since we want to kill any pending tasks
Dispose_NoLock();
cancellations = CancelAll_NoLock();
}
RaiseCancellation_NoLock(cancellations);
}
private static void RaiseCancellation_NoLock(List<CancellationTokenSource> cancellations)
{
if (cancellations == null)
{
return;
}
// cancel can cause outer code to be run inlined, run it outside of the lock.
cancellations.Do(s => s.Cancel());
}
private bool HasAnyWork_NoLock
{
get
{
return WorkItemCount_NoLock > 0;
}
}
private List<CancellationTokenSource> CancelAll_NoLock()
{
// nothing to do
if (_cancellationMap.Count == 0)
{
return null;
}
// make a copy
var cancellations = _cancellationMap.Values.ToList();
// clear cancellation map
_cancellationMap.Clear();
return cancellations;
}
protected void Cancel_NoLock(object key)
{
CancellationTokenSource source;
if (_cancellationMap.TryGetValue(key, out source))
{
source.Cancel();
_cancellationMap.Remove(key);
}
}
public bool TryTake(TKey key, out WorkItem workInfo, out CancellationTokenSource source)
{
lock (_gate)
{
if (TryTake_NoLock(key, out workInfo))
{
if (!HasAnyWork_NoLock)
{
// last work is done.
_progressReporter.Stop();
}
source = GetNewCancellationSource_NoLock(key);
workInfo.AsyncToken.Dispose();
return true;
}
else
{
source = null;
return false;
}
}
}
public bool TryTakeAnyWork(ProjectId preferableProjectId, out WorkItem workItem, out CancellationTokenSource source)
{
lock (_gate)
{
// there must be at least one item in the map when this is called unless host is shutting down.
if (TryTakeAnyWork_NoLock(preferableProjectId, out workItem))
{
if (!HasAnyWork_NoLock)
{
// last work is done.
_progressReporter.Stop();
}
source = GetNewCancellationSource_NoLock(workItem.Key);
workItem.AsyncToken.Dispose();
return true;
}
else
{
source = null;
return false;
}
}
}
protected CancellationTokenSource GetNewCancellationSource_NoLock(object key)
{
Contract.Requires(!_cancellationMap.ContainsKey(key));
var source = new CancellationTokenSource();
_cancellationMap.Add(key, source);
return source;
}
}
}
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
namespace Platform.VirtualFileSystem.Providers
{
/// <summary>
/// This class provides a skeletal implementation of the <c>INodeAttributes</c>interface to minimize the effort
/// required to implement the interface.
/// <seealso cref="INodeAttributes"/>
/// </summary>
public abstract class AbstractTypeBasedNodeAttributes
: AbstractNodeAttributes, INodeAttributes
{
private readonly INode node;
private readonly IList<PropertyInfo> properties;
protected INode Node
{
get
{
return this.node;
}
}
protected AbstractTypeBasedNodeAttributes(INode node)
{
this.node = node;
var type = this.GetType();
var propInfos = type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance);
this.properties = new List<PropertyInfo>(propInfos.Length);
foreach (var propInfo in propInfos)
{
if (HasCustomAttribute(propInfo, typeof(NodeAttributeAttribute)))
{
this.properties.Add(propInfo);
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public override IEnumerator<KeyValuePair<string, object>> GetEnumerator()
{
foreach (var name in this.Names)
{
yield return new KeyValuePair<string, object>(name, this[name]);
}
}
[NodeAttribute]
public override bool? ReadOnly
{
get
{
return false;
}
set
{
}
}
[NodeAttribute]
public override bool? IsHidden
{
get
{
return false;
}
set
{
}
}
[NodeAttribute]
public override DateTime? CreationTime
{
get
{
return null;
}
set
{
}
}
[NodeAttribute]
public override DateTime? LastAccessTime
{
get
{
return null;
}
set
{
}
}
[NodeAttribute]
public override DateTime? LastWriteTime
{
get
{
return null;
}
set
{
}
}
[NodeAttribute]
public override bool Exists
{
get
{
return false;
}
}
void IRefreshable.Refresh()
{
Refresh();
}
public override INodeAttributes Refresh()
{
return this;
}
public override IEnumerable<string> Names
{
get
{
foreach (var propInfo in this.properties)
{
yield return propInfo.Name;
}
}
}
public virtual int Count
{
get
{
return this.properties.Count;
}
}
public override IEnumerable<object> Values
{
get
{
foreach (var propInfo in this.properties)
{
yield return propInfo.GetValue(this, null);
}
}
}
public override bool Supports(string name)
{
return this[name] != null;
}
protected static bool HasCustomAttribute(PropertyInfo propertyInfo, Type attributeType)
{
if (propertyInfo.GetCustomAttributes(attributeType, false).Length > 0)
{
return true;
}
else
{
if (propertyInfo.DeclaringType.BaseType == null)
{
return false;
}
propertyInfo = propertyInfo.DeclaringType.BaseType.GetProperty(propertyInfo.Name);
if (propertyInfo == null)
{
return false;
}
return HasCustomAttribute(propertyInfo, attributeType);
}
}
protected override object GetValue(string name)
{
switch (name)
{
case "CreationTime":
case "creationtime":
return this.CreationTime;
case "LastAccessTime":
case "lastaccesstime":
return this.LastAccessTime;
case "LastWriteTime":
case "lastwritetime":
return this.LastWriteTime;
case "Exists":
case "exists":
return this.Exists;
case "ReadOnly":
case "readonly":
return this.ReadOnly;
case "Hidden":
case "hidden":
return this.IsHidden;
}
foreach (var propertyInfo in this.properties)
{
if (propertyInfo.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase))
{
try
{
var value = propertyInfo.GetValue(this, null);
if (value == null)
{
return null;
}
if (value.GetType() != propertyInfo.PropertyType
&& Nullable.GetUnderlyingType(value.GetType()) != propertyInfo.PropertyType
&& value.GetType() != Nullable.GetUnderlyingType(propertyInfo.PropertyType))
{
value = Convert.ChangeType(value, propertyInfo.PropertyType);
}
return value;
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
}
}
return null;
}
protected override void SetValue(string name, object value)
{
switch (name.ToLower())
{
case "CreationTime":
case "creationtime":
this.CreationTime = (DateTime?)value;
return;
case "LastAccessTime":
case "lastaccesstime":
this.LastAccessTime = (DateTime?)value;
return;
case "LastWriteTime":
case "lastwritetime":
this.LastWriteTime = (DateTime?)value;
return;
case "ReadOnly":
case "readonly":
this.ReadOnly = (bool)value;
return;
case "Hidden":
case "hidden":
this.IsHidden = (bool)value;
return;
}
foreach (var propertyInfo in this.properties)
{
if (propertyInfo.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase))
{
try
{
if (value.GetType() != propertyInfo.PropertyType
&& Nullable.GetUnderlyingType(value.GetType()) != propertyInfo.PropertyType
&& value.GetType() != Nullable.GetUnderlyingType(propertyInfo.PropertyType))
{
value = Convert.ChangeType(value, propertyInfo.PropertyType);
}
propertyInfo.SetValue(this, value, null);
return;
}
catch (TargetInvocationException e)
{
throw e.InnerException;
}
}
}
}
public override object SyncLock
{
get
{
return this;
}
}
public override IAutoLock GetAutoLock()
{
return new AutoLock(this);
}
public override INodeAttributesUpdateContext AquireUpdateContext()
{
return new StandardNodeAttributesUpdateContext(this);
}
}
}
| |
// 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 gcav = Google.Cloud.AIPlatform.V1;
using sys = System;
namespace Google.Cloud.AIPlatform.V1
{
/// <summary>Resource name for the <c>Context</c> resource.</summary>
public sealed partial class ContextName : gax::IResourceName, sys::IEquatable<ContextName>
{
/// <summary>The possible contents of <see cref="ContextName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>.
/// </summary>
ProjectLocationMetadataStoreContext = 1,
}
private static gax::PathTemplate s_projectLocationMetadataStoreContext = new gax::PathTemplate("projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}");
/// <summary>Creates a <see cref="ContextName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ContextName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static ContextName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ContextName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ContextName"/> with the pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ContextName"/> constructed from the provided ids.</returns>
public static ContextName FromProjectLocationMetadataStoreContext(string projectId, string locationId, string metadataStoreId, string contextId) =>
new ContextName(ResourceNameType.ProjectLocationMetadataStoreContext, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), metadataStoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(metadataStoreId, nameof(metadataStoreId)), contextId: gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ContextName"/> with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ContextName"/> with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string metadataStoreId, string contextId) =>
FormatProjectLocationMetadataStoreContext(projectId, locationId, metadataStoreId, contextId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ContextName"/> with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ContextName"/> with pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>.
/// </returns>
public static string FormatProjectLocationMetadataStoreContext(string projectId, string locationId, string metadataStoreId, string contextId) =>
s_projectLocationMetadataStoreContext.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(metadataStoreId, nameof(metadataStoreId)), gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId)));
/// <summary>Parses the given resource name string into a new <see cref="ContextName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="contextName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ContextName"/> if successful.</returns>
public static ContextName Parse(string contextName) => Parse(contextName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ContextName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="contextName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ContextName"/> if successful.</returns>
public static ContextName Parse(string contextName, bool allowUnparsed) =>
TryParse(contextName, allowUnparsed, out ContextName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ContextName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="contextName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ContextName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string contextName, out ContextName result) => TryParse(contextName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ContextName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="contextName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ContextName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string contextName, bool allowUnparsed, out ContextName result)
{
gax::GaxPreconditions.CheckNotNull(contextName, nameof(contextName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationMetadataStoreContext.TryParseName(contextName, out resourceName))
{
result = FromProjectLocationMetadataStoreContext(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(contextName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ContextName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string contextId = null, string locationId = null, string metadataStoreId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ContextId = contextId;
LocationId = locationId;
MetadataStoreId = metadataStoreId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ContextName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/metadataStores/{metadata_store}/contexts/{context}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="metadataStoreId">The <c>MetadataStore</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param>
public ContextName(string projectId, string locationId, string metadataStoreId, string contextId) : this(ResourceNameType.ProjectLocationMetadataStoreContext, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), metadataStoreId: gax::GaxPreconditions.CheckNotNullOrEmpty(metadataStoreId, nameof(metadataStoreId)), contextId: gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Context</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ContextId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>MetadataStore</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string MetadataStoreId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationMetadataStoreContext: return s_projectLocationMetadataStoreContext.Expand(ProjectId, LocationId, MetadataStoreId, ContextId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ContextName);
/// <inheritdoc/>
public bool Equals(ContextName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ContextName a, ContextName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ContextName a, ContextName b) => !(a == b);
}
public partial class Context
{
/// <summary>
/// <see cref="gcav::ContextName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::ContextName ContextName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::ContextName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gcav::ContextName"/>-typed view over the <see cref="ParentContexts"/> resource name property.
/// </summary>
public gax::ResourceNameList<gcav::ContextName> ParentContextsAsContextNames
{
get => new gax::ResourceNameList<gcav::ContextName>(ParentContexts, s => string.IsNullOrEmpty(s) ? null : gcav::ContextName.Parse(s, allowUnparsed: true));
}
}
}
| |
//
// ListViewAccessible.cs
//
// Authors:
// Eitan Isaacson <eitan@ascender.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
// Copyright (C) 2009 Eitan Isaacson
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Collections.Generic;
using Hyena.Data.Gui;
namespace Hyena.Data.Gui.Accessibility
{
public partial class ListViewAccessible<T> : Hyena.Gui.BaseWidgetAccessible, ICellAccessibleParent
{
private ListView<T> list_view;
private Dictionary<int, ColumnCellAccessible> cell_cache;
public ListViewAccessible (GLib.Object widget) : base (widget as Gtk.Widget)
{
list_view = (ListView<T>) widget;
// TODO replace with list_view.Name?
Name = "ListView";
Description = "ListView";
Role = Atk.Role.Table;
if (list_view.Parent != null) {
Parent = list_view.Parent.RefAccessible ();
}
cell_cache = new Dictionary<int, ColumnCellAccessible> ();
list_view.ModelChanged += OnModelChanged;
list_view.ModelReloaded += OnModelChanged;
OnModelChanged (null, null);
list_view.SelectionProxy.FocusChanged += OnSelectionFocusChanged;
list_view.ActiveColumnChanged += OnSelectionFocusChanged;
ListViewAccessible_Selection ();
ListViewAccessible_Table ();
}
protected ListViewAccessible (IntPtr raw) : base (raw)
{
}
protected override Atk.StateSet OnRefStateSet ()
{
Atk.StateSet states = base.OnRefStateSet ();
states.AddState (Atk.StateType.ManagesDescendants);
return states;
}
protected override int OnGetIndexInParent ()
{
for (int i=0; i < Parent.NAccessibleChildren; i++) {
if (Parent.RefAccessibleChild (i) == this) {
return i;
}
}
return -1;
}
protected override int OnGetNChildren ()
{
return n_columns * n_rows + n_columns;
}
protected override Atk.Object OnRefChild (int index)
{
ColumnCellAccessible child;
if (cell_cache.ContainsKey (index)) {
return cell_cache[index];
}
// FIXME workaround to prevent crashing on Grid ListViews
if (list_view.ColumnController == null)
return null;
var columns = list_view.ColumnController.Where (c => c.Visible);
if (index - n_columns < 0) {
child = columns.ElementAtOrDefault (index)
.HeaderCell
.GetAccessible (this) as ColumnCellAccessible;
} else {
int column = (index - n_columns) % n_columns;
int row = (index - n_columns) / n_columns;
var cell = columns.ElementAtOrDefault (column).GetCell (0);
cell.Bind (list_view.Model[row]);
child = (ColumnCellAccessible) cell.GetAccessible (this);
}
cell_cache.Add (index, child);
return child;
}
public override Atk.Object RefAccessibleAtPoint (int x, int y, Atk.CoordType coordType)
{
int row, col;
list_view.GetCellAtPoint (x, y, coordType, out row, out col);
return RefAt (row, col);
}
private void OnModelChanged (object o, EventArgs a)
{
ThreadAssist.ProxyToMain (EmitModelChanged);
}
private void EmitModelChanged ()
{
GLib.Signal.Emit (this, "model_changed");
cell_cache.Clear ();
/*var handler = ModelChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}*/
}
private void OnSelectionFocusChanged (object o, EventArgs a)
{
ThreadAssist.ProxyToMain (EmitDescendantChanged);
}
private void EmitDescendantChanged ()
{
var cell = ActiveCell;
if (cell != null) {
GLib.Signal.Emit (this, "active-descendant-changed", cell.Handle);
}
}
private Atk.Object ActiveCell {
get {
if (list_view.HeaderFocused) {
return OnRefChild (list_view.ActiveColumn);
} else {
if (list_view.Selection != null) {
return RefAt (list_view.Selection.FocusedIndex, list_view.ActiveColumn);
} else {
return null;
}
}
}
}
private int n_columns {
get {
return list_view.ColumnController != null
? list_view.ColumnController.Count (c => c.Visible)
: 1;
}
}
private int n_rows {
get { return list_view.Model.Count; }
}
#region ICellAccessibleParent
public int GetCellIndex (ColumnCellAccessible cell)
{
foreach (KeyValuePair<int, ColumnCellAccessible> kv in cell_cache)
{
if ((ColumnCellAccessible)kv.Value == cell)
return (int)kv.Key;
}
return -1;
}
public Gdk.Rectangle GetCellExtents (ColumnCellAccessible cell, Atk.CoordType coord_type)
{
int cache_index = GetCellIndex (cell);
int minval = Int32.MinValue;
if (cache_index == -1)
return new Gdk.Rectangle (minval, minval, minval, minval);
if (cache_index - n_columns >= 0)
{
int column = (cache_index - NColumns)%NColumns;
int row = (cache_index - NColumns)/NColumns;
return list_view.GetColumnCellExtents (row, column, true, coord_type);
} else
{
return list_view.GetColumnHeaderCellExtents (cache_index, true, coord_type);
}
}
public bool IsCellShowing (ColumnCellAccessible cell)
{
Gdk.Rectangle cell_extents = GetCellExtents (cell, Atk.CoordType.Window);
if (cell_extents.X == Int32.MinValue && cell_extents.Y == Int32.MinValue)
return false;
return true;
}
public bool IsCellFocused (ColumnCellAccessible cell)
{
int cell_index = GetCellIndex (cell);
if (cell_index % NColumns != 0)
return false; // Only 0 column cells get focus now.
int row = cell_index / NColumns;
return row == list_view.Selection.FocusedIndex;
}
public bool IsCellSelected (ColumnCellAccessible cell)
{
return IsChildSelected (GetCellIndex (cell));
}
public bool IsCellActive (ColumnCellAccessible cell)
{
return (ActiveCell == (Atk.Object)cell);
}
public void InvokeColumnHeaderMenu (ColumnCellAccessible cell)
{
list_view.InvokeColumnHeaderMenu (GetCellIndex (cell));
}
public void ClickColumnHeader (ColumnCellAccessible cell)
{
list_view.ClickColumnHeader (GetCellIndex (cell));
}
public void CellRedrawn (int column, int row)
{
int index;
if (row >= 0)
index = row * n_columns + column + n_columns;
else
index = column;
if (cell_cache.ContainsKey (index)) {
cell_cache[index].Redrawn ();
}
}
#endregion
}
}
| |
// based on Cookbook formulae for audio EQ biquad filter coefficients
// http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
// by Robert Bristow-Johnson <rbj@audioimagination.com>
// alpha = sin(w0)/(2*Q) (case: Q)
// = sin(w0)*sinh( ln(2)/2 * BW * w0/sin(w0) ) (case: BW)
// = sin(w0)/2 * sqrt( (A + 1/A)*(1/S - 1) + 2 ) (case: S)
// Q: (the EE kind of definition, except for peakingEQ in which A*Q is
// the classic EE Q. That adjustment in definition was made so that
// a boost of N dB followed by a cut of N dB for identical Q and
// f0/Fs results in a precisely flat unity gain filter or "wire".)
//
// BW: the bandwidth in octaves (between -3 dB frequencies for BPF
// and notch or between midpoint (dBgain/2) gain frequencies for
// peaking EQ)
//
// S: a "shelf slope" parameter (for shelving EQ only). When S = 1,
// the shelf slope is as steep as it can be and remain monotonically
// increasing or decreasing gain with frequency. The shelf slope, in
// dB/octave, remains proportional to S for all other values for a
// fixed f0/Fs and dBgain.
using System;
namespace NAudio.Dsp
{
internal class BiQuadFilter
{
// coefficients
private double a0;
private double a1;
private double a2;
private double b0;
private double b1;
private double b2;
private BiQuadFilter()
{
}
public void Transform(float[] inBuffer, float[] outBuffer)
{
float[] x = inBuffer;
float[] y = outBuffer;
for (int n = 0; n < inBuffer.Length; n++)
{
y[n] = (float) (
(b0/a0)*x[n] + (b1/a0)*x[n - 1] + (b2/a0)*x[n - 2]
- (a1/a0)*y[n - 1] - (a2/a0)*y[n - 2]);
}
}
/// <summary>
/// H(s) = 1 / (s^2 + s/Q + 1)
/// </summary>
public static BiQuadFilter LowPassFilter(float sampleRate, float cutoffFrequency, float q)
{
double w0 = 2*Math.PI*cutoffFrequency/sampleRate;
double cosw0 = Math.Cos(w0);
double alpha = Math.Sin(w0)/(2*q);
var filter = new BiQuadFilter();
filter.b0 = (1 - cosw0)/2;
filter.b1 = 1 - cosw0;
filter.b2 = (1 - cosw0)/2;
filter.a0 = 1 + alpha;
filter.a1 = -2*cosw0;
filter.a2 = 1 - alpha;
return filter;
}
/// <summary>
/// H(s) = s^2 / (s^2 + s/Q + 1)
/// </summary>
public static BiQuadFilter HighPassFilter(float sampleRate, float cutoffFrequency, float q)
{
double w0 = 2*Math.PI*cutoffFrequency/sampleRate;
double cosw0 = Math.Cos(w0);
double alpha = Math.Sin(w0)/(2*q);
var filter = new BiQuadFilter();
filter.b0 = (1 + Math.Cos(w0))/2;
filter.b1 = -(1 + Math.Cos(w0));
filter.b2 = (1 + Math.Cos(w0))/2;
filter.a0 = 1 + alpha;
filter.a1 = -2*Math.Cos(w0);
filter.a2 = 1 - alpha;
return filter;
}
/// <summary>
/// H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q)
/// </summary>
public static BiQuadFilter BandPassFilterConstantSkirtGain(float sampleRate, float centreFrequency, float q)
{
double w0 = 2*Math.PI*centreFrequency/sampleRate;
double cosw0 = Math.Cos(w0);
double sinw0 = Math.Sin(w0);
double alpha = sinw0/(2*q);
var filter = new BiQuadFilter();
filter.b0 = sinw0/2; // = Q*alpha
filter.b1 = 0;
filter.b2 = -sinw0/2; // = -Q*alpha
filter.a0 = 1 + alpha;
filter.a1 = -2*cosw0;
filter.a2 = 1 - alpha;
return filter;
}
/// <summary>
/// H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain)
/// </summary>
public static BiQuadFilter BandPassFilterConstantPeakGain(float sampleRate, float centreFrequency, float q)
{
double w0 = 2*Math.PI*centreFrequency/sampleRate;
double cosw0 = Math.Cos(w0);
double sinw0 = Math.Sin(w0);
double alpha = sinw0/(2*q);
var filter = new BiQuadFilter();
filter.b0 = alpha;
filter.b1 = 0;
filter.b2 = -alpha;
filter.a0 = 1 + alpha;
filter.a1 = -2*cosw0;
filter.a2 = 1 - alpha;
return filter;
}
/// <summary>
/// H(s) = (s^2 + 1) / (s^2 + s/Q + 1)
/// </summary>
public static BiQuadFilter NotchFilter(float sampleRate, float centreFrequency, float q)
{
double w0 = 2*Math.PI*centreFrequency/sampleRate;
double cosw0 = Math.Cos(w0);
double sinw0 = Math.Sin(w0);
double alpha = sinw0/(2*q);
var filter = new BiQuadFilter();
filter.b0 = 1;
filter.b1 = -2*cosw0;
filter.b2 = 1;
filter.a0 = 1 + alpha;
filter.a1 = -2*cosw0;
filter.a2 = 1 - alpha;
return filter;
}
/// <summary>
/// H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1)
/// </summary>
public static BiQuadFilter AllPassFilter(float sampleRate, float centreFrequency, float q)
{
double w0 = 2*Math.PI*centreFrequency/sampleRate;
double cosw0 = Math.Cos(w0);
double sinw0 = Math.Sin(w0);
double alpha = sinw0/(2*q);
var filter = new BiQuadFilter();
filter.b0 = 1 - alpha;
filter.b1 = -2*cosw0;
filter.b2 = 1 + alpha;
filter.a0 = 1 + alpha;
filter.a1 = -2*cosw0;
filter.a2 = 1 - alpha;
return filter;
}
/// <summary>
/// H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1)
/// </summary>
public static BiQuadFilter PeakingEQ(float sampleRate, float centreFrequency, float q, float dbGain)
{
double w0 = 2*Math.PI*centreFrequency/sampleRate;
double cosw0 = Math.Cos(w0);
double sinw0 = Math.Sin(w0);
double alpha = sinw0/(2*q);
double A = Math.Pow(10, dbGain/40); // TODO: should we square root this value?
var filter = new BiQuadFilter();
filter.b0 = 1 + alpha*A;
filter.b1 = -2*cosw0;
filter.b2 = 1 - alpha*A;
filter.a0 = 1 + alpha/A;
filter.a1 = -2*cosw0;
filter.a2 = 1 - alpha/A;
return filter;
}
/// <summary>
/// H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1)
/// </summary>
/// <param name="sampleRate"></param>
/// <param name="cutoffFrequency"></param>
/// <param name="shelfSlope">
/// a "shelf slope" parameter (for shelving EQ only).
/// When S = 1, the shelf slope is as steep as it can be and remain monotonically
/// increasing or decreasing gain with frequency. The shelf slope, in dB/octave,
/// remains proportional to S for all other values for a fixed f0/Fs and dBgain.
/// </param>
/// <param name="dbGain">Gain in decibels</param>
public static BiQuadFilter LowShelf(float sampleRate, float cutoffFrequency, float shelfSlope, float dbGain)
{
double w0 = 2*Math.PI*cutoffFrequency/sampleRate;
double cosw0 = Math.Cos(w0);
double sinw0 = Math.Sin(w0);
double A = Math.Pow(10, dbGain/40); // TODO: should we square root this value?
double alpha = sinw0/2*Math.Sqrt((A + 1/A)*(1/shelfSlope - 1) + 2);
double temp = 2*Math.Sqrt(A)*alpha;
var filter = new BiQuadFilter();
filter.b0 = A*((A + 1) - (A - 1)*cosw0 + temp);
filter.b1 = 2*A*((A - 1) - (A + 1)*cosw0);
filter.b2 = A*((A + 1) - (A - 1)*cosw0 - temp);
filter.a0 = (A + 1) + (A - 1)*cosw0 + temp;
filter.a1 = -2*((A - 1) + (A + 1)*cosw0);
filter.a2 = (A + 1) + (A - 1)*cosw0 - temp;
return filter;
}
/// <summary>
/// H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A)
/// </summary>
/// <param name="sampleRate"></param>
/// <param name="cutoffFrequency"></param>
/// <param name="shelfSlope"></param>
/// <param name="dbGain"></param>
/// <returns></returns>
public static BiQuadFilter HighShelf(float sampleRate, float cutoffFrequency, float shelfSlope, float dbGain)
{
double w0 = 2*Math.PI*cutoffFrequency/sampleRate;
double cosw0 = Math.Cos(w0);
double sinw0 = Math.Sin(w0);
double A = Math.Pow(10, dbGain/40); // TODO: should we square root this value?
double alpha = sinw0/2*Math.Sqrt((A + 1/A)*(1/shelfSlope - 1) + 2);
double temp = 2*Math.Sqrt(A)*alpha;
var filter = new BiQuadFilter();
filter.b0 = A*((A + 1) + (A - 1)*cosw0 + temp);
filter.b1 = -2*A*((A - 1) + (A + 1)*cosw0);
filter.b2 = A*((A + 1) + (A - 1)*cosw0 - temp);
filter.a0 = (A + 1) - (A - 1)*cosw0 + temp;
filter.a1 = 2*((A - 1) - (A + 1)*cosw0);
filter.a2 = (A + 1) - (A - 1)*cosw0 - temp;
return filter;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Buffers.Text;
using static System.Buffers.Binary.BinaryPrimitives;
using static System.Runtime.InteropServices.MemoryMarshal;
namespace System.Text.Http.Parser.Internal
{
internal static class HttpUtilities
{
public const string Http10Version = "HTTP/1.0";
public const string Http11Version = "HTTP/1.1";
public const string HttpUriScheme = "http://";
public const string HttpsUriScheme = "https://";
// readonly primitive statics can be Jit'd to consts https://github.com/dotnet/coreclr/issues/1079
private readonly static ulong _httpSchemeLong = GetAsciiStringAsLong(HttpUriScheme + "\0");
private readonly static ulong _httpsSchemeLong = GetAsciiStringAsLong(HttpsUriScheme);
private readonly static ulong _httpConnectMethodLong = GetAsciiStringAsLong("CONNECT ");
private readonly static ulong _httpDeleteMethodLong = GetAsciiStringAsLong("DELETE \0");
private const uint _httpGetMethodInt = 542393671; // retun of GetAsciiStringAsInt("GET "); const results in better codegen
private readonly static ulong _httpHeadMethodLong = GetAsciiStringAsLong("HEAD \0\0\0");
private readonly static ulong _httpPatchMethodLong = GetAsciiStringAsLong("PATCH \0\0");
private readonly static ulong _httpPostMethodLong = GetAsciiStringAsLong("POST \0\0\0");
private readonly static ulong _httpPutMethodLong = GetAsciiStringAsLong("PUT \0\0\0\0");
private readonly static ulong _httpOptionsMethodLong = GetAsciiStringAsLong("OPTIONS ");
private readonly static ulong _httpTraceMethodLong = GetAsciiStringAsLong("TRACE \0\0");
private const ulong _http10VersionLong = 3471766442030158920; // GetAsciiStringAsLong("HTTP/1.0"); const results in better codegen
private const ulong _http11VersionLong = 3543824036068086856; // GetAsciiStringAsLong("HTTP/1.1"); const results in better codegen
private readonly static ulong _mask8Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff });
private readonly static ulong _mask7Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00 });
private readonly static ulong _mask6Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00 });
private readonly static ulong _mask5Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00 });
private readonly static ulong _mask4Chars = GetMaskAsLong(new byte[] { 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 });
private readonly static Tuple<ulong, ulong, Http.Method, int>[] _knownMethods =
{
Tuple.Create(_mask4Chars, _httpPutMethodLong, Http.Method.Put, 3),
Tuple.Create(_mask5Chars, _httpPostMethodLong, Http.Method.Post, 4),
Tuple.Create(_mask5Chars, _httpHeadMethodLong, Http.Method.Head, 4),
Tuple.Create(_mask6Chars, _httpTraceMethodLong, Http.Method.Trace, 5),
Tuple.Create(_mask6Chars, _httpPatchMethodLong, Http.Method.Patch, 5),
Tuple.Create(_mask7Chars, _httpDeleteMethodLong, Http.Method.Delete, 6),
Tuple.Create(_mask8Chars, _httpConnectMethodLong, Http.Method.Connect, 7),
Tuple.Create(_mask8Chars, _httpOptionsMethodLong, Http.Method.Options, 7),
};
private readonly static string[] _methodNames = CreateMethodNames();
private static string[] CreateMethodNames()
{
var methodNames = new string[9];
methodNames[(byte)Http.Method.Get] = "GET";
methodNames[(byte)Http.Method.Put] = "PUT";
methodNames[(byte)Http.Method.Delete] = "DELETE";
methodNames[(byte)Http.Method.Post] = "POST";
methodNames[(byte)Http.Method.Head] = "HEAD";
methodNames[(byte)Http.Method.Trace] = "TRACE";
methodNames[(byte)Http.Method.Patch] = "PATCH";
methodNames[(byte)Http.Method.Connect] = "CONNECT";
methodNames[(byte)Http.Method.Options] = "OPTIONS";
return methodNames;
}
private static ulong GetAsciiStringAsLong(string str)
{
Debug.Assert(str.Length == 8, "String must be exactly 8 (ASCII) characters long.");
Span<byte> span = stackalloc byte[8];
Encodings.Utf16.ToUtf8(AsBytes(str.AsSpan()), span, out int consumed, out int written);
return Read<ulong>(span);
}
private static uint GetAsciiStringAsInt(string str)
{
Debug.Assert(str.Length == 4, "String must be exactly 4 (ASCII) characters long.");
Span<byte> span = stackalloc byte[4];
Encodings.Utf16.ToUtf8(AsBytes(str.AsSpan()), span, out int consumed, out int written);
return Read<uint>(span);
}
private unsafe static ulong GetMaskAsLong(byte[] bytes)
{
Debug.Assert(bytes.Length == 8, "Mask must be exactly 8 bytes long.");
fixed (byte* ptr = bytes)
{
return *(ulong*)ptr;
}
}
public unsafe static string GetAsciiStringNonNullCharacters(this Span<byte> span)
{
if (span.IsEmpty)
{
return string.Empty;
}
var asciiString = new string('\0', span.Length);
fixed (char* output = asciiString)
fixed (byte* buffer = &MemoryMarshal.GetReference(span))
{
// This version if AsciiUtilities returns null if there are any null (0 byte) characters
// in the string
if (!AsciiUtilities.TryGetAsciiString(buffer, output, span.Length))
{
throw new InvalidOperationException();
}
}
return asciiString;
}
public static string GetAsciiStringEscaped(this Span<byte> span, int maxChars)
{
var sb = new StringBuilder();
for (var i = 0; i < Math.Min(span.Length, maxChars); i++)
{
var ch = span[i];
sb.Append(ch < 0x20 || ch >= 0x7F ? $"\\x{ch:X2}" : ((char)ch).ToString());
}
if (span.Length > maxChars)
{
sb.Append("...");
}
return sb.ToString();
}
/// <summary>
/// Checks that up to 8 bytes from <paramref name="span"/> correspond to a known HTTP method.
/// </summary>
/// <remarks>
/// A "known HTTP method" can be an HTTP method name defined in the HTTP/1.1 RFC.
/// Since all of those fit in at most 8 bytes, they can be optimally looked up by reading those bytes as a long. Once
/// in that format, it can be checked against the known method.
/// The Known Methods (CONNECT, DELETE, GET, HEAD, PATCH, POST, PUT, OPTIONS, TRACE) are all less than 8 bytes
/// and will be compared with the required space. A mask is used if the Known method is less than 8 bytes.
/// To optimize performance the GET method will be checked first.
/// </remarks>
/// <returns><c>true</c> if the input matches a known string, <c>false</c> otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool GetKnownMethod(this Span<byte> span, out Http.Method method, out int length)
{
fixed (byte* data = &MemoryMarshal.GetReference(span))
{
method = GetKnownMethod(data, span.Length, out length);
return method != Http.Method.Custom;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe static Http.Method GetKnownMethod(byte* data, int length, out int methodLength)
{
methodLength = 0;
if (length < sizeof(uint))
{
return Http.Method.Custom;
}
else if (*(uint*)data == _httpGetMethodInt)
{
methodLength = 3;
return Http.Method.Get;
}
else if (length < sizeof(ulong))
{
return Http.Method.Custom;
}
else
{
var value = *(ulong*)data;
foreach (var x in _knownMethods)
{
if ((value & x.Item1) == x.Item2)
{
methodLength = x.Item4;
return x.Item3;
}
}
}
return Http.Method.Custom;
}
/// <summary>
/// Checks 9 bytes from <paramref name="span"/> correspond to a known HTTP version.
/// </summary>
/// <remarks>
/// A "known HTTP version" Is is either HTTP/1.0 or HTTP/1.1.
/// Since those fit in 8 bytes, they can be optimally looked up by reading those bytes as a long. Once
/// in that format, it can be checked against the known versions.
/// The Known versions will be checked with the required '\r'.
/// To optimize performance the HTTP/1.1 will be checked first.
/// </remarks>
/// <returns><c>true</c> if the input matches a known string, <c>false</c> otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool GetKnownVersion(this Span<byte> span, out Http.Version knownVersion, out byte length)
{
fixed (byte* data = &MemoryMarshal.GetReference(span))
{
knownVersion = GetKnownVersion(data, span.Length);
if (knownVersion != Http.Version.Unknown)
{
length = sizeof(ulong);
return true;
}
length = 0;
return false;
}
}
/// <summary>
/// Checks 9 bytes from <paramref name="location"/> correspond to a known HTTP version.
/// </summary>
/// <remarks>
/// A "known HTTP version" Is is either HTTP/1.0 or HTTP/1.1.
/// Since those fit in 8 bytes, they can be optimally looked up by reading those bytes as a long. Once
/// in that format, it can be checked against the known versions.
/// The Known versions will be checked with the required '\r'.
/// To optimize performance the HTTP/1.1 will be checked first.
/// </remarks>
/// <returns><c>true</c> if the input matches a known string, <c>false</c> otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe static Http.Version GetKnownVersion(byte* location, int length)
{
Http.Version knownVersion;
var version = *(ulong*)location;
if (length < sizeof(ulong) + 1 || location[sizeof(ulong)] != (byte)'\r')
{
knownVersion = Http.Version.Unknown;
}
else if (version == _http11VersionLong)
{
knownVersion = Http.Version.Http11;
}
else if (version == _http10VersionLong)
{
knownVersion = Http.Version.Http10;
}
else
{
knownVersion = Http.Version.Unknown;
}
return knownVersion;
}
/// <summary>
/// Checks 8 bytes from <paramref name="span"/> that correspond to 'http://' or 'https://'
/// </summary>
/// <param name="span">The span</param>
/// <param name="knownScheme">A reference to the known scheme, if the input matches any</param>
/// <returns>True when memory starts with known http or https schema</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool GetKnownHttpScheme(this Span<byte> span, out HttpScheme knownScheme)
{
fixed (byte* data = &MemoryMarshal.GetReference(span))
{
return GetKnownHttpScheme(data, span.Length, out knownScheme);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe bool GetKnownHttpScheme(byte* location, int length, out HttpScheme knownScheme)
{
if (length >= sizeof(ulong))
{
var scheme = *(ulong*)location;
if ((scheme & _mask7Chars) == _httpSchemeLong)
{
knownScheme = HttpScheme.Http;
return true;
}
if (scheme == _httpsSchemeLong)
{
knownScheme = HttpScheme.Https;
return true;
}
}
knownScheme = HttpScheme.Unknown;
return false;
}
public static string VersionToString(Http.Version httpVersion)
{
switch (httpVersion)
{
case Http.Version.Http10:
return Http10Version;
case Http.Version.Http11:
return Http11Version;
default:
return null;
}
}
public static string MethodToString(Http.Method method)
{
int methodIndex = (int)method;
if (methodIndex >= 0 && methodIndex <= 8)
{
return _methodNames[methodIndex];
}
return null;
}
public static string SchemeToString(HttpScheme scheme)
{
switch (scheme)
{
case HttpScheme.Http:
return HttpUriScheme;
case HttpScheme.Https:
return HttpsUriScheme;
default:
return null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System
{
/// <summary>
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
public struct Span<T>
{
/// <summary>A byref or a native ptr.</summary>
private readonly ByReference<T> _pointer;
/// <summary>The number of elements this Span contains.</summary>
#if PROJECTN
[Bound]
#endif
private readonly int _length;
/// <summary>
/// Creates a new span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()));
_length = array.Length;
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and covering the remainder of the array.
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
_length = array.Length - start;
}
/// <summary>
/// Creates a new span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the span.</param>
/// <param name="length">The number of items in the span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (default(T) == null && array.GetType() != typeof(T[]))
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
_length = length;
}
/// <summary>
/// Creates a new span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Span(void* pointer, int length)
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
_length = length;
}
/// <summary>
/// Create a new span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because neither the
/// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
/// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length) => new Span<T>(ref objectData, length);
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Span(ref T ptr, int length)
{
Debug.Assert(length >= 0);
_pointer = new ByReference<T>(ref ptr);
_length = length;
}
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
public ref T DangerousGetPinnableReference()
{
return ref _pointer.Value;
}
/// <summary>
/// The number of items in the span.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Returns a reference to specified element of the Span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public ref T this[int index]
{
#if PROJECTN
[BoundsChecking]
get
{
return ref Unsafe.Add(ref _pointer.Value, index);
}
#else
#if CORERT
[Intrinsic]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
return ref Unsafe.Add(ref _pointer.Value, index);
}
#endif
}
/// <summary>
/// Clears the contents of this span.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
Span.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint)));
}
else
{
Span.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>());
}
}
/// <summary>
/// Fills the contents of this span with the given value.
/// </summary>
public void Fill(T value)
{
if (Unsafe.SizeOf<T>() == 1)
{
uint length = (uint)_length;
if (length == 0)
return;
T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below.
Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length);
}
else
{
// Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations
nuint length = (uint)_length;
if (length == 0)
return;
ref T r = ref DangerousGetPinnableReference();
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
nuint elementSize = (uint)Unsafe.SizeOf<T>();
nuint i = 0;
for (; i < (length & ~(nuint)7); i += 8)
{
Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value;
}
if (i < (length & ~(nuint)3))
{
Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
i += 4;
}
for (; i < length; i++)
{
Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value;
}
}
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
/// </summary>
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// <summary>
/// Copies the contents of this span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
/// </summary>
/// <param name="destination">The span to copy items into.</param>
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
public bool TryCopyTo(Span<T> destination)
{
if ((uint)_length > (uint)destination.Length)
return false;
Span.CopyTo<T>(ref destination._pointer.Value, ref _pointer.Value, _length);
return true;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(Span<T> left, Span<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(Span<T> left, Span<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(T[] array) => new Span<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/>
/// </summary>
public static implicit operator Span<T>(ArraySegment<T> arraySegment) => new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length);
/// <summary>
/// Forms a slice out of the given span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start);
}
/// <summary>
/// Forms a slice out of the given span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
}
/// <summary>
/// Copies the contents of this span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T[] ToArray()
{
if (_length == 0)
return Array.Empty<T>();
var destination = new T[_length];
Span.CopyTo<T>(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, _length);
return destination;
}
// <summary>
/// Returns an empty <see cref="Span{T}"/>
/// </summary>
public static Span<T> Empty => default(Span<T>);
}
}
| |
using System;
using System.IO;
using NUnit.Framework;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Test;
using Org.BouncyCastle.X509;
namespace Org.BouncyCastle.Tests
{
[TestFixture]
public class Gost3410Test
: SimpleTest
{
private void ecGOST3410Test()
{
IBigInteger r = new BigInteger("29700980915817952874371204983938256990422752107994319651632687982059210933395");
IBigInteger s = new BigInteger("46959264877825372965922731380059061821746083849389763294914877353246631700866");
byte[] kData = new BigInteger("53854137677348463731403841147996619241504003434302020712960838528893196233395").ToByteArrayUnsigned();
SecureRandom k = FixedSecureRandom.From(kData);
IBigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p
ECCurve curve = new FPCurve(
mod_p, // p
new BigInteger("7"), // a
new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b
ECDomainParameters spec = new ECDomainParameters(
curve,
curve.CreatePoint(
new BigInteger("2"),
new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280"),
false),
new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q
ECPrivateKeyParameters sKey = new ECPrivateKeyParameters(
"ECGOST3410",
new BigInteger("55441196065363246126355624130324183196576709222340016572108097750006097525544"), // d
spec);
ECPublicKeyParameters vKey = new ECPublicKeyParameters(
"ECGOST3410",
curve.CreatePoint(
new BigInteger("57520216126176808443631405023338071176630104906313632182896741342206604859403"),
new BigInteger("17614944419213781543809391949654080031942662045363639260709847859438286763994"),
false),
spec);
ISigner sgr = SignerUtilities.GetSigner("ECGOST3410");
sgr.Init(true, new ParametersWithRandom(sKey, k));
byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
sgr.BlockUpdate(message, 0, message.Length);
byte[] sigBytes = sgr.GenerateSignature();
sgr.Init(false, vKey);
sgr.BlockUpdate(message, 0, message.Length);
if (!sgr.VerifySignature(sigBytes))
{
Fail("ECGOST3410 verification failed");
}
IBigInteger[] sig = decode(sigBytes);
if (!r.Equals(sig[0]))
{
Fail(
": r component wrong." + SimpleTest.NewLine
+ " expecting: " + r + SimpleTest.NewLine
+ " got : " + sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail(
": s component wrong." + SimpleTest.NewLine
+ " expecting: " + s + SimpleTest.NewLine
+ " got : " + sig[1]);
}
}
private void generationTest()
{
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
ISigner s = SignerUtilities.GetSigner("GOST3410");
IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");
g.Init(
new Gost3410KeyGenerationParameters(
new SecureRandom(),
CryptoProObjectIdentifiers.GostR3410x94CryptoProA));
IAsymmetricCipherKeyPair p = g.GenerateKeyPair();
IAsymmetricKeyParameter sKey = p.Private;
IAsymmetricKeyParameter vKey = p.Public;
s.Init(true, sKey);
s.BlockUpdate(data, 0, data.Length);
byte[] sigBytes = s.GenerateSignature();
s = SignerUtilities.GetSigner("GOST3410");
s.Init(false, vKey);
s.BlockUpdate(data, 0, data.Length);
if (!s.VerifySignature(sigBytes))
{
Fail("GOST3410 verification failed");
}
//
// default initialisation test
//
s = SignerUtilities.GetSigner("GOST3410");
g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");
// TODO This is supposed to be a 'default initialisation' test, but don't have a factory
// These values are defaults from JCE provider
g.Init(
new Gost3410KeyGenerationParameters(
new SecureRandom(),
CryptoProObjectIdentifiers.GostR3410x94CryptoProA));
p = g.GenerateKeyPair();
sKey = p.Private;
vKey = p.Public;
s.Init(true, sKey);
s.BlockUpdate(data, 0, data.Length);
sigBytes = s.GenerateSignature();
s = SignerUtilities.GetSigner("GOST3410");
s.Init(false, vKey);
s.BlockUpdate(data, 0, data.Length);
if (!s.VerifySignature(sigBytes))
{
Fail("GOST3410 verification failed");
}
//
// encoded test
//
//KeyFactory f = KeyFactory.getInstance("GOST3410");
//X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.GetEncoded());
//Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)f.generatePublic(x509s);
byte[] vKeyEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();
Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)
PublicKeyFactory.CreateKey(vKeyEnc);
if (!k1.Y.Equals(((Gost3410PublicKeyParameters)vKey).Y))
{
Fail("public number not decoded properly");
}
//PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.GetEncoded());
//Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)f.generatePrivate(pkcs8);
byte[] sKeyEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();
Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)
PrivateKeyFactory.CreateKey(sKeyEnc);
if (!k2.X.Equals(((Gost3410PrivateKeyParameters)sKey).X))
{
Fail("private number not decoded properly");
}
//
// ECGOST3410 generation test
//
s = SignerUtilities.GetSigner("ECGOST3410");
g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");
IBigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p
ECCurve curve = new FPCurve(
mod_p, // p
new BigInteger("7"), // a
new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b
ECDomainParameters ecSpec = new ECDomainParameters(
curve,
curve.CreatePoint(
new BigInteger("2"),
new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280"),
false),
new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q
g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
p = g.GenerateKeyPair();
sKey = p.Private;
vKey = p.Public;
s.Init(true, sKey);
s.BlockUpdate(data, 0, data.Length);
sigBytes = s.GenerateSignature();
s = SignerUtilities.GetSigner("ECGOST3410");
s.Init(false, vKey);
s.BlockUpdate(data, 0, data.Length);
if (!s.VerifySignature(sigBytes))
{
Fail("ECGOST3410 verification failed");
}
}
private void keyStoreTest(
IAsymmetricKeyParameter sKey,
IAsymmetricKeyParameter vKey)
// throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, UnrecoverableKeyException
{
//
// keystore test
//
// KeyStore ks = KeyStore.GetInstance("JKS");
// ks.Load(null, null);
Pkcs12StoreBuilder ksBuilder = new Pkcs12StoreBuilder();
Pkcs12Store ks = ksBuilder.Build();
//
// create the certificate - version 3
//
X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
certGen.SetSerialNumber(BigInteger.One);
certGen.SetIssuerDN(new X509Name("CN=Test"));
certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
certGen.SetSubjectDN(new X509Name("CN=Test"));
certGen.SetPublicKey(vKey);
certGen.SetSignatureAlgorithm("GOST3411withGOST3410");
X509Certificate cert = certGen.Generate(sKey);
X509CertificateEntry certEntry = new X509CertificateEntry(cert);
// ks.SetKeyEntry("gost", sKey, "gost".ToCharArray(), new X509Certificate[] { cert });
ks.SetKeyEntry("gost", new AsymmetricKeyEntry(sKey), new X509CertificateEntry[] { certEntry });
MemoryStream bOut = new MemoryStream();
ks.Save(bOut, "gost".ToCharArray(), new SecureRandom());
// ks = KeyStore.getInstance("JKS");
ks = ksBuilder.Build();
ks.Load(new MemoryStream(bOut.ToArray(), false), "gost".ToCharArray());
// IAsymmetricKeyParameter gKey = (AsymmetricKeyParameter)ks.GetKey("gost", "gost".ToCharArray());
// AsymmetricKeyEntry gKeyEntry = (AsymmetricKeyEntry)
ks.GetKey("gost");
}
private void parametersTest()
{
// AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("GOST3410");
// a.init(512, random);
// AlgorithmParameters params = a.generateParameters();
//
// byte[] encodeParams = params.getEncoded();
//
// AlgorithmParameters a2 = AlgorithmParameters.getInstance("GOST3410");
// a2.init(encodeParams);
//
// // a and a2 should be equivalent!
// byte[] encodeParams_2 = a2.getEncoded();
//
// if (!arrayEquals(encodeParams, encodeParams_2))
// {
// Fail("encode/decode parameters failed");
// }
// GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec(
// CryptoProObjectIdentifiers.gostR3410_94_CryptoPro_B.getId());
// g.initialize(gost3410P, new SecureRandom());
IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");
g.Init(
new Gost3410KeyGenerationParameters(
new SecureRandom(),
CryptoProObjectIdentifiers.GostR3410x94CryptoProB));
IAsymmetricCipherKeyPair p = g.GenerateKeyPair();
IAsymmetricKeyParameter sKey = p.Private;
IAsymmetricKeyParameter vKey = p.Public;
ISigner s = SignerUtilities.GetSigner("GOST3410");
byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
s.Init(true, sKey);
s.BlockUpdate(data, 0, data.Length);
byte[] sigBytes = s.GenerateSignature();
s = SignerUtilities.GetSigner("GOST3410");
s.Init(false, vKey);
s.BlockUpdate(data, 0, data.Length);
if (!s.VerifySignature(sigBytes))
{
Fail("GOST3410 verification failed");
}
keyStoreTest(sKey, vKey);
}
private IBigInteger[] decode(
byte[] encoding)
{
byte[] r = new byte[32];
byte[] s = new byte[32];
Array.Copy(encoding, 0, s, 0, 32);
Array.Copy(encoding, 32, r, 0, 32);
IBigInteger[] sig = new BigInteger[2];
sig[0] = new BigInteger(1, r);
sig[1] = new BigInteger(1, s);
return sig;
}
public override string Name
{
get { return "GOST3410/ECGOST3410"; }
}
public override void PerformTest()
{
ecGOST3410Test();
generationTest();
parametersTest();
}
public static void Main(
string[] args)
{
RunTest(new Gost3410Test());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System;
using System.Collections;
using UnityEngine;
using UtyRx;
namespace Assets.Scripts.Environment.Reactive
{
public static class UnityScheduler
{
public static void SetDefaultForUnity()
{
Scheduler.MainThread = new MainThreadScheduler();
Scheduler.DefaultSchedulers.ConstantTimeOperations = Scheduler.Immediate;
Scheduler.DefaultSchedulers.TailRecursion = Scheduler.Immediate;
Scheduler.DefaultSchedulers.Iteration = Scheduler.CurrentThread;
Scheduler.DefaultSchedulers.TimeBasedOperations = Scheduler.MainThread;
Scheduler.DefaultSchedulers.AsyncConversions = Scheduler.ThreadPool;
}
class MainThreadScheduler : IScheduler, ISchedulerPeriodic, ISchedulerQueueing
{
readonly Action<object> scheduleAction;
public MainThreadScheduler()
{
MainThreadDispatcher.Initialize();
scheduleAction = new Action<object>(Schedule);
}
// delay action is run in StartCoroutine
// Okay to action run synchronous and guaranteed run on MainThread
IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
{
// zero == every frame
if (dueTime == TimeSpan.Zero)
{
yield return null; // not immediately, run next frame
}
else
{
yield return new WaitForSeconds((float)dueTime.TotalSeconds);
}
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
IEnumerator PeriodicAction(TimeSpan period, Action action, ICancelable cancellation)
{
// zero == every frame
if (period == TimeSpan.Zero)
{
while (true)
{
yield return null; // not immediately, run next frame
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
}
else
{
var seconds = (float)(period.TotalMilliseconds / 1000.0);
var yieldInstruction = new WaitForSeconds(seconds); // cache single instruction object
while (true)
{
yield return yieldInstruction;
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
}
}
public DateTimeOffset Now
{
get { return Scheduler.Now; }
}
void Schedule(object state)
{
var t = (UtyRx.Tuple<BooleanDisposable, Action>)state;
if (!t.Item1.IsDisposed)
{
t.Item2();
}
}
public IDisposable Schedule(Action action)
{
var d = new BooleanDisposable();
MainThreadDispatcher.Post(scheduleAction, UtyRx.Tuple.Create(d, action));
return d;
}
public IDisposable Schedule(DateTimeOffset dueTime, Action action)
{
return Schedule(dueTime - Now, action);
}
public IDisposable Schedule(TimeSpan dueTime, Action action)
{
var d = new BooleanDisposable();
var time = Scheduler.Normalize(dueTime);
MainThreadDispatcher.SendStartCoroutine(DelayAction(time, action, d));
return d;
}
public IDisposable SchedulePeriodic(TimeSpan period, Action action)
{
var d = new BooleanDisposable();
var time = Scheduler.Normalize(period);
MainThreadDispatcher.SendStartCoroutine(PeriodicAction(time, action, d));
return d;
}
void ScheduleQueueing<T>(object state)
{
var t = (UtyRx.Tuple<ICancelable, T, Action<T>>)state;
if (!t.Item1.IsDisposed)
{
t.Item3(t.Item2);
}
}
public void ScheduleQueueing<T>(ICancelable cancel, T state, Action<T> action)
{
MainThreadDispatcher.Post(QueuedAction<T>.Instance, UtyRx.Tuple.Create(cancel, state, action));
}
static class QueuedAction<T>
{
public static readonly Action<object> Instance = new Action<object>(Invoke);
public static void Invoke(object state)
{
var t = (UtyRx.Tuple<ICancelable, T, Action<T>>)state;
if (!t.Item1.IsDisposed)
{
t.Item3(t.Item2);
}
}
}
}
class IgnoreTimeScaleMainThreadScheduler : IScheduler, ISchedulerPeriodic, ISchedulerQueueing
{
readonly Action<object> scheduleAction;
public IgnoreTimeScaleMainThreadScheduler()
{
MainThreadDispatcher.Initialize();
scheduleAction = new Action<object>(Schedule);
}
IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
{
if (dueTime == TimeSpan.Zero)
{
yield return null;
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
else
{
var elapsed = 0f;
var dt = (float)dueTime.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
elapsed += Time.unscaledDeltaTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
}
}
}
IEnumerator PeriodicAction(TimeSpan period, Action action, ICancelable cancellation)
{
// zero == every frame
if (period == TimeSpan.Zero)
{
while (true)
{
yield return null; // not immediately, run next frame
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
}
else
{
var elapsed = 0f;
var dt = (float)period.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
elapsed += Time.unscaledDeltaTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
elapsed = 0;
}
}
}
}
public DateTimeOffset Now
{
get { return Scheduler.Now; }
}
void Schedule(object state)
{
var t = (UtyRx.Tuple<BooleanDisposable, Action>)state;
if (!t.Item1.IsDisposed)
{
t.Item2();
}
}
public IDisposable Schedule(Action action)
{
var d = new BooleanDisposable();
MainThreadDispatcher.Post(scheduleAction, UtyRx.Tuple.Create(d, action));
return d;
}
public IDisposable Schedule(DateTimeOffset dueTime, Action action)
{
return Schedule(dueTime - Now, action);
}
public IDisposable Schedule(TimeSpan dueTime, Action action)
{
var d = new BooleanDisposable();
var time = Scheduler.Normalize(dueTime);
MainThreadDispatcher.SendStartCoroutine(DelayAction(time, action, d));
return d;
}
public IDisposable SchedulePeriodic(TimeSpan period, Action action)
{
var d = new BooleanDisposable();
var time = Scheduler.Normalize(period);
MainThreadDispatcher.SendStartCoroutine(PeriodicAction(time, action, d));
return d;
}
public void ScheduleQueueing<T>(ICancelable cancel, T state, Action<T> action)
{
MainThreadDispatcher.Post(QueuedAction<T>.Instance, UtyRx.Tuple.Create(cancel, state, action));
}
static class QueuedAction<T>
{
public static readonly Action<object> Instance = new Action<object>(Invoke);
public static void Invoke(object state)
{
var t = (UtyRx.Tuple<ICancelable, T, Action<T>>)state;
if (!t.Item1.IsDisposed)
{
t.Item3(t.Item2);
}
}
}
}
class FixedUpdateMainThreadScheduler : IScheduler, ISchedulerPeriodic, ISchedulerQueueing
{
public FixedUpdateMainThreadScheduler()
{
MainThreadDispatcher.Initialize();
}
IEnumerator ImmediateAction<T>(T state, Action<T> action, ICancelable cancellation)
{
yield return null;
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action, state);
}
IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
{
if (dueTime == TimeSpan.Zero)
{
yield return null;
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
else
{
var startTime = Time.fixedTime;
var dt = (float)dueTime.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var elapsed = Time.fixedTime - startTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
}
}
}
IEnumerator PeriodicAction(TimeSpan period, Action action, ICancelable cancellation)
{
// zero == every frame
if (period == TimeSpan.Zero)
{
while (true)
{
yield return null;
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
}
else
{
var startTime = Time.fixedTime;
var dt = (float)period.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
var ft = Time.fixedTime;
var elapsed = ft - startTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
startTime = ft;
}
}
}
}
public DateTimeOffset Now
{
get { return Scheduler.Now; }
}
public IDisposable Schedule(Action action)
{
return Schedule(TimeSpan.Zero, action);
}
public IDisposable Schedule(DateTimeOffset dueTime, Action action)
{
return Schedule(dueTime - Now, action);
}
public IDisposable Schedule(TimeSpan dueTime, Action action)
{
var d = new BooleanDisposable();
var time = Scheduler.Normalize(dueTime);
MainThreadDispatcher.StartFixedUpdateMicroCoroutine(DelayAction(time, action, d));
return d;
}
public IDisposable SchedulePeriodic(TimeSpan period, Action action)
{
var d = new BooleanDisposable();
var time = Scheduler.Normalize(period);
MainThreadDispatcher.StartFixedUpdateMicroCoroutine(PeriodicAction(time, action, d));
return d;
}
public void ScheduleQueueing<T>(ICancelable cancel, T state, Action<T> action)
{
MainThreadDispatcher.StartFixedUpdateMicroCoroutine(ImmediateAction(state, action, cancel));
}
}
class EndOfFrameMainThreadScheduler : IScheduler, ISchedulerPeriodic, ISchedulerQueueing
{
public EndOfFrameMainThreadScheduler()
{
MainThreadDispatcher.Initialize();
}
IEnumerator ImmediateAction<T>(T state, Action<T> action, ICancelable cancellation)
{
yield return null;
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action, state);
}
IEnumerator DelayAction(TimeSpan dueTime, Action action, ICancelable cancellation)
{
if (dueTime == TimeSpan.Zero)
{
yield return null;
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
else
{
var elapsed = 0f;
var dt = (float)dueTime.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
elapsed += Time.deltaTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
break;
}
}
}
}
IEnumerator PeriodicAction(TimeSpan period, Action action, ICancelable cancellation)
{
// zero == every frame
if (period == TimeSpan.Zero)
{
while (true)
{
yield return null;
if (cancellation.IsDisposed) yield break;
MainThreadDispatcher.UnsafeSend(action);
}
}
else
{
var elapsed = 0f;
var dt = (float)period.TotalSeconds;
while (true)
{
yield return null;
if (cancellation.IsDisposed) break;
elapsed += Time.deltaTime;
if (elapsed >= dt)
{
MainThreadDispatcher.UnsafeSend(action);
elapsed = 0;
}
}
}
}
public DateTimeOffset Now
{
get { return Scheduler.Now; }
}
public IDisposable Schedule(Action action)
{
return Schedule(TimeSpan.Zero, action);
}
public IDisposable Schedule(DateTimeOffset dueTime, Action action)
{
return Schedule(dueTime - Now, action);
}
public IDisposable Schedule(TimeSpan dueTime, Action action)
{
var d = new BooleanDisposable();
var time = Scheduler.Normalize(dueTime);
MainThreadDispatcher.StartEndOfFrameMicroCoroutine(DelayAction(time, action, d));
return d;
}
public IDisposable SchedulePeriodic(TimeSpan period, Action action)
{
var d = new BooleanDisposable();
var time = Scheduler.Normalize(period);
MainThreadDispatcher.StartEndOfFrameMicroCoroutine(PeriodicAction(time, action, d));
return d;
}
public void ScheduleQueueing<T>(ICancelable cancel, T state, Action<T> action)
{
MainThreadDispatcher.StartEndOfFrameMicroCoroutine(ImmediateAction(state, action, cancel));
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Sql.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Sql.Fluent.Models;
using Microsoft.Azure.Management.Sql.Fluent.SqlServerKey.Update;
using Microsoft.Azure.Management.Sql.Fluent.SqlServerKeyOperations.Definition;
using Microsoft.Azure.Management.Sql.Fluent.SqlServerKeyOperations.SqlServerKeyOperationsDefinition;
using System;
internal partial class SqlServerKeyImpl
{
/// <summary>
/// Gets the resource ID string.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasId.Id
{
get
{
return this.Id();
}
}
/// <summary>
/// Sets the server key creation date.
/// </summary>
/// <param name="creationDate">The server key creation date.</param>
/// <return>The next stage of the definition.</return>
SqlServerKey.Update.IUpdate SqlServerKey.Update.IWithCreationDate.WithCreationDate(DateTime creationDate)
{
return this.WithCreationDate(creationDate);
}
/// <summary>
/// Sets the server key creation date.
/// </summary>
/// <param name="creationDate">The server key creation date.</param>
/// <return>The next stage of the definition.</return>
SqlServerKeyOperations.Definition.IWithCreate SqlServerKeyOperations.Definition.IWithCreationDate.WithCreationDate(DateTime creationDate)
{
return this.WithCreationDate(creationDate);
}
/// <summary>
/// Gets the name of the resource.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name
{
get
{
return this.Name();
}
}
/// <summary>
/// Sets the parent SQL server for the new Server Key.
/// </summary>
/// <param name="sqlServerId">The parent SQL server ID.</param>
/// <return>The next stage of the definition.</return>
SqlServerKeyOperations.Definition.IWithServerKeyType SqlServerKeyOperations.Definition.IWithSqlServer.WithExistingSqlServerId(string sqlServerId)
{
return this.WithExistingSqlServerId(sqlServerId);
}
/// <summary>
/// Sets the parent SQL server name and resource group it belongs to.
/// </summary>
/// <param name="resourceGroupName">The name of the resource group the parent SQL server.</param>
/// <param name="sqlServerName">The parent SQL server name.</param>
/// <return>The next stage of the definition.</return>
SqlServerKeyOperations.Definition.IWithServerKeyType SqlServerKeyOperations.Definition.IWithSqlServer.WithExistingSqlServer(string resourceGroupName, string sqlServerName)
{
return this.WithExistingSqlServer(resourceGroupName, sqlServerName);
}
/// <summary>
/// Sets the parent SQL server for the new Server Key.
/// </summary>
/// <param name="sqlServer">The parent SQL server.</param>
/// <return>The next stage of the definition.</return>
SqlServerKeyOperations.Definition.IWithServerKeyType SqlServerKeyOperations.Definition.IWithSqlServer.WithExistingSqlServer(ISqlServer sqlServer)
{
return this.WithExistingSqlServer(sqlServer);
}
/// <summary>
/// Sets the thumbprint of the server key.
/// </summary>
/// <param name="thumbprint">The thumbprint of the server key.</param>
/// <return>The next stage of the definition.</return>
SqlServerKey.Update.IUpdate SqlServerKey.Update.IWithThumbprint.WithThumbprint(string thumbprint)
{
return this.WithThumbprint(thumbprint);
}
/// <summary>
/// Sets the thumbprint of the server key.
/// </summary>
/// <param name="thumbprint">The thumbprint of the server key.</param>
/// <return>The next stage of the definition.</return>
SqlServerKeyOperations.Definition.IWithCreate SqlServerKeyOperations.Definition.IWithThumbprint.WithThumbprint(string thumbprint)
{
return this.WithThumbprint(thumbprint);
}
/// <summary>
/// Begins an update for a new resource.
/// This is the beginning of the builder pattern used to update top level resources
/// in Azure. The final method completing the definition and starting the actual resource creation
/// process in Azure is Appliable.apply().
/// </summary>
/// <return>The stage of new resource update.</return>
SqlServerKey.Update.IUpdate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IUpdatable<SqlServerKey.Update.IUpdate>.Update()
{
return this.Update();
}
/// <summary>
/// Gets the server key creation date.
/// </summary>
System.DateTime? Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.CreationDate
{
get
{
return this.CreationDate();
}
}
/// <summary>
/// Gets the resource location.
/// </summary>
Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.Region
{
get
{
return this.Region();
}
}
/// <summary>
/// Gets the URI of the server key.
/// </summary>
string Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.Uri
{
get
{
return this.Uri();
}
}
/// <summary>
/// Gets the kind of encryption protector; this is metadata used for the Azure Portal experience.
/// </summary>
string Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.Kind
{
get
{
return this.Kind();
}
}
/// <summary>
/// Gets the thumbprint of the server key.
/// </summary>
string Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.Thumbprint
{
get
{
return this.Thumbprint();
}
}
/// <summary>
/// Gets the server key type.
/// </summary>
Models.ServerKeyType Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.ServerKeyType
{
get
{
return this.ServerKeyType();
}
}
/// <summary>
/// Gets the parent SQL server ID.
/// </summary>
string Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.ParentId
{
get
{
return this.ParentId();
}
}
/// <summary>
/// Gets name of the SQL Server to which this DNS alias belongs.
/// </summary>
string Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.SqlServerName
{
get
{
return this.SqlServerName();
}
}
/// <summary>
/// Deletes the DNS alias.
/// </summary>
void Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.Delete()
{
this.Delete();
}
/// <summary>
/// Deletes the DNS alias asynchronously.
/// </summary>
/// <return>A representation of the deferred computation of this call.</return>
async Task Microsoft.Azure.Management.Sql.Fluent.ISqlServerKey.DeleteAsync(CancellationToken cancellationToken)
{
await this.DeleteAsync(cancellationToken);
}
/// <summary>
/// Gets the name of the resource group.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasResourceGroup.ResourceGroupName
{
get
{
return this.ResourceGroupName();
}
}
/// <summary>
/// Sets the server key type as "AzureKeyVault" and the URI to the key.
/// </summary>
/// <param name="uri">The URI of the server key.</param>
/// <return>The next stage of the definition.</return>
SqlServerKeyOperations.Definition.IWithCreate SqlServerKeyOperations.Definition.IWithServerKeyType.WithAzureKeyVaultKey(string uri)
{
return this.WithAzureKeyVaultKey(uri);
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Xml;
using SIL.IO;
using SIL.Xml;
namespace SIL.TestUtilities
{
public class TempLiftFile : TempFile
{
public TempLiftFile(string xmlOfEntries)
: this(xmlOfEntries, /*LiftIO.Validation.Validator.LiftVersion*/ "0.12")
{
}
public TempLiftFile(string xmlOfEntries, string claimedLiftVersion)
: this(null, xmlOfEntries, claimedLiftVersion)
{
}
public TempLiftFile(TemporaryFolder parentFolder, string xmlOfEntries, string claimedLiftVersion)
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
if (parentFolder != null)
{
_path = parentFolder.GetPathForNewTempFile(false) + ".lift";
}
else
{
var temp = System.IO.Path.GetTempFileName();
_path = temp + ".lift";
File.Move(temp, _path);
}
string liftContents = string.Format("<?xml version='1.0' encoding='utf-8'?><lift version='{0}'>{1}</lift>", claimedLiftVersion, xmlOfEntries);
File.WriteAllText(_path, liftContents);
}
public TempLiftFile(string fileName, TemporaryFolder parentFolder, string xmlOfEntries, string claimedLiftVersion)
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
_path = parentFolder.Combine(fileName);
string liftContents = string.Format("<?xml version='1.0' encoding='utf-8'?><lift version='{0}'>{1}</lift>", claimedLiftVersion, xmlOfEntries);
File.WriteAllText(_path, liftContents);
}
private TempLiftFile()
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
}
/// <summary>
/// Create a TempLiftFile based on a pre-existing file, which will be deleted when this is disposed.
/// </summary>
public static TempLiftFile TrackExisting(string path)
{
Debug.Assert(File.Exists(path));
TempLiftFile t = new TempLiftFile();
t._path = path;
return t;
}
}
/// <summary>
/// This is useful for unit tests. When it is disposed, it will delete the file.
/// </summary>
/// <example>using(f = new TemporaryFile(){}</example>
public class TempFileFromFolder : TempFile
{
/// <summary>
/// Create a tempfile within the given parent folder
/// </summary>
public TempFileFromFolder(TemporaryFolder parentFolder)
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
_path = parentFolder != null ? parentFolder.GetPathForNewTempFile(true) : System.IO.Path.GetTempFileName();
}
public TempFileFromFolder(TemporaryFolder parentFolder, string name, string contents)
: base(true) // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
{
_path = parentFolder.Combine(name);
File.WriteAllText(_path, contents);
}
public static TempFile CreateXmlFileWithContents(string fileName, TemporaryFolder folder, string xmlBody)
{
string path = folder.Combine(fileName);
using (var reader = XmlReader.Create(new StringReader(xmlBody)))
{
using (var writer = XmlWriter.Create(path, CanonicalXmlSettings.CreateXmlWriterSettings()))
{
writer.WriteStartDocument();
writer.WriteNode(reader, false);
}
}
return new TempFile(path, true);
}
public static TempFile CreateAt(string path, string contents)
{
File.WriteAllText(path, contents);
return TrackExisting(path);
}
}
/// <summary>
/// This is useful for unit tests. When it is disposed, it works hard to empty and remove the folder.
/// </summary>
/// <example>using(f = new TemporaryFolder("My Export Tests"){}</example>
public class TemporaryFolder : IDisposable
{
private string _path;
/// <summary>
/// Create a TemporaryFolder based on a pre-existing directory, which will be deleted when this is disposed.
/// </summary>
static public TemporaryFolder TrackExisting(string path)
{
Debug.Assert(Directory.Exists(path), @"TrackExisting given non existant folder to track.");
var f = new TemporaryFolder(false);
f._path = path;
return f;
}
[Obsolete("Go ahead and give it a name related to the test. Makes it easier to track down problems.")]
public TemporaryFolder()
: this(System.IO.Path.GetRandomFileName())
{
}
/// <summary>
/// Private constructor that doesn't create a file. Used when tracking a pre-existing
/// directory.
/// </summary>
private TemporaryFolder(bool ignored)
{
}
public TemporaryFolder(string name)
{
_path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), name);
if (Directory.Exists(_path))
{
TestUtilities.DeleteFolderThatMayBeInUse(_path);
}
Directory.CreateDirectory(_path);
}
public TemporaryFolder(TemporaryFolder parent, string name)
{
_path = parent.Combine(name);
if (Directory.Exists(_path))
{
TestUtilities.DeleteFolderThatMayBeInUse(_path);
}
Directory.CreateDirectory(_path);
}
[Obsolete("Path is preferred")]
public string FolderPath
{
get { return _path; }
}
/// <summary>
/// Same as FolderPath, but I repent of that poor name
/// </summary>
public string Path
{
get { return _path; }
}
public void Dispose()
{
TestUtilities.DeleteFolderThatMayBeInUse(_path);
}
[Obsolete("It's better to wrap the use of this in a using() so that it is automatically cleaned up, even if a test fails.")]
public void Delete()
{
TestUtilities.DeleteFolderThatMayBeInUse(_path);
}
public string GetPathForNewTempFile(bool doCreateTheFile)
{
string s = System.IO.Path.GetRandomFileName();
s = System.IO.Path.Combine(_path, s);
if (doCreateTheFile)
{
File.Create(s).Close();
}
return s;
}
public TempFile GetNewTempFile(bool doCreateTheFile)
{
string s = System.IO.Path.GetRandomFileName();
s = System.IO.Path.Combine(_path, s);
if (doCreateTheFile)
{
File.Create(s).Close();
}
return TempFile.TrackExisting(s);
}
[Obsolete("It's better to use the explict GetNewTempFile, which makes you say if you want the file to be created or not, and give you back a whole TempFile class, which is itself IDisposable.")]
public string GetTemporaryFile()
{
return GetTemporaryFile(System.IO.Path.GetRandomFileName());
}
[Obsolete("It's better to use the explict GetNewTempFile, which makes you say if you want the file to be created or not, and give you back a whole TempFile class, which is itself IDisposable.")]
public string GetTemporaryFile(string name)
{
string s = System.IO.Path.Combine(_path, name);
File.Create(s).Close();
return s;
}
/// <summary>
/// Similar to Path.Combine, but you don't have to specify the location of the temporaryfolder itself, and you can add multiple parts to combine.
/// </summary>
/// <example> string path = t.Combine("stuff", "toys", "ball.txt")</example>
public string Combine(params string[] partsOfThePath)
{
string result = _path;
foreach (var s in partsOfThePath)
{
result = System.IO.Path.Combine(result, s);
}
return result;
}
}
}
| |
#pragma warning disable 1591
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace GtfsService.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
#pragma warning restore 1591
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.PythonTools.Editor;
using TestUtilities;
using TestUtilities.Python;
using TestUtilities.UI;
using TestUtilities.UI.Python;
using System.Threading;
using Microsoft.PythonTools.Intellisense;
namespace PythonToolsUITests {
public class RemoveImportTests {
public void FromImport1(VisualStudioApp app) {
string expectedText = @"from sys import oar
oar";
RemoveLightBulbTest(app, "FromImport1.py", 1, 1, true, expectedText);
RemoveLightBulbTest(app, "FromImport1.py", 1, 1, false, expectedText);
}
public void FromImport2(VisualStudioApp app) {
string expectedText = @"from sys import baz
baz";
RemoveLightBulbTest(app, "FromImport2.py", 1, 1, true, expectedText);
}
public void FromImportParens1(VisualStudioApp app) {
string expectedText = @"from sys import (oar)
oar";
RemoveLightBulbTest(app, "FromImportParens1.py", 1, 1, true, expectedText);
}
public void FromImportParens2(VisualStudioApp app) {
string expectedText = @"from sys import (baz)
baz";
RemoveLightBulbTest(app, "FromImportParens2.py", 1, 1, true, expectedText);
}
public void FromImportParensTrailingComma1(VisualStudioApp app) {
string expectedText = @"from sys import (baz, )
baz";
RemoveLightBulbTest(app, "FromImportParensTrailingComma1.py", 1, 1, true, expectedText);
}
public void FromImportParensTrailingComma2(VisualStudioApp app) {
string expectedText = @"from sys import (oar, )
oar";
RemoveLightBulbTest(app, "FromImportParensTrailingComma2.py", 1, 1, true, expectedText);
}
public void Import1(VisualStudioApp app) {
string expectedText = @"import oar
oar";
RemoveLightBulbTest(app, "Import1.py", 1, 1, true, expectedText);
}
public void Import2(VisualStudioApp app) {
string expectedText = @"import baz
baz";
RemoveLightBulbTest(app, "Import2.py", 1, 1, true, expectedText);
}
public void Import3(VisualStudioApp app) {
string expectedText = @"import baz
baz";
RemoveLightBulbTest(app, "Import3.py", 1, 1, true, expectedText);
}
public void Import4(VisualStudioApp app) {
string expectedText = @"import oar, quox
oar
quox";
RemoveLightBulbTest(app, "Import4.py", 1, 1, true, expectedText);
}
public void Import5(VisualStudioApp app) {
string expectedText = @"import oar, quox
oar
quox";
RemoveLightBulbTest(app, "Import5.py", 1, 1, true, expectedText);
}
public void Import6(VisualStudioApp app) {
string expectedText = @"import oar, quox
oar
quox";
RemoveLightBulbTest(app, "Import6.py", 1, 1, true, expectedText);
}
public void ImportComment(VisualStudioApp app) {
string expectedText = @"#baz
import oar, quox
#fob
#oar
oar
quox";
RemoveLightBulbTest(app, "ImportComment.py", 1, 1, true, expectedText);
}
public void FromImportComment(VisualStudioApp app) {
string expectedText = @"#baz
from xyz import oar, quox
#fob
#oar
oar
quox";
RemoveLightBulbTest(app, "FromImportComment.py", 1, 1, true, expectedText);
}
public void ImportDup(VisualStudioApp app) {
string expectedText = @"";
RemoveLightBulbTest(app, "ImportDup.py", 1, 1, true, expectedText);
}
public void FromImportDup(VisualStudioApp app) {
string expectedText = @"";
RemoveLightBulbTest(app, "FromImportDup.py", 1, 1, true, expectedText);
}
public void Import(VisualStudioApp app) {
string expectedText = @"";
RemoveLightBulbTest(app, "Import.py", 1, 1, true, expectedText);
}
public void FromImport(VisualStudioApp app) {
string expectedText = @"";
RemoveLightBulbTest(app, "FromImport.py", 1, 1, true, expectedText);
}
public void FutureImport(VisualStudioApp app) {
string expectedText = @"from __future__ import with_statement";
RemoveLightBulbTest(app, "FutureImport.py", 1, 1, true, expectedText);
}
public void LocalScopeDontRemoveGlobal(VisualStudioApp app) {
string expectedText = @"import dne
def f():
import baz
baz";
RemoveLightBulbTest(app, "LocalScopeDontRemoveGlobal.py", 4, 10, false, expectedText);
}
public void LocalScopeOnly(VisualStudioApp app) {
string expectedText = @"import dne
def f():
oar";
RemoveLightBulbTest(app, "LocalScopeOnly.py", 4, 10, false, expectedText);
}
public void ImportTrailingWhitespace(VisualStudioApp app) {
string expectedText = @"fob";
RemoveLightBulbTest(app, "ImportTrailingWhitespace.py", 1, 1, true, expectedText);
}
public void ClosureReference(VisualStudioApp app) {
string expectedText = @"def f():
import something
def g():
something";
RemoveLightBulbTest(app, "ClosureReference.py", 1, 1, true, expectedText);
RemoveLightBulbTest(app, "ClosureReference.py", 2, 14, false, expectedText);
}
public void NameMangledUnmangled(VisualStudioApp app) {
string expectedText = @"class C:
def f(self):
import __fob
x = _C__fob";
RemoveLightBulbTest(app, "NameMangleUnmangled.py", 1, 1, true, expectedText);
RemoveLightBulbTest(app, "NameMangleUnmangled.py", 3, 14, false, expectedText);
}
public void NameMangledMangled(VisualStudioApp app) {
string expectedText = @"class C:
def f(self):
import __fob
x = __fob";
RemoveLightBulbTest(app, "NameMangleMangled.py", 1, 1, true, expectedText);
RemoveLightBulbTest(app, "NameMangleMangled.py", 3, 14, false, expectedText);
}
public void EmptyFuncDef1(VisualStudioApp app) {
string expectedText = @"def f():
pass";
RemoveLightBulbTest(app, "EmptyFuncDef1.py", 1, 1, true, expectedText);
RemoveLightBulbTest(app, "EmptyFuncDef1.py", 2, 7, false, expectedText);
}
public void EmptyFuncDef2(VisualStudioApp app) {
string expectedText = @"def f():
pass";
RemoveLightBulbTest(app, "EmptyFuncDef2.py", 1, 1, true, expectedText);
RemoveLightBulbTest(app, "EmptyFuncDef2.py", 2, 7, false, expectedText);
}
public void EmptyFuncDefWhitespace(VisualStudioApp app) {
string expectedText = @"def f():
pass";
RemoveLightBulbTest(app, "EmptyFuncDefWhitespace.py", 1, 1, true, expectedText);
RemoveLightBulbTest(app, "EmptyFuncDefWhitespace.py", 2, 7, false, expectedText);
}
public void ImportStar(VisualStudioApp app) {
string expectedText = @"from sys import *";
RemoveLightBulbTest(app, "ImportStar.py", 1, 1, true, expectedText);
}
private static void RemoveLightBulbTest(VisualStudioApp app, string filename, int line, int column, bool allScopes, string expectedText) {
var project = app.OpenProject(app.CopyProjectForTest(@"TestData\RemoveImport.sln"));
var item = project.ProjectItems.Item(filename);
var window = item.Open();
window.Activate();
var doc = app.GetDocument(item.Document.FullName);
VsProjectAnalyzer analyzer = null;
doc.InvokeTask(async () => {
var point = doc.TextView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(line - 1).Start.Add(column - 1);
doc.TextView.Caret.MoveTo(point);
analyzer = await doc.WaitForAnalyzerAtCaretAsync();
});
Assert.IsNotNull(analyzer, "Failed to get analyzer");
analyzer.WaitForCompleteAnalysis(_ => true);
if (allScopes) {
app.ExecuteCommand("EditorContextMenus.CodeWindow.RemoveImports.AllScopes");
} else {
app.ExecuteCommand("EditorContextMenus.CodeWindow.RemoveImports.CurrentScope");
}
doc.WaitForText(expectedText);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace Southwind{
/// <summary>
/// Strongly-typed collection for the OrdersQry class.
/// </summary>
[Serializable]
public partial class OrdersQryCollection : ReadOnlyList<OrdersQry, OrdersQryCollection>
{
public OrdersQryCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the orders qry view.
/// </summary>
[Serializable]
public partial class OrdersQry : ReadOnlyRecord<OrdersQry>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("orders qry", TableType.View, DataService.GetInstance("Southwind"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"";
//columns
TableSchema.TableColumn colvarOrderID = new TableSchema.TableColumn(schema);
colvarOrderID.ColumnName = "OrderID";
colvarOrderID.DataType = DbType.Int32;
colvarOrderID.MaxLength = 10;
colvarOrderID.AutoIncrement = false;
colvarOrderID.IsNullable = false;
colvarOrderID.IsPrimaryKey = false;
colvarOrderID.IsForeignKey = false;
colvarOrderID.IsReadOnly = false;
schema.Columns.Add(colvarOrderID);
TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema);
colvarCustomerID.ColumnName = "CustomerID";
colvarCustomerID.DataType = DbType.AnsiStringFixedLength;
colvarCustomerID.MaxLength = 5;
colvarCustomerID.AutoIncrement = false;
colvarCustomerID.IsNullable = true;
colvarCustomerID.IsPrimaryKey = false;
colvarCustomerID.IsForeignKey = false;
colvarCustomerID.IsReadOnly = false;
schema.Columns.Add(colvarCustomerID);
TableSchema.TableColumn colvarEmployeeID = new TableSchema.TableColumn(schema);
colvarEmployeeID.ColumnName = "EmployeeID";
colvarEmployeeID.DataType = DbType.Int32;
colvarEmployeeID.MaxLength = 10;
colvarEmployeeID.AutoIncrement = false;
colvarEmployeeID.IsNullable = true;
colvarEmployeeID.IsPrimaryKey = false;
colvarEmployeeID.IsForeignKey = false;
colvarEmployeeID.IsReadOnly = false;
schema.Columns.Add(colvarEmployeeID);
TableSchema.TableColumn colvarOrderDate = new TableSchema.TableColumn(schema);
colvarOrderDate.ColumnName = "OrderDate";
colvarOrderDate.DataType = DbType.DateTime;
colvarOrderDate.MaxLength = 0;
colvarOrderDate.AutoIncrement = false;
colvarOrderDate.IsNullable = true;
colvarOrderDate.IsPrimaryKey = false;
colvarOrderDate.IsForeignKey = false;
colvarOrderDate.IsReadOnly = false;
schema.Columns.Add(colvarOrderDate);
TableSchema.TableColumn colvarRequiredDate = new TableSchema.TableColumn(schema);
colvarRequiredDate.ColumnName = "RequiredDate";
colvarRequiredDate.DataType = DbType.DateTime;
colvarRequiredDate.MaxLength = 0;
colvarRequiredDate.AutoIncrement = false;
colvarRequiredDate.IsNullable = true;
colvarRequiredDate.IsPrimaryKey = false;
colvarRequiredDate.IsForeignKey = false;
colvarRequiredDate.IsReadOnly = false;
schema.Columns.Add(colvarRequiredDate);
TableSchema.TableColumn colvarShippedDate = new TableSchema.TableColumn(schema);
colvarShippedDate.ColumnName = "ShippedDate";
colvarShippedDate.DataType = DbType.DateTime;
colvarShippedDate.MaxLength = 0;
colvarShippedDate.AutoIncrement = false;
colvarShippedDate.IsNullable = true;
colvarShippedDate.IsPrimaryKey = false;
colvarShippedDate.IsForeignKey = false;
colvarShippedDate.IsReadOnly = false;
schema.Columns.Add(colvarShippedDate);
TableSchema.TableColumn colvarShipVia = new TableSchema.TableColumn(schema);
colvarShipVia.ColumnName = "ShipVia";
colvarShipVia.DataType = DbType.Int32;
colvarShipVia.MaxLength = 10;
colvarShipVia.AutoIncrement = false;
colvarShipVia.IsNullable = true;
colvarShipVia.IsPrimaryKey = false;
colvarShipVia.IsForeignKey = false;
colvarShipVia.IsReadOnly = false;
schema.Columns.Add(colvarShipVia);
TableSchema.TableColumn colvarFreight = new TableSchema.TableColumn(schema);
colvarFreight.ColumnName = "Freight";
colvarFreight.DataType = DbType.Decimal;
colvarFreight.MaxLength = 0;
colvarFreight.AutoIncrement = false;
colvarFreight.IsNullable = true;
colvarFreight.IsPrimaryKey = false;
colvarFreight.IsForeignKey = false;
colvarFreight.IsReadOnly = false;
schema.Columns.Add(colvarFreight);
TableSchema.TableColumn colvarShipName = new TableSchema.TableColumn(schema);
colvarShipName.ColumnName = "ShipName";
colvarShipName.DataType = DbType.String;
colvarShipName.MaxLength = 40;
colvarShipName.AutoIncrement = false;
colvarShipName.IsNullable = true;
colvarShipName.IsPrimaryKey = false;
colvarShipName.IsForeignKey = false;
colvarShipName.IsReadOnly = false;
schema.Columns.Add(colvarShipName);
TableSchema.TableColumn colvarShipAddress = new TableSchema.TableColumn(schema);
colvarShipAddress.ColumnName = "ShipAddress";
colvarShipAddress.DataType = DbType.String;
colvarShipAddress.MaxLength = 60;
colvarShipAddress.AutoIncrement = false;
colvarShipAddress.IsNullable = true;
colvarShipAddress.IsPrimaryKey = false;
colvarShipAddress.IsForeignKey = false;
colvarShipAddress.IsReadOnly = false;
schema.Columns.Add(colvarShipAddress);
TableSchema.TableColumn colvarShipCity = new TableSchema.TableColumn(schema);
colvarShipCity.ColumnName = "ShipCity";
colvarShipCity.DataType = DbType.String;
colvarShipCity.MaxLength = 15;
colvarShipCity.AutoIncrement = false;
colvarShipCity.IsNullable = true;
colvarShipCity.IsPrimaryKey = false;
colvarShipCity.IsForeignKey = false;
colvarShipCity.IsReadOnly = false;
schema.Columns.Add(colvarShipCity);
TableSchema.TableColumn colvarShipRegion = new TableSchema.TableColumn(schema);
colvarShipRegion.ColumnName = "ShipRegion";
colvarShipRegion.DataType = DbType.String;
colvarShipRegion.MaxLength = 15;
colvarShipRegion.AutoIncrement = false;
colvarShipRegion.IsNullable = true;
colvarShipRegion.IsPrimaryKey = false;
colvarShipRegion.IsForeignKey = false;
colvarShipRegion.IsReadOnly = false;
schema.Columns.Add(colvarShipRegion);
TableSchema.TableColumn colvarShipPostalCode = new TableSchema.TableColumn(schema);
colvarShipPostalCode.ColumnName = "ShipPostalCode";
colvarShipPostalCode.DataType = DbType.String;
colvarShipPostalCode.MaxLength = 10;
colvarShipPostalCode.AutoIncrement = false;
colvarShipPostalCode.IsNullable = true;
colvarShipPostalCode.IsPrimaryKey = false;
colvarShipPostalCode.IsForeignKey = false;
colvarShipPostalCode.IsReadOnly = false;
schema.Columns.Add(colvarShipPostalCode);
TableSchema.TableColumn colvarShipCountry = new TableSchema.TableColumn(schema);
colvarShipCountry.ColumnName = "ShipCountry";
colvarShipCountry.DataType = DbType.String;
colvarShipCountry.MaxLength = 15;
colvarShipCountry.AutoIncrement = false;
colvarShipCountry.IsNullable = true;
colvarShipCountry.IsPrimaryKey = false;
colvarShipCountry.IsForeignKey = false;
colvarShipCountry.IsReadOnly = false;
schema.Columns.Add(colvarShipCountry);
TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema);
colvarCompanyName.ColumnName = "CompanyName";
colvarCompanyName.DataType = DbType.String;
colvarCompanyName.MaxLength = 40;
colvarCompanyName.AutoIncrement = false;
colvarCompanyName.IsNullable = false;
colvarCompanyName.IsPrimaryKey = false;
colvarCompanyName.IsForeignKey = false;
colvarCompanyName.IsReadOnly = false;
schema.Columns.Add(colvarCompanyName);
TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema);
colvarAddress.ColumnName = "Address";
colvarAddress.DataType = DbType.String;
colvarAddress.MaxLength = 60;
colvarAddress.AutoIncrement = false;
colvarAddress.IsNullable = true;
colvarAddress.IsPrimaryKey = false;
colvarAddress.IsForeignKey = false;
colvarAddress.IsReadOnly = false;
schema.Columns.Add(colvarAddress);
TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema);
colvarCity.ColumnName = "City";
colvarCity.DataType = DbType.String;
colvarCity.MaxLength = 15;
colvarCity.AutoIncrement = false;
colvarCity.IsNullable = true;
colvarCity.IsPrimaryKey = false;
colvarCity.IsForeignKey = false;
colvarCity.IsReadOnly = false;
schema.Columns.Add(colvarCity);
TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema);
colvarRegion.ColumnName = "Region";
colvarRegion.DataType = DbType.String;
colvarRegion.MaxLength = 15;
colvarRegion.AutoIncrement = false;
colvarRegion.IsNullable = true;
colvarRegion.IsPrimaryKey = false;
colvarRegion.IsForeignKey = false;
colvarRegion.IsReadOnly = false;
schema.Columns.Add(colvarRegion);
TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema);
colvarPostalCode.ColumnName = "PostalCode";
colvarPostalCode.DataType = DbType.String;
colvarPostalCode.MaxLength = 10;
colvarPostalCode.AutoIncrement = false;
colvarPostalCode.IsNullable = true;
colvarPostalCode.IsPrimaryKey = false;
colvarPostalCode.IsForeignKey = false;
colvarPostalCode.IsReadOnly = false;
schema.Columns.Add(colvarPostalCode);
TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema);
colvarCountry.ColumnName = "Country";
colvarCountry.DataType = DbType.String;
colvarCountry.MaxLength = 15;
colvarCountry.AutoIncrement = false;
colvarCountry.IsNullable = true;
colvarCountry.IsPrimaryKey = false;
colvarCountry.IsForeignKey = false;
colvarCountry.IsReadOnly = false;
schema.Columns.Add(colvarCountry);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["Southwind"].AddSchema("orders qry",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public OrdersQry()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public OrdersQry(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public OrdersQry(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public OrdersQry(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("OrderID")]
[Bindable(true)]
public int OrderID
{
get
{
return GetColumnValue<int>("OrderID");
}
set
{
SetColumnValue("OrderID", value);
}
}
[XmlAttribute("CustomerID")]
[Bindable(true)]
public string CustomerID
{
get
{
return GetColumnValue<string>("CustomerID");
}
set
{
SetColumnValue("CustomerID", value);
}
}
[XmlAttribute("EmployeeID")]
[Bindable(true)]
public int? EmployeeID
{
get
{
return GetColumnValue<int?>("EmployeeID");
}
set
{
SetColumnValue("EmployeeID", value);
}
}
[XmlAttribute("OrderDate")]
[Bindable(true)]
public DateTime? OrderDate
{
get
{
return GetColumnValue<DateTime?>("OrderDate");
}
set
{
SetColumnValue("OrderDate", value);
}
}
[XmlAttribute("RequiredDate")]
[Bindable(true)]
public DateTime? RequiredDate
{
get
{
return GetColumnValue<DateTime?>("RequiredDate");
}
set
{
SetColumnValue("RequiredDate", value);
}
}
[XmlAttribute("ShippedDate")]
[Bindable(true)]
public DateTime? ShippedDate
{
get
{
return GetColumnValue<DateTime?>("ShippedDate");
}
set
{
SetColumnValue("ShippedDate", value);
}
}
[XmlAttribute("ShipVia")]
[Bindable(true)]
public int? ShipVia
{
get
{
return GetColumnValue<int?>("ShipVia");
}
set
{
SetColumnValue("ShipVia", value);
}
}
[XmlAttribute("Freight")]
[Bindable(true)]
public decimal? Freight
{
get
{
return GetColumnValue<decimal?>("Freight");
}
set
{
SetColumnValue("Freight", value);
}
}
[XmlAttribute("ShipName")]
[Bindable(true)]
public string ShipName
{
get
{
return GetColumnValue<string>("ShipName");
}
set
{
SetColumnValue("ShipName", value);
}
}
[XmlAttribute("ShipAddress")]
[Bindable(true)]
public string ShipAddress
{
get
{
return GetColumnValue<string>("ShipAddress");
}
set
{
SetColumnValue("ShipAddress", value);
}
}
[XmlAttribute("ShipCity")]
[Bindable(true)]
public string ShipCity
{
get
{
return GetColumnValue<string>("ShipCity");
}
set
{
SetColumnValue("ShipCity", value);
}
}
[XmlAttribute("ShipRegion")]
[Bindable(true)]
public string ShipRegion
{
get
{
return GetColumnValue<string>("ShipRegion");
}
set
{
SetColumnValue("ShipRegion", value);
}
}
[XmlAttribute("ShipPostalCode")]
[Bindable(true)]
public string ShipPostalCode
{
get
{
return GetColumnValue<string>("ShipPostalCode");
}
set
{
SetColumnValue("ShipPostalCode", value);
}
}
[XmlAttribute("ShipCountry")]
[Bindable(true)]
public string ShipCountry
{
get
{
return GetColumnValue<string>("ShipCountry");
}
set
{
SetColumnValue("ShipCountry", value);
}
}
[XmlAttribute("CompanyName")]
[Bindable(true)]
public string CompanyName
{
get
{
return GetColumnValue<string>("CompanyName");
}
set
{
SetColumnValue("CompanyName", value);
}
}
[XmlAttribute("Address")]
[Bindable(true)]
public string Address
{
get
{
return GetColumnValue<string>("Address");
}
set
{
SetColumnValue("Address", value);
}
}
[XmlAttribute("City")]
[Bindable(true)]
public string City
{
get
{
return GetColumnValue<string>("City");
}
set
{
SetColumnValue("City", value);
}
}
[XmlAttribute("Region")]
[Bindable(true)]
public string Region
{
get
{
return GetColumnValue<string>("Region");
}
set
{
SetColumnValue("Region", value);
}
}
[XmlAttribute("PostalCode")]
[Bindable(true)]
public string PostalCode
{
get
{
return GetColumnValue<string>("PostalCode");
}
set
{
SetColumnValue("PostalCode", value);
}
}
[XmlAttribute("Country")]
[Bindable(true)]
public string Country
{
get
{
return GetColumnValue<string>("Country");
}
set
{
SetColumnValue("Country", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string OrderID = @"OrderID";
public static string CustomerID = @"CustomerID";
public static string EmployeeID = @"EmployeeID";
public static string OrderDate = @"OrderDate";
public static string RequiredDate = @"RequiredDate";
public static string ShippedDate = @"ShippedDate";
public static string ShipVia = @"ShipVia";
public static string Freight = @"Freight";
public static string ShipName = @"ShipName";
public static string ShipAddress = @"ShipAddress";
public static string ShipCity = @"ShipCity";
public static string ShipRegion = @"ShipRegion";
public static string ShipPostalCode = @"ShipPostalCode";
public static string ShipCountry = @"ShipCountry";
public static string CompanyName = @"CompanyName";
public static string Address = @"Address";
public static string City = @"City";
public static string Region = @"Region";
public static string PostalCode = @"PostalCode";
public static string Country = @"Country";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using SteamBot.SteamGroups;
using SteamKit2;
using SteamKit2.Internal;
using SteamTrade;
using SteamTrade.TradeOffer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace SteamBot
{
public class Bot : IDisposable
{
#region Bot delegates
public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id);
#endregion
#region Private readonly variables
private readonly SteamUser.LogOnDetails logOnDetails;
private readonly string schemaLang;
private readonly string logFile;
private readonly Dictionary<SteamID, UserHandler> userHandlers;
private readonly Log.LogLevel consoleLogLevel;
private readonly Log.LogLevel fileLogLevel;
private readonly UserHandlerCreator createHandler;
private readonly bool isProccess;
private readonly BackgroundWorker botThread;
#endregion
#region Private variables
private Task<Inventory> myInventoryTask;
private TradeManager tradeManager;
private TradeOfferManager tradeOfferManager;
private int tradePollingInterval;
private string myUserNonce;
private string myUniqueId;
private bool cookiesAreInvalid = true;
private List<SteamID> friends;
private bool disposed = false;
private string consoleInput;
#endregion
#region Public readonly variables
/// <summary>
/// Userhandler class bot is running.
/// </summary>
public readonly string BotControlClass;
/// <summary>
/// The display name of bot to steam.
/// </summary>
public readonly string DisplayName;
/// <summary>
/// The chat response from the config file.
/// </summary>
public readonly string ChatResponse;
/// <summary>
/// The website url from the config file.
/// </summary>
public readonly string BotWebsiteURL;
/// <summary>
/// The website name from the config file.
/// </summary>
public readonly string BotWebsiteName;
/// <summary>
/// The database password of website from the config file.
/// </summary>
public readonly string BotDBPassword;
/// <summary>
/// The steamid of the admin who gets all profit offers from the config file.
/// </summary>
public readonly string ProfitAdmin;
/// <summary>
/// An array of admins for bot.
/// </summary>
public readonly IEnumerable<SteamID> Admins;
public readonly SteamClient SteamClient;
public readonly SteamUser SteamUser;
public readonly SteamFriends SteamFriends;
public readonly SteamTrading SteamTrade;
public readonly SteamGameCoordinator SteamGameCoordinator;
public readonly SteamNotifications SteamNotifications;
/// <summary>
/// The amount of time the bot will trade for.
/// </summary>
public readonly int MaximumTradeTime;
/// <summary>
/// The amount of time the bot will wait between user interactions with trade.
/// </summary>
public readonly int MaximumActionGap;
/// <summary>
/// The api key of bot.
/// </summary>
public readonly string ApiKey;
public readonly SteamWeb SteamWeb;
/// <summary>
/// The prefix shown before bot's display name.
/// </summary>
public readonly string DisplayNamePrefix;
/// <summary>
/// The instance of the Logger for the bot.
/// </summary>
public readonly Log Log;
#endregion
#region Public variables
public string AuthCode;
public bool IsRunning;
/// <summary>
/// Is bot fully Logged in.
/// Set only when bot did successfully Log in.
/// </summary>
public bool IsLoggedIn { get; private set; }
/// <summary>
/// The current trade the bot is in.
/// </summary>
public Trade CurrentTrade { get; private set; }
/// <summary>
/// The current game bot is in.
/// Default: 0 = No game.
/// </summary>
public int CurrentGame { get; private set; }
public SteamAuth.SteamGuardAccount SteamGuardAccount;
#endregion
public IEnumerable<SteamID> FriendsList
{
get
{
CreateFriendsListIfNecessary();
return friends;
}
}
public Inventory MyInventory
{
get
{
myInventoryTask.Wait();
return myInventoryTask.Result;
}
}
/// <summary>
/// Compatibility sanity.
/// </summary>
[Obsolete("Refactored to be Log instead of log")]
public Log log { get { return Log; } }
public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
{
userHandlers = new Dictionary<SteamID, UserHandler>();
logOnDetails = new SteamUser.LogOnDetails
{
Username = config.Username,
Password = config.Password
};
DisplayName = config.DisplayName;
ChatResponse = config.ChatResponse;
BotWebsiteURL = config.BotWebsiteURL;
BotWebsiteName = config.BotWebsiteName;
BotDBPassword = config.BotDBPassword;
ProfitAdmin = config.ProfitAdmin;
MaximumTradeTime = config.MaximumTradeTime;
MaximumActionGap = config.MaximumActionGap;
DisplayNamePrefix = config.DisplayNamePrefix;
tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
schemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
Admins = config.Admins;
ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
isProccess = process;
try
{
if (config.LogLevel != null)
{
consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
}
else consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
}
catch (ArgumentException)
{
Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
consoleLogLevel = Log.LogLevel.Info;
}
try
{
fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
}
catch (ArgumentException)
{
Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
fileLogLevel = Log.LogLevel.Info;
}
logFile = config.LogFile;
Log = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel);
createHandler = handlerCreator;
BotControlClass = config.BotControlClass;
SteamWeb = new SteamWeb();
// Hacking around https
ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;
Log.Debug("Initializing Steam Bot...");
SteamClient = new SteamClient();
SteamClient.AddHandler(new SteamNotifications());
SteamTrade = SteamClient.GetHandler<SteamTrading>();
SteamUser = SteamClient.GetHandler<SteamUser>();
SteamFriends = SteamClient.GetHandler<SteamFriends>();
SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
SteamNotifications = SteamClient.GetHandler<SteamNotifications>();
botThread = new BackgroundWorker { WorkerSupportsCancellation = true };
botThread.DoWork += BackgroundWorkerOnDoWork;
botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
botThread.RunWorkerAsync();
}
~Bot()
{
Dispose(false);
}
private void CreateFriendsListIfNecessary()
{
if (friends != null)
return;
friends = new List<SteamID>();
for (int i = 0; i < SteamFriends.GetFriendCount(); i++)
friends.Add(SteamFriends.GetFriendByIndex(i));
}
/// <summary>
/// Occurs when the bot needs the SteamGuard authentication code.
/// </summary>
/// <remarks>
/// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/>
/// </remarks>
public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired;
/// <summary>
/// Starts the callback thread and connects to Steam via SteamKit2.
/// </summary>
/// <remarks>
/// THIS NEVER RETURNS.
/// </remarks>
/// <returns><c>true</c>. See remarks</returns>
public bool StartBot()
{
IsRunning = true;
Log.Info("Connecting...");
if (!botThread.IsBusy)
botThread.RunWorkerAsync();
SteamClient.Connect();
Log.Success("Done Loading Bot!");
return true; // never get here
}
/// <summary>
/// Disconnect from the Steam network and stop the callback
/// thread.
/// </summary>
public void StopBot()
{
IsRunning = false;
Log.Debug("Trying to shut down bot thread.");
SteamClient.Disconnect();
botThread.CancelAsync();
while (botThread.IsBusy)
Thread.Yield();
userHandlers.Clear();
}
/// <summary>
/// Creates a new trade with the given partner.
/// </summary>
/// <returns>
/// <c>true</c>, if trade was opened,
/// <c>false</c> if there is another trade that must be closed first.
/// </returns>
public bool OpenTrade(SteamID other)
{
if (CurrentTrade != null || CheckCookies() == false)
return false;
SteamTrade.Trade(other);
return true;
}
/// <summary>
/// Closes the current active trade.
/// </summary>
public void CloseTrade()
{
if (CurrentTrade == null)
return;
UnsubscribeTrade(GetUserHandler(CurrentTrade.OtherSID), CurrentTrade);
tradeManager.StopTrade();
CurrentTrade = null;
}
void OnTradeTimeout(object sender, EventArgs args)
{
// ignore event params and just null out the trade.
GetUserHandler(CurrentTrade.OtherSID).OnTradeTimeout();
}
/// <summary>
/// Create a new trade offer with the specified partner
/// </summary>
/// <param name="other">SteamId of the partner</param>
/// <returns></returns>
public TradeOffer NewTradeOffer(SteamID other)
{
return tradeOfferManager.NewOffer(other);
}
/// <summary>
/// Try to get a specific trade offer using the offerid
/// </summary>
/// <param name="offerId"></param>
/// <param name="tradeOffer"></param>
/// <returns></returns>
public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer)
{
return tradeOfferManager.GetOffer(offerId, out tradeOffer);
}
public void HandleBotCommand(string command)
{
try
{
if (command == "linkauth")
{
LinkMobileAuth();
}
else if (command == "getauth")
{
try
{
Log.Success("Generated Steam Guard code: " + SteamGuardAccount.GenerateSteamGuardCode());
}
catch (NullReferenceException)
{
Log.Error("Unable to generate Steam Guard code.");
}
}
else if (command == "unlinkauth")
{
if (SteamGuardAccount == null)
{
Log.Error("Mobile authenticator is not active on this bot.");
}
else if (SteamGuardAccount.DeactivateAuthenticator())
{
Log.Success("Deactivated authenticator on this account.");
}
else
{
Log.Error("Failed to deactivate authenticator on this account.");
}
}
else
{
GetUserHandler(SteamClient.SteamID).OnBotCommand(command);
}
}
catch (ObjectDisposedException e)
{
// Writing to console because odds are the error was caused by a disposed Log.
Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
if (!this.IsRunning)
{
Console.WriteLine("The Bot is no longer running and could not write to the Log. Try Starting this bot first.");
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
}
}
public void HandleInput(string input)
{
consoleInput = input;
}
public string WaitForInput()
{
consoleInput = null;
while (true)
{
if (consoleInput != null)
{
return consoleInput;
}
Thread.Sleep(5);
}
}
bool HandleTradeSessionStart(SteamID other)
{
if (CurrentTrade != null)
return false;
try
{
tradeManager.InitializeTrade(SteamUser.SteamID, other);
CurrentTrade = tradeManager.CreateTrade(SteamUser.SteamID, other);
CurrentTrade.OnClose += CloseTrade;
SubscribeTrade(CurrentTrade, GetUserHandler(other));
tradeManager.StartTradeThread(CurrentTrade);
return true;
}
catch (SteamTrade.Exceptions.InventoryFetchException)
{
// we shouldn't get here because the inv checks are also
// done in the TradeProposedCallback handler.
/*string response = String.Empty;
if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64())
{
response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private.";
}
else
{
response = "Trade failed. Could not correctly fetch my backpack.";
}
SteamFriends.SendChatMessage(other,
EChatEntryType.ChatMsg,
response);
Log.Info ("Bot sent other: {0}", response);
CurrentTrade = null;*/
return false;
}
}
public void SetGamePlaying(int id)
{
var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed);
if (id != 0)
gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed
{
game_id = new GameID(id),
});
SteamClient.Send(gamePlaying);
CurrentGame = id;
}
void HandleSteamMessage(ICallbackMsg msg)
{
Log.Debug(msg.ToString());
#region Login
msg.Handle<SteamClient.ConnectedCallback>(callback =>
{
Log.Debug("Connection Callback: {0}", callback.Result);
if (callback.Result == EResult.OK)
{
UserLogOn();
}
else
{
Log.Error("Failed to connect to Steam Community, trying again...");
SteamClient.Connect();
}
});
msg.Handle<SteamUser.LoggedOnCallback>(callback =>
{
Log.Debug("Logged On Callback: {0}", callback.Result);
if (callback.Result == EResult.OK)
{
myUserNonce = callback.WebAPIUserNonce;
}
else
{
Log.Error("Login Error: {0}", callback.Result);
}
if (callback.Result == EResult.AccountLogonDeniedNeedTwoFactorCode)
{
var mobileAuthCode = GetMobileAuthCode();
if (string.IsNullOrEmpty(mobileAuthCode))
{
Log.Error("Failed to generate 2FA code. Make sure you have linked the authenticator via SteamBot.");
}
else
{
logOnDetails.TwoFactorCode = mobileAuthCode;
Log.Success("Generated 2FA code.");
}
}
else if (callback.Result == EResult.TwoFactorCodeMismatch)
{
SteamAuth.TimeAligner.AlignTime();
logOnDetails.TwoFactorCode = SteamGuardAccount.GenerateSteamGuardCode();
Log.Success("Regenerated 2FA code.");
}
else if (callback.Result == EResult.AccountLogonDenied)
{
Log.Interface("This account is SteamGuard enabled. Enter the code via the `auth' command.");
// try to get the steamguard auth code from the event callback
var eva = new SteamGuardRequiredEventArgs();
FireOnSteamGuardRequired(eva);
if (!String.IsNullOrEmpty(eva.SteamGuard))
logOnDetails.AuthCode = eva.SteamGuard;
else
logOnDetails.AuthCode = Console.ReadLine();
}
else if (callback.Result == EResult.InvalidLoginAuthCode)
{
Log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
logOnDetails.AuthCode = Console.ReadLine();
}
});
msg.Handle<SteamUser.LoginKeyCallback>(callback =>
{
myUniqueId = callback.UniqueID.ToString();
UserWebLogOn();
if (Trade.CurrentSchema == null)
{
Log.Info("Downloading Schema...");
Trade.CurrentSchema = Schema.FetchSchema(ApiKey, schemaLang);
Log.Success("Schema Downloaded!");
}
SteamFriends.SetPersonaName(DisplayNamePrefix + DisplayName);
SteamFriends.SetPersonaState(EPersonaState.Online);
Log.Success("Steam Bot Logged In Completely!");
GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
});
msg.Handle<SteamUser.WebAPIUserNonceCallback>(webCallback =>
{
Log.Debug("Received new WebAPIUserNonce.");
if (webCallback.Result == EResult.OK)
{
myUserNonce = webCallback.Nonce;
UserWebLogOn();
}
else
{
Log.Error("WebAPIUserNonce Error: " + webCallback.Result);
}
});
msg.Handle<SteamUser.UpdateMachineAuthCallback>(
authCallback => OnUpdateMachineAuthCallback(authCallback)
);
#endregion
#region Friends
msg.Handle<SteamFriends.FriendsListCallback>(callback =>
{
foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
{
switch (friend.SteamID.AccountType)
{
case EAccountType.Clan:
if (friend.Relationship == EFriendRelationship.RequestRecipient)
{
if (GetUserHandler(friend.SteamID).OnGroupAdd())
{
AcceptGroupInvite(friend.SteamID);
}
else
{
DeclineGroupInvite(friend.SteamID);
}
}
break;
default:
CreateFriendsListIfNecessary();
if (friend.Relationship == EFriendRelationship.None)
{
friends.Remove(friend.SteamID);
GetUserHandler(friend.SteamID).OnFriendRemove();
RemoveUserHandler(friend.SteamID);
}
else if (friend.Relationship == EFriendRelationship.RequestRecipient)
{
if (GetUserHandler(friend.SteamID).OnFriendAdd())
{
if (!friends.Contains(friend.SteamID))
{
friends.Add(friend.SteamID);
}
else
{
Log.Error("Friend was added who was already in friends list: " + friend.SteamID);
}
SteamFriends.AddFriend(friend.SteamID);
}
else
{
SteamFriends.RemoveFriend(friend.SteamID);
RemoveUserHandler(friend.SteamID);
}
}
break;
}
}
});
msg.Handle<SteamFriends.FriendMsgCallback>(callback =>
{
EChatEntryType type = callback.EntryType;
if (callback.EntryType == EChatEntryType.ChatMsg)
{
Log.Info("Chat Message from {0}: {1}",
SteamFriends.GetFriendPersonaName(callback.Sender),
callback.Message
);
GetUserHandler(callback.Sender).OnMessageHandler(callback.Message, type);
}
});
#endregion
#region Group Chat
msg.Handle<SteamFriends.ChatMsgCallback>(callback =>
{
GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message);
});
#endregion
#region Trading
msg.Handle<SteamTrading.SessionStartCallback>(callback =>
{
bool started = HandleTradeSessionStart(callback.OtherClient);
if (!started)
Log.Error("Could not start the trade session.");
else
Log.Debug("SteamTrading.SessionStartCallback handled successfully. Trade Opened.");
});
msg.Handle<SteamTrading.TradeProposedCallback>(callback =>
{
if (CheckCookies() == false)
{
SteamTrade.RespondToTrade(callback.TradeID, false);
return;
}
try
{
tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
}
catch (WebException we)
{
SteamFriends.SendChatMessage(callback.OtherClient,
EChatEntryType.ChatMsg,
"Trade error: " + we.Message);
SteamTrade.RespondToTrade(callback.TradeID, false);
return;
}
catch (Exception)
{
SteamFriends.SendChatMessage(callback.OtherClient,
EChatEntryType.ChatMsg,
"Trade declined. Could not correctly fetch your backpack.");
SteamTrade.RespondToTrade(callback.TradeID, false);
return;
}
//if (tradeManager.OtherInventory.IsPrivate)
//{
// SteamFriends.SendChatMessage(callback.OtherClient,
// EChatEntryType.ChatMsg,
// "Trade declined. Your backpack cannot be private.");
// SteamTrade.RespondToTrade (callback.TradeID, false);
// return;
//}
if (CurrentTrade == null && GetUserHandler(callback.OtherClient).OnTradeRequest())
SteamTrade.RespondToTrade(callback.TradeID, true);
else
SteamTrade.RespondToTrade(callback.TradeID, false);
});
msg.Handle<SteamTrading.TradeResultCallback>(callback =>
{
if (callback.Response == EEconTradeResponse.Accepted)
{
Log.Debug("Trade Status: {0}", callback.Response);
Log.Info("Trade Accepted!");
GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString());
}
else
{
Log.Warn("Trade failed: {0}", callback.Response);
CloseTrade();
GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString());
}
});
#endregion
#region Disconnect
msg.Handle<SteamUser.LoggedOffCallback>(callback =>
{
IsLoggedIn = false;
Log.Warn("Logged off Steam. Reason: {0}", callback.Result);
});
msg.Handle<SteamClient.DisconnectedCallback>(callback =>
{
if (IsLoggedIn)
{
IsLoggedIn = false;
CloseTrade();
Log.Warn("Disconnected from Steam Network!");
}
SteamClient.Connect();
});
#endregion
#region Notifications
msg.Handle<SteamBot.SteamNotifications.NotificationCallback>(callback =>
{
//currently only appears to be of trade offer
if (callback.Notifications.Count != 0)
{
foreach (var notification in callback.Notifications)
{
Log.Info(notification.UserNotificationType + " notification");
}
}
// Get offers only if cookies are valid
if (CheckCookies())
tradeOfferManager.GetOffers();
});
msg.Handle<SteamBot.SteamNotifications.CommentNotificationCallback>(callback =>
{
//various types of comment notifications on profile/activity feed etc
//Log.Info("received CommentNotificationCallback");
//Log.Info("New Commments " + callback.CommentNotifications.CountNewComments);
//Log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner);
//Log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions);
});
#endregion
}
string GetMobileAuthCode()
{
var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username));
if (File.Exists(authFile))
{
SteamGuardAccount = Newtonsoft.Json.JsonConvert.DeserializeObject<SteamAuth.SteamGuardAccount>(File.ReadAllText(authFile));
return SteamGuardAccount.GenerateSteamGuardCode();
}
return string.Empty;
}
/// <summary>
/// Link a mobile authenticator to bot account, using SteamTradeOffersBot as the authenticator.
/// Called from bot manager console. Usage: "exec [index] linkauth"
/// If successful, 2FA will be required upon the next login.
/// Use "exec [index] getauth" if you need to get a Steam Guard code for the account.
/// To deactivate the authenticator, use "exec [index] unlinkauth".
/// </summary>
void LinkMobileAuth()
{
new Thread(() =>
{
var login = new SteamAuth.UserLogin(logOnDetails.Username, logOnDetails.Password);
var loginResult = login.DoLogin();
if (loginResult == SteamAuth.LoginResult.NeedEmail)
{
while (loginResult == SteamAuth.LoginResult.NeedEmail)
{
Log.Interface("Enter Steam Guard code from email (type \"input [index] [code]\"):");
var emailCode = WaitForInput();
login.EmailCode = emailCode;
loginResult = login.DoLogin();
}
}
if (loginResult == SteamAuth.LoginResult.LoginOkay)
{
Log.Info("Linking mobile authenticator...");
var authLinker = new SteamAuth.AuthenticatorLinker(login.Session);
var addAuthResult = authLinker.AddAuthenticator();
if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber)
{
while (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber)
{
Log.Interface("Enter phone number with country code, e.g. +1XXXXXXXXXXX (type \"input [index] [number]\"):");
var phoneNumber = WaitForInput();
authLinker.PhoneNumber = phoneNumber;
addAuthResult = authLinker.AddAuthenticator();
}
}
if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.AwaitingFinalization)
{
SteamGuardAccount = authLinker.LinkedAccount;
try
{
var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username));
Directory.CreateDirectory(Path.Combine(System.Windows.Forms.Application.StartupPath, "authfiles"));
File.WriteAllText(authFile, Newtonsoft.Json.JsonConvert.SerializeObject(SteamGuardAccount));
Log.Interface("Enter SMS code (type \"input [index] [code]\"):");
var smsCode = WaitForInput();
var authResult = authLinker.FinalizeAddAuthenticator(smsCode);
if (authResult == SteamAuth.AuthenticatorLinker.FinalizeResult.Success)
{
Log.Success("Linked authenticator.");
}
else
{
Log.Error("Error linking authenticator: " + authResult);
}
}
catch (IOException)
{
Log.Error("Failed to save auth file. Aborting authentication.");
}
}
else
{
Log.Error("Error adding authenticator: " + addAuthResult);
}
}
else
{
if (loginResult == SteamAuth.LoginResult.Need2FA)
{
Log.Error("Mobile authenticator has already been linked!");
}
else
{
Log.Error("Error performing mobile login: " + loginResult);
}
}
}).Start();
}
void UserLogOn()
{
// get sentry file which has the machine hw info saved
// from when a steam guard code was entered
Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)));
if (fi.Exists && fi.Length > 0)
logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName));
else
logOnDetails.SentryFileHash = null;
SteamUser.LogOn(logOnDetails);
}
void UserWebLogOn()
{
do
{
IsLoggedIn = SteamWeb.Authenticate(myUniqueId, SteamClient, myUserNonce);
if (!IsLoggedIn)
{
Log.Warn("Authentication failed, retrying in 2s...");
Thread.Sleep(2000);
}
} while (!IsLoggedIn);
Log.Success("User Authenticated!");
tradeManager = new TradeManager(ApiKey, SteamWeb);
tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximumActionGap, tradePollingInterval);
tradeManager.OnTimeout += OnTradeTimeout;
tradeOfferManager = new TradeOfferManager(ApiKey, SteamWeb);
SubscribeTradeOffer(tradeOfferManager);
cookiesAreInvalid = false;
// Success, check trade offers which we have received while we were offline
tradeOfferManager.GetOffers();
}
/// <summary>
/// Checks if sessionId and token cookies are still valid.
/// Sets cookie flag if they are invalid.
/// </summary>
/// <returns>true if cookies are valid; otherwise false</returns>
bool CheckCookies()
{
// We still haven't re-authenticated
if (cookiesAreInvalid)
return false;
try
{
if (!SteamWeb.VerifyCookies())
{
// Cookies are no longer valid
Log.Warn("Cookies are invalid. Need to re-authenticate.");
cookiesAreInvalid = true;
SteamUser.RequestWebAPIUserNonce();
return false;
}
}
catch
{
// Even if exception is caught, we should still continue.
Log.Warn("Cookie check failed. http://steamcommunity.com is possibly down.");
}
return true;
}
UserHandler GetUserHandler(SteamID sid)
{
if (!userHandlers.ContainsKey(sid))
userHandlers[sid] = createHandler(this, sid);
return userHandlers[sid];
}
void RemoveUserHandler(SteamID sid)
{
if (userHandlers.ContainsKey(sid))
userHandlers.Remove(sid);
}
static byte[] SHAHash(byte[] input)
{
SHA1Managed sha = new SHA1Managed();
byte[] output = sha.ComputeHash(input);
sha.Clear();
return output;
}
void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth)
{
byte[] hash = SHAHash(machineAuth.Data);
Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
File.WriteAllBytes(System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data);
var authResponse = new SteamUser.MachineAuthDetails
{
BytesWritten = machineAuth.BytesToWrite,
FileName = machineAuth.FileName,
FileSize = machineAuth.BytesToWrite,
Offset = machineAuth.Offset,
SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote
OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs
LastError = 0, // result from win32 GetLastError
Result = EResult.OK, // if everything went okay, otherwise ~who knows~
JobID = machineAuth.JobID, // so we respond to the correct server job
};
// send off our response
SteamUser.SendMachineAuthResponse(authResponse);
}
/// <summary>
/// Gets the bot's inventory and stores it in MyInventory.
/// </summary>
/// <example> This sample shows how to find items in the bot's inventory from a user handler.
/// <code>
/// Bot.GetInventory(); // Get the inventory first
/// foreach (var item in Bot.MyInventory.Items)
/// {
/// if (item.Defindex == 5021)
/// {
/// // Bot has a key in its inventory
/// }
/// }
/// </code>
/// </example>
public void GetInventory()
{
myInventoryTask = Task.Factory.StartNew((Func<Inventory>)FetchBotsInventory);
}
public void TradeOfferRouter(TradeOffer offer)
{
if (offer.OfferState == TradeOfferState.TradeOfferStateActive)
{
GetUserHandler(offer.PartnerSteamId).OnNewTradeOffer(offer);
}
}
public void SubscribeTradeOffer(TradeOfferManager tradeOfferManager)
{
tradeOfferManager.OnNewTradeOffer += TradeOfferRouter;
}
//todo: should unsubscribe eventually...
public void UnsubscribeTradeOffer(TradeOfferManager tradeOfferManager)
{
tradeOfferManager.OnNewTradeOffer -= TradeOfferRouter;
}
/// <summary>
/// Subscribes all listeners of this to the trade.
/// </summary>
public void SubscribeTrade(Trade trade, UserHandler handler)
{
trade.OnSuccess += handler.OnTradeSuccess;
trade.OnAwaitingConfirmation += handler._OnTradeAwaitingConfirmation;
trade.OnClose += handler.OnTradeClose;
trade.OnError += handler.OnTradeError;
trade.OnStatusError += handler.OnStatusError;
//trade.OnTimeout += OnTradeTimeout;
trade.OnAfterInit += handler.OnTradeInit;
trade.OnUserAddItem += handler.OnTradeAddItem;
trade.OnUserRemoveItem += handler.OnTradeRemoveItem;
trade.OnMessage += handler.OnTradeMessageHandler;
trade.OnUserSetReady += handler.OnTradeReadyHandler;
trade.OnUserAccept += handler.OnTradeAcceptHandler;
}
/// <summary>
/// Unsubscribes all listeners of this from the current trade.
/// </summary>
public void UnsubscribeTrade(UserHandler handler, Trade trade)
{
trade.OnSuccess -= handler.OnTradeSuccess;
trade.OnAwaitingConfirmation -= handler._OnTradeAwaitingConfirmation;
trade.OnClose -= handler.OnTradeClose;
trade.OnError -= handler.OnTradeError;
trade.OnStatusError -= handler.OnStatusError;
//Trade.OnTimeout -= OnTradeTimeout;
trade.OnAfterInit -= handler.OnTradeInit;
trade.OnUserAddItem -= handler.OnTradeAddItem;
trade.OnUserRemoveItem -= handler.OnTradeRemoveItem;
trade.OnMessage -= handler.OnTradeMessageHandler;
trade.OnUserSetReady -= handler.OnTradeReadyHandler;
trade.OnUserAccept -= handler.OnTradeAcceptHandler;
}
/// <summary>
/// Fetch the Bot's inventory and log a warning if it's private
/// </summary>
private Inventory FetchBotsInventory()
{
var inventory = Inventory.FetchInventory(SteamUser.SteamID, ApiKey, SteamWeb);
if (inventory.IsPrivate)
{
log.Warn("The bot's backpack is private! If your bot adds any items it will fail! Your bot's backpack should be Public.");
}
return inventory;
}
public void AcceptAllMobileTradeConfirmations()
{
if (SteamGuardAccount == null)
{
Log.Warn("Bot account does not have 2FA enabled.");
}
else
{
SteamGuardAccount.Session.SteamLogin = SteamWeb.Token;
SteamGuardAccount.Session.SteamLoginSecure = SteamWeb.TokenSecure;
try
{
foreach (var confirmation in SteamGuardAccount.FetchConfirmations())
{
if (SteamGuardAccount.AcceptConfirmation(confirmation))
{
Log.Success("Confirmed {0}. (Confirmation ID #{1})", confirmation.ConfirmationDescription, confirmation.ConfirmationID);
}
}
}
catch (SteamAuth.SteamGuardAccount.WGTokenInvalidException)
{
Log.Error("Invalid session when trying to fetch trade confirmations.");
}
}
}
/// <summary>
/// Get duration of escrow in days. Call this before sending a trade offer.
/// Credit to: https://www.reddit.com/r/SteamBot/comments/3w8j7c/code_getescrowduration_for_c/
/// </summary>
/// <param name="steamId">Steam ID of user you want to send a trade offer to</param>
/// <param name="token">User's trade token. Can be an empty string if user is on bot's friends list.</param>
/// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception>
/// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception>
/// <returns>TradeOfferEscrowDuration</returns>
public TradeOfferEscrowDuration GetEscrowDuration(SteamID steamId, string token)
{
var url = "https://steamcommunity.com/tradeoffer/new/";
var data = new System.Collections.Specialized.NameValueCollection();
data.Add("partner", steamId.AccountID.ToString());
if (!string.IsNullOrEmpty(token))
{
data.Add("token", token);
}
var resp = SteamWeb.Fetch(url, "GET", data, false);
if (string.IsNullOrWhiteSpace(resp))
{
throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration.");
}
return ParseEscrowResponse(resp);
}
/// <summary>
/// Get duration of escrow in days. Call this after receiving a trade offer.
/// </summary>
/// <param name="tradeOfferId">The ID of the trade offer</param>
/// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception>
/// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception>
/// <returns>TradeOfferEscrowDuration</returns>
public TradeOfferEscrowDuration GetEscrowDuration(string tradeOfferId)
{
var url = "http://steamcommunity.com/tradeoffer/" + tradeOfferId;
var resp = SteamWeb.Fetch(url, "GET", null, false);
if (string.IsNullOrWhiteSpace(resp))
{
throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration.");
}
return ParseEscrowResponse(resp);
}
private TradeOfferEscrowDuration ParseEscrowResponse(string resp)
{
var myM = Regex.Match(resp, @"g_daysMyEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase);
var theirM = Regex.Match(resp, @"g_daysTheirEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase);
if (!myM.Groups["days"].Success || !theirM.Groups["days"].Success)
{
var steamErrorM = Regex.Match(resp, @"<div id=""error_msg"">([^>]+)<\/div>", RegexOptions.IgnoreCase);
if (steamErrorM.Groups.Count > 1)
{
var steamError = Regex.Replace(steamErrorM.Groups[1].Value.Trim(), @"\t|\n|\r", ""); ;
throw new TradeOfferEscrowDurationParseException(steamError);
}
else
{
throw new TradeOfferEscrowDurationParseException(string.Empty);
}
}
return new TradeOfferEscrowDuration()
{
DaysMyEscrow = int.Parse(myM.Groups["days"].Value),
DaysTheirEscrow = int.Parse(theirM.Groups["days"].Value)
};
}
public class TradeOfferEscrowDuration
{
public int DaysMyEscrow { get; set; }
public int DaysTheirEscrow { get; set; }
}
public class TradeOfferEscrowDurationParseException : Exception
{
public TradeOfferEscrowDurationParseException() : base() { }
public TradeOfferEscrowDurationParseException(string message) : base(message) { }
}
#region Background Worker Methods
private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
if (runWorkerCompletedEventArgs.Error != null)
{
Exception ex = runWorkerCompletedEventArgs.Error;
Log.Error("Unhandled exceptions in bot {0} callback thread: {1} {2}",
DisplayName,
Environment.NewLine,
ex);
Log.Info("This bot died. Stopping it..");
//backgroundWorker.RunWorkerAsync();
//Thread.Sleep(10000);
StopBot();
//StartBot();
}
}
private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
ICallbackMsg msg;
while (!botThread.CancellationPending)
{
try
{
msg = SteamClient.WaitForCallback(true);
HandleSteamMessage(msg);
}
catch (WebException e)
{
Log.Error("URI: {0} >> {1}", (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown"), e.ToString());
System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds.
}
catch (Exception e)
{
Log.Error(e.ToString());
Log.Warn("Restarting bot...");
}
}
}
#endregion Background Worker Methods
private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e)
{
// Set to null in case this is another attempt
this.AuthCode = null;
EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired;
if (handler != null)
handler(this, e);
else
{
while (true)
{
if (this.AuthCode != null)
{
e.SteamGuard = this.AuthCode;
break;
}
Thread.Sleep(5);
}
}
}
#region Group Methods
/// <summary>
/// Accepts the invite to a Steam Group
/// </summary>
/// <param name="group">SteamID of the group to accept the invite from.</param>
private void AcceptGroupInvite(SteamID group)
{
var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite);
AcceptInvite.Body.GroupID = group.ConvertToUInt64();
AcceptInvite.Body.AcceptInvite = true;
this.SteamClient.Send(AcceptInvite);
}
/// <summary>
/// Declines the invite to a Steam Group
/// </summary>
/// <param name="group">SteamID of the group to decline the invite from.</param>
private void DeclineGroupInvite(SteamID group)
{
var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite);
DeclineInvite.Body.GroupID = group.ConvertToUInt64();
DeclineInvite.Body.AcceptInvite = false;
this.SteamClient.Send(DeclineInvite);
}
/// <summary>
/// Invites a use to the specified Steam Group
/// </summary>
/// <param name="user">SteamID of the user to invite.</param>
/// <param name="groupId">SteamID of the group to invite the user to.</param>
public void InviteUserToGroup(SteamID user, SteamID groupId)
{
var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan);
InviteUser.Body.GroupID = groupId.ConvertToUInt64();
InviteUser.Body.Invitee = user.ConvertToUInt64();
InviteUser.Body.UnknownInfo = true;
this.SteamClient.Send(InviteUser);
}
#endregion
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposed)
return;
StopBot();
if (disposing)
Log.Dispose();
disposed = true;
}
}
}
| |
/*
* Copyright (c) 2009 Jim Radford http://www.jimradford.com
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Web;
using SuperPutty.Data;
using SuperPutty.Utils;
using SuperPutty.Gui;
using log4net;
namespace SuperPutty
{
public partial class dlgEditSession : Form
{
private static readonly ILog Log = LogManager.GetLogger(typeof(dlgEditSession));
public delegate bool SessionNameValidationHandler(string name, out string error);
private SessionData Session;
private String OldHostname;
private bool isInitialized = false;
private ImageListPopup imgPopup = null;
public dlgEditSession(SessionData session, ImageList iconList)
{
Session = session;
InitializeComponent();
// get putty saved settings from the registry to populate
// the dropdown
PopulatePuttySettings();
if (!String.IsNullOrEmpty(Session.SessionName))
{
this.Text = "Edit session: " + session.SessionName;
this.textBoxSessionName.Text = Session.SessionName;
this.textBoxHostname.Text = Session.Host;
this.textBoxPort.Text = Session.Port.ToString();
this.textBoxExtraArgs.Text = Session.ExtraArgs;
this.textBoxUsername.Text = Session.Username;
switch (Session.Proto)
{
case ConnectionProtocol.Raw:
radioButtonRaw.Checked = true;
break;
case ConnectionProtocol.Rlogin:
radioButtonRlogin.Checked = true;
break;
case ConnectionProtocol.Serial:
radioButtonSerial.Checked = true;
break;
case ConnectionProtocol.SSH:
radioButtonSSH.Checked = true;
break;
case ConnectionProtocol.Telnet:
radioButtonTelnet.Checked = true;
break;
case ConnectionProtocol.Cygterm:
radioButtonCygterm.Checked = true;
break;
case ConnectionProtocol.Mintty:
radioButtonMintty.Checked = true;
break;
default:
radioButtonSSH.Checked = true;
break;
}
foreach(String settings in this.comboBoxPuttyProfile.Items){
if (settings == session.PuttySession)
{
this.comboBoxPuttyProfile.SelectedItem = settings;
break;
}
}
this.buttonSave.Enabled = true;
}
else
{
this.Text = "Create new session";
radioButtonSSH.Checked = true;
this.buttonSave.Enabled = false;
}
// Setup icon chooser
this.buttonImageSelect.ImageList = iconList;
this.buttonImageSelect.ImageKey = string.IsNullOrEmpty(Session.ImageKey)
? SessionTreeview.ImageKeySession
: Session.ImageKey;
this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey);
this.isInitialized = true;
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.BeginInvoke(new MethodInvoker(delegate { this.textBoxSessionName.Focus(); }));
}
private void PopulatePuttySettings()
{
foreach (String sessionName in PuttyDataHelper.GetSessionNames())
{
comboBoxPuttyProfile.Items.Add(sessionName);
}
comboBoxPuttyProfile.SelectedItem = PuttyDataHelper.SessionDefaultSettings;
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
private void buttonSave_Click(object sender, EventArgs e)
{
Session.SessionName = textBoxSessionName.Text.Trim();
Session.PuttySession = comboBoxPuttyProfile.Text.Trim();
Session.Host = textBoxHostname.Text.Trim();
Session.ExtraArgs = textBoxExtraArgs.Text.Trim();
Session.Port = int.Parse(textBoxPort.Text.Trim());
Session.Username = textBoxUsername.Text.Trim();
Session.Password = textBoxPassword.Text;
Session.SessionId = SessionData.CombineSessionIds(SessionData.GetSessionParentId(Session.SessionId), Session.SessionName);
Session.ImageKey = buttonImageSelect.ImageKey;
for (int i = 0; i < groupBox1.Controls.Count; i++)
{
RadioButton rb = (RadioButton)groupBox1.Controls[i];
if (rb.Checked)
{
Session.Proto = (ConnectionProtocol)rb.Tag;
}
}
DialogResult = DialogResult.OK;
}
/// <summary>
/// Special UI handling for cygterm or mintty sessions
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radioButtonCygterm_CheckedChanged(object sender, EventArgs e)
{
string host = this.textBoxHostname.Text;
bool isLocalShell = this.radioButtonCygterm.Checked || this.radioButtonMintty.Checked;
this.textBoxPort.Enabled = !isLocalShell;
this.textBoxExtraArgs.Enabled = !isLocalShell;
this.textBoxUsername.Enabled = !isLocalShell;
if (isLocalShell)
{
if (String.IsNullOrEmpty(host) || !host.StartsWith(CygtermStartInfo.LocalHost))
{
OldHostname = this.textBoxHostname.Text;
this.textBoxHostname.Text = CygtermStartInfo.LocalHost;
}
}
}
private void radioButtonRaw_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonRaw.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
}
}
private void radioButtonTelnet_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonTelnet.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
this.textBoxPort.Text = "23";
}
}
private void radioButtonRlogin_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonRlogin.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
this.textBoxPort.Text = "513";
}
}
private void radioButtonSSH_CheckedChanged(object sender, EventArgs e)
{
if (this.radioButtonSSH.Checked && this.isInitialized)
{
if (!string.IsNullOrEmpty(OldHostname))
{
this.textBoxHostname.Text = OldHostname;
OldHostname = null;
}
this.textBoxPort.Text = "22";
}
}
public static int GetDefaultPort(ConnectionProtocol protocol)
{
int port = 22;
switch (protocol)
{
case ConnectionProtocol.Raw:
break;
case ConnectionProtocol.Rlogin:
port = 513;
break;
case ConnectionProtocol.Serial:
break;
case ConnectionProtocol.Telnet:
port = 23;
break;
}
return port;
}
#region Icon
private void buttonImageSelect_Click(object sender, EventArgs e)
{
if (this.imgPopup == null)
{
int n = buttonImageSelect.ImageList.Images.Count;
int x = (int) Math.Floor(Math.Sqrt(n)) + 1;
int cols = x;
int rows = x;
imgPopup = new ImageListPopup();
imgPopup.BackgroundColor = Color.FromArgb(241, 241, 241);
imgPopup.BackgroundOverColor = Color.FromArgb(102, 154, 204);
imgPopup.Init(this.buttonImageSelect.ImageList, 8, 8, cols, rows);
imgPopup.ItemClick += new ImageListPopupEventHandler(this.OnItemClicked);
}
Point pt = PointToScreen(new Point(buttonImageSelect.Left, buttonImageSelect.Bottom));
imgPopup.Show(pt.X + 2, pt.Y);
}
private void OnItemClicked(object sender, ImageListPopupEventArgs e)
{
if (imgPopup == sender)
{
buttonImageSelect.ImageKey = e.SelectedItem;
this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey);
}
}
#endregion
#region Validation Logic
public SessionNameValidationHandler SessionNameValidator { get; set; }
private void textBoxSessionName_Validating(object sender, CancelEventArgs e)
{
if (this.SessionNameValidator != null)
{
string error;
if (!this.SessionNameValidator(this.textBoxSessionName.Text, out error))
{
e.Cancel = true;
this.SetError(this.textBoxSessionName, error ?? "Invalid Session Name");
}
}
}
private void textBoxSessionName_Validated(object sender, EventArgs e)
{
this.SetError(this.textBoxSessionName, String.Empty);
}
private void textBoxPort_Validating(object sender, CancelEventArgs e)
{
int val;
if (!Int32.TryParse(this.textBoxPort.Text, out val))
{
e.Cancel = true;
this.SetError(this.textBoxPort, "Invalid Port");
}
}
private void textBoxPort_Validated(object sender, EventArgs e)
{
this.SetError(this.textBoxPort, String.Empty);
}
private void textBoxHostname_Validating(object sender, CancelEventArgs e)
{
if (string.IsNullOrEmpty((string)this.comboBoxPuttyProfile.SelectedItem) &&
string.IsNullOrEmpty(this.textBoxHostname.Text.Trim()))
{
if (sender == this.textBoxHostname)
{
this.SetError(this.textBoxHostname, "A host name must be specified if a Putty Session Profile is not selected");
}
else if (sender == this.comboBoxPuttyProfile)
{
this.SetError(this.comboBoxPuttyProfile, "A Putty Session Profile must be selected if a Host Name is not provided");
}
}
else
{
this.SetError(this.textBoxHostname, String.Empty);
this.SetError(this.comboBoxPuttyProfile, String.Empty);
}
}
private void comboBoxPuttyProfile_Validating(object sender, CancelEventArgs e)
{
this.textBoxHostname_Validating(sender, e);
}
private void comboBoxPuttyProfile_SelectedIndexChanged(object sender, EventArgs e)
{
this.ValidateChildren(ValidationConstraints.ImmediateChildren);
}
void SetError(Control control, string error)
{
this.errorProvider.SetError(control, error);
this.EnableDisableSaveButton();
}
void EnableDisableSaveButton()
{
this.buttonSave.Enabled = (
this.errorProvider.GetError(this.textBoxSessionName) == String.Empty &&
this.errorProvider.GetError(this.textBoxHostname) == String.Empty &&
this.errorProvider.GetError(this.textBoxPort) == String.Empty &&
this.errorProvider.GetError(this.comboBoxPuttyProfile) == String.Empty);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using UIWidgets;
namespace UIWidgetsSamples {
public enum SteamSpySortFields
{
Name,
ScoreRank,
Owners,
Players,
PlayersIn2Week,
Time,
}
public class SteamSpyView : ListViewCustomHeight<SteamSpyComponent,SteamSpyItem> {
bool isSteamSpyViewStarted;
public override void Start()
{
if (isSteamSpyViewStarted)
{
return ;
}
isSteamSpyViewStarted = true;
sortComparers = new Dictionary<SteamSpySortFields,Comparison<SteamSpyItem>>(){
{SteamSpySortFields.Name, NameComparer},
{SteamSpySortFields.ScoreRank, ScoreRankComparer},
{SteamSpySortFields.Owners, OwnersComparer},
{SteamSpySortFields.Players, PlayersComparer},
{SteamSpySortFields.PlayersIn2Week, PlayersIn2WeekComparer},
{SteamSpySortFields.Time, TimeComparer},
};
Sort = false;
base.Start();
StartCoroutine(LoadData());
}
public override void OnEnable()
{
base.OnEnable();
if (isSteamSpyViewStarted && DataSource.Count==0)
{
StartCoroutine(LoadData());
}
}
IEnumerator LoadData()
{
WWW www = new WWW("https://ilih.ru/steamspy/");
yield return www;
var lines = www.text.Split('\n');
DataSource.BeginUpdate();
DataSource.Clear();
lines.ForEach(ParseLine);
DataSource.EndUpdate();
}
void ParseLine(string line)
{
if (line=="")
{
return ;
}
var info = line.Split('\t');
var item = new SteamSpyItem(){
Name = info[0],
ScoreRank = (info[1]=="") ? -1 : int.Parse(info[1]),
Owners = int.Parse(info[2]),
OwnersVariance = int.Parse(info[3]),
Players = int.Parse(info[4]),
PlayersVariance = int.Parse(info[5]),
PlayersIn2Week = int.Parse(info[6]),
PlayersIn2WeekVariance = int.Parse(info[7]),
AverageTimeIn2Weeks = int.Parse(info[8]),
MedianTimeIn2Weeks = int.Parse(info[9]),
};
DataSource.Add(item);
}
protected override void SetData(SteamSpyComponent component, SteamSpyItem item)
{
component.SetData(item);
}
protected override void HighlightColoring(SteamSpyComponent component)
{
//base.HighlightColoring(component);
component.Name.color = HighlightedColor;
component.ScoreRank.color = HighlightedColor;
component.Owners.color = HighlightedColor;
component.Players.color = HighlightedColor;
component.PlayersIn2Week.color = HighlightedColor;
component.TimeIn2Week.color = HighlightedColor;
}
protected override void SelectColoring(SteamSpyComponent component)
{
//base.SelectColoring(component);
component.Name.color = SelectedColor;
component.ScoreRank.color = SelectedColor;
component.Owners.color = SelectedColor;
component.Players.color = SelectedColor;
component.PlayersIn2Week.color = SelectedColor;
component.TimeIn2Week.color = SelectedColor;
}
protected override void DefaultColoring(SteamSpyComponent component)
{
//base.DefaultColoring(component);
component.Name.color = DefaultColor;
component.ScoreRank.color = DefaultColor;
component.Owners.color = DefaultColor;
component.Players.color = DefaultColor;
component.PlayersIn2Week.color = DefaultColor;
component.TimeIn2Week.color = DefaultColor;
}
SteamSpySortFields currentSortField = SteamSpySortFields.Players;
Dictionary<SteamSpySortFields,Comparison<SteamSpyItem>> sortComparers;
public void ToggleSort(SteamSpySortFields field)
{
if (field==currentSortField)
{
DataSource.Reverse();
}
else if (sortComparers.ContainsKey(field))
{
currentSortField = field;
DataSource.Sort(sortComparers[field]);
}
}
#region used in Button.OnClick()
public void SortByName()
{
ToggleSort(SteamSpySortFields.Name);
}
public void SortByScoreRank()
{
ToggleSort(SteamSpySortFields.ScoreRank);
}
public void SortByOwners()
{
ToggleSort(SteamSpySortFields.Owners);
}
public void SortByPlayers()
{
ToggleSort(SteamSpySortFields.Players);
}
public void SortByPlayersIn2Week()
{
ToggleSort(SteamSpySortFields.PlayersIn2Week);
}
public void SortByTime()
{
ToggleSort(SteamSpySortFields.Time);
}
#endregion
#region Items comparers
static protected int NameComparer(SteamSpyItem x, SteamSpyItem y)
{
return x.Name.CompareTo(y.Name);
}
static protected int ScoreRankComparer(SteamSpyItem x, SteamSpyItem y)
{
return x.ScoreRank.CompareTo(y.ScoreRank);
}
static protected int OwnersComparer(SteamSpyItem x, SteamSpyItem y)
{
return x.Owners.CompareTo(y.Owners);
}
static protected int PlayersComparer(SteamSpyItem x, SteamSpyItem y)
{
return x.Players.CompareTo(y.Players);
}
static protected int PlayersIn2WeekComparer(SteamSpyItem x, SteamSpyItem y)
{
return x.PlayersIn2Week.CompareTo(y.PlayersIn2Week);
}
static protected int TimeComparer(SteamSpyItem x, SteamSpyItem y)
{
return x.AverageTimeIn2Weeks.CompareTo(y.AverageTimeIn2Weeks);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using ICSharpCode.SharpZipLib.Zip;
using MarkdownSharp;
using NuGet;
using Splat;
using ICSharpCode.SharpZipLib.Core;
namespace Squirrel
{
internal static class FrameworkTargetVersion
{
public static FrameworkName Net40 = new FrameworkName(".NETFramework,Version=v4.0");
public static FrameworkName Net45 = new FrameworkName(".NETFramework,Version=v4.5");
}
public interface IReleasePackage
{
string InputPackageFile { get; }
string ReleasePackageFile { get; }
string SuggestedReleaseFileName { get; }
string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null);
}
public static class VersionComparer
{
public static bool Matches(IVersionSpec versionSpec, SemanticVersion version)
{
if (versionSpec == null)
return true; // I CAN'T DEAL WITH THIS
bool minVersion;
if (versionSpec.MinVersion == null) {
minVersion = true; // no preconditon? LET'S DO IT
} else if (versionSpec.IsMinInclusive) {
minVersion = version >= versionSpec.MinVersion;
} else {
minVersion = version > versionSpec.MinVersion;
}
bool maxVersion;
if (versionSpec.MaxVersion == null) {
maxVersion = true; // no preconditon? LET'S DO IT
} else if (versionSpec.IsMaxInclusive) {
maxVersion = version <= versionSpec.MaxVersion;
} else {
maxVersion = version < versionSpec.MaxVersion;
}
return maxVersion && minVersion;
}
}
public class ReleasePackage : IEnableLogger, IReleasePackage
{
IEnumerable<IPackage> localPackageCache;
public ReleasePackage(string inputPackageFile, bool isReleasePackage = false)
{
InputPackageFile = inputPackageFile;
if (isReleasePackage) {
ReleasePackageFile = inputPackageFile;
}
}
public string InputPackageFile { get; protected set; }
public string ReleasePackageFile { get; protected set; }
public string SuggestedReleaseFileName {
get {
var zp = new ZipPackage(InputPackageFile);
return String.Format("{0}-{1}-full.nupkg", zp.Id, zp.Version);
}
}
public Version Version { get { return InputPackageFile.ToVersion(); } }
public string CreateReleasePackage(string outputFile, string packagesRootDir = null, Func<string, string> releaseNotesProcessor = null, Action<string> contentsPostProcessHook = null)
{
Contract.Requires(!String.IsNullOrEmpty(outputFile));
releaseNotesProcessor = releaseNotesProcessor ?? (x => (new Markdown()).Transform(x));
if (ReleasePackageFile != null) {
return ReleasePackageFile;
}
var package = new ZipPackage(InputPackageFile);
// we can tell from here what platform(s) the package targets
// but given this is a simple package we only
// ever expect one entry here (crash hard otherwise)
var frameworks = package.GetSupportedFrameworks();
if (frameworks.Count() > 1) {
var platforms = frameworks
.Aggregate(new StringBuilder(), (sb, f) => sb.Append(f.ToString() + "; "));
throw new InvalidOperationException(String.Format(
"The input package file {0} targets multiple platforms - {1} - and cannot be transformed into a release package.", InputPackageFile, platforms));
} else if (!frameworks.Any()) {
throw new InvalidOperationException(String.Format(
"The input package file {0} targets no platform and cannot be transformed into a release package.", InputPackageFile));
}
var targetFramework = frameworks.Single();
// Recursively walk the dependency tree and extract all of the
// dependent packages into the a temporary directory
this.Log().Info("Creating release package: {0} => {1}", InputPackageFile, outputFile);
var dependencies = findAllDependentPackages(
package,
new LocalPackageRepository(packagesRootDir),
frameworkName: targetFramework);
string tempPath = null;
using (Utility.WithTempDirectory(out tempPath, null)) {
var tempDir = new DirectoryInfo(tempPath);
extractZipDecoded(InputPackageFile, tempPath);
this.Log().Info("Extracting dependent packages: [{0}]", String.Join(",", dependencies.Select(x => x.Id)));
extractDependentPackages(dependencies, tempDir, targetFramework);
var specPath = tempDir.GetFiles("*.nuspec").First().FullName;
this.Log().Info("Removing unnecessary data");
removeDependenciesFromPackageSpec(specPath);
removeDeveloperDocumentation(tempDir);
if (releaseNotesProcessor != null) {
renderReleaseNotesMarkdown(specPath, releaseNotesProcessor);
}
addDeltaFilesToContentTypes(tempDir.FullName);
if (contentsPostProcessHook != null) {
contentsPostProcessHook(tempPath);
}
createZipEncoded(outputFile, tempPath);
ReleasePackageFile = outputFile;
return ReleasePackageFile;
}
}
// nupkg file %-encodes zip entry names. This method decodes entry names before writing to disk.
// We must do this, or PathTooLongException may be thrown for some unicode entry names.
void extractZipDecoded(string zipFilePath, string outFolder)
{
var zf = new ZipFile(zipFilePath);
foreach (ZipEntry zipEntry in zf) {
if (!zipEntry.IsFile) continue;
var entryFileName = Uri.UnescapeDataString(zipEntry.Name);
var buffer = new byte[4096];
var zipStream = zf.GetInputStream(zipEntry);
var fullZipToPath = Path.Combine(outFolder, entryFileName);
var directoryName = Path.GetDirectoryName(fullZipToPath);
if (directoryName.Length > 0) {
Directory.CreateDirectory(directoryName);
}
using (FileStream streamWriter = File.Create(fullZipToPath)) {
StreamUtils.Copy(zipStream, streamWriter, buffer);
}
}
}
// Create zip file with entry names %-encoded, as nupkg file does.
void createZipEncoded(string zipFilePath, string folder)
{
folder = Path.GetFullPath(folder);
var offset = folder.Length + (folder.EndsWith("\\", StringComparison.OrdinalIgnoreCase) ? 1 : 0);
var fsOut = File.Create(zipFilePath);
var zipStream = new ZipOutputStream(fsOut);
zipStream.SetLevel(5);
compressFolderEncoded(folder, zipStream, offset);
zipStream.IsStreamOwner = true;
zipStream.Close();
}
void compressFolderEncoded(string path, ZipOutputStream zipStream, int folderOffset)
{
string[] files = Directory.GetFiles(path);
foreach (string filename in files) {
FileInfo fi = new FileInfo(filename);
string entryName = filename.Substring(folderOffset);
entryName = ZipEntry.CleanName(entryName);
entryName = Uri.EscapeUriString(entryName);
var newEntry = new ZipEntry(entryName);
newEntry.DateTime = fi.LastWriteTime;
newEntry.Size = fi.Length;
zipStream.PutNextEntry(newEntry);
var buffer = new byte[4096];
using (FileStream streamReader = File.OpenRead(filename)) {
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
string[] folders = Directory.GetDirectories(path);
foreach (string folder in folders) {
compressFolderEncoded(folder, zipStream, folderOffset);
}
}
void extractDependentPackages(IEnumerable<IPackage> dependencies, DirectoryInfo tempPath, FrameworkName framework)
{
dependencies.ForEach(pkg => {
this.Log().Info("Scanning {0}", pkg.Id);
pkg.GetLibFiles().ForEach(file => {
var outPath = new FileInfo(Path.Combine(tempPath.FullName, file.Path));
if (!VersionUtility.IsCompatible(framework , new[] { file.TargetFramework }))
{
this.Log().Info("Ignoring {0} as the target framework is not compatible", outPath);
return;
}
Directory.CreateDirectory(outPath.Directory.FullName);
using (var of = File.Create(outPath.FullName)) {
this.Log().Info("Writing {0} to {1}", file.Path, outPath);
file.GetStream().CopyTo(of);
}
});
});
}
void removeDeveloperDocumentation(DirectoryInfo expandedRepoPath)
{
expandedRepoPath.GetAllFilesRecursively()
.Where(x => x.Name.EndsWith(".dll", true, CultureInfo.InvariantCulture))
.Select(x => new FileInfo(x.FullName.ToLowerInvariant().Replace(".dll", ".xml")))
.Where(x => x.Exists)
.ForEach(x => x.Delete());
}
void renderReleaseNotesMarkdown(string specPath, Func<string, string> releaseNotesProcessor)
{
var doc = new XmlDocument();
doc.Load(specPath);
// XXX: This code looks full tart
var metadata = doc.DocumentElement.ChildNodes
.OfType<XmlElement>()
.First(x => x.Name.ToLowerInvariant() == "metadata");
var releaseNotes = metadata.ChildNodes
.OfType<XmlElement>()
.FirstOrDefault(x => x.Name.ToLowerInvariant() == "releasenotes");
if (releaseNotes == null) {
this.Log().Info("No release notes found in {0}", specPath);
return;
}
releaseNotes.InnerText = String.Format("<![CDATA[\n" + "{0}\n" + "]]>",
releaseNotesProcessor(releaseNotes.InnerText));
doc.Save(specPath);
}
void removeDependenciesFromPackageSpec(string specPath)
{
var xdoc = new XmlDocument();
xdoc.Load(specPath);
var metadata = xdoc.DocumentElement.FirstChild;
var dependenciesNode = metadata.ChildNodes.OfType<XmlElement>().FirstOrDefault(x => x.Name.ToLowerInvariant() == "dependencies");
if (dependenciesNode != null) {
metadata.RemoveChild(dependenciesNode);
}
xdoc.Save(specPath);
}
internal IEnumerable<IPackage> findAllDependentPackages(
IPackage package = null,
IPackageRepository packageRepository = null,
HashSet<string> packageCache = null,
FrameworkName frameworkName = null)
{
package = package ?? new ZipPackage(InputPackageFile);
packageCache = packageCache ?? new HashSet<string>();
var deps = package.DependencySets
.Where(x => x.TargetFramework == null
|| x.TargetFramework == frameworkName)
.SelectMany(x => x.Dependencies);
return deps.SelectMany(dependency => {
var ret = matchPackage(packageRepository, dependency.Id, dependency.VersionSpec);
if (ret == null) {
var message = String.Format("Couldn't find file for package in {1}: {0}", dependency.Id, packageRepository.Source);
this.Log().Error(message);
throw new Exception(message);
}
if (packageCache.Contains(ret.GetFullName())) {
return Enumerable.Empty<IPackage>();
}
packageCache.Add(ret.GetFullName());
return findAllDependentPackages(ret, packageRepository, packageCache, frameworkName).StartWith(ret).Distinct(y => y.GetFullName());
}).ToArray();
}
IPackage matchPackage(IPackageRepository packageRepository, string id, IVersionSpec version)
{
return packageRepository.FindPackagesById(id).FirstOrDefault(x => VersionComparer.Matches(version, x.Version));
}
static internal void addDeltaFilesToContentTypes(string rootDirectory)
{
var doc = new XmlDocument();
var path = Path.Combine(rootDirectory, "[Content_Types].xml");
doc.Load(path);
ContentType.Merge(doc);
using (var sw = new StreamWriter(path, false, Encoding.UTF8)) {
doc.Save(sw);
}
}
}
public class ChecksumFailedException : Exception
{
public string Filename { get; set; }
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2015 Tim Stair
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using CardMaker.Card;
using CardMaker.Data;
using CardMaker.Events.Args;
using CardMaker.Events.Managers;
using CardMaker.XML;
using Support.UI;
using LayoutEventArgs = CardMaker.Events.Args.LayoutEventArgs;
namespace CardMaker.Forms
{
public partial class MDICanvas : Form
{
private const int SELECTION_BUFFER = 3;
private const int SELECTION_BUFFER_SPACE = SELECTION_BUFFER*2;
private bool m_bElementSelected;
private MouseMode m_eMouseMode = MouseMode.Unknown;
private ResizeDirection m_eResizeDirection = ResizeDirection.Up;
private ProjectLayoutElement m_zSelectedElement;
private List<ProjectLayoutElement> m_listSelectedElements;
private List<Point> m_listSelectedOriginalPosition;
private List<float> m_listSelectedOriginalRotation;
private Dictionary<ProjectLayoutElement, ElementPosition> m_dictionarySelectedUndo;
private Point m_pointOriginalMouseDown = Point.Empty;
private TranslationLock m_eTranslationLockState = TranslationLock.Unset;
private readonly ContextMenuStrip m_zContextMenu = new ContextMenuStrip();
private readonly CardCanvas m_zCardCanvas;
private float m_fZoom = 1.0f;
private float m_fZoomRatio = 1.0f;
private const int TRANSLATION_LOCK_DEAD_ZONE = 3; // 3 pixels of movement
private enum MouseMode
{
Unknown,
MoveResize,
Move,
Rotate,
}
private enum TranslationLock
{
Unset,
WaitingToSet,
Vertical, // lock to vertical only
Horizontal, // lock to horizontal only
}
private enum ElementCenterAlign
{
None,
Layout,
FirstElement
}
private TranslationLock TranslationLockState
{
get { return m_eTranslationLockState; }
set
{
// Logger.AddLogLine(m_eTranslationLockState + "=>" + value);
m_eTranslationLockState = value;
}
}
[Flags]
private enum ResizeDirection
{
None = 0,
Up = 1 << 0,
Down = 1 << 1,
Left = 1 << 2,
Right = 1 << 3,
UpLeft = Up | Left,
UpRight = Up | Right,
DownLeft = Down | Left,
DownRight = Down | Right,
Move = 1 << 8,
}
public MDICanvas()
{
InitializeComponent();
var zBitmap = new Bitmap(32, 32);
Graphics zGraphics = Graphics.FromImage(zBitmap);
Brush zBlack = new SolidBrush(Color.LightGray);
Brush zWhite = new SolidBrush(Color.White);
zGraphics.FillRectangle(zBlack, 0, 0, 16, 16);
zGraphics.FillRectangle(zWhite, 16, 0, 16, 16);
zGraphics.FillRectangle(zBlack, 16, 16, 16, 16);
zGraphics.FillRectangle(zWhite, 0, 16, 16, 16);
panelCardCanvas.BackgroundImage = zBitmap;
CardMakerInstance.CanvasUserAction = false;
// m_zCardCanvas is a panel within the panelCardCanvas
m_zCardCanvas = new CardCanvas
{
Location = new Point(0, 0),
};
ChangeMouseMode(MouseMode.MoveResize);
m_zCardCanvas.MouseMove += cardCanvas_MouseMove;
m_zCardCanvas.MouseDown += cardCanvas_MouseDown;
m_zCardCanvas.MouseUp += cardCanvas_MouseUp;
m_zCardCanvas.ContextMenuStrip = m_zContextMenu;
m_zContextMenu.RenderMode = ToolStripRenderMode.System;
m_zContextMenu.Opening += contextmenuOpening_Handler;
panelCardCanvas.Controls.Add(m_zCardCanvas);
LayoutManager.Instance.LayoutUpdated += Layout_Updated;
LayoutManager.Instance.LayoutLoaded += Layout_Loaded;
LayoutManager.Instance.LayoutRenderUpdated += LayoutRender_Updated;
LayoutManager.Instance.DeckIndexChanged += DeckIndex_Changed;
ElementManager.Instance.ElementSelected += Element_Selected;
ProjectManager.Instance.ProjectOpened += Project_Opened;
verticalCenterButton.Image = Properties.Resources.VerticalAlign.ToBitmap();
customVerticalAlignButton.Image = Properties.Resources.VerticalCustomAlign.ToBitmap();
horizontalCenterButton.Image = Properties.Resources.HorizontalAlign.ToBitmap();
customHoritonalAlignButton.Image = Properties.Resources.HorizontalCustomAlign.ToBitmap();
customAlignButton.Image = Properties.Resources.CustomAlign.ToBitmap();
}
#region Form Overrides
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (!numericUpDownZoom.Focused)
{
int nHChange = 0;
int nVChange = 0;
// NOTE: this method only detects keydown events
switch (keyData)
{
case Keys.Control | Keys.Add:
numericUpDownZoom.Value = Math.Min(numericUpDownZoom.Maximum,
numericUpDownZoom.Value + numericUpDownZoom.Increment);
break;
case Keys.Control | Keys.Subtract:
numericUpDownZoom.Value = Math.Max(numericUpDownZoom.Minimum,
numericUpDownZoom.Value - numericUpDownZoom.Increment);
break;
// focus is taken by the MDICanvas, reset it after each change below & reset the translation lock
case Keys.Shift | Keys.Up:
LayoutManager.Instance.FireElementOrderAdjustRequest(-1);
TranslationLockState = TranslationLock.Unset;
m_zCardCanvas.Focus();
break;
case Keys.Shift | Keys.Down:
LayoutManager.Instance.FireElementOrderAdjustRequest(1);
TranslationLockState = TranslationLock.Unset;
m_zCardCanvas.Focus();
break;
case Keys.Control | Keys.Up:
LayoutManager.Instance.FireElementSelectAdjustRequest(-1);
TranslationLockState = TranslationLock.Unset;
m_zCardCanvas.Focus();
break;
case Keys.Control | Keys.Down:
LayoutManager.Instance.FireElementSelectAdjustRequest(1);
TranslationLockState = TranslationLock.Unset;
m_zCardCanvas.Focus();
break;
case Keys.ShiftKey | Keys.Shift:
if (TranslationLock.Unset == TranslationLockState)
{
TranslationLockState = TranslationLock.WaitingToSet;
}
break;
case Keys.Up:
nVChange = -1;
m_zCardCanvas.Focus();
break;
case Keys.Down:
nVChange = 1;
m_zCardCanvas.Focus();
break;
case Keys.Left:
nHChange = -1;
m_zCardCanvas.Focus();
break;
case Keys.Right:
nHChange = 1;
m_zCardCanvas.Focus();
break;
case Keys.M:
ChangeMouseMode(MouseMode.Move == m_eMouseMode
? MouseMode.MoveResize
: MouseMode.Move);
break;
case Keys.R:
ChangeMouseMode(MouseMode.Rotate == m_eMouseMode
? MouseMode.MoveResize
: MouseMode.Rotate);
break;
}
ElementManager.Instance.ProcessSelectedElementsChange(nHChange, nVChange, 0, 0);
}
return base.ProcessCmdKey(ref msg, keyData);
}
protected override CreateParams CreateParams
{
get
{
const int CP_NOCLOSE_BUTTON = 0x200;
CreateParams zParams = base.CreateParams;
zParams.ClassStyle = zParams.ClassStyle | CP_NOCLOSE_BUTTON;
return zParams;
}
}
#endregion
#region Manager Events
void Element_Selected(object sender, ElementEventArgs args)
{
Redraw();
}
void DeckIndex_Changed(object sender, DeckChangeEventArgs args)
{
Redraw();
}
void Layout_Updated(object sender, LayoutEventArgs args)
{
// pass the loaded deck into the renderer
m_zCardCanvas.Reset(args.Deck);
Redraw();
}
void Layout_Loaded(object sender, LayoutEventArgs args)
{
// pass the loaded deck into the renderer
m_zCardCanvas.Reset(args.Deck);
Redraw();
}
void LayoutRender_Updated(object sender, LayoutEventArgs args)
{
Redraw();
}
void Project_Opened(object sender, ProjectEventArgs e)
{
m_zCardCanvas.Reset(null);
Redraw();
}
#endregion
#region Form Events
private void contextmenuOpening_Handler(object sender, CancelEventArgs e)
{
m_zContextMenu.Items.Clear();
if (null != LayoutManager.Instance.ActiveDeck.CardLayout.Element)
{
Point pointMouse = m_zCardCanvas.PointToClient(MousePosition);
// add only the items that the mouse is within the rectangle of
foreach (ProjectLayoutElement zElement in LayoutManager.Instance.ActiveDeck.CardLayout.Element)
{
if (!zElement.enabled)
{
continue;
}
var zRect = new RectangleF(zElement.x*m_fZoom, zElement.y*m_fZoom, zElement.width*m_fZoom,
zElement.height*m_fZoom);
if (zRect.Contains(pointMouse))
{
var zItem = m_zContextMenu.Items.Add(zElement.name, null, contextmenuClick_Handler);
zItem.Tag = zElement;
}
}
}
if (1 == m_zContextMenu.Items.Count)
{
// auto-select if there's only one!
contextmenuClick_Handler(m_zContextMenu.Items[0], new EventArgs());
e.Cancel = true;
}
if (0 == m_zContextMenu.Items.Count)
{
e.Cancel = true;
}
}
private void contextmenuClick_Handler(object sender, EventArgs e)
{
ElementManager.Instance.FireElementSelectRequestedEvent((ProjectLayoutElement)((ToolStripItem) sender).Tag);
}
private void cardCanvas_MouseMove(object sender, MouseEventArgs e)
{
#warning this would be better with event handler subscribing/unsubscribing (didn't work so well with the 60 seconds I invested in trying it)
switch (m_eMouseMode)
{
case MouseMode.Rotate:
cardCanvas_MouseMoveRotateMode(sender, e);
break;
case MouseMode.Move:
case MouseMode.MoveResize:
cardCanvas_MouseMoveGeneralMode(sender, e);
break;
}
}
private void cardCanvas_MouseMoveRotateMode(object sender, MouseEventArgs e)
{
#warning this is a really bad place for this... maybe switch the mouse handler if in rotate only mode
if (m_eMouseMode == MouseMode.Rotate)
{
if (MouseButtons.Left == e.Button)
{
int nYDiff = e.Y - m_pointOriginalMouseDown.Y;
var nNewRotation = (int) ((float) nYDiff/m_fZoom);
if (null != m_listSelectedElements)
{
int nIdx = 0;
foreach (var selectedElement in m_listSelectedElements)
{
selectedElement.rotation = nNewRotation + m_listSelectedOriginalRotation[nIdx];
nIdx++;
}
}
if (nNewRotation != 0)
{
ElementManager.Instance.FireElementBoundsUpdateEvent();
}
}
}
}
private void cardCanvas_MouseMoveGeneralMode(object sender, MouseEventArgs e)
{
if (MouseButtons.Left == e.Button)
{
if (m_bElementSelected)
{
int nX = e.X;
int nY = e.Y;
var bElementBoundsChanged = false;
if (Cursor == Cursors.SizeAll)
{
if (TranslationLock.WaitingToSet == TranslationLockState)
{
// setup the lock (if outside the dead zone)
int nXDiff = Math.Abs(nX - m_pointOriginalMouseDown.X);
int nYDiff = Math.Abs(nY - m_pointOriginalMouseDown.Y);
if (nXDiff > TRANSLATION_LOCK_DEAD_ZONE || nYDiff > TRANSLATION_LOCK_DEAD_ZONE)
{
TranslationLockState = nXDiff > nYDiff
? TranslationLock.Horizontal
: TranslationLock.Vertical;
}
}
switch (TranslationLockState)
{
case TranslationLock.Horizontal:
nY = m_pointOriginalMouseDown.Y;
break;
case TranslationLock.Vertical:
nX = m_pointOriginalMouseDown.X;
break;
}
var nXUnzoomed = (int) ((float) nX*m_fZoomRatio);
var nYUnzoomed = (int) ((float) nY*m_fZoomRatio);
if (null != m_listSelectedElements)
{
int idx = 0;
foreach (var selectedElement in m_listSelectedElements)
{
selectedElement.x = nXUnzoomed - m_listSelectedOriginalPosition[idx].X;
selectedElement.y = nYUnzoomed - m_listSelectedOriginalPosition[idx].Y;
idx++;
}
}
bElementBoundsChanged = true;
}
else if (Cursor == Cursors.SizeNS)
{
switch (m_eResizeDirection)
{
case ResizeDirection.Up:
bElementBoundsChanged |= ResizeUp(nY);
break;
case ResizeDirection.Down:
bElementBoundsChanged |= ResizeDown(nY);
break;
}
}
else if (Cursor == Cursors.SizeWE)
{
switch (m_eResizeDirection)
{
case ResizeDirection.Left:
bElementBoundsChanged |= ResizeLeft(nX);
break;
case ResizeDirection.Right:
bElementBoundsChanged |= ResizeRight(nX);
break;
}
}
else if (Cursor == Cursors.SizeNESW)
{
switch (m_eResizeDirection)
{
case ResizeDirection.UpRight:
bElementBoundsChanged |= ResizeUp(nY);
bElementBoundsChanged |= ResizeRight(nX);
break;
case ResizeDirection.DownLeft:
bElementBoundsChanged |= ResizeDown(nY);
bElementBoundsChanged |= ResizeLeft(nX);
break;
}
}
else if (Cursor == Cursors.SizeNWSE)
{
switch (m_eResizeDirection)
{
case ResizeDirection.UpLeft:
bElementBoundsChanged |= ResizeUp(nY);
bElementBoundsChanged |= ResizeLeft(nX);
break;
case ResizeDirection.DownRight:
bElementBoundsChanged |= ResizeDown(nY);
bElementBoundsChanged |= ResizeRight(nX);
break;
}
}
if (bElementBoundsChanged)
{
ElementManager.Instance.FireElementBoundsUpdateEvent();
}
}
}
if (MouseButtons.None == e.Button)
{
var zElement = ElementManager.Instance.GetSelectedElement();
if (null != zElement)
{
m_eResizeDirection = ResizeDirection.None;
var nX = e.X;
var nY = e.Y;
var nEdgeRight = (int) (zElement.x*m_fZoom + zElement.width*m_fZoom + SELECTION_BUFFER);
var nEdgeLeft = (int) (zElement.x*m_fZoom - SELECTION_BUFFER);
var nEdgeTop = (int) (zElement.y*m_fZoom - SELECTION_BUFFER);
var nEdgeBottom = (int) (zElement.y*m_fZoom + zElement.height*m_fZoom + SELECTION_BUFFER);
// first verify the cursor is within the SELECTION_BUFFER sized area
if ((nX >= (nEdgeLeft)) && (nX <= (nEdgeRight)) &&
(nY >= (nEdgeTop)) && (nY <= (nEdgeBottom)))
{
if (SELECTION_BUFFER_SPACE >= (nX - nEdgeLeft))
{
m_eResizeDirection |= ResizeDirection.Left;
}
if (SELECTION_BUFFER_SPACE >= (nEdgeRight - nX))
{
m_eResizeDirection |= ResizeDirection.Right;
}
if (SELECTION_BUFFER_SPACE >= (nY - nEdgeTop))
{
m_eResizeDirection |= ResizeDirection.Up;
}
if (SELECTION_BUFFER_SPACE >= (nEdgeBottom - nY))
{
m_eResizeDirection |= ResizeDirection.Down;
}
if (MouseMode.Move == m_eMouseMode)
m_eResizeDirection = ResizeDirection.None;
switch (m_eResizeDirection)
{
case ResizeDirection.Down:
case ResizeDirection.Up:
Cursor = Cursors.SizeNS;
break;
case ResizeDirection.Left:
case ResizeDirection.Right:
Cursor = Cursors.SizeWE;
break;
case ResizeDirection.UpLeft:
case ResizeDirection.DownRight:
Cursor = Cursors.SizeNWSE;
break;
case ResizeDirection.UpRight:
case ResizeDirection.DownLeft:
Cursor = Cursors.SizeNESW;
break;
case ResizeDirection.None:
// if no edge was found to be selected it's a move
Cursor = Cursors.SizeAll;
m_eResizeDirection = ResizeDirection.Move;
break;
}
}
else
{
Cursor = Cursors.Default;
}
}
}
if (MouseButtons.Middle == e.Button)
{
var nXDiff = m_pointOriginalMouseDown.X - e.X;
var nYDiff = m_pointOriginalMouseDown.Y - e.Y;
panelCardCanvas.ScrollToXY(
panelCardCanvas.AutoScrollPosition.X - nXDiff,
panelCardCanvas.AutoScrollPosition.Y - nYDiff);
// after the panel adjust the original mouse down has to be adjusted! Get its position based on the canvas itself
m_pointOriginalMouseDown = m_zCardCanvas.PointToClient(Cursor.Position);
}
}
private void cardCanvas_MouseUp(object sender, MouseEventArgs e)
{
CardMakerInstance.CanvasUserAction = false;
if (null != m_listSelectedElements && m_bElementSelected)
{
ElementManager.Instance.ConfigureUserAction(m_dictionarySelectedUndo, ElementManager.Instance.GetUndoRedoPoints());
}
m_dictionarySelectedUndo = null;
m_listSelectedElements = null;
m_zSelectedElement = null;
m_bElementSelected = false;
TranslationLockState = TranslationLock.Unset;
}
private void cardCanvas_MouseDown(object sender, MouseEventArgs e)
{
if (MouseButtons.Left == e.Button)
{
ProjectLayoutElement zElement = ElementManager.Instance.GetSelectedElement();
if (null != zElement)
{
CardMakerInstance.CanvasUserAction = true;
m_pointOriginalMouseDown = e.Location;
if (TranslationLock.WaitingToSet != TranslationLockState)
{
TranslationLockState = TranslationLock.Unset;
}
int nX = e.X;
int nY = e.Y;
if ((nX >= (int) (zElement.x*m_fZoom - SELECTION_BUFFER) &&
nX <= (int) (zElement.x*m_fZoom + zElement.width*m_fZoom + SELECTION_BUFFER)) &&
(nY >= (int) (zElement.y*m_fZoom - SELECTION_BUFFER) &&
nY <= (int) (zElement.y*m_fZoom + zElement.height*m_fZoom + SELECTION_BUFFER))
|| m_eMouseMode == MouseMode.Rotate)
{
// Setup the start position and allow movement
var nXUnzoomed = (int) ((float) nX*m_fZoomRatio);
var nYUnzoomed = (int) ((float) nY*m_fZoomRatio);
// store the offset in "normal" size
m_bElementSelected = true;
m_zSelectedElement = zElement;
m_listSelectedElements = ElementManager.Instance.SelectedElements;
if (null != m_listSelectedElements)
{
m_listSelectedOriginalPosition = new List<Point>();
m_listSelectedOriginalRotation = new List<float>();
foreach (var zSelectedElement in m_listSelectedElements)
{
m_listSelectedOriginalPosition.Add(new Point(
nXUnzoomed - zSelectedElement.x,
nYUnzoomed - zSelectedElement.y));
m_listSelectedOriginalRotation.Add(zSelectedElement.rotation);
}
// setup the undo dictionary (covers all types of changes allowed with canvas mouse movement)
m_dictionarySelectedUndo = ElementManager.Instance.GetUndoRedoPoints();
}
}
}
}
if (MouseButtons.Middle == e.Button)
{
//initiate panning
m_pointOriginalMouseDown = e.Location;
}
}
private void numericUpDownZoom_ValueChanged(object sender, EventArgs e)
{
if (LayoutManager.Instance.ActiveDeck == null)
{
return;
}
m_fZoom = (float)numericUpDownZoom.Value;
m_fZoomRatio = 1.0f / m_fZoom;
TranslationLockState = TranslationLock.Unset;
m_zCardCanvas.CardRenderer.ZoomLevel = m_fZoom;
LayoutManager.Instance.ActiveDeck.ResetDeckCache();
m_zCardCanvas.UpdateSize();
m_zCardCanvas.Invalidate();
}
#endregion
/// <summary>
/// Invalidates the panel and card canvas
/// </summary>
private void Redraw()
{
panelCardCanvas.Invalidate();
m_zCardCanvas.Invalidate();
}
private bool ResizeRight(int nX)
{
int nWidth = (int)((float)nX * m_fZoomRatio) - m_zSelectedElement.x;
if (1 <= nWidth)
{
m_zSelectedElement.width = nWidth;
return true;
}
return false;
}
private bool ResizeLeft(int nX)
{
int nWidth = m_zSelectedElement.width + (m_zSelectedElement.x - (int)((float)nX * m_fZoomRatio));
if ((0 <= nX) && (1 <= nWidth))
{
m_zSelectedElement.width = nWidth;
m_zSelectedElement.x = (int)((float)nX * m_fZoomRatio);
return true;
}
return false;
}
private bool ResizeUp(int nY)
{
int nHeight = m_zSelectedElement.height + (m_zSelectedElement.y - (int)((float)nY * m_fZoomRatio));
if ((0 <= nY) && (1 <= nHeight))
{
m_zSelectedElement.height = nHeight;
m_zSelectedElement.y = (int)((float)nY * m_fZoomRatio);
return true;
}
return false;
}
private bool ResizeDown(int nY)
{
int nHeight = (int)((float)nY * m_fZoomRatio) - m_zSelectedElement.y;
if (1 <= nHeight)
{
m_zSelectedElement.height = nHeight;
return true;
}
return false;
}
private void TriggerMouseMoveAtMouseLocation()
{
var pLocation = panelCardCanvas.PointToClient(Cursor.Position);
cardCanvas_MouseMoveGeneralMode(null, new MouseEventArgs(MouseButtons.None, 0, pLocation.X, pLocation.Y, 0));
}
private void ChangeMouseMode(MouseMode eDestinationMode)
{
if (eDestinationMode == m_eMouseMode)
{
return;
}
m_eMouseMode = eDestinationMode;
switch (m_eMouseMode)
{
case MouseMode.Move:
Text = "Canvas [Mode: Move-only]";
TriggerMouseMoveAtMouseLocation();
break;
case MouseMode.MoveResize:
Text = "Canvas [Mode: Normal]";
TriggerMouseMoveAtMouseLocation();
break;
case MouseMode.Rotate:
Text = "Canvas [Mode: Rotate-only]";
Cursor = new Cursor(Properties.Resources.RotateCursor.Handle);
break;
}
}
private void verticalCenterButton_Click(object sender, EventArgs e)
{
var listSelectedElements = ElementManager.Instance.SelectedElements;
if (listSelectedElements == null || listSelectedElements.Count == 0)
{
return;
}
var zLayout = LayoutManager.Instance.ActiveLayout;
var dictionaryOriginalPositions = ElementManager.Instance.GetUndoRedoPoints();
foreach (var zElement in ElementManager.Instance.SelectedElements)
{
zElement.y = (zLayout.height - zElement.height) / 2;
}
ElementManager.Instance.ConfigureUserAction(dictionaryOriginalPositions,
ElementManager.Instance.GetUndoRedoPoints());
ElementManager.Instance.FireElementBoundsUpdateEvent();
}
private void horizontalCenterButton_Click(object sender, EventArgs e)
{
var listSelectedElements = ElementManager.Instance.SelectedElements;
if (listSelectedElements == null || listSelectedElements.Count == 0)
{
return;
}
var zLayout = LayoutManager.Instance.ActiveLayout;
var dictionaryOriginalPositions = ElementManager.Instance.GetUndoRedoPoints();
foreach (var zElement in ElementManager.Instance.SelectedElements)
{
zElement.x = (zLayout.width - zElement.width) / 2;
}
ElementManager.Instance.ConfigureUserAction(dictionaryOriginalPositions,
ElementManager.Instance.GetUndoRedoPoints());
ElementManager.Instance.FireElementBoundsUpdateEvent();
}
private void customAlignElementButton_Click(object sender, EventArgs e)
{
var listSelectedElements = ElementManager.Instance.SelectedElements;
if (listSelectedElements == null || listSelectedElements.Count == 0)
{
return;
}
const string VERTICAL_SPACING = "vertical_spacing";
const string APPLY_ELEMENT_WIDTHS = "apply_element_widths";
const string HORIZONTAL_SPACING = "horizontal_spacing";
const string APPLY_ELEMENT_HEIGHTS = "apply_element_heights";
var zQuery = new QueryPanelDialog("Custom Align Elements", 450, 150, false);
zQuery.SetIcon(CardMakerInstance.ApplicationIcon);
zQuery.AddNumericBox("Vertical Pixel Spacing", 0, int.MinValue, int.MaxValue, VERTICAL_SPACING);
zQuery.AddCheckBox("Include Element Heights", false, APPLY_ELEMENT_HEIGHTS);
zQuery.AddNumericBox("Horizontal Pixel Spacing", 0, int.MinValue, int.MaxValue, HORIZONTAL_SPACING);
zQuery.AddCheckBox("Include Element Widths", false, APPLY_ELEMENT_WIDTHS);
if (DialogResult.OK != zQuery.ShowDialog(CardMakerInstance.ApplicationForm))
{
return;
}
var nVerticalSpace = (int)zQuery.GetDecimal(VERTICAL_SPACING);
var nHorizontalSpace = (int)zQuery.GetDecimal(HORIZONTAL_SPACING);
var bApplyElementWidths = zQuery.GetBool(APPLY_ELEMENT_WIDTHS);
var bApplyElementHeights = zQuery.GetBool(APPLY_ELEMENT_HEIGHTS);
var dictionaryOriginalPositions = ElementManager.Instance.GetUndoRedoPoints();
// apply the translation
var nX = listSelectedElements[0].x;
var nY = listSelectedElements[0].y;
foreach (var zElement in listSelectedElements)
{
zElement.x = nX;
zElement.y = nY;
nX += bApplyElementWidths ? zElement.width : 0;
nY += bApplyElementHeights ? zElement.height : 0;
nX += nHorizontalSpace;
nY += nVerticalSpace;
}
ElementManager.Instance.ConfigureUserAction(dictionaryOriginalPositions,
ElementManager.Instance.GetUndoRedoPoints());
ElementManager.Instance.FireElementBoundsUpdateEvent();
}
private void customVerticalAlignButton_Click(object sender, EventArgs e)
{
var listSelectedElements = ElementManager.Instance.SelectedElements;
if (listSelectedElements == null || listSelectedElements.Count == 0)
{
return;
}
const string VERTICAL_SPACING = "vertical_spacing";
const string APPLY_ELEMENT_HEIGHTS = "apply_element_heights";
const string ELEMENT_CENTERING = "element_centering";
var zQuery = new QueryPanelDialog("Custom Vertical Align Elements", 450, 150, false);
zQuery.SetIcon(CardMakerInstance.ApplicationIcon);
zQuery.AddNumericBox("Vertical Pixel Spacing", 0, int.MinValue, int.MaxValue, VERTICAL_SPACING);
zQuery.AddCheckBox("Include Element Heights", false, APPLY_ELEMENT_HEIGHTS);
zQuery.AddPullDownBox("Horizontal Centering", Enum.GetNames(typeof (ElementCenterAlign)), 0,
ELEMENT_CENTERING);
if (DialogResult.OK != zQuery.ShowDialog(CardMakerInstance.ApplicationForm))
{
return;
}
var nVerticalSpace = (int)zQuery.GetDecimal(VERTICAL_SPACING);
var bApplyElementHeights = zQuery.GetBool(APPLY_ELEMENT_HEIGHTS);
var eCenterAlignment = (ElementCenterAlign) zQuery.GetIndex(ELEMENT_CENTERING);
// determine the centering
var nCenterX = 0;
switch (eCenterAlignment)
{
case ElementCenterAlign.FirstElement:
nCenterX = listSelectedElements[0].x + (listSelectedElements[0].width/2);
break;
case ElementCenterAlign.Layout:
nCenterX = LayoutManager.Instance.ActiveLayout.width / 2;
break;
}
// apply the translation
var dictionaryOriginalPositions = ElementManager.Instance.GetUndoRedoPoints();
var nY = listSelectedElements[0].y;
for (var nIdx = 0; nIdx < listSelectedElements.Count; nIdx++)
{
var zElement = listSelectedElements[nIdx];
zElement.y = nY;
nY += bApplyElementHeights ? zElement.height : 0;
nY += nVerticalSpace;
switch (eCenterAlignment)
{
case ElementCenterAlign.FirstElement:
if (0 < nIdx)
{
zElement.x = nCenterX - (zElement.width / 2);
}
break;
case ElementCenterAlign.Layout:
zElement.x = nCenterX - (zElement.width / 2);
break;
}
}
ElementManager.Instance.ConfigureUserAction(dictionaryOriginalPositions,
ElementManager.Instance.GetUndoRedoPoints());
ElementManager.Instance.FireElementBoundsUpdateEvent();
}
private void customHoritonalAlignButton_Click(object sender, EventArgs e)
{
var listSelectedElements = ElementManager.Instance.SelectedElements;
if (listSelectedElements == null || listSelectedElements.Count == 0)
{
return;
}
const string HORIZONTAL_SPACING = "horizontal_spacing";
const string APPLY_ELEMENT_WIDTHS = "apply_element_widths";
const string ELEMENT_CENTERING = "element_centering";
var zQuery = new QueryPanelDialog("Custom Horizontal Align Elements", 450, 150, false);
zQuery.SetIcon(CardMakerInstance.ApplicationIcon);
zQuery.AddNumericBox("Horizontal Pixel Spacing", 0, int.MinValue, int.MaxValue, HORIZONTAL_SPACING);
zQuery.AddCheckBox("Include Element Widths", false, APPLY_ELEMENT_WIDTHS);
zQuery.AddPullDownBox("Vertical Centering", Enum.GetNames(typeof(ElementCenterAlign)), 0,
ELEMENT_CENTERING);
if (DialogResult.OK != zQuery.ShowDialog(CardMakerInstance.ApplicationForm))
{
return;
}
var nHorizontalSpace = (int)zQuery.GetDecimal(HORIZONTAL_SPACING);
var bApplyElementWidths = zQuery.GetBool(APPLY_ELEMENT_WIDTHS);
var eCenterAlignment = (ElementCenterAlign)zQuery.GetIndex(ELEMENT_CENTERING);
// determine the centering
var nCenterY = 0;
switch (eCenterAlignment)
{
case ElementCenterAlign.FirstElement:
nCenterY = listSelectedElements[0].y + (listSelectedElements[0].height / 2);
break;
case ElementCenterAlign.Layout:
nCenterY = LayoutManager.Instance.ActiveLayout.height / 2;
break;
}
var dictionaryOriginalPositions = ElementManager.Instance.GetUndoRedoPoints();
// apply the translation
var nX = listSelectedElements[0].x;
for (var nIdx = 0; nIdx < listSelectedElements.Count; nIdx++)
{
var zElement = listSelectedElements[nIdx];
zElement.x = nX;
nX += bApplyElementWidths ? zElement.width : 0;
nX += nHorizontalSpace;
switch (eCenterAlignment)
{
case ElementCenterAlign.FirstElement:
if (0 < nIdx)
{
zElement.y = nCenterY - (zElement.width / 2);
}
break;
case ElementCenterAlign.Layout:
zElement.y = nCenterY - (zElement.width / 2);
break;
}
}
ElementManager.Instance.ConfigureUserAction(dictionaryOriginalPositions,
ElementManager.Instance.GetUndoRedoPoints());
ElementManager.Instance.FireElementBoundsUpdateEvent();
}
}
}
| |
namespace Gu.Wpf.NumericInput
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
/// <summary>
/// DependencyProperties for <see cref="BaseBox"/>
/// </summary>
public abstract partial class BaseBox
{
private static readonly DependencyPropertyKey HasFormattedViewPropertyKey = DependencyProperty.RegisterReadOnly(
nameof(HasFormattedView),
typeof(bool),
typeof(BaseBox),
new PropertyMetadata(default(bool)));
/// <summary>Identifies the <see cref="HasFormattedView"/> dependency property.</summary>
public static readonly DependencyProperty HasFormattedViewProperty = HasFormattedViewPropertyKey.DependencyProperty;
/// <summary>Identifies the <see cref="TextValueConverter"/> dependency property.</summary>
public static readonly DependencyProperty TextValueConverterProperty = DependencyProperty.Register(
nameof(TextValueConverter),
typeof(IValueConverter),
typeof(BaseBox),
new PropertyMetadata(default(IValueConverter), OnTextValueConverterChanged));
/// <summary>Identifies the <see cref="ValidationTrigger"/> dependency property.</summary>
public static readonly DependencyProperty ValidationTriggerProperty = NumericBox.ValidationTriggerProperty.AddOwner(
typeof(BaseBox),
new FrameworkPropertyMetadata(ValidationTrigger.LostFocus, FrameworkPropertyMetadataOptions.Inherits, OnValidationTriggerChanged));
/// <summary>Identifies the <see cref="ValidationRules"/> dependency property.</summary>
public static readonly DependencyProperty ValidationRulesProperty = DependencyProperty.Register(
nameof(ValidationRules),
typeof(IReadOnlyList<ValidationRule>),
typeof(BaseBox),
new PropertyMetadata(default(IReadOnlyList<ValidationRule>), OnValidationRulesChanged));
private static readonly DependencyPropertyKey FormattedTextPropertyKey = DependencyProperty.RegisterReadOnly(
nameof(FormattedText),
typeof(string),
typeof(BaseBox),
new PropertyMetadata(default(string)));
/// <summary>Identifies the <see cref="FormattedText"/> dependency property.</summary>
public static readonly DependencyProperty FormattedTextProperty = FormattedTextPropertyKey.DependencyProperty;
private static readonly DependencyPropertyKey IsValidationDirtyPropertyKey = DependencyProperty.RegisterReadOnly(
nameof(IsValidationDirty),
typeof(bool),
typeof(BaseBox),
new PropertyMetadata(
BooleanBoxes.False,
OnIsValidationDirtyChanged));
/// <summary>Identifies the <see cref="IsValidationDirty"/> dependency property.</summary>
internal static readonly DependencyProperty IsValidationDirtyProperty = IsValidationDirtyPropertyKey.DependencyProperty;
private static readonly DependencyPropertyKey IsFormattingDirtyPropertyKey = DependencyProperty.RegisterReadOnly(
nameof(IsFormattingDirty),
typeof(bool),
typeof(BaseBox),
new PropertyMetadata(
BooleanBoxes.False,
OnIsFormattingDirtyChanged));
/// <summary>Identifies the <see cref="IsFormattingDirty"/> dependency property.</summary>
internal static readonly DependencyProperty IsFormattingDirtyProperty = IsFormattingDirtyPropertyKey.DependencyProperty;
/// <summary>Identifies the <see cref="StringFormat"/> dependency property.</summary>
public static readonly DependencyProperty StringFormatProperty = NumericBox.StringFormatProperty.AddOwner(
typeof(BaseBox),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.Inherits, OnStringFormatChanged));
/// <summary>Identifies the <see cref="Culture"/> dependency property.</summary>
public static readonly DependencyProperty CultureProperty = NumericBox.CultureProperty.AddOwner(
typeof(BaseBox),
new FrameworkPropertyMetadata(
CultureInfo.CurrentUICulture,
FrameworkPropertyMetadataOptions.Inherits,
OnCultureChanged));
/// <summary>Identifies the <see cref="RegexPattern"/> dependency property.</summary>
public static readonly DependencyProperty RegexPatternProperty = DependencyProperty.Register(
nameof(RegexPattern),
typeof(string),
typeof(BaseBox),
new PropertyMetadata(default(string), OnRegexPatternChanged));
/// <summary>Identifies the <see cref="TextSource"/> dependency property.</summary>
protected static readonly DependencyPropertyKey TextSourcePropertyKey = DependencyProperty.RegisterReadOnly(
nameof(TextSource),
typeof(TextSource),
typeof(BaseBox),
new PropertyMetadata(TextSource.None, OnTextSourceChanged));
/// <summary>Identifies the <see cref="TextSource"/> dependency property.</summary>
public static readonly DependencyProperty TextSourceProperty = TextSourcePropertyKey.DependencyProperty;
/// <summary>Identifies the <see cref="Status"/> dependency property.</summary>
internal static readonly DependencyPropertyKey StatusPropertyKey = DependencyProperty.RegisterReadOnly(
nameof(Status),
typeof(Status),
typeof(BaseBox),
new PropertyMetadata(Status.Idle, OnStatusChanged));
/// <summary>Identifies the <see cref="Status"/> dependency property.</summary>
internal static readonly DependencyProperty StatusProperty = StatusPropertyKey.DependencyProperty;
static BaseBox()
{
TextProperty.OverrideMetadataWithOptions(typeof(BaseBox), FrameworkPropertyMetadataOptions.NotDataBindable);
DefaultStyleKeyProperty.OverrideMetadata(typeof(BaseBox), new FrameworkPropertyMetadata(typeof(BaseBox)));
}
[Category(nameof(NumericBox))]
[Browsable(true)]
public bool HasFormattedView
{
get => (bool)this.GetValue(HasFormattedViewProperty);
protected internal set => this.SetValue(HasFormattedViewPropertyKey, value);
}
public IValueConverter TextValueConverter
{
get => (IValueConverter)this.GetValue(TextValueConverterProperty);
set => this.SetValue(TextValueConverterProperty, value);
}
/// <summary>
/// Gets or sets a value indicating when validation is performed, the default is LostFocus to be consistent with vanilla WPF TextBox
/// Setting ValidationTrigger="PropertyChanged" validates as you type even if the binding has UpdateSourceTrigger=LostFocus.
/// Inherits so can be set on for example a Window.
/// </summary>
public ValidationTrigger ValidationTrigger
{
get => (ValidationTrigger)this.GetValue(ValidationTriggerProperty);
set => this.SetValue(ValidationTriggerProperty, value);
}
public IReadOnlyList<ValidationRule> ValidationRules
{
get => (IReadOnlyList<ValidationRule>)this.GetValue(ValidationRulesProperty);
set => this.SetValue(ValidationRulesProperty, value);
}
[Category(nameof(NumericBox))]
[Browsable(true)]
public string FormattedText
{
get => (string)this.GetValue(FormattedTextProperty);
protected set => this.SetValue(FormattedTextPropertyKey, value);
}
internal bool IsFormattingDirty
{
get => (bool)this.GetValue(IsFormattingDirtyProperty);
set => this.SetValue(IsFormattingDirtyPropertyKey, value ? BooleanBoxes.True : BooleanBoxes.False);
}
internal bool IsValidationDirty
{
get => (bool)this.GetValue(IsValidationDirtyProperty);
set => this.SetValue(IsValidationDirtyPropertyKey, value ? BooleanBoxes.True : BooleanBoxes.False);
}
/// <summary>
/// Gets or sets the culture for the control.
/// The control has an explicit culture and does not use <see cref="System.Threading.Thread.CurrentUICulture"/>
/// </summary>
[Category(nameof(NumericBox))]
[Browsable(true)]
[TypeConverter(typeof(CultureInfoConverter))]
public IFormatProvider Culture
{
get => (IFormatProvider)this.GetValue(CultureProperty);
set => this.SetValue(CultureProperty, value);
}
[Category(nameof(NumericBox))]
[Browsable(true)]
public string StringFormat
{
get => (string)this.GetValue(StringFormatProperty);
set => this.SetValue(StringFormatProperty, value);
}
/// <summary>
/// Gets or sets a regex pattern for validation
/// </summary>
[Category(nameof(NumericBox))]
[Browsable(true)]
public string RegexPattern
{
get => (string)this.GetValue(RegexPatternProperty);
set => this.SetValue(RegexPatternProperty, value);
}
public TextSource TextSource
{
get => (TextSource)this.GetValue(TextSourceProperty);
protected set => this.SetValue(TextSourcePropertyKey, value);
}
internal Status Status
{
get => (Status)this.GetValue(StatusProperty);
set => this.SetValue(StatusPropertyKey, value);
}
private static void OnIsValidationDirtyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine(e);
var box = (BaseBox)d;
if (box.TextSource != TextSource.None && Equals(e.NewValue, BooleanBoxes.True))
{
box.RaiseEvent(ValidationDirtyEventArgs);
}
}
private static void OnIsFormattingDirtyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine(e);
if (Equals(e.NewValue, BooleanBoxes.True))
{
((BaseBox)d).RaiseEvent(FormatDirtyEventArgs);
}
}
private static void OnTextValueConverterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var box = (BaseBox)d;
if (box.TextSource != TextSource.None)
{
box.IsFormattingDirty = true;
box.IsValidationDirty = true;
}
}
private static void OnValidationTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var box = (BaseBox)d;
if (box.TextSource != TextSource.None)
{
switch ((ValidationTrigger)e.NewValue)
{
case ValidationTrigger.PropertyChanged:
box.UpdateValidation();
break;
case ValidationTrigger.LostFocus:
if (box.IsKeyboardFocused)
{
box.IsValidationDirty = true;
}
else
{
box.UpdateValidation();
}
break;
case ValidationTrigger.Explicit:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
private static void OnValidationRulesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var box = (BaseBox)d;
if (box.TextSource != TextSource.None)
{
box.IsValidationDirty = true;
}
}
private static void OnStringFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var box = (BaseBox)d;
if (box.TextSource != TextSource.None)
{
box.OnStringFormatChanged((string)e.OldValue, (string)e.NewValue);
box.IsFormattingDirty = true;
box.IsValidationDirty = true;
}
}
private static void OnCultureChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var box = (BaseBox)d;
if (box.TextSource != TextSource.None)
{
box.OnCultureChanged((IFormatProvider)e.OldValue, (IFormatProvider)e.NewValue);
box.IsFormattingDirty = true;
box.IsValidationDirty = true;
}
}
private static void OnRegexPatternChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var box = (BaseBox)d;
if (box.TextSource != TextSource.None)
{
box.IsValidationDirty = true;
}
}
private static void OnStatusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine(e);
}
private static void OnTextSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine(e);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ARPrestoCallbackManager.cs" company="Google LLC">
//
// Copyright 2018 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCoreInternal
{
using System;
using System.Collections.Generic;
using GoogleARCore;
using UnityEngine;
#if UNITY_IOS && !UNITY_EDITOR
using AndroidImport = GoogleARCoreInternal.DllImportNoop;
using IOSImport = System.Runtime.InteropServices.DllImportAttribute;
#else
using AndroidImport = System.Runtime.InteropServices.DllImportAttribute;
using IOSImport = GoogleARCoreInternal.DllImportNoop;
#endif
internal class ARPrestoCallbackManager
{
private static ARPrestoCallbackManager s_Instance;
private static IAndroidPermissionsCheck s_AndroidPermissionCheck;
private CheckApkAvailabilityResultCallback m_CheckApkAvailabilityResultCallback;
private RequestApkInstallationResultCallback m_RequestApkInstallationResultCallback;
private CameraPermissionRequestProvider m_RequestCameraPermissionCallback;
private EarlyUpdateCallback m_EarlyUpdateCallback;
private OnBeforeSetConfigurationCallback m_OnBeforeSetConfigurationCallback;
private OnBeforeResumeSessionCallback m_OnBeforeResumeSessionCallback;
private List<Action<ApkAvailabilityStatus>> m_PendingAvailabilityCheckCallbacks =
new List<Action<ApkAvailabilityStatus>>();
private List<Action<ApkInstallationStatus>> m_PendingInstallationRequestCallbacks =
new List<Action<ApkInstallationStatus>>();
public delegate void EarlyUpdateCallback();
private delegate void OnBeforeSetConfigurationCallback(
IntPtr sessionHandle, IntPtr configHandle);
private delegate void OnBeforeResumeSessionCallback(IntPtr sessionHandle);
private delegate void CameraPermissionRequestProvider(
CameraPermissionsResultCallback onComplete, IntPtr context);
private delegate void CameraPermissionsResultCallback(bool granted,
IntPtr context);
private delegate void CheckApkAvailabilityResultCallback(ApiAvailability status,
IntPtr context);
private delegate void RequestApkInstallationResultCallback(
ApiApkInstallationStatus status, IntPtr context);
private delegate void SessionCreationResultCallback(
IntPtr sessionHandle, IntPtr frameHandle, IntPtr context, ApiArStatus status);
public event Action EarlyUpdate;
public event Action<IntPtr> BeforeResumeSession;
public event Action<IntPtr, IntPtr> OnSetConfiguration;
public static ARPrestoCallbackManager Instance
{
get
{
if (s_Instance == null)
{
if (s_AndroidPermissionCheck == null &&
!InstantPreviewManager.IsProvidingPlatform)
{
s_AndroidPermissionCheck = AndroidPermissionsManager.GetInstance();
}
s_Instance = new ARPrestoCallbackManager();
s_Instance._Initialize();
}
return s_Instance;
}
}
public AsyncTask<ApkAvailabilityStatus> CheckApkAvailability()
{
Action<ApkAvailabilityStatus> onComplete;
AsyncTask<ApkAvailabilityStatus> task =
new AsyncTask<ApkAvailabilityStatus>(out onComplete);
if (InstantPreviewManager.IsProvidingPlatform)
{
InstantPreviewManager.LogLimitedSupportMessage("determine ARCore APK " +
"availability");
return task;
}
ExternApi.ArPresto_checkApkAvailability(m_CheckApkAvailabilityResultCallback,
IntPtr.Zero);
m_PendingAvailabilityCheckCallbacks.Add(onComplete);
return task;
}
public AsyncTask<ApkInstallationStatus> RequestApkInstallation(bool userRequested)
{
Action<ApkInstallationStatus> onComplete;
AsyncTask<ApkInstallationStatus> task =
new AsyncTask<ApkInstallationStatus>(out onComplete);
if (InstantPreviewManager.IsProvidingPlatform)
{
InstantPreviewManager.LogLimitedSupportMessage("request installation of ARCore " +
"APK");
return task;
}
ExternApi.ArPresto_requestApkInstallation(userRequested,
m_RequestApkInstallationResultCallback, IntPtr.Zero);
m_PendingInstallationRequestCallbacks.Add(onComplete);
return task;
}
internal static void ResetInstance()
{
s_Instance = null;
s_AndroidPermissionCheck = null;
}
internal static void SetAndroidPermissionCheck(
IAndroidPermissionsCheck androidPermissionsCheck)
{
s_AndroidPermissionCheck = androidPermissionsCheck;
}
[AOT.MonoPInvokeCallback(typeof(CheckApkAvailabilityResultCallback))]
private static void _OnCheckApkAvailabilityResultTrampoline(
ApiAvailability status, IntPtr context)
{
Instance._OnCheckApkAvailabilityResult(status.ToApkAvailabilityStatus());
}
[AOT.MonoPInvokeCallback(typeof(RequestApkInstallationResultCallback))]
private static void _OnApkInstallationResultTrampoline(
ApiApkInstallationStatus status, IntPtr context)
{
Instance._OnRequestApkInstallationResult(status.ToApkInstallationStatus());
}
[AOT.MonoPInvokeCallback(typeof(CameraPermissionRequestProvider))]
private static void _RequestCameraPermissionTrampoline(
CameraPermissionsResultCallback onComplete, IntPtr context)
{
Instance._RequestCameraPermission(onComplete, context);
}
[AOT.MonoPInvokeCallback(typeof(EarlyUpdateCallback))]
private static void _EarlyUpdateTrampoline()
{
if (Instance.EarlyUpdate != null)
{
Instance.EarlyUpdate();
}
}
[AOT.MonoPInvokeCallback(typeof(OnBeforeSetConfigurationCallback))]
private static void _BeforeSetConfigurationTrampoline(
IntPtr sessionHandle, IntPtr configHandle)
{
if (Instance.OnSetConfiguration != null)
{
Instance.OnSetConfiguration(sessionHandle, configHandle);
}
}
[AOT.MonoPInvokeCallback(typeof(OnBeforeResumeSessionCallback))]
private static void _BeforeResumeSessionTrampoline(IntPtr sessionHandle)
{
if (Instance.BeforeResumeSession != null)
{
Instance.BeforeResumeSession(sessionHandle);
}
}
private void _Initialize()
{
m_EarlyUpdateCallback = new EarlyUpdateCallback(_EarlyUpdateTrampoline);
if (InstantPreviewManager.IsProvidingPlatform)
{
// Instant preview does not support updated function signature returning 'bool'.
ExternApi.ArCoreUnity_setArPrestoInitialized(m_EarlyUpdateCallback);
}
else if (!ExternApi.ArCoreUnity_setArPrestoInitialized(m_EarlyUpdateCallback))
{
Debug.LogError(
"Missing Unity Engine ARCore support. Please ensure that the Unity project " +
"has the 'Player Settings > XR Settings > ARCore Supported' checkbox enabled.");
}
IntPtr javaVMHandle = IntPtr.Zero;
IntPtr activityHandle = IntPtr.Zero;
ExternApi.ArCoreUnity_getJniInfo(ref javaVMHandle, ref activityHandle);
m_CheckApkAvailabilityResultCallback =
new CheckApkAvailabilityResultCallback(_OnCheckApkAvailabilityResultTrampoline);
m_RequestApkInstallationResultCallback =
new RequestApkInstallationResultCallback(_OnApkInstallationResultTrampoline);
m_RequestCameraPermissionCallback =
new CameraPermissionRequestProvider(_RequestCameraPermissionTrampoline);
m_OnBeforeSetConfigurationCallback =
new OnBeforeSetConfigurationCallback(_BeforeSetConfigurationTrampoline);
m_OnBeforeResumeSessionCallback =
new OnBeforeResumeSessionCallback(_BeforeResumeSessionTrampoline);
ExternApi.ArPresto_initialize(
javaVMHandle, activityHandle, m_RequestCameraPermissionCallback,
m_OnBeforeSetConfigurationCallback, m_OnBeforeResumeSessionCallback);
}
private void _OnCheckApkAvailabilityResult(ApkAvailabilityStatus status)
{
foreach (var onComplete in m_PendingAvailabilityCheckCallbacks)
{
onComplete(status);
}
m_PendingAvailabilityCheckCallbacks.Clear();
}
private void _OnRequestApkInstallationResult(ApkInstallationStatus status)
{
foreach (var onComplete in m_PendingInstallationRequestCallbacks)
{
onComplete(status);
}
m_PendingInstallationRequestCallbacks.Clear();
}
private void _RequestCameraPermission(CameraPermissionsResultCallback onComplete,
IntPtr context)
{
const string cameraPermissionName = "android.permission.CAMERA";
if (s_AndroidPermissionCheck != null)
{
s_AndroidPermissionCheck.RequestAndroidPermission(cameraPermissionName)
.ThenAction((grantResult) =>
{
onComplete(grantResult.IsAllGranted, context);
});
}
}
private struct ExternApi
{
#pragma warning disable 626
[AndroidImport(ApiConstants.ARCoreShimApi)]
public static extern void ArCoreUnity_getJniInfo(
ref IntPtr javaVM, ref IntPtr activity);
[AndroidImport(ApiConstants.ARCoreShimApi)]
public static extern bool ArCoreUnity_setArPrestoInitialized(
EarlyUpdateCallback onEarlyUpdate);
[AndroidImport(ApiConstants.ARPrestoApi)]
public static extern void ArPresto_initialize(
IntPtr javaVM, IntPtr activity,
CameraPermissionRequestProvider requestCameraPermission,
OnBeforeSetConfigurationCallback onBeforeSetConfiguration,
OnBeforeResumeSessionCallback onBeforeResumeSession);
[AndroidImport(ApiConstants.ARPrestoApi)]
public static extern void ArPresto_checkApkAvailability(
CheckApkAvailabilityResultCallback onResult, IntPtr context);
[AndroidImport(ApiConstants.ARPrestoApi)]
public static extern void ArPresto_requestApkInstallation(
bool user_requested, RequestApkInstallationResultCallback onResult, IntPtr context);
#pragma warning restore 626
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
{
[ComVisible(true)]
[ComDefaultInterface(typeof(EnvDTE.CodeFunction))]
public sealed partial class CodeAccessorFunction : AbstractCodeElement, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2
{
internal static EnvDTE.CodeFunction Create(CodeModelState state, AbstractCodeMember parent, MethodKind kind)
{
var newElement = new CodeAccessorFunction(state, parent, kind);
return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(newElement);
}
private readonly ParentHandle<AbstractCodeMember> _parentHandle;
private readonly MethodKind _kind;
private CodeAccessorFunction(CodeModelState state, AbstractCodeMember parent, MethodKind kind)
: base(state, parent.FileCodeModel)
{
Debug.Assert(kind == MethodKind.EventAdd ||
kind == MethodKind.EventRaise ||
kind == MethodKind.EventRemove ||
kind == MethodKind.PropertyGet ||
kind == MethodKind.PropertySet);
_parentHandle = new ParentHandle<AbstractCodeMember>(parent);
_kind = kind;
}
private AbstractCodeMember ParentMember
{
get { return _parentHandle.Value; }
}
private bool IsPropertyAccessor()
{
return _kind == MethodKind.PropertyGet || _kind == MethodKind.PropertySet;
}
internal override SyntaxNode LookupNode()
{
var parentNode = _parentHandle.Value.LookupNode();
if (parentNode == null)
{
throw Exceptions.ThrowEFail();
}
SyntaxNode accessorNode;
if (!CodeModelService.TryGetAccessorNode(parentNode, _kind, out accessorNode))
{
throw Exceptions.ThrowEFail();
}
return accessorNode;
}
public override EnvDTE.vsCMElement Kind
{
get { return EnvDTE.vsCMElement.vsCMElementFunction; }
}
public override object Parent
{
get { return _parentHandle.Value; }
}
public override EnvDTE.CodeElements Children
{
get { return EmptyCollection.Create(this.State, this); }
}
protected override string GetName()
{
return this.ParentMember.Name;
}
protected override void SetName(string value)
{
this.ParentMember.Name = value;
}
protected override string GetFullName()
{
return this.ParentMember.FullName;
}
public EnvDTE.CodeElements Attributes
{
get { return EmptyCollection.Create(this.State, this); }
}
public EnvDTE.vsCMAccess Access
{
get
{
var node = LookupNode();
return CodeModelService.GetAccess(node);
}
set
{
UpdateNode(FileCodeModel.UpdateAccess, value);
}
}
public bool CanOverride
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
public string Comment
{
get
{
throw Exceptions.ThrowEFail();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public string DocComment
{
get
{
return string.Empty;
}
set
{
throw Exceptions.ThrowENotImpl();
}
}
public EnvDTE.vsCMFunction FunctionKind
{
get
{
// TODO: What does VB do here? Handle EventRaise...
switch (_kind)
{
case MethodKind.PropertyGet:
case MethodKind.EventRemove:
return EnvDTE.vsCMFunction.vsCMFunctionPropertyGet;
case MethodKind.PropertySet:
case MethodKind.EventAdd:
return EnvDTE.vsCMFunction.vsCMFunctionPropertySet;
default:
throw Exceptions.ThrowEUnexpected();
}
}
}
public bool IsGeneric
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).IsGeneric;
}
else
{
return ((CodeEvent)this.ParentMember).IsGeneric;
}
}
}
public EnvDTE80.vsCMOverrideKind OverrideKind
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).OverrideKind;
}
else
{
return ((CodeEvent)this.ParentMember).OverrideKind;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).OverrideKind = value;
}
else
{
((CodeEvent)this.ParentMember).OverrideKind = value;
}
}
}
public bool IsOverloaded
{
get { return false; }
}
public bool IsShared
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).IsShared;
}
else
{
return ((CodeEvent)this.ParentMember).IsShared;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).IsShared = value;
}
else
{
((CodeEvent)this.ParentMember).IsShared = value;
}
}
}
public bool MustImplement
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).MustImplement;
}
else
{
return ((CodeEvent)this.ParentMember).MustImplement;
}
}
set
{
if (IsPropertyAccessor())
{
((CodeProperty)this.ParentMember).MustImplement = value;
}
else
{
((CodeEvent)this.ParentMember).MustImplement = value;
}
}
}
public EnvDTE.CodeElements Overloads
{
get
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeElements Parameters
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).Parameters;
}
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeTypeRef Type
{
get
{
if (IsPropertyAccessor())
{
return ((CodeProperty)this.ParentMember).Type;
}
throw Exceptions.ThrowEFail();
}
set
{
throw Exceptions.ThrowEFail();
}
}
public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
public EnvDTE.CodeParameter AddParameter(string name, object type, object position)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
public void RemoveParameter(object element)
{
// TODO(DustinCa): Check VB
throw Exceptions.ThrowEFail();
}
}
}
| |
using System;
using OpenBveApi;
using OpenBveApi.Math;
namespace OpenBve {
internal static class AnimatedObjectParser {
// parse animated object config
/// <summary>Loads a collection of animated objects from a file.</summary>
/// <param name="FileName">The text file to load the animated object from. Must be an absolute file name.</param>
/// <param name="Encoding">The encoding the file is saved in. If the file uses a byte order mark, the encoding indicated by the byte order mark is used and the Encoding parameter is ignored.</param>
/// <param name="LoadMode">The texture load mode.</param>
/// <returns>The collection of animated objects.</returns>
internal static ObjectManager.AnimatedObjectCollection ReadObject(string FileName, System.Text.Encoding Encoding, ObjectManager.ObjectLoadMode LoadMode) {
System.Globalization.CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture;
ObjectManager.AnimatedObjectCollection Result = new ObjectManager.AnimatedObjectCollection();
Result.Objects = new ObjectManager.AnimatedObject[4];
int ObjectCount = 0;
// load file
string[] Lines = System.IO.File.ReadAllLines(FileName, Encoding);
bool rpnUsed = false;
for (int i = 0; i < Lines.Length; i++) {
int j = Lines[i].IndexOf(';');
if (j >= 0) {
Lines[i] = Lines[i].Substring(0, j).Trim();
} else {
Lines[i] = Lines[i].Trim();
}
if (Lines[i].IndexOf("functionrpn", StringComparison.OrdinalIgnoreCase) >= 0) {
rpnUsed = true;
}
}
if (rpnUsed) {
Interface.AddMessage(Interface.MessageType.Error, false, "An animated object file contains RPN functions. These were never meant to be used directly, only for debugging. They won't be supported indefinately. Please get rid of them in file " + FileName);
}
for (int i = 0; i < Lines.Length; i++) {
if (Lines[i].Length != 0) {
switch (Lines[i].ToLowerInvariant()) {
case "[include]":
{
i++;
Vector3 position = new Vector3(0.0, 0.0, 0.0);
ObjectManager.UnifiedObject[] obj = new OpenBve.ObjectManager.UnifiedObject[4];
int objCount = 0;
while (i < Lines.Length && !(Lines[i].StartsWith("[", StringComparison.Ordinal) & Lines[i].EndsWith("]", StringComparison.Ordinal))) {
if (Lines[i].Length != 0) {
int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
if (j > 0) {
string a = Lines[i].Substring(0, j).TrimEnd();
string b = Lines[i].Substring(j + 1).TrimStart();
switch (a.ToLowerInvariant()) {
case "position":
{
string[] s = b.Split(',');
if (s.Length == 3) {
double x, y, z;
if (!double.TryParse(s[0], System.Globalization.NumberStyles.Float, Culture, out x)) {
Interface.AddMessage(Interface.MessageType.Error, false, "X is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[1], System.Globalization.NumberStyles.Float, Culture, out y)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Y is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[2], System.Globalization.NumberStyles.Float, Culture, out z)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Z is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else {
position = new Vector3(x, y, z);
}
} else {
Interface.AddMessage(Interface.MessageType.Error, false, "Exactly 3 arguments are expected in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
}
} break;
default:
Interface.AddMessage(Interface.MessageType.Error, false, "The attribute " + a + " is not supported at line " + (i + 1).ToString(Culture) + " in file " + FileName);
break;
}
} else {
string Folder = System.IO.Path.GetDirectoryName(FileName);
if (Path.ContainsInvalidChars(Lines[i])) {
Interface.AddMessage(Interface.MessageType.Error, false, Lines[i] + " contains illegal characters at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else {
string file = OpenBveApi.Path.CombineFile(Folder, Lines[i]);
if (System.IO.File.Exists(file)) {
if (obj.Length == objCount) {
Array.Resize<ObjectManager.UnifiedObject>(ref obj, obj.Length << 1);
}
obj[objCount] = ObjectManager.LoadObject(file, Encoding, LoadMode, false, false, false);
objCount++;
} else {
Interface.AddMessage(Interface.MessageType.Error, true, "File " + file + " not found at line " + (i + 1).ToString(Culture) + " in file " + FileName);
}
}
}
}
i++;
}
i--;
for (int j = 0; j < objCount; j++) {
if (obj[j] != null) {
if (obj[j] is ObjectManager.StaticObject) {
ObjectManager.StaticObject s = (ObjectManager.StaticObject)obj[j];
s.Dynamic = true;
if (ObjectCount >= Result.Objects.Length) {
Array.Resize<ObjectManager.AnimatedObject>(ref Result.Objects, Result.Objects.Length << 1);
}
ObjectManager.AnimatedObject a = new ObjectManager.AnimatedObject();
ObjectManager.AnimatedObjectState aos = new ObjectManager.AnimatedObjectState();
aos.Object = s;
aos.Position = position;
a.States = new ObjectManager.AnimatedObjectState[] { aos };
Result.Objects[ObjectCount] = a;
ObjectCount++;
} else if (obj[j] is ObjectManager.AnimatedObjectCollection) {
ObjectManager.AnimatedObjectCollection a = (ObjectManager.AnimatedObjectCollection)obj[j];
for (int k = 0; k < a.Objects.Length; k++) {
if (ObjectCount >= Result.Objects.Length) {
Array.Resize<ObjectManager.AnimatedObject>(ref Result.Objects, Result.Objects.Length << 1);
}
for (int h = 0; h < a.Objects[k].States.Length; h++) {
a.Objects[k].States[h].Position.X += position.X;
a.Objects[k].States[h].Position.Y += position.Y;
a.Objects[k].States[h].Position.Z += position.Z;
}
Result.Objects[ObjectCount] = a.Objects[k];
ObjectCount++;
}
}
}
}
}
break;
case "[object]":
{
i++;
if (Result.Objects.Length == ObjectCount) {
Array.Resize<ObjectManager.AnimatedObject>(ref Result.Objects, Result.Objects.Length << 1);
}
Result.Objects[ObjectCount] = new ObjectManager.AnimatedObject();
Result.Objects[ObjectCount].States = new ObjectManager.AnimatedObjectState[] { };
Result.Objects[ObjectCount].CurrentState = -1;
Result.Objects[ObjectCount].TranslateXDirection = new Vector3(1.0, 0.0, 0.0);
Result.Objects[ObjectCount].TranslateYDirection = new Vector3(0.0, 1.0, 0.0);
Result.Objects[ObjectCount].TranslateZDirection = new Vector3(0.0, 0.0, 1.0);
Result.Objects[ObjectCount].RotateXDirection = new Vector3(1.0, 0.0, 0.0);
Result.Objects[ObjectCount].RotateYDirection = new Vector3(0.0, 1.0, 0.0);
Result.Objects[ObjectCount].RotateZDirection = new Vector3(0.0, 0.0, 1.0);
Result.Objects[ObjectCount].TextureShiftXDirection = new Vector2(1.0, 0.0);
Result.Objects[ObjectCount].TextureShiftYDirection = new Vector2(0.0, 1.0);
Result.Objects[ObjectCount].RefreshRate = 0.0;
Result.Objects[ObjectCount].ObjectIndex = -1;
Vector3 Position = new Vector3(0.0, 0.0, 0.0);
bool timetableUsed = false;
string[] StateFiles = null;
string StateFunctionRpn = null;
int StateFunctionLine = -1;
while (i < Lines.Length && !(Lines[i].StartsWith("[", StringComparison.Ordinal) & Lines[i].EndsWith("]", StringComparison.Ordinal))) {
if (Lines[i].Length != 0) {
int j = Lines[i].IndexOf("=", StringComparison.Ordinal);
if (j > 0) {
string a = Lines[i].Substring(0, j).TrimEnd();
string b = Lines[i].Substring(j + 1).TrimStart();
switch (a.ToLowerInvariant()) {
case "position":
{
string[] s = b.Split(',');
if (s.Length == 3) {
double x, y, z;
if (!double.TryParse(s[0], System.Globalization.NumberStyles.Float, Culture, out x)) {
Interface.AddMessage(Interface.MessageType.Error, false, "X is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[1], System.Globalization.NumberStyles.Float, Culture, out y)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Y is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[2], System.Globalization.NumberStyles.Float, Culture, out z)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Z is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else {
Position = new Vector3(x, y, z);
}
} else {
Interface.AddMessage(Interface.MessageType.Error, false, "Exactly 3 arguments are expected in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
}
} break;
case "states":
{
string[] s = b.Split(',');
if (s.Length >= 1) {
string Folder = System.IO.Path.GetDirectoryName(FileName);
StateFiles = new string[s.Length];
bool NullObject = true;
for (int k = 0; k < s.Length; k++) {
s[k] = s[k].Trim();
if (s[k].Length == 0) {
Interface.AddMessage(Interface.MessageType.Error, false, "File" + k.ToString(Culture) + " is an empty string - did you mean something else? - in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
StateFiles[k] = null;
} else if (Path.ContainsInvalidChars(s[k])) {
Interface.AddMessage(Interface.MessageType.Error, false, "File" + k.ToString(Culture) + " contains illegal characters in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
StateFiles[k] = null;
} else {
StateFiles[k] = OpenBveApi.Path.CombineFile(Folder, s[k]);
if (!System.IO.File.Exists(StateFiles[k])) {
Interface.AddMessage(Interface.MessageType.Error, true, "File " + StateFiles[k] + " not found in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
StateFiles[k] = null;
}
}
if (StateFiles[k] != null)
{
NullObject = false;
}
}
if (NullObject == true)
{
Interface.AddMessage(Interface.MessageType.Error, false, "No statefiles were found in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
return null;
}
} else {
Interface.AddMessage(Interface.MessageType.Error, false, "At least one argument is expected in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
return null;
}
} break;
case "statefunction":
try {
StateFunctionLine = i;
StateFunctionRpn = FunctionScripts.GetPostfixNotationFromInfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "statefunctionrpn":
{
StateFunctionLine = i;
StateFunctionRpn = b;
} break;
case "translatexdirection":
case "translateydirection":
case "translatezdirection":
{
string[] s = b.Split(',');
if (s.Length == 3) {
double x, y, z;
if (!double.TryParse(s[0], System.Globalization.NumberStyles.Float, Culture, out x)) {
Interface.AddMessage(Interface.MessageType.Error, false, "X is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[1], System.Globalization.NumberStyles.Float, Culture, out y)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Y is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[2], System.Globalization.NumberStyles.Float, Culture, out z)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Z is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else {
switch (a.ToLowerInvariant()) {
case "translatexdirection":
Result.Objects[ObjectCount].TranslateXDirection = new Vector3(x, y, z);
break;
case "translateydirection":
Result.Objects[ObjectCount].TranslateYDirection = new Vector3(x, y, z);
break;
case "translatezdirection":
Result.Objects[ObjectCount].TranslateZDirection = new Vector3(x, y, z);
break;
}
}
} else {
Interface.AddMessage(Interface.MessageType.Error, false, "Exactly 3 arguments are expected in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
}
} break;
case "translatexfunction":
try {
Result.Objects[ObjectCount].TranslateXFunction = FunctionScripts.GetFunctionScriptFromInfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "translateyfunction":
try {
Result.Objects[ObjectCount].TranslateYFunction = FunctionScripts.GetFunctionScriptFromInfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "translatezfunction":
try {
Result.Objects[ObjectCount].TranslateZFunction = FunctionScripts.GetFunctionScriptFromInfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "translatexfunctionrpn":
try {
Result.Objects[ObjectCount].TranslateXFunction = FunctionScripts.GetFunctionScriptFromPostfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "translateyfunctionrpn":
try {
Result.Objects[ObjectCount].TranslateYFunction = FunctionScripts.GetFunctionScriptFromPostfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "translatezfunctionrpn":
try {
Result.Objects[ObjectCount].TranslateZFunction = FunctionScripts.GetFunctionScriptFromPostfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "rotatexdirection":
case "rotateydirection":
case "rotatezdirection":
{
string[] s = b.Split(',');
if (s.Length == 3) {
double x, y, z;
if (!double.TryParse(s[0], System.Globalization.NumberStyles.Float, Culture, out x)) {
Interface.AddMessage(Interface.MessageType.Error, false, "X is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[1], System.Globalization.NumberStyles.Float, Culture, out y)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Y is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[2], System.Globalization.NumberStyles.Float, Culture, out z)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Z is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (x == 0.0 & y == 0.0 & z == 0.0) {
Interface.AddMessage(Interface.MessageType.Error, false, "The direction indicated by X, Y and Z is expected to be non-zero in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else {
switch (a.ToLowerInvariant()) {
case "rotatexdirection":
Result.Objects[ObjectCount].RotateXDirection = new Vector3(x, y, z);
break;
case "rotateydirection":
Result.Objects[ObjectCount].RotateYDirection = new Vector3(x, y, z);
break;
case "rotatezdirection":
Result.Objects[ObjectCount].RotateZDirection = new Vector3(x, y, z);
break;
}
}
} else {
Interface.AddMessage(Interface.MessageType.Error, false, "Exactly 3 arguments are expected in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
}
} break;
case "rotatexfunction":
try {
Result.Objects[ObjectCount].RotateXFunction = FunctionScripts.GetFunctionScriptFromInfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "rotateyfunction":
try {
Result.Objects[ObjectCount].RotateYFunction = FunctionScripts.GetFunctionScriptFromInfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "rotatezfunction":
try {
Result.Objects[ObjectCount].RotateZFunction = FunctionScripts.GetFunctionScriptFromInfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "rotatexfunctionrpn":
try {
Result.Objects[ObjectCount].RotateXFunction = FunctionScripts.GetFunctionScriptFromPostfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "rotateyfunctionrpn":
try {
Result.Objects[ObjectCount].RotateYFunction = FunctionScripts.GetFunctionScriptFromPostfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "rotatezfunctionrpn":
try {
Result.Objects[ObjectCount].RotateZFunction = FunctionScripts.GetFunctionScriptFromPostfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "rotatexdamping":
case "rotateydamping":
case "rotatezdamping":
{
string[] s = b.Split(',');
if (s.Length == 2) {
double nf, dr;
if (!double.TryParse(s[0], System.Globalization.NumberStyles.Float, Culture, out nf)) {
Interface.AddMessage(Interface.MessageType.Error, false, "NaturalFrequency is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[1], System.Globalization.NumberStyles.Float, Culture, out dr)) {
Interface.AddMessage(Interface.MessageType.Error, false, "DampingRatio is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (nf <= 0.0) {
Interface.AddMessage(Interface.MessageType.Error, false, "NaturalFrequency is expected to be positive in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (dr <= 0.0) {
Interface.AddMessage(Interface.MessageType.Error, false, "DampingRatio is expected to be positive in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else {
switch (a.ToLowerInvariant()) {
case "rotatexdamping":
Result.Objects[ObjectCount].RotateXDamping = new ObjectManager.Damping(nf, dr);
break;
case "rotateydamping":
Result.Objects[ObjectCount].RotateYDamping = new ObjectManager.Damping(nf, dr);
break;
case "rotatezdamping":
Result.Objects[ObjectCount].RotateZDamping = new ObjectManager.Damping(nf, dr);
break;
}
}
} else {
Interface.AddMessage(Interface.MessageType.Error, false, "Exactly 2 arguments are expected in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
}
} break;
case "textureshiftxdirection":
case "textureshiftydirection":
{
string[] s = b.Split(',');
if (s.Length == 2) {
double x, y;
if (!double.TryParse(s[0], System.Globalization.NumberStyles.Float, Culture, out x)) {
Interface.AddMessage(Interface.MessageType.Error, false, "X is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (!double.TryParse(s[1], System.Globalization.NumberStyles.Float, Culture, out y)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Y is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else {
switch (a.ToLowerInvariant()) {
case "textureshiftxdirection":
Result.Objects[ObjectCount].TextureShiftXDirection = new Vector2(x, y);
break;
case "textureshiftydirection":
Result.Objects[ObjectCount].TextureShiftYDirection = new Vector2(x, y);
break;
}
}
} else {
Interface.AddMessage(Interface.MessageType.Error, false, "Exactly 2 arguments are expected in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
}
} break;
case "textureshiftxfunction":
try {
Result.Objects[ObjectCount].TextureShiftXFunction = FunctionScripts.GetFunctionScriptFromInfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "textureshiftyfunction":
try {
Result.Objects[ObjectCount].TextureShiftYFunction = FunctionScripts.GetFunctionScriptFromInfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "textureshiftxfunctionrpn":
try {
Result.Objects[ObjectCount].TextureShiftXFunction = FunctionScripts.GetFunctionScriptFromPostfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "textureshiftyfunctionrpn":
try {
Result.Objects[ObjectCount].TextureShiftYFunction = FunctionScripts.GetFunctionScriptFromPostfixNotation(b);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} break;
case "textureoverride":
switch (b.ToLowerInvariant()) {
case "none":
break;
case "timetable":
if (!timetableUsed) {
Timetable.AddObjectForCustomTimetable(Result.Objects[ObjectCount]);
timetableUsed = true;
}
break;
default:
Interface.AddMessage(Interface.MessageType.Error, false, "Unrecognized value in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
break;
}
break;
case "refreshrate":
{
double r;
if (!double.TryParse(b, System.Globalization.NumberStyles.Float, Culture, out r)) {
Interface.AddMessage(Interface.MessageType.Error, false, "Value is invalid in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else if (r < 0.0) {
Interface.AddMessage(Interface.MessageType.Error, false, "Value is expected to be non-negative in " + a + " at line " + (i + 1).ToString(Culture) + " in file " + FileName);
} else {
Result.Objects[ObjectCount].RefreshRate = r;
}
} break;
default:
Interface.AddMessage(Interface.MessageType.Error, false, "The attribute " + a + " is not supported at line " + (i + 1).ToString(Culture) + " in file " + FileName);
break;
}
} else {
Interface.AddMessage(Interface.MessageType.Error, false, "Invalid statement " + Lines[i] + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
return null;
}
}
i++;
}
i--;
if (StateFiles != null) {
// create the object
if (timetableUsed) {
if (StateFunctionRpn != null) {
StateFunctionRpn = "timetable 0 == " + StateFunctionRpn + " -1 ?";
} else {
StateFunctionRpn = "timetable";
}
}
if (StateFunctionRpn != null) {
try {
Result.Objects[ObjectCount].StateFunction = FunctionScripts.GetFunctionScriptFromPostfixNotation(StateFunctionRpn);
} catch (Exception ex) {
Interface.AddMessage(Interface.MessageType.Error, false, ex.Message + " in StateFunction at line " + (StateFunctionLine + 1).ToString(Culture) + " in file " + FileName);
}
}
Result.Objects[ObjectCount].States = new ObjectManager.AnimatedObjectState[StateFiles.Length];
bool ForceTextureRepeatX = Result.Objects[ObjectCount].TextureShiftXFunction != null & Result.Objects[ObjectCount].TextureShiftXDirection.X != 0.0 |
Result.Objects[ObjectCount].TextureShiftYFunction != null & Result.Objects[ObjectCount].TextureShiftYDirection.Y != 0.0;
bool ForceTextureRepeatY = Result.Objects[ObjectCount].TextureShiftXFunction != null & Result.Objects[ObjectCount].TextureShiftXDirection.X != 0.0 |
Result.Objects[ObjectCount].TextureShiftYFunction != null & Result.Objects[ObjectCount].TextureShiftYDirection.Y != 0.0;
for (int k = 0; k < StateFiles.Length; k++) {
Result.Objects[ObjectCount].States[k].Position = new Vector3(0.0, 0.0, 0.0);
if (StateFiles[k] != null) {
Result.Objects[ObjectCount].States[k].Object = ObjectManager.LoadStaticObject(StateFiles[k], Encoding, LoadMode, false, ForceTextureRepeatX, ForceTextureRepeatY);
if (Result.Objects[ObjectCount].States[k].Object != null) {
Result.Objects[ObjectCount].States[k].Object.Dynamic = true;
}
} else {
Result.Objects[ObjectCount].States[k].Object = null;
}
for (int j = 0; j < Result.Objects[ObjectCount].States.Length; j++) {
Result.Objects[ObjectCount].States[j].Position = Position;
}
}
} else {
Result.Objects[ObjectCount].States = new ObjectManager.AnimatedObjectState[] { };
}
ObjectCount++;
}
break;
default:
Interface.AddMessage(Interface.MessageType.Error, false, "Invalid statement " + Lines[i] + " encountered at line " + (i + 1).ToString(Culture) + " in file " + FileName);
return null;
}
}
}
Array.Resize<ObjectManager.AnimatedObject>(ref Result.Objects, ObjectCount);
return Result;
}
}
}
| |
// 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 gagr = Google.Api.Gax.ResourceNames;
using gcdcv = Google.Cloud.Dialogflow.Cx.V3;
using sys = System;
namespace Google.Cloud.Dialogflow.Cx.V3
{
/// <summary>Resource name for the <c>SecuritySettings</c> resource.</summary>
public sealed partial class SecuritySettingsName : gax::IResourceName, sys::IEquatable<SecuritySettingsName>
{
/// <summary>The possible contents of <see cref="SecuritySettingsName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>.
/// </summary>
ProjectLocationSecuritySettings = 1,
}
private static gax::PathTemplate s_projectLocationSecuritySettings = new gax::PathTemplate("projects/{project}/locations/{location}/securitySettings/{security_settings}");
/// <summary>Creates a <see cref="SecuritySettingsName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="SecuritySettingsName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static SecuritySettingsName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SecuritySettingsName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SecuritySettingsName"/> with the pattern
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="securitySettingsId">The <c>SecuritySettings</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SecuritySettingsName"/> constructed from the provided ids.</returns>
public static SecuritySettingsName FromProjectLocationSecuritySettings(string projectId, string locationId, string securitySettingsId) =>
new SecuritySettingsName(ResourceNameType.ProjectLocationSecuritySettings, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), securitySettingsId: gax::GaxPreconditions.CheckNotNullOrEmpty(securitySettingsId, nameof(securitySettingsId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecuritySettingsName"/> with pattern
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="securitySettingsId">The <c>SecuritySettings</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecuritySettingsName"/> with pattern
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string securitySettingsId) =>
FormatProjectLocationSecuritySettings(projectId, locationId, securitySettingsId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecuritySettingsName"/> with pattern
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="securitySettingsId">The <c>SecuritySettings</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecuritySettingsName"/> with pattern
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>.
/// </returns>
public static string FormatProjectLocationSecuritySettings(string projectId, string locationId, string securitySettingsId) =>
s_projectLocationSecuritySettings.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(securitySettingsId, nameof(securitySettingsId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="SecuritySettingsName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="securitySettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SecuritySettingsName"/> if successful.</returns>
public static SecuritySettingsName Parse(string securitySettingsName) => Parse(securitySettingsName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SecuritySettingsName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="securitySettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="SecuritySettingsName"/> if successful.</returns>
public static SecuritySettingsName Parse(string securitySettingsName, bool allowUnparsed) =>
TryParse(securitySettingsName, allowUnparsed, out SecuritySettingsName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SecuritySettingsName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="securitySettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SecuritySettingsName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string securitySettingsName, out SecuritySettingsName result) =>
TryParse(securitySettingsName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SecuritySettingsName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="securitySettingsName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SecuritySettingsName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string securitySettingsName, bool allowUnparsed, out SecuritySettingsName result)
{
gax::GaxPreconditions.CheckNotNull(securitySettingsName, nameof(securitySettingsName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationSecuritySettings.TryParseName(securitySettingsName, out resourceName))
{
result = FromProjectLocationSecuritySettings(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(securitySettingsName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SecuritySettingsName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string securitySettingsId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
SecuritySettingsId = securitySettingsId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SecuritySettingsName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/securitySettings/{security_settings}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="securitySettingsId">The <c>SecuritySettings</c> ID. Must not be <c>null</c> or empty.</param>
public SecuritySettingsName(string projectId, string locationId, string securitySettingsId) : this(ResourceNameType.ProjectLocationSecuritySettings, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), securitySettingsId: gax::GaxPreconditions.CheckNotNullOrEmpty(securitySettingsId, nameof(securitySettingsId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>SecuritySettings</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string SecuritySettingsId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationSecuritySettings: return s_projectLocationSecuritySettings.Expand(ProjectId, LocationId, SecuritySettingsId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as SecuritySettingsName);
/// <inheritdoc/>
public bool Equals(SecuritySettingsName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SecuritySettingsName a, SecuritySettingsName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SecuritySettingsName a, SecuritySettingsName b) => !(a == b);
}
/// <summary>Resource name for the <c>InspectTemplate</c> resource.</summary>
public sealed partial class InspectTemplateName : gax::IResourceName, sys::IEquatable<InspectTemplateName>
{
/// <summary>The possible contents of <see cref="InspectTemplateName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </summary>
OrganizationLocationInspectTemplate = 1,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </summary>
ProjectLocationInspectTemplate = 2,
}
private static gax::PathTemplate s_organizationLocationInspectTemplate = new gax::PathTemplate("organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}");
private static gax::PathTemplate s_projectLocationInspectTemplate = new gax::PathTemplate("projects/{project}/locations/{location}/inspectTemplates/{inspect_template}");
/// <summary>Creates a <see cref="InspectTemplateName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="InspectTemplateName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static InspectTemplateName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new InspectTemplateName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="InspectTemplateName"/> with the pattern
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="inspectTemplateId">The <c>InspectTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="InspectTemplateName"/> constructed from the provided ids.</returns>
public static InspectTemplateName FromOrganizationLocationInspectTemplate(string organizationId, string locationId, string inspectTemplateId) =>
new InspectTemplateName(ResourceNameType.OrganizationLocationInspectTemplate, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), inspectTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(inspectTemplateId, nameof(inspectTemplateId)));
/// <summary>
/// Creates a <see cref="InspectTemplateName"/> with the pattern
/// <c>projects/{project}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="inspectTemplateId">The <c>InspectTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="InspectTemplateName"/> constructed from the provided ids.</returns>
public static InspectTemplateName FromProjectLocationInspectTemplate(string projectId, string locationId, string inspectTemplateId) =>
new InspectTemplateName(ResourceNameType.ProjectLocationInspectTemplate, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), inspectTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(inspectTemplateId, nameof(inspectTemplateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InspectTemplateName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="inspectTemplateId">The <c>InspectTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InspectTemplateName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </returns>
public static string Format(string organizationId, string locationId, string inspectTemplateId) =>
FormatOrganizationLocationInspectTemplate(organizationId, locationId, inspectTemplateId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InspectTemplateName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="inspectTemplateId">The <c>InspectTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InspectTemplateName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </returns>
public static string FormatOrganizationLocationInspectTemplate(string organizationId, string locationId, string inspectTemplateId) =>
s_organizationLocationInspectTemplate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(inspectTemplateId, nameof(inspectTemplateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="InspectTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="inspectTemplateId">The <c>InspectTemplate</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="InspectTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/inspectTemplates/{inspect_template}</c>.
/// </returns>
public static string FormatProjectLocationInspectTemplate(string projectId, string locationId, string inspectTemplateId) =>
s_projectLocationInspectTemplate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(inspectTemplateId, nameof(inspectTemplateId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="InspectTemplateName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/inspectTemplates/{inspect_template}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="inspectTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="InspectTemplateName"/> if successful.</returns>
public static InspectTemplateName Parse(string inspectTemplateName) => Parse(inspectTemplateName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="InspectTemplateName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/inspectTemplates/{inspect_template}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="inspectTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="InspectTemplateName"/> if successful.</returns>
public static InspectTemplateName Parse(string inspectTemplateName, bool allowUnparsed) =>
TryParse(inspectTemplateName, allowUnparsed, out InspectTemplateName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InspectTemplateName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/inspectTemplates/{inspect_template}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="inspectTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InspectTemplateName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string inspectTemplateName, out InspectTemplateName result) =>
TryParse(inspectTemplateName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="InspectTemplateName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/inspectTemplates/{inspect_template}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="inspectTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="InspectTemplateName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string inspectTemplateName, bool allowUnparsed, out InspectTemplateName result)
{
gax::GaxPreconditions.CheckNotNull(inspectTemplateName, nameof(inspectTemplateName));
gax::TemplatedResourceName resourceName;
if (s_organizationLocationInspectTemplate.TryParseName(inspectTemplateName, out resourceName))
{
result = FromOrganizationLocationInspectTemplate(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_projectLocationInspectTemplate.TryParseName(inspectTemplateName, out resourceName))
{
result = FromProjectLocationInspectTemplate(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(inspectTemplateName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private InspectTemplateName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string inspectTemplateId = null, string locationId = null, string organizationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
InspectTemplateId = inspectTemplateId;
LocationId = locationId;
OrganizationId = organizationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="InspectTemplateName"/> class from the component parts of pattern
/// <c>organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="inspectTemplateId">The <c>InspectTemplate</c> ID. Must not be <c>null</c> or empty.</param>
public InspectTemplateName(string organizationId, string locationId, string inspectTemplateId) : this(ResourceNameType.OrganizationLocationInspectTemplate, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), inspectTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(inspectTemplateId, nameof(inspectTemplateId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>InspectTemplate</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string InspectTemplateId { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.OrganizationLocationInspectTemplate: return s_organizationLocationInspectTemplate.Expand(OrganizationId, LocationId, InspectTemplateId);
case ResourceNameType.ProjectLocationInspectTemplate: return s_projectLocationInspectTemplate.Expand(ProjectId, LocationId, InspectTemplateId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as InspectTemplateName);
/// <inheritdoc/>
public bool Equals(InspectTemplateName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(InspectTemplateName a, InspectTemplateName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(InspectTemplateName a, InspectTemplateName b) => !(a == b);
}
/// <summary>Resource name for the <c>DeidentifyTemplate</c> resource.</summary>
public sealed partial class DeidentifyTemplateName : gax::IResourceName, sys::IEquatable<DeidentifyTemplateName>
{
/// <summary>The possible contents of <see cref="DeidentifyTemplateName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </summary>
OrganizationLocationDeidentifyTemplate = 1,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </summary>
ProjectLocationDeidentifyTemplate = 2,
}
private static gax::PathTemplate s_organizationLocationDeidentifyTemplate = new gax::PathTemplate("organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}");
private static gax::PathTemplate s_projectLocationDeidentifyTemplate = new gax::PathTemplate("projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}");
/// <summary>Creates a <see cref="DeidentifyTemplateName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="DeidentifyTemplateName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static DeidentifyTemplateName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new DeidentifyTemplateName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="DeidentifyTemplateName"/> with the pattern
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deidentifyTemplateId">
/// The <c>DeidentifyTemplate</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>A new instance of <see cref="DeidentifyTemplateName"/> constructed from the provided ids.</returns>
public static DeidentifyTemplateName FromOrganizationLocationDeidentifyTemplate(string organizationId, string locationId, string deidentifyTemplateId) =>
new DeidentifyTemplateName(ResourceNameType.OrganizationLocationDeidentifyTemplate, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deidentifyTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(deidentifyTemplateId, nameof(deidentifyTemplateId)));
/// <summary>
/// Creates a <see cref="DeidentifyTemplateName"/> with the pattern
/// <c>projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deidentifyTemplateId">
/// The <c>DeidentifyTemplate</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>A new instance of <see cref="DeidentifyTemplateName"/> constructed from the provided ids.</returns>
public static DeidentifyTemplateName FromProjectLocationDeidentifyTemplate(string projectId, string locationId, string deidentifyTemplateId) =>
new DeidentifyTemplateName(ResourceNameType.ProjectLocationDeidentifyTemplate, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deidentifyTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(deidentifyTemplateId, nameof(deidentifyTemplateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DeidentifyTemplateName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deidentifyTemplateId">
/// The <c>DeidentifyTemplate</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="DeidentifyTemplateName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </returns>
public static string Format(string organizationId, string locationId, string deidentifyTemplateId) =>
FormatOrganizationLocationDeidentifyTemplate(organizationId, locationId, deidentifyTemplateId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DeidentifyTemplateName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deidentifyTemplateId">
/// The <c>DeidentifyTemplate</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="DeidentifyTemplateName"/> with pattern
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </returns>
public static string FormatOrganizationLocationDeidentifyTemplate(string organizationId, string locationId, string deidentifyTemplateId) =>
s_organizationLocationDeidentifyTemplate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deidentifyTemplateId, nameof(deidentifyTemplateId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="DeidentifyTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deidentifyTemplateId">
/// The <c>DeidentifyTemplate</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="DeidentifyTemplateName"/> with pattern
/// <c>projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>.
/// </returns>
public static string FormatProjectLocationDeidentifyTemplate(string projectId, string locationId, string deidentifyTemplateId) =>
s_projectLocationDeidentifyTemplate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(deidentifyTemplateId, nameof(deidentifyTemplateId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="DeidentifyTemplateName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="deidentifyTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="DeidentifyTemplateName"/> if successful.</returns>
public static DeidentifyTemplateName Parse(string deidentifyTemplateName) => Parse(deidentifyTemplateName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="DeidentifyTemplateName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="deidentifyTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="DeidentifyTemplateName"/> if successful.</returns>
public static DeidentifyTemplateName Parse(string deidentifyTemplateName, bool allowUnparsed) =>
TryParse(deidentifyTemplateName, allowUnparsed, out DeidentifyTemplateName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DeidentifyTemplateName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="deidentifyTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DeidentifyTemplateName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string deidentifyTemplateName, out DeidentifyTemplateName result) =>
TryParse(deidentifyTemplateName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="DeidentifyTemplateName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>
/// </description>
/// </item>
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="deidentifyTemplateName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="DeidentifyTemplateName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string deidentifyTemplateName, bool allowUnparsed, out DeidentifyTemplateName result)
{
gax::GaxPreconditions.CheckNotNull(deidentifyTemplateName, nameof(deidentifyTemplateName));
gax::TemplatedResourceName resourceName;
if (s_organizationLocationDeidentifyTemplate.TryParseName(deidentifyTemplateName, out resourceName))
{
result = FromOrganizationLocationDeidentifyTemplate(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_projectLocationDeidentifyTemplate.TryParseName(deidentifyTemplateName, out resourceName))
{
result = FromProjectLocationDeidentifyTemplate(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(deidentifyTemplateName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private DeidentifyTemplateName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string deidentifyTemplateId = null, string locationId = null, string organizationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
DeidentifyTemplateId = deidentifyTemplateId;
LocationId = locationId;
OrganizationId = organizationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="DeidentifyTemplateName"/> class from the component parts of
/// pattern <c>organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="deidentifyTemplateId">
/// The <c>DeidentifyTemplate</c> ID. Must not be <c>null</c> or empty.
/// </param>
public DeidentifyTemplateName(string organizationId, string locationId, string deidentifyTemplateId) : this(ResourceNameType.OrganizationLocationDeidentifyTemplate, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), deidentifyTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(deidentifyTemplateId, nameof(deidentifyTemplateId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>DeidentifyTemplate</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string DeidentifyTemplateId { get; }
/// <summary>
/// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.OrganizationLocationDeidentifyTemplate: return s_organizationLocationDeidentifyTemplate.Expand(OrganizationId, LocationId, DeidentifyTemplateId);
case ResourceNameType.ProjectLocationDeidentifyTemplate: return s_projectLocationDeidentifyTemplate.Expand(ProjectId, LocationId, DeidentifyTemplateId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as DeidentifyTemplateName);
/// <inheritdoc/>
public bool Equals(DeidentifyTemplateName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(DeidentifyTemplateName a, DeidentifyTemplateName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(DeidentifyTemplateName a, DeidentifyTemplateName b) => !(a == b);
}
public partial class GetSecuritySettingsRequest
{
/// <summary>
/// <see cref="gcdcv::SecuritySettingsName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::SecuritySettingsName SecuritySettingsName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::SecuritySettingsName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListSecuritySettingsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class CreateSecuritySettingsRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteSecuritySettingsRequest
{
/// <summary>
/// <see cref="gcdcv::SecuritySettingsName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::SecuritySettingsName SecuritySettingsName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::SecuritySettingsName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class SecuritySettings
{
/// <summary>
/// <see cref="gcdcv::SecuritySettingsName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdcv::SecuritySettingsName SecuritySettingsName
{
get => string.IsNullOrEmpty(Name) ? null : gcdcv::SecuritySettingsName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="InspectTemplateName"/>-typed view over the <see cref="InspectTemplate"/> resource name property.
/// </summary>
public InspectTemplateName InspectTemplateAsInspectTemplateName
{
get => string.IsNullOrEmpty(InspectTemplate) ? null : InspectTemplateName.Parse(InspectTemplate, allowUnparsed: true);
set => InspectTemplate = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="DeidentifyTemplateName"/>-typed view over the <see cref="DeidentifyTemplate"/> resource name
/// property.
/// </summary>
public DeidentifyTemplateName DeidentifyTemplateAsDeidentifyTemplateName
{
get => string.IsNullOrEmpty(DeidentifyTemplate) ? null : DeidentifyTemplateName.Parse(DeidentifyTemplate, allowUnparsed: true);
set => DeidentifyTemplate = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections;
using Loon.Utils;
using Loon.Utils.Collection;
using Loon.Java.Collections;
namespace Loon.Core.Graphics.Component
{
public class CollisionManager : CollisionChecker
{
private ArrayMap freeObjects = new ArrayMap();
private HashedSet collisionClasses = new HashedSet();
private CollisionChecker collisionChecker = new BSPCollisionChecker();
public void Initialize(int cellSize) {
this.collisionChecker.Initialize(cellSize);
}
public void Clear() {
lock (typeof(CollisionManager)) {
if (collisionChecker != null) {
collisionChecker.Dispose();
collisionChecker.Clear();
}
if (freeObjects != null) {
freeObjects.Clear();
}
if (collisionClasses != null) {
CollectionUtils.Clear(collisionClasses);
}
}
}
private void MakeCollisionObjects(Type cls, bool includeSubclasses) {
ArrayMap.Entry[] entries;
ArrayMap.Entry entry;
if (cls == null) {
entries = this.freeObjects.ToEntrys();
for (int i = 0; i < entries.Length; i++) {
entry = entries[i];
IEnumerator itr = ((LinkedList)entry.GetValue()).GetEnumerator();
for (; itr.MoveNext();) {
Actor actor = (Actor) itr.Current;
this.collisionChecker.AddObject(actor);
}
CollectionUtils.Add(this.collisionClasses,entry.GetKey());
}
this.freeObjects.Clear();
} else if (!CollectionUtils.Contains(cls,this.collisionClasses)) {
LinkedList entries2 = (LinkedList) this.freeObjects.Remove(cls);
if (entries2 != null) {
CollectionUtils.Add(this.collisionClasses,cls);
for (IEnumerator it = entries2.GetEnumerator(); it.MoveNext(); )
{
Actor entry1 = (Actor) it.Current;
this.collisionChecker.AddObject(entry1);
}
}
}
if (includeSubclasses) {
entries = this.freeObjects.ToEntrys();
for (int i_0 = 0; i_0 < entries.Length; i_0++) {
entry = entries[i_0];
if (cls.IsAssignableFrom((Type) entry.GetKey())) {
this.MakeCollisionObjects((Type) entry.GetKey(), false);
}
}
}
}
private void PrepareForCollision(Actor actor, Type cls) {
this.MakeCollisionObjects(actor.GetType(), false);
this.MakeCollisionObjects(cls, true);
}
public void AddObject(Actor actor) {
Type cls = actor.GetType();
if (CollectionUtils.Contains(cls,this.collisionClasses)) {
this.collisionChecker.AddObject(actor);
} else {
LinkedList classSet = (LinkedList) this.freeObjects.Get(cls);
if (classSet == null) {
classSet = new LinkedList();
this.freeObjects.Put(cls, classSet);
}
CollectionUtils.Add(classSet,actor);
}
}
public IList GetIntersectingObjects(Actor actor, Type cls) {
lock (typeof(CollisionManager)) {
this.PrepareForCollision(actor, cls);
return this.collisionChecker.GetIntersectingObjects(actor, cls);
}
}
public IList GetNeighbours(Actor actor, float distance, bool diag,
Type cls) {
lock (typeof(CollisionManager)) {
this.PrepareForCollision(actor, cls);
return this.collisionChecker.GetNeighbours(actor, distance, diag,
cls);
}
}
public IList GetObjects(Type cls) {
lock (typeof(CollisionManager)) {
IList result = this.collisionChecker.GetObjects(cls);
ArrayMap.Entry[] entries = this.freeObjects.ToEntrys();
for (int i = 0; i < entries.Length; i++) {
ArrayMap.Entry entry = entries[i];
if (cls == null || cls.IsAssignableFrom((Type) entry.GetKey())) {
CollectionUtils.AddAll((ICollection) entry.GetValue(),result);
}
}
return result;
}
}
public IList GetObjectsAt(float x, float y, Type cls) {
lock (typeof(CollisionManager)) {
this.MakeCollisionObjects(cls, true);
return this.collisionChecker.GetObjectsAt(x, y, cls);
}
}
public IList GetObjectsInRange(float x, float y, float r, Type cls) {
lock (typeof(CollisionManager)) {
this.MakeCollisionObjects(cls, true);
return this.collisionChecker.GetObjectsInRange(x, y, r, cls);
}
}
public IList GetObjectsList() {
lock (typeof(CollisionManager)) {
return this.GetObjects((Type) null);
}
}
public Actor GetOnlyIntersectingObject(Actor o, Type cls) {
lock (typeof(CollisionManager)) {
this.PrepareForCollision(o, cls);
return this.collisionChecker.GetOnlyIntersectingObject(o, cls);
}
}
public Actor GetOnlyObjectAt(Actor o, float dx, float dy, Type cls) {
lock (typeof(CollisionManager)) {
this.PrepareForCollision(o, cls);
return this.collisionChecker.GetOnlyObjectAt(o, dx, dy, cls);
}
}
public void RemoveObject(Actor o) {
lock (typeof(CollisionManager)) {
LinkedList classSet = (LinkedList) this.freeObjects.Get(o
.GetType());
if (classSet != null) {
classSet.Remove(o);
} else {
this.collisionChecker.RemoveObject(o);
}
}
}
public void RemoveObject(Type cls) {
lock (typeof(CollisionManager)) {
LinkedList classSet = (LinkedList) this.freeObjects.Get(cls);
if (collisionClasses != null) {
CollectionUtils.Remove(collisionClasses,cls);
}
if (classSet != null) {
classSet.Remove(cls);
}
}
}
public void UpdateObjectLocation(Actor o, float oldX, float oldY) {
lock (typeof(CollisionManager)) {
if (!this.freeObjects.ContainsKey(o.GetType())) {
this.collisionChecker.UpdateObjectLocation(o, oldX, oldY);
}
}
}
public void UpdateObjectSize(Actor o) {
lock (typeof(CollisionManager)) {
if (!this.freeObjects.ContainsKey(o.GetType())) {
this.collisionChecker.UpdateObjectSize(o);
}
}
}
public void Dispose() {
lock (typeof(CollisionManager)) {
if (freeObjects != null) {
freeObjects.Clear();
freeObjects = null;
}
if (collisionClasses != null) {
CollectionUtils.Clear(collisionClasses);
collisionClasses = null;
}
if (collisionChecker != null) {
collisionChecker.Dispose();
collisionChecker.Clear();
collisionChecker = null;
}
}
}
public IIterator GetActorsIterator() {
lock (typeof(CollisionManager)) {
return collisionChecker.GetActorsIterator();
}
}
public IList GetActorsList() {
lock (typeof(CollisionManager)) {
return collisionChecker.GetActorsList();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System {
using System;
using System.Threading;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Diagnostics;
using System.Diagnostics.Contracts;
// DateTimeOffset is a value type that consists of a DateTime and a time zone offset,
// ie. how far away the time is from GMT. The DateTime is stored whole, and the offset
// is stored as an Int16 internally to save space, but presented as a TimeSpan.
//
// The range is constrained so that both the represented clock time and the represented
// UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime
// for actual UTC times, and a slightly constrained range on one end when an offset is
// present.
//
// This class should be substitutable for date time in most cases; so most operations
// effectively work on the clock time. However, the underlying UTC time is what counts
// for the purposes of identity, sorting and subtracting two instances.
//
//
// There are theoretically two date times stored, the UTC and the relative local representation
// or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable
// for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this
// out and for internal readability.
[StructLayout(LayoutKind.Auto)]
[Serializable]
public struct DateTimeOffset : IComparable, IFormattable,
IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>, ISerializable, IDeserializationCallback
{
// Constants
internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14;
internal const Int64 MinOffset = -MaxOffset;
private const long UnixEpochTicks = TimeSpan.TicksPerDay * DateTime.DaysTo1970; // 621,355,968,000,000,000
private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800
private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000
internal const long UnixMinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
internal const long UnixMaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
// Static Fields
public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero);
public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero);
// Instance Fields
private DateTime m_dateTime;
private Int16 m_offsetMinutes;
// Constructors
// Constructs a DateTimeOffset from a tick count and offset
public DateTimeOffset(long ticks, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
// Let the DateTime constructor do the range checks
DateTime dateTime = new DateTime(ticks);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds,
// extracts the local offset. For UTC, creates a UTC instance with a zero offset.
public DateTimeOffset(DateTime dateTime) {
TimeSpan offset;
if (dateTime.Kind != DateTimeKind.Utc) {
// Local and Unspecified are both treated as Local
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
else {
offset = new TimeSpan(0);
}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time
// consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that
// the offset corresponds to the local.
public DateTimeOffset(DateTime dateTime, TimeSpan offset) {
if (dateTime.Kind == DateTimeKind.Local) {
if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetLocalMismatch"), nameof(offset));
}
}
else if (dateTime.Kind == DateTimeKind.Utc) {
if (offset != TimeSpan.Zero) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetUtcMismatch"), nameof(offset));
}
}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second and offset.
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond and offset
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond, Calendar and offset.
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset);
}
// Returns a DateTimeOffset representing the current date and time. The
// resolution of the returned value depends on the system timer. For
// Windows NT 3.5 and later the timer resolution is approximately 10ms,
// for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98
// it is approximately 55ms.
//
public static DateTimeOffset Now {
get {
return new DateTimeOffset(DateTime.Now);
}
}
public static DateTimeOffset UtcNow {
get {
return new DateTimeOffset(DateTime.UtcNow);
}
}
public DateTime DateTime {
get {
return ClockDateTime;
}
}
public DateTime UtcDateTime {
[Pure]
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
return DateTime.SpecifyKind(m_dateTime, DateTimeKind.Utc);
}
}
public DateTime LocalDateTime {
[Pure]
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
return UtcDateTime.ToLocalTime();
}
}
// Adjust to a given offset with the same UTC time. Can throw ArgumentException
//
public DateTimeOffset ToOffset(TimeSpan offset) {
return new DateTimeOffset((m_dateTime + offset).Ticks, offset);
}
// Instance Properties
// The clock or visible time represented. This is just a wrapper around the internal date because this is
// the chosen storage mechanism. Going through this helper is good for readability and maintainability.
// This should be used for display but not identity.
private DateTime ClockDateTime {
get {
return new DateTime((m_dateTime + Offset).Ticks, DateTimeKind.Unspecified);
}
}
// Returns the date part of this DateTimeOffset. The resulting value
// corresponds to this DateTimeOffset with the time-of-day part set to
// zero (midnight).
//
public DateTime Date {
get {
return ClockDateTime.Date;
}
}
// Returns the day-of-month part of this DateTimeOffset. The returned
// value is an integer between 1 and 31.
//
public int Day {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 31);
return ClockDateTime.Day;
}
}
// Returns the day-of-week part of this DateTimeOffset. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public DayOfWeek DayOfWeek {
get {
Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
return ClockDateTime.DayOfWeek;
}
}
// Returns the day-of-year part of this DateTimeOffset. The returned value
// is an integer between 1 and 366.
//
public int DayOfYear {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 366); // leap year
return ClockDateTime.DayOfYear;
}
}
// Returns the hour part of this DateTimeOffset. The returned value is an
// integer between 0 and 23.
//
public int Hour {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 24);
return ClockDateTime.Hour;
}
}
// Returns the millisecond part of this DateTimeOffset. The returned value
// is an integer between 0 and 999.
//
public int Millisecond {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 1000);
return ClockDateTime.Millisecond;
}
}
// Returns the minute part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Minute {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
return ClockDateTime.Minute;
}
}
// Returns the month part of this DateTimeOffset. The returned value is an
// integer between 1 and 12.
//
public int Month {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
return ClockDateTime.Month;
}
}
public TimeSpan Offset {
get {
return new TimeSpan(0, m_offsetMinutes, 0);
}
}
// Returns the second part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Second {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
return ClockDateTime.Second;
}
}
// Returns the tick count for this DateTimeOffset. The returned value is
// the number of 100-nanosecond intervals that have elapsed since 1/1/0001
// 12:00am.
//
public long Ticks {
get {
return ClockDateTime.Ticks;
}
}
public long UtcTicks {
get {
return UtcDateTime.Ticks;
}
}
// Returns the time-of-day part of this DateTimeOffset. The returned value
// is a TimeSpan that indicates the time elapsed since midnight.
//
public TimeSpan TimeOfDay {
get {
return ClockDateTime.TimeOfDay;
}
}
// Returns the year part of this DateTimeOffset. The returned value is an
// integer between 1 and 9999.
//
public int Year {
get {
Contract.Ensures(Contract.Result<int>() >= 1 && Contract.Result<int>() <= 9999);
return ClockDateTime.Year;
}
}
// Returns the DateTimeOffset resulting from adding the given
// TimeSpan to this DateTimeOffset.
//
public DateTimeOffset Add(TimeSpan timeSpan) {
return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// days to this DateTimeOffset. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddDays(double days) {
return new DateTimeOffset(ClockDateTime.AddDays(days), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// hours to this DateTimeOffset. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddHours(double hours) {
return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset);
}
// Returns the DateTimeOffset resulting from the given number of
// milliseconds to this DateTimeOffset. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to this DateTimeOffset. The value
// argument is permitted to be negative.
//
public DateTimeOffset AddMilliseconds(double milliseconds) {
return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// minutes to this DateTimeOffset. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddMinutes(double minutes) {
return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset);
}
public DateTimeOffset AddMonths(int months) {
return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// seconds to this DateTimeOffset. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddSeconds(double seconds) {
return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// 100-nanosecond ticks to this DateTimeOffset. The value argument
// is permitted to be negative.
//
public DateTimeOffset AddTicks(long ticks) {
return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// years to this DateTimeOffset. The result is computed by incrementing
// (or decrementing) the year part of this DateTimeOffset by value
// years. If the month and day of this DateTimeOffset is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of this DateTimeOffset.
//
public DateTimeOffset AddYears(int years) {
return new DateTimeOffset(ClockDateTime.AddYears(years), Offset);
}
// Compares two DateTimeOffset values, returning an integer that indicates
// their relationship.
//
public static int Compare(DateTimeOffset first, DateTimeOffset second) {
return DateTime.Compare(first.UtcDateTime, second.UtcDateTime);
}
// Compares this DateTimeOffset to a given object. This method provides an
// implementation of the IComparable interface. The object
// argument must be another DateTimeOffset, or otherwise an exception
// occurs. Null is considered less than any instance.
//
int IComparable.CompareTo(Object obj) {
if (obj == null) return 1;
if (!(obj is DateTimeOffset)) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTimeOffset"));
}
DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > objUtc) return 1;
if (utc < objUtc) return -1;
return 0;
}
public int CompareTo(DateTimeOffset other) {
DateTime otherUtc = other.UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > otherUtc) return 1;
if (utc < otherUtc) return -1;
return 0;
}
// Checks if this DateTimeOffset is equal to a given object. Returns
// true if the given object is a boxed DateTimeOffset and its value
// is equal to the value of this DateTimeOffset. Returns false
// otherwise.
//
public override bool Equals(Object obj) {
if (obj is DateTimeOffset) {
return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime);
}
return false;
}
public bool Equals(DateTimeOffset other) {
return UtcDateTime.Equals(other.UtcDateTime);
}
public bool EqualsExact(DateTimeOffset other) {
//
// returns true when the ClockDateTime, Kind, and Offset match
//
// currently the Kind should always be Unspecified, but there is always the possibility that a future version
// of DateTimeOffset overloads the Kind field
//
return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind);
}
// Compares two DateTimeOffset values for equality. Returns true if
// the two DateTimeOffset values are equal, or false if they are
// not equal.
//
public static bool Equals(DateTimeOffset first, DateTimeOffset second) {
return DateTime.Equals(first.UtcDateTime, second.UtcDateTime);
}
// Creates a DateTimeOffset from a Windows filetime. A Windows filetime is
// a long representing the date and time as the number of
// 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
//
public static DateTimeOffset FromFileTime(long fileTime) {
return new DateTimeOffset(DateTime.FromFileTime(fileTime));
}
public static DateTimeOffset FromUnixTimeSeconds(long seconds) {
if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds) {
throw new ArgumentOutOfRangeException(nameof(seconds),
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), UnixMinSeconds, UnixMaxSeconds));
}
long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) {
const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) {
throw new ArgumentOutOfRangeException(nameof(milliseconds),
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), MinMilliseconds, MaxMilliseconds));
}
long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
// ----- SECTION: private serialization instance methods ----------------*
void IDeserializationCallback.OnDeserialization(Object sender) {
try {
m_offsetMinutes = ValidateOffset(Offset);
m_dateTime = ValidateDate(ClockDateTime, Offset);
}
catch (ArgumentException e) {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
info.AddValue("DateTime", m_dateTime);
info.AddValue("OffsetMinutes", m_offsetMinutes);
}
DateTimeOffset(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException(nameof(info));
}
m_dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime));
m_offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16));
}
// Returns the hash code for this DateTimeOffset.
//
public override int GetHashCode() {
return UtcDateTime.GetHashCode();
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input) {
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) {
return Parse(input, formatProvider, DateTimeStyles.None);
}
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) {
styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) {
return ParseExact(input, format, formatProvider, DateTimeStyles.None);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) {
styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExact(input,
format,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) {
styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExactMultiple(input,
formats,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public TimeSpan Subtract(DateTimeOffset value) {
return UtcDateTime.Subtract(value.UtcDateTime);
}
public DateTimeOffset Subtract(TimeSpan value) {
return new DateTimeOffset(ClockDateTime.Subtract(value), Offset);
}
public long ToFileTime() {
return UtcDateTime.ToFileTime();
}
public long ToUnixTimeSeconds() {
// Truncate sub-second precision before offsetting by the Unix Epoch to avoid
// the last digit being off by one for dates that result in negative Unix times.
//
// For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0
// ticks = 621355967990010000
// ticksFromEpoch = ticks - UnixEpochTicks = -9990000
// secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0
//
// Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division,
// whereas we actually always want to round *down* when converting to Unix time. This happens
// automatically for positive Unix time values. Now the example becomes:
// seconds = ticks / TimeSpan.TicksPerSecond = 62135596799
// secondsFromEpoch = seconds - UnixEpochSeconds = -1
//
// In other words, we want to consistently round toward the time 1/1/0001 00:00:00,
// rather than toward the Unix Epoch (1/1/1970 00:00:00).
long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond;
return seconds - UnixEpochSeconds;
}
public long ToUnixTimeMilliseconds() {
// Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid
// the last digit being off by one for dates that result in negative Unix times
long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond;
return milliseconds - UnixEpochMilliseconds;
}
public DateTimeOffset ToLocalTime() {
return ToLocalTime(false);
}
internal DateTimeOffset ToLocalTime(bool throwOnOverflow)
{
return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow));
}
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset);
}
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset);
}
public String ToString(IFormatProvider formatProvider) {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
}
public String ToString(String format, IFormatProvider formatProvider) {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
}
public DateTimeOffset ToUniversalTime() {
return new DateTimeOffset(UtcDateTime);
}
public static Boolean TryParse(String input, out DateTimeOffset result) {
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) {
styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result) {
styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExact(input,
format,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result) {
styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExactMultiple(input,
formats,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
// Ensures the TimeSpan is valid to go in a DateTimeOffset.
private static Int16 ValidateOffset(TimeSpan offset) {
Int64 ticks = offset.Ticks;
if (ticks % TimeSpan.TicksPerMinute != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetPrecision"), nameof(offset));
}
if (ticks < MinOffset || ticks > MaxOffset) {
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("Argument_OffsetOutOfRange"));
}
return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute);
}
// Ensures that the time and offset are in range.
private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) {
// The key validation is that both the UTC and clock times fit. The clock time is validated
// by the DateTime constructor.
Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
// This operation cannot overflow because offset should have already been validated to be within
// 14 hours and the DateTime instance is more than that distance from the boundaries of Int64.
Int64 utcTicks = dateTime.Ticks - offset.Ticks;
if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) {
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("Argument_UTCOutOfRange"));
}
// make sure the Kind is set to Unspecified
//
return new DateTime(utcTicks, DateTimeKind.Unspecified);
}
private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) {
if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeStyles"), parameterName);
}
if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) {
throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeStyles"), parameterName);
}
if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetInvalidDateTimeStyles"), parameterName);
}
Contract.EndContractBlock();
// RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatibility with DateTime
style &= ~DateTimeStyles.RoundtripKind;
// AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse
style &= ~DateTimeStyles.AssumeLocal;
return style;
}
// Operators
public static implicit operator DateTimeOffset (DateTime dateTime) {
return new DateTimeOffset(dateTime);
}
public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset);
}
public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset);
}
public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime - right.UtcDateTime;
}
public static bool operator ==(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime == right.UtcDateTime;
}
public static bool operator !=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime != right.UtcDateTime;
}
public static bool operator <(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime < right.UtcDateTime;
}
public static bool operator <=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime <= right.UtcDateTime;
}
public static bool operator >(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime > right.UtcDateTime;
}
public static bool operator >=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime >= right.UtcDateTime;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorLogger;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using TextSpan = Microsoft.CodeAnalysis.Text.TextSpan;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal sealed class VisualStudioDocumentNavigationService : ForegroundThreadAffinitizedObject, IDocumentNavigationService
{
private readonly IServiceProvider _serviceProvider;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
public VisualStudioDocumentNavigationService(
SVsServiceProvider serviceProvider,
IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
{
_serviceProvider = serviceProvider;
_editorAdaptersFactoryService = editorAdaptersFactoryService;
}
public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsSecondaryBuffer(workspace, documentId))
{
return true;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length);
if (boundedTextSpan != textSpan)
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e))
{
}
return false;
}
var vsTextSpan = text.GetVsTextSpanForSpan(textSpan);
return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan);
}
public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsSecondaryBuffer(workspace, documentId))
{
return true;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset);
return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan);
}
public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace = 0)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsSecondaryBuffer(workspace, documentId))
{
return true;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length);
if (boundedPosition != position)
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e))
{
}
return false;
}
var vsTextSpan = text.GetVsTextSpanForPosition(position, virtualSpace);
return CanMapFromSecondaryBufferToPrimaryBuffer(workspace, documentId, vsTextSpan);
}
public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread);
}
var document = OpenDocument(workspace, documentId, options);
if (document == null)
{
return false;
}
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var textBuffer = text.Container.GetTextBuffer();
var boundedTextSpan = GetSpanWithinDocumentBounds(textSpan, text.Length);
if (boundedTextSpan != textSpan)
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e))
{
}
}
var vsTextSpan = text.GetVsTextSpanForSpan(boundedTextSpan);
if (IsSecondaryBuffer(workspace, documentId) &&
!vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan))
{
return false;
}
return NavigateTo(textBuffer, vsTextSpan);
}
public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread);
}
var document = OpenDocument(workspace, documentId, options);
if (document == null)
{
return false;
}
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var textBuffer = text.Container.GetTextBuffer();
var vsTextSpan = text.GetVsTextSpanForLineOffset(lineNumber, offset);
if (IsSecondaryBuffer(workspace, documentId) &&
!vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan))
{
return false;
}
return NavigateTo(textBuffer, vsTextSpan);
}
public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options)
{
// Navigation should not change the context of linked files and Shared Projects.
documentId = workspace.GetDocumentIdInCurrentContext(documentId);
if (!IsForeground())
{
throw new InvalidOperationException(ServicesVSResources.Navigation_must_be_performed_on_the_foreground_thread);
}
var document = OpenDocument(workspace, documentId, options);
if (document == null)
{
return false;
}
var text = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None);
var textBuffer = text.Container.GetTextBuffer();
var boundedPosition = GetPositionWithinDocumentBounds(position, text.Length);
if (boundedPosition != position)
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException e) when (FatalError.ReportWithoutCrash(e))
{
}
}
var vsTextSpan = text.GetVsTextSpanForPosition(boundedPosition, virtualSpace);
if (IsSecondaryBuffer(workspace, documentId) &&
!vsTextSpan.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out vsTextSpan))
{
return false;
}
return NavigateTo(textBuffer, vsTextSpan);
}
/// <summary>
/// It is unclear why, but we are sometimes asked to navigate to a position that is not
/// inside the bounds of the associated <see cref="Document"/>. This method returns a
/// position that is guaranteed to be inside the <see cref="Document"/> bounds. If the
/// returned position is different from the given position, then the worst observable
/// behavior is either no navigation or navigation to the end of the document. See the
/// following bugs for more details:
/// https://devdiv.visualstudio.com/DevDiv/_workitems?id=112211
/// https://devdiv.visualstudio.com/DevDiv/_workitems?id=136895
/// https://devdiv.visualstudio.com/DevDiv/_workitems?id=224318
/// https://devdiv.visualstudio.com/DevDiv/_workitems?id=235409
/// </summary>
private static int GetPositionWithinDocumentBounds(int position, int documentLength)
{
return Math.Min(documentLength, Math.Max(position, 0));
}
/// <summary>
/// It is unclear why, but we are sometimes asked to navigate to a <see cref="TextSpan"/>
/// that is not inside the bounds of the associated <see cref="Document"/>. This method
/// returns a span that is guaranteed to be inside the <see cref="Document"/> bounds. If
/// the returned span is different from the given span, then the worst observable behavior
/// is either no navigation or navigation to the end of the document.
/// See https://github.com/dotnet/roslyn/issues/7660 for more details.
/// </summary>
private static TextSpan GetSpanWithinDocumentBounds(TextSpan span, int documentLength)
{
return TextSpan.FromBounds(GetPositionWithinDocumentBounds(span.Start, documentLength), GetPositionWithinDocumentBounds(span.End, documentLength));
}
private static Document OpenDocument(Workspace workspace, DocumentId documentId, OptionSet options)
{
options = options ?? workspace.Options;
// Always open the document again, even if the document is already open in the
// workspace. If a document is already open in a preview tab and it is opened again
// in a permanent tab, this allows the document to transition to the new state.
if (workspace.CanOpenDocuments)
{
if (options.GetOption(NavigationOptions.PreferProvisionalTab))
{
// If we're just opening the provisional tab, then do not "activate" the document
// (i.e. don't give it focus). This way if a user is just arrowing through a set
// of FindAllReferences results, they don't have their cursor placed into the document.
var state = __VSNEWDOCUMENTSTATE.NDS_Provisional | __VSNEWDOCUMENTSTATE.NDS_NoActivate;
using (var scope = new NewDocumentStateScope(state, VSConstants.NewDocumentStateReason.Navigation))
{
workspace.OpenDocument(documentId);
}
}
else
{
workspace.OpenDocument(documentId);
}
}
if (!workspace.IsDocumentOpen(documentId))
{
return null;
}
return workspace.CurrentSolution.GetDocument(documentId);
}
private bool NavigateTo(ITextBuffer textBuffer, VsTextSpan vsTextSpan)
{
using (Logger.LogBlock(FunctionId.NavigationService_VSDocumentNavigationService_NavigateTo, CancellationToken.None))
{
var vsTextBuffer = _editorAdaptersFactoryService.GetBufferAdapter(textBuffer);
if (vsTextBuffer == null)
{
Debug.Fail("Could not get IVsTextBuffer for document!");
return false;
}
var textManager = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager));
if (textManager == null)
{
Debug.Fail("Could not get IVsTextManager service!");
return false;
}
return ErrorHandler.Succeeded(
textManager.NavigateToLineAndColumn2(
vsTextBuffer, VSConstants.LOGVIEWID.TextView_guid, vsTextSpan.iStartLine, vsTextSpan.iStartIndex, vsTextSpan.iEndLine, vsTextSpan.iEndIndex, (uint)_VIEWFRAMETYPE.vftCodeWindow));
}
}
private bool IsSecondaryBuffer(Workspace workspace, DocumentId documentId)
{
var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;
if (visualStudioWorkspace == null)
{
return false;
}
var containedDocument = visualStudioWorkspace.GetHostDocument(documentId) as ContainedDocument;
if (containedDocument == null)
{
return false;
}
return true;
}
private bool CanMapFromSecondaryBufferToPrimaryBuffer(Workspace workspace, DocumentId documentId, VsTextSpan spanInSecondaryBuffer)
{
return spanInSecondaryBuffer.TryMapSpanFromSecondaryBufferToPrimaryBuffer(workspace, documentId, out var spanInPrimaryBuffer);
}
}
}
| |
using System;
using GameTimer;
using System.Linq;
using System.Threading.Tasks;
namespace MenuBuddy
{
public class Tree<T> : ScrollLayout, ITree<T>, IHasContent, IDisposable
{
#region Events
public event EventHandler<SelectionChangeEventArgs<T>> OnSelectedItemChange;
#endregion //Events
#region Fields
/// <summary>
/// The stack layout that will hold all the tree items
/// </summary>
public StackLayout Stack { get; private set; }
protected IScreen Screen
{
get; set;
}
public StackAlignment Alignment
{
get
{
return ((IStackLayout)Stack).Alignment;
}
set
{
((IStackLayout)Stack).Alignment = value;
}
}
#endregion //Fields
#region Properties
/// <summary>
/// The currently selected item
/// </summary>
private TreeItem<T> _selectedTreeItem;
public TreeItem<T> SelectedTreeItem
{
get
{
return _selectedTreeItem;
}
set
{
_selectedTreeItem = value;
//fire off the selected event
if (null != OnSelectedItemChange)
{
OnSelectedItemChange(this, new SelectionChangeEventArgs<T>(_selectedTreeItem.Item));
}
}
}
public T SelectedItem
{
get
{
return SelectedTreeItem.Item;
}
set
{
//get all the current tree items
var treeItems = Stack.Items.OfType<TreeItem<T>>().ToList();
//Go through the tree items and expand them if they contain the desired item
foreach (var treeItem in treeItems)
{
var result = treeItem.FindItem(value);
if (null != result)
{
SelectedTreeItem = result;
return;
}
}
}
}
public bool HasBackground { get; set; }
protected Background Background { get; set; }
public override ITransitionObject TransitionObject
{
get
{
return base.TransitionObject;
}
set
{
base.TransitionObject = value;
foreach (var item in Items)
{
var transitionableItem = item as ITransitionable;
if (null != transitionableItem)
{
transitionableItem.TransitionObject = TransitionObject;
}
}
}
}
#endregion //Properties
#region Methods
public Tree(IScreen screen)
{
//TreeItems = new List<TreeItem>();
Stack = new StackLayout()
{
Alignment = StackAlignment.Top
};
Screen = screen;
Background = new Background();
}
public Tree(Tree<T> inst) : base(inst)
{
Stack = new StackLayout(inst.Stack);
Screen = inst.Screen;
SelectedTreeItem = inst.SelectedTreeItem;
Background = inst.Background;
}
public override async Task LoadContent(IScreen screen)
{
await base.LoadContent(screen);
base.AddItem(Stack);
await Stack.LoadContent(screen);
await Background.LoadContent(screen);
}
public override void UnloadContent()
{
base.UnloadContent();
Background?.UnloadContent();
Background = null;
Stack?.UnloadContent();
Stack = null;
OnSelectedItemChange = null;
}
public override IScreenItem DeepCopy()
{
return new Tree<T>(this);
}
protected void PrepareAdd(IScreenItem item)
{
//Make sure the thing is in the tree
var treeItem = item as TreeItem<T>;
if (null != treeItem)
{
treeItem.AddToTree(Screen);
}
var transitionable = item as ITransitionable;
if (null != transitionable)
{
transitionable.TransitionObject = this.TransitionObject;
}
}
public override void AddItem(IScreenItem item)
{
PrepareAdd(item);
//add to the stack control
Stack.AddItem(item);
UpdateMinMaxScroll();
UpdateScrollBars();
}
public void InsertItem(IScreenItem item, IScreenItem prevItem)
{
PrepareAdd(item);
//add to the stack control
Stack.InsertItem(item, prevItem);
UpdateMinMaxScroll();
UpdateScrollBars();
}
public void InsertItemBefore(IScreenItem item, IScreenItem nextItem)
{
PrepareAdd(item);
//add to the stack control
Stack.InsertItemBefore(item, nextItem);
UpdateMinMaxScroll();
UpdateScrollBars();
}
public override bool RemoveItem(IScreenItem item)
{
var removed = Stack.RemoveItem(item);
if (removed)
{
UpdateMinMaxScroll();
UpdateScrollBars();
}
return removed;
}
public override void DrawBackground(IScreen screen, GameClock gameTime)
{
Background.Draw(this, screen);
base.DrawBackground(screen, gameTime);
}
public bool DisplayItem(T item)
{
//get all the current tree items
var treeItems = Stack.Items.OfType<TreeItem<T>>().ToList();
//Go through the tree items and expand them if they contain the desired item
foreach (var treeItem in treeItems)
{
if (treeItem.DisplayItem(item))
{
return true;
}
}
return false;
}
#endregion //Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Color = Microsoft.Xna.Framework.Color;
using Rectangle = Microsoft.Xna.Framework.Rectangle;
namespace RenderLike {
/// <summary>
/// Horizontal alignment used by various string printing methods
/// </summary>
public enum HorizontalAligment {
Left,
Center,
Right
}
/// <summary>
/// Vertical alignment used by various string printing methods
/// </summary>
public enum VerticalAlignment {
Top,
Center,
Bottom
}
/// <summary>
/// Wrapping mode used by various string printing methods
/// </summary>
public enum WrappingType {
/// <summary>
/// No wrapping is performed - characters will be trimmed if too long to fit
/// </summary>
None,
/// <summary>
/// String is wrapped to new line if too long to fit
/// </summary>
Character,
/// <summary>
/// String is wrapped to new line if too long to fit, respecting word boundaries (spaces)
/// </summary>
Word
}
internal struct Cell {
public Color Back;
public char Char;
public Color Fore;
public override string ToString() {
return $"Tile: {Char}";
}
}
public class Surface {
internal readonly Cell[] Cells;
internal bool[] DirtyCells;
internal Font Font;
internal readonly RLConsole ParentConsole;
internal Surface(int width, int height, Font font, RLConsole parent, int index) {
Width = width;
Height = height;
Index = index;
Font = font;
ParentConsole = parent;
Rect = new Rectangle(0, 0, width, height);
Cells = new Cell[width*height];
DirtyCells = new bool[width*height];
DefaultBackground = Color.Black;
DefaultForeground = Color.White;
for (int i = 0; i < width*height; i++) {
Cells[i].Back = DefaultBackground;
Cells[i].Char = ' ';
Cells[i].Fore = DefaultForeground;
}
}
/// <summary>
/// Width of the surface in number of character cells
/// </summary>
public int Width { get; private set; }
/// <summary>
/// Height of surface in number of character cells
/// </summary>
public int Height { get; private set; }
public int Index { get; set; }
public Rectangle Rect { get; private set; }
/// <summary>
/// The default background color used by drawing methods when not specified
/// </summary>
public Color DefaultBackground { get; set; }
/// <summary>
/// The default foreground color used by drawing methods when not specified
/// </summary>
public Color DefaultForeground { get; set; }
/// <summary>
/// Returns the character at the given position in cell coordinates.
/// Position must be within the surface boundaries or this method will throw an ArgumentOutOfRangeException.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public char GetChar(int x, int y) {
if (x < 0 || x >= Width)
throw new ArgumentOutOfRangeException("x");
if (y < 0 || y >= Height)
throw new ArgumentOutOfRangeException("y");
return Cells[x + y*Width].Char;
}
/// <summary>
/// Returns the foreground color at the given position in cell coordinates.
/// Position must be within the surface boundaries or this method will throw an ArgumentOutOfRangeException.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public Color GetForeground(int x, int y) {
if (x < 0 || x >= Width)
throw new ArgumentOutOfRangeException("x");
if (y < 0 || y >= Height)
throw new ArgumentOutOfRangeException("y");
return Cells[x + y*Width].Fore;
}
/// <summary>
/// Returns the background color at the given position in cell coordinates.
/// Position must be within the surface boundaries or this method will throw an ArgumentOutOfRangeException.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public Color GetBackground(int x, int y) {
if (x < 0 || x >= Width)
throw new ArgumentOutOfRangeException("x");
if (y < 0 || y >= Height)
throw new ArgumentOutOfRangeException("y");
return Cells[x + y*Width].Back;
}
/// <summary>
/// Changes the foreground color of the specified cell without affecting the character or background
/// Position must be within the surface boundaries or this method will throw an ArgumentOutOfRangeException.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="fore"></param>
public void SetForeground(int x, int y, Color fore) {
if (x < 0 || x >= Width)
throw new ArgumentOutOfRangeException("x");
if (y < 0 || y >= Height)
throw new ArgumentOutOfRangeException("y");
SetCell(x, y, null, fore, null);
}
/// <summary>
/// Changes the background color of the specified cell without affecting the character or foreground
/// Position must be within the surface boundaries or this method will throw an ArgumentOutOfRangeException.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="back"></param>
public void SetBackground(int x, int y, Color back) {
if (x < 0 || x >= Width)
throw new ArgumentOutOfRangeException("x");
if (y < 0 || y >= Height)
throw new ArgumentOutOfRangeException("y");
SetCell(x, y, null, null, back);
}
/// <summary>
/// Changes the character at the specified cell without affecting the foreground or background
/// Position must be within the surface boundaries or this method will throw an ArgumentOutOfRangeException.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="c"></param>
public void SetChar(int x, int y, char c) {
if (x < 0 || x >= Width)
throw new ArgumentOutOfRangeException("x");
if (y < 0 || y >= Height)
throw new ArgumentOutOfRangeException("y");
SetCell(x, y, c, null, null);
}
/// <summary>
/// Prints the specified character using specified foreground and background colors.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="c"></param>
/// <param name="fore"></param>
/// <param name="back"></param>
public void PrintChar(int x, int y, char c, Color fore, Color back) {
SetCell(x, y, c, fore, back);
}
/// <summary>
/// Prints the character using the specified foreground and default background colors
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="c"></param>
/// <param name="fore"></param>
public void PrintChar(int x, int y, char c, Color fore) {
SetCell(x, y, c, fore, DefaultBackground);
}
/// <summary>
/// Prints the character using the default background and foreground colors
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="c"></param>
public void PrintChar(int x, int y, char c) {
SetCell(x, y, c, DefaultForeground, DefaultBackground);
}
/// <summary>
/// Prints the string using the specified foreground and background colors
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="str"></param>
/// <param name="fore"></param>
/// <param name="back"></param>
public void PrintString(int x, int y, string str, Color fore, Color back) {
if (str == null)
throw new ArgumentNullException("str");
for (int i = 0; i < str.Length; i++) {
PrintChar(x + i, y, str[i], fore, back);
}
}
/// <summary>
/// Prints a string using the default foreground and background colors
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="str"></param>
public void PrintString(int x, int y, string str) {
PrintString(x, y, str, DefaultForeground, DefaultBackground);
}
/// <summary>
/// Prints a string using the specified foreground and default background colors
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="str"></param>
/// <param name="fore"></param>
public void PrintString(int x, int y, string str, Color fore) {
PrintString(x, y, str, fore, DefaultBackground);
}
/// <summary>
/// Prints the string within the specified rectangle, with the specified alignments and wrapping
/// </summary>
/// <param name="rect"></param>
/// <param name="str"></param>
/// <param name="hAlign"></param>
/// <param name="vAlign"></param>
/// <param name="wrapping"></param>
public void PrintStringRect(Rectangle rect, string str, HorizontalAligment hAlign, VerticalAlignment vAlign,
WrappingType wrapping) {
if (str == null)
throw new ArgumentNullException("str");
switch (wrapping) {
case WrappingType.None:
if (str.Length > rect.Width) {
str = str.Substring(0, rect.Width);
}
int nx = rect.X + GetHorizontalDelta(str.Length, rect.Width, hAlign);
int ny = rect.Y + GetVerticalDelta(1, rect.Height, vAlign);
PrintString(nx, ny, str);
break;
case WrappingType.Character:
string[] stringlist = GetCharWrappedLines(str, rect.Width);
for (int i = 0; i < stringlist.Length; i++) {
str = stringlist[i];
nx = rect.X + GetHorizontalDelta(str.Length, rect.Width, hAlign);
ny = i + rect.Y + GetVerticalDelta(stringlist.Length, rect.Height, vAlign);
// note XNA.Rectangle.Bottom is EXCLUSIVE!
if (ny >= rect.Top && ny < rect.Bottom) {
PrintString(nx, ny, str);
}
}
break;
case WrappingType.Word:
stringlist = GetWordWrappedLines(str, rect.Width);
for (int i = 0; i < stringlist.Length; i++) {
str = stringlist[i];
nx = rect.X + GetHorizontalDelta(str.Length, rect.Width, hAlign);
ny = i + rect.Y + GetVerticalDelta(stringlist.Length, rect.Height, vAlign);
// note XNA.Rectangle.Bottom is EXCLUSIVE!
if (ny >= rect.Top && ny < rect.Bottom) {
PrintString(nx, ny, str);
}
}
break;
}
}
/// <summary>
/// Prints the string within the specified rectangle, with the specified alignments. No wrapping is performed.
/// </summary>
/// <param name="rect"></param>
/// <param name="str"></param>
/// <param name="hAlign"></param>
/// <param name="vAlign"></param>
public void PrintStringRect(Rectangle rect, string str, HorizontalAligment hAlign,
VerticalAlignment vAlign = VerticalAlignment.Top) {
PrintStringRect(rect, str, hAlign, vAlign, WrappingType.None);
}
/// <summary>
/// Clears the surface, setting each cell character to space and each cell to the default foreground and background
/// colors.
/// </summary>
public void Clear() {
ClearSurface();
}
/// <summary>
/// Fills the specified rectangle with the character and colors specified.
/// </summary>
/// <param name="rect"></param>
/// <param name="c"></param>
/// <param name="fore"></param>
/// <param name="back"></param>
public void Fill(Rectangle rect, char c, Color fore, Color back) {
for (int y = rect.Top; y < rect.Bottom; y++) {
for (int x = rect.Left; x < rect.Right; x++) {
SetCell(x, y, c, fore, back);
}
}
}
/// <summary>
/// Fills a rectangle with the specified character using the default foreground and background colors.
/// </summary>
/// <param name="rect"></param>
/// <param name="c"></param>
public void Fill(Rectangle rect, char c) {
Fill(rect, c, DefaultForeground, DefaultBackground);
}
/// <summary>
/// Fills a rectangle with the specified character and foreground color and the default background color.
/// </summary>
/// <param name="rect"></param>
/// <param name="c"></param>
/// <param name="fore"></param>
public void Fill(Rectangle rect, char c, Color fore) {
Fill(rect, c, fore, DefaultBackground);
}
/// <summary>
/// Fills a rectangle with the provided colors. Does not change the characters within the rectangle.
/// </summary>
/// <param name="rect"></param>
/// <param name="fore"></param>
/// <param name="back"></param>
public void Fill(Rectangle rect, Color fore, Color back) {
for (int y = rect.Top; y < rect.Bottom; y++) {
for (int x = rect.Left; x < rect.Right; x++) {
SetCell(x, y, null, fore, back);
}
}
}
/// <summary>
/// Draw a horizontal line using the specified character
/// </summary>
/// <param name="leftX"></param>
/// <param name="leftY"></param>
/// <param name="length"></param>
/// <param name="c"></param>
/// <param name="fore"></param>
/// <param name="back"></param>
public void DrawHorizontalLine(int leftX, int leftY, int length, char c, Color fore, Color back) {
for (int i = 0; i < length; i++) {
PrintChar(leftX + i, leftY, c, fore, back);
}
}
/// <summary>
/// Draw a horizontal line using special characters, assuming one of the default font layouts (or similar) is being
/// used.
/// </summary>
/// <param name="leftX"></param>
/// <param name="leftY"></param>
/// <param name="length"></param>
/// <param name="fore"></param>
/// <param name="back"></param>
public void DrawHorizontalLine(int leftX, int leftY, int length, Color fore, Color back) {
DrawHorizontalLine(leftX, leftY, length, (char) SpecialChar.HorizontalLine, fore, back);
}
/// <summary>
/// Draw a horizontal line using special characters, assuming one of the default font layouts (or similar) is being
/// used.
/// The default background is used.
/// </summary>
/// <param name="leftX"></param>
/// <param name="leftY"></param>
/// <param name="length"></param>
/// <param name="fore"></param>
public void DrawHorizontalLine(int leftX, int leftY, int length, Color fore) {
DrawHorizontalLine(leftX, leftY, length, fore, DefaultBackground);
}
/// <summary>
/// Draw a horizontal line using special characters, assuming one of the default font layouts (or similar) is being
/// used.
/// The default foreground and background colors are used.
/// </summary>
/// <param name="leftX"></param>
/// <param name="leftY"></param>
/// <param name="length"></param>
public void DrawHorizontalLine(int leftX, int leftY, int length) {
DrawHorizontalLine(leftX, leftY, length, DefaultForeground, DefaultBackground);
}
/// <summary>
/// Draw a vertical line using the specified character
/// </summary>
/// <param name="topX"></param>
/// <param name="topY"></param>
/// <param name="length"></param>
/// <param name="c"></param>
/// <param name="fore"></param>
/// <param name="back"></param>
public void DrawVerticalLine(int topX, int topY, int length, char c, Color fore, Color back) {
for (int i = 0; i < length; i++) {
PrintChar(topX, topY + i, c, fore, back);
}
}
/// <summary>
/// Draw a vertical line using special characters, assuming one of the default font layouts (or similar) is being used.
/// </summary>
/// <param name="topX"></param>
/// <param name="topY"></param>
/// <param name="length"></param>
/// <param name="fore"></param>
/// <param name="back"></param>
public void DrawVerticalLine(int topX, int topY, int length, Color fore, Color back) {
DrawVerticalLine(topX, topY, length, (char) SpecialChar.VerticalLine, fore, back);
}
/// <summary>
/// Draw a vertical line using special characters, assuming one of the default font layouts (or similar) is being used.
/// The default background color is used.
/// </summary>
/// <param name="topX"></param>
/// <param name="topY"></param>
/// <param name="length"></param>
/// <param name="fore"></param>
public void DrawVerticalLine(int topX, int topY, int length, Color fore) {
DrawVerticalLine(topX, topY, length, fore, DefaultBackground);
}
/// <summary>
/// Draw a vertical line using special characters, assuming one of the default font layouts (or similar) is being used.
/// The default foreground and background colors are used.
/// </summary>
/// <param name="topX"></param>
/// <param name="topY"></param>
/// <param name="length"></param>
public void DrawVerticalLine(int topX, int topY, int length) {
DrawVerticalLine(topX, topY, length, DefaultForeground, DefaultBackground);
}
/// <summary>
/// Draws a frame using special characters, assuming one of the default font layouts (or similar) is being used.
/// If title is not null or empty, then this string is printed a the top left corner of the frame.
/// </summary>
/// <param name="rect"></param>
/// <param name="title"></param>
/// <param name="clear">If true, clears the region inside the frame with the given back color</param>
/// <param name="fore"></param>
/// <param name="back"></param>
public void DrawFrame(Rectangle rect, string title, bool clear, Color fore, Color back) {
if (clear) {
Fill(rect, ' ', fore, back);
}
DrawHorizontalLine(rect.Left, rect.Top, rect.Width - 1, fore, back);
DrawHorizontalLine(rect.Left, rect.Bottom - 1, rect.Width - 1, fore, back);
DrawVerticalLine(rect.Left, rect.Top, rect.Height - 1, fore, back);
DrawVerticalLine(rect.Right - 1, rect.Top, rect.Height - 1, fore, back);
PrintChar(rect.Left, rect.Top, (char) SpecialChar.NorthWestLine, fore, back);
PrintChar(rect.Right - 1, rect.Top, (char) SpecialChar.NorthEastLine, fore, back);
PrintChar(rect.Left, rect.Bottom - 1, (char) SpecialChar.SouthWestLine, fore, back);
PrintChar(rect.Right - 1, rect.Bottom - 1, (char) SpecialChar.SouthEastLine, fore, back);
if (!string.IsNullOrEmpty(title)) {
PrintString(rect.Left + 1, rect.Top, title, back, fore);
}
}
/// <summary>
/// Draws a frame using special characters, assuming one of the default font layouts (or similar) is being used.
/// If title is not null or empty, then this string is printed a the top left corner of the frame.
/// </summary>
/// <param name="rect"></param>
/// <param name="title"></param>
/// <param name="clear">If true, clears the region inside the frame with the default back color</param>
public void DrawFrame(Rectangle rect, string title = null, bool clear = false) {
DrawFrame(rect, title, clear, DefaultForeground, DefaultBackground);
}
private int GetHorizontalDelta(int strLength, int width, HorizontalAligment hAlign) {
int dx;
switch (hAlign) {
case HorizontalAligment.Left:
dx = 0;
break;
case HorizontalAligment.Center:
dx = (width - strLength)/2;
break;
case HorizontalAligment.Right:
default:
dx = (width - strLength);
break;
}
return dx;
}
private int GetVerticalDelta(int numLines, int height, VerticalAlignment vAlign) {
int dy;
switch (vAlign) {
case VerticalAlignment.Top:
dy = 0;
break;
case VerticalAlignment.Center:
dy = (height - numLines)/2;
break;
case VerticalAlignment.Bottom:
default:
dy = height - numLines;
break;
}
return dy;
}
private string[] GetCharWrappedLines(string str, int maxWidth) {
var stringlist = new List<string>();
int count = 0;
var builder = new StringBuilder();
for (int i = 0; i < str.Length; i++) {
builder.Append(str[i]);
count++;
if (count >= maxWidth) {
count = 0;
stringlist.Add(builder.ToString());
builder.Clear();
}
}
stringlist.Add(builder.ToString());
return stringlist.ToArray();
}
private string[] GetWordWrappedLines(string str, int width) {
var lines = new List<string>();
string[] words = Explode(str);
int currlength = 0;
var currentLine = new StringBuilder();
for (int i = 0; i < words.Length; i++) {
if (words[i].Length + currlength > width) {
if (currlength > 0) {
lines.Add(currentLine.ToString());
currentLine.Clear();
currlength = 0;
}
if (words[i].Length > width) {
string[] cwlines = GetCharWrappedLines(words[i], width);
foreach (string s in cwlines) {
lines.Add(s);
}
currlength = 0;
}
else {
currentLine.Append(words[i] + ' ');
currlength += words[i].Length + 1;
}
}
else {
currentLine.Append(words[i] + ' ');
currlength += words[i].Length + 1;
}
}
if (currentLine.Length > 0)
lines.Add(currentLine.ToString());
return lines.ToArray();
}
private string[] Explode(string str) {
var stringList = new List<string>();
int currIndex = 0;
var builder = new StringBuilder();
while (true) {
while (currIndex < str.Length && char.IsWhiteSpace(str[currIndex])) {
currIndex++;
}
while (currIndex < str.Length && !char.IsWhiteSpace(str[currIndex])) {
builder.Append(str[currIndex]);
currIndex++;
}
stringList.Add(builder.ToString());
builder.Clear();
if (currIndex >= str.Length)
break;
}
return stringList.ToArray();
}
internal virtual void SetCell(int x, int y, char? c, Color? fore, Color? back) {
if (x < 0 || x >= Width || y < 0 || y >= Height)
return;
if (back.HasValue)
Cells[x + y*Width].Back = back.Value;
if (fore.HasValue)
Cells[x + y*Width].Fore = fore.Value;
if (c.HasValue)
Cells[x + y*Width].Char = c.Value;
// At least something chnaged, mark the cell up as dirty.
if (back.HasValue || fore.HasValue || c.HasValue)
DirtyCells[x + y*Width] = true;
}
/// <summary>
/// Render this surface into a RenderTarget2D
/// </summary>
/// <returns>A drawn RenderTarget2D with this surfaces data on it</returns>
internal virtual RenderTarget2D RenderSurface(RenderTarget2D renderTarget) {
ParentConsole.Graphics.SetRenderTarget(renderTarget);
ParentConsole.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
var fontSrc = new Rectangle(0, 0, 10, 10);
for (int y = 0; y < Height; y++) {
for (int x = 0; x < Width; x++) {
if (DirtyCells[x + y*Width]) {
// Background
Font.SetFontSourceRect(ref fontSrc, (char) Font.SolidChar);
ParentConsole.SpriteBatch.Draw(Font.Texture,
new Vector2(x*Font.CharacterWidth, y*Font.CharacterWidth),
fontSrc,
Cells[x + y*Width].Back);
// Foreground
Font.SetFontSourceRect(ref fontSrc, Cells[x + y*Width].Char);
ParentConsole.SpriteBatch.Draw(Font.Texture,
new Vector2(x*Font.CharacterWidth, y*Font.CharacterHeight),
fontSrc,
Cells[x + y*Width].Fore);
}
}
}
ParentConsole.SpriteBatch.End();
ParentConsole.Graphics.SetRenderTarget(null);
return renderTarget;
}
internal virtual void ClearSurface() {
for (int i = 0; i < Width*Height; i++) {
Cells[i].Back = DefaultBackground;
Cells[i].Char = ' ';
Cells[i].Fore = DefaultForeground;
}
Array.Clear(DirtyCells, 0, DirtyCells.Length);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
using System.Reflection;
#else
using PRI.ProductivityExtensions.ActionExtensions;
#endif
using System.Runtime.CompilerServices;
using System.Threading;
#if SUPPORT_ASYNC_CONSUMER
using System.Threading.Tasks;
#endif
using PRI.Messaging.Patterns.Exceptions;
using PRI.Messaging.Primitives;
using TokenType= System.Tuple<System.Guid, System.Action<PRI.Messaging.Primitives.IMessage>, System.Func<PRI.Messaging.Primitives.IMessage, System.Threading.Tasks.Task>>;
[assembly: InternalsVisibleTo("Tests")]
[assembly: InternalsVisibleTo("Tests-Core")]
namespace PRI.Messaging.Patterns
{
/// <summary>
/// An implementation of a composable bus https://en.wikipedia.org/wiki/Bus_(computing) that transfers messages between zero or more producers
/// and zero or more consumers, decoupling producers from consumers.
/// <example>
/// Compose a bus from any/all consumers located in current directory in the Rock.QL.Endeavor.MessageHandlers namespace with a filename that matches Rock.QL.Endeavor.*Handler*.dll
/// <code>
/// var bus = new Bus();
/// var directory = Path.GetDirectoryName(new Uri(GetType().Assembly.CodeBase).LocalPath);
/// bus.AddHandlersAndTranslators(directory, "Rock.QL.Endeavor.*Handler*.dll", "Rock.QL.Endeavor.MessageHandlers");
/// </code>
/// Manually compose a bus and send it a message
/// <code>
/// var bus = new Bus();
///
/// var message2Consumer = new MessageConsumer();
/// bus.AddHandler(message2Consumer);
///
/// bus.Handle(new Message());
/// </code>
/// </example>
/// </summary>
public class Bus : IBus, IDisposable
{
internal readonly Dictionary<string, Action<IMessage>> _consumerInvokers = new Dictionary<string, Action<IMessage>>();
internal readonly Dictionary<string, Dictionary<Guid, Action<IMessage>>> _consumerInvokersDictionaries =
new Dictionary<string, Dictionary<Guid, Action<IMessage>>>();
#if SUPPORT_ASYNC_CONSUMER // TODO: add more tests
internal readonly Dictionary<string, Func<IMessage, Task>> _asyncConsumerInvokers =
new Dictionary<string, Func<IMessage, Task>>();
internal readonly Dictionary<string, Dictionary<Guid, Func<IMessage, Task>>> _asyncConsumerInvokersDictionaries =
new Dictionary<string, Dictionary<Guid, Func<IMessage, Task>>>();
#endif
#if in_progress
internal readonly Dictionary<IMessage, Dictionary<string, string>> _outgoingMessageHeaders =
new Dictionary<IMessage, Dictionary<string, string>>();
#endif
private ReaderWriterLockSlim _readerWriterConsumersLock = new ReaderWriterLockSlim();
private ReaderWriterLockSlim _readerWriterAsyncConsumersLock = new ReaderWriterLockSlim();
#if PARANOID
private readonly List<Guid> _invokedConsumers = new List<Guid>();
#endif // PARANOID
protected virtual void Handle(IMessage message, out bool wasProcessed)
{
var isEvent = message is IEvent;
var messageType = message.GetType();
Action<IMessage> consumerInvoker;
bool consumerExists;
_readerWriterConsumersLock.EnterReadLock();
Guid messageTypeGuid;
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
messageTypeGuid = messageType.GetTypeInfo().GUID;
#else
messageTypeGuid = messageType.GUID;
#endif
try
{
consumerExists = _consumerInvokers.TryGetValue(messageType.AssemblyQualifiedName ?? messageTypeGuid.ToString(),
out consumerInvoker);
}
finally
{
_readerWriterConsumersLock.ExitReadLock();
}
wasProcessed = false;
if (consumerExists)
{
#if PARANOID
_invokedConsumers.AddRange(_consumerInvokersDictionaries[messageType.AssemblyQualifiedName ?? messageType.GUID.ToString()].Keys);
#endif // PARANOID
consumerInvoker(message);
wasProcessed = true;
if (!isEvent)
return;
}
// check base type hierarchy.
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
messageType = messageType.GetTypeInfo().BaseType;
#else
messageType = messageType.BaseType;
#endif
while (messageType != null && messageType != typeof(object))
{
_readerWriterConsumersLock.EnterReadLock();
try
{
consumerExists = _consumerInvokers.TryGetValue(messageType.AssemblyQualifiedName ?? messageTypeGuid.ToString(),
out consumerInvoker);
}
finally
{
_readerWriterConsumersLock.ExitReadLock();
}
if (consumerExists)
{
consumerInvoker(message);
wasProcessed = true;
if (!isEvent)
return;
}
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
messageType = messageType.GetTypeInfo().BaseType;
#else
messageType = messageType.BaseType;
#endif
}
// check any implemented interfaces
messageType = message.GetType();
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
var interfaces = messageType.GetTypeInfo().ImplementedInterfaces;
#else
var interfaces = messageType.FindInterfaces((type, criteria) => true, null);
#endif
foreach (var interfaceType in interfaces)
{
_readerWriterConsumersLock.EnterReadLock();
try
{
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
var guid = interfaceType.GetTypeInfo().GUID;
#else
var guid = interfaceType.GUID;
#endif
consumerExists = _consumerInvokers.TryGetValue(interfaceType.AssemblyQualifiedName ?? guid.ToString(),
out consumerInvoker);
}
finally
{
_readerWriterConsumersLock.ExitReadLock();
}
if (!consumerExists) continue;
consumerInvoker(message);
wasProcessed = true;
if (!isEvent)
return;
}
}
public virtual void Handle(IMessage message)
{
bool wasProcessed;
Handle(message, out wasProcessed);
}
public void AddTranslator<TIn, TOut>(IPipe<TIn, TOut> pipe) where TIn : IMessage where TOut : IMessage
{
pipe.AttachConsumer(new ActionConsumer<TOut>(m => this.Handle(m)));
Action<IMessage> handler = o => pipe.Handle((TIn) o);
var typeGuid = typeof(TIn).AssemblyQualifiedName ??
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
typeof(TIn).GetTypeInfo().GUID.ToString();
#else
typeof(TIn).GUID.ToString();
#endif
// never gets removed, inline guid
var delegateGuid = Guid.NewGuid();
_readerWriterConsumersLock.EnterWriteLock();
try
{
if (_consumerInvokers.ContainsKey(typeGuid))
{
_consumerInvokersDictionaries[typeGuid][delegateGuid] = handler;
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
Action<IMessage> actions = _consumerInvokersDictionaries[typeGuid].Values.First();
foreach (var action in _consumerInvokersDictionaries[typeGuid].Values.Skip(1))
{
actions = actions + action;
}
_consumerInvokers[typeGuid] = actions;
#else
_consumerInvokers[typeGuid] =
_consumerInvokersDictionaries[typeGuid].Values.Sum();
#endif
}
else
{
_consumerInvokersDictionaries.Add(typeGuid,
new Dictionary<Guid, Action<IMessage>> {{delegateGuid, handler}});
_consumerInvokers.Add(typeGuid, handler);
}
}
finally
{
_readerWriterConsumersLock.ExitWriteLock();
}
}
#if SUPPORT_ASYNC_CONSUMER
private Func<IMessage, Task> CreateAsyncConsumerDelegate<TIn>(IAsyncConsumer<TIn> asyncConsumer) where TIn : IMessage
{
return async o => await asyncConsumer.HandleAsync((TIn)o).ConfigureAwait(false);
}
#endif
private Action<IMessage> CreateConsumerDelegate<TIn>(IConsumer<TIn> consumer) where TIn : IMessage
{
return o => consumer.Handle((TIn) o);
}
public object AddHandler<TIn>(IConsumer<TIn> consumer) where TIn : IMessage
{
Action<IMessage> handler = CreateConsumerDelegate(consumer);
var typeGuid = typeof(TIn).AssemblyQualifiedName ??
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
typeof(TIn).GetTypeInfo().GUID.ToString();
#else
typeof(TIn).GUID.ToString();
#endif
var delegateGuid = Guid.NewGuid();
#if SUPPORT_ASYNC_CONSUMER
var asyncConsumer = consumer as IAsyncConsumer<TIn>;
if (asyncConsumer == null)
{
#endif
_readerWriterConsumersLock.EnterWriteLock();
try
{
if (_consumerInvokers.ContainsKey(typeGuid))
{
_consumerInvokersDictionaries[typeGuid][delegateGuid] = handler;
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
Action<IMessage> actions = _consumerInvokersDictionaries[typeGuid].Values.First();
foreach (var action in _consumerInvokersDictionaries[typeGuid].Values.Skip(1))
{
actions = actions + action;
}
_consumerInvokers[typeGuid] = actions;
#else
_consumerInvokers[typeGuid] = _consumerInvokersDictionaries[typeGuid].Values.Sum();
#endif
}
else
{
try
{
_consumerInvokersDictionaries.Add(typeGuid,
new Dictionary<Guid, Action<IMessage>> {{delegateGuid, handler}});
}
catch (ArgumentException ex)
{
throw new UnexpectedDuplicateKeyException(ex, typeGuid, _consumerInvokersDictionaries.Keys,
"invoker dictionaries");
}
try
{
_consumerInvokers.Add(typeGuid, handler);
}
catch (ArgumentException ex)
{
throw new UnexpectedDuplicateKeyException(ex, typeGuid, _consumerInvokers.Keys, "invokers");
}
}
}
finally
{
_readerWriterConsumersLock.ExitWriteLock();
}
return new TokenType(delegateGuid, handler, null);
#if SUPPORT_ASYNC_CONSUMER
}
var asyncHandler = CreateAsyncConsumerDelegate(asyncConsumer);
_readerWriterAsyncConsumersLock.EnterWriteLock();
try
{
if (_asyncConsumerInvokers.ContainsKey(typeGuid))
{
_asyncConsumerInvokersDictionaries[typeGuid][delegateGuid] = asyncHandler;
_asyncConsumerInvokers[typeGuid] = _asyncConsumerInvokersDictionaries[typeGuid].Values.Sum();
}
else
{
_asyncConsumerInvokersDictionaries.Add(typeGuid,
new Dictionary<Guid, Func<IMessage, Task>> {{delegateGuid, asyncHandler}});
_asyncConsumerInvokers.Add(typeGuid, asyncHandler);
}
}
finally
{
_readerWriterAsyncConsumersLock.ExitWriteLock();
}
_readerWriterConsumersLock.EnterWriteLock();
try
{
if (_consumerInvokers.ContainsKey(typeGuid))
{
_consumerInvokersDictionaries[typeGuid][delegateGuid] = handler;
_consumerInvokers[typeGuid] = _consumerInvokersDictionaries[typeGuid].Values.Sum();
}
else
{
_consumerInvokersDictionaries.Add(typeGuid,
new Dictionary<Guid, Action<IMessage>> { { delegateGuid, handler } });
_consumerInvokers.Add(typeGuid, handler);
}
}
finally
{
_readerWriterConsumersLock.ExitWriteLock();
}
return new TokenType(delegateGuid, handler, asyncHandler);
#endif
}
#if PARANOID
internal
#else
public
#endif
void RemoveHandler<TIn>(IConsumer<TIn> consumer, object tag
#if PARANOID
, bool nocheck = false
#endif // PARANOID
) where TIn : IMessage
{
if (tag == null)
throw new ArgumentNullException(nameof(tag));
var tuple = tag as TokenType;
if (tuple == null)
throw new InvalidOperationException();
var typeGuid = typeof(TIn).AssemblyQualifiedName ??
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
typeof(TIn).GetTypeInfo().GUID.ToString();
#else
typeof(TIn).GUID.ToString();
#endif
_readerWriterConsumersLock.EnterUpgradeableReadLock();
try
{
var hasConsumerType = _consumerInvokers.ContainsKey(typeGuid);
if (!hasConsumerType)
return;
#if PARANOID
if (!nocheck && !_invokedConsumers.Contains(tuple.Item1))
throw new MessageHandlerRemovedBeforeProcessingMessageException<TIn>();
#endif // PARANOID
_readerWriterConsumersLock.EnterWriteLock();
try
{
_consumerInvokersDictionaries[typeGuid].Remove(tuple.Item1);
if (_consumerInvokersDictionaries[typeGuid].Any()) // any more left for that type?
{
#if NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4
Action<IMessage> actions = _consumerInvokersDictionaries[typeGuid].Values.First();
foreach (var action in _consumerInvokersDictionaries[typeGuid].Values.Skip(1))
{
actions = actions + action;
}
_consumerInvokers[typeGuid] = actions;
#else
_consumerInvokers[typeGuid] = _consumerInvokersDictionaries[typeGuid].Values.Sum();
#endif
}
else
{
_consumerInvokers.Remove(typeGuid); // if no more, get rid of invoker
_consumerInvokersDictionaries.Remove(typeGuid);
}
}
finally
{
_readerWriterConsumersLock.ExitWriteLock();
}
}
finally
{
_readerWriterConsumersLock.ExitUpgradeableReadLock();
}
}
#if PARANOID
public void RemoveHandler<TIn>(IConsumer<TIn> consumer, object tag) where TIn : IMessage
{
RemoveHandler(consumer, tag, nocheck: false);
}
#endif
#if in_progress
ThreadLocal<Dictionary<string,string>> currentMessageDictionary = new ThreadLocal<Dictionary<string, string>>();
public void AddHeader(IMessage message, string key, string value)
{
Dictionary<string, string> dict;
if (_outgoingMessageHeaders.ContainsKey(message))
{
dict = _outgoingMessageHeaders[message];
}
else
{
dict = new Dictionary<string, string>();
_outgoingMessageHeaders[message] = dict;
}
dict[key] = value;
}
#endif // in_progress
#if SUPPORT_ASYNC_CONSUMER
public Task HandleAsync(IMessage message)
{
bool wasProcessed;
return HandleAsync(message, out wasProcessed);
}
public Task HandleAsync(IMessage message, out bool wasProcessed)
{
var isEvent = message is IEvent;
var messageType = message.GetType();
Func<IMessage, Task> consumerInvoker;
Task task = null;
bool hasConsumer;
_readerWriterAsyncConsumersLock.EnterReadLock();
var messageTypeGuid = messageType.AssemblyQualifiedName ?? messageType.GUID.ToString();
try
{
hasConsumer = _asyncConsumerInvokers.TryGetValue(messageTypeGuid, out consumerInvoker);
}
finally
{
_readerWriterAsyncConsumersLock.ExitReadLock();
}
wasProcessed = false;
if (hasConsumer)
{
#if PARANOID
_invokedConsumers.AddRange(_consumerInvokersDictionaries[messageTypeGuid].Keys);
#endif // PARANOID
task = consumerInvoker(message);
wasProcessed = true;
if (!isEvent)
return task;
}
// check base type hierarchy.
messageType = messageType.BaseType;
while (messageType != null && messageType != typeof(object))
{
_readerWriterAsyncConsumersLock.EnterReadLock();
try
{
hasConsumer = _asyncConsumerInvokers.TryGetValue(messageTypeGuid, out consumerInvoker);
}
finally
{
_readerWriterAsyncConsumersLock.ExitReadLock();
}
if (hasConsumer)
{
#if PARANOID
_invokedConsumers.AddRange(_consumerInvokersDictionaries[messageTypeGuid].Keys);
#endif // PARANOID
var newTask = consumerInvoker(message);
wasProcessed = true;
// merge tasks, if needed
task = task != null ? Task.WhenAll(task, newTask) : newTask;
if (!isEvent)
return task;
}
messageType = messageType.BaseType;
}
// check any implemented interfaces
messageType = message.GetType();
foreach (var interfaceType in messageType.FindInterfaces((type, criteria) => true, null))
{
_readerWriterAsyncConsumersLock.EnterReadLock();
var interfaceTypeGuid = interfaceType.AssemblyQualifiedName ?? interfaceType.GUID.ToString();
try
{
hasConsumer = _asyncConsumerInvokers.TryGetValue(interfaceTypeGuid, out consumerInvoker);
}
finally
{
_readerWriterAsyncConsumersLock.ExitReadLock();
}
if (!hasConsumer) continue;
#if PARANOID
_invokedConsumers.AddRange(_consumerInvokersDictionaries[interfaceTypeGuid].Keys);
#endif // PARANOID
var newTask = consumerInvoker(message);
wasProcessed = true;
// merge tasks if needed
task = task != null ? Task.WhenAll(task, newTask) : newTask;
if (!isEvent)
return task;
}
if (task != null)
return task;
Handle(message); // if no async handlers, handle synchronously
return Task.FromResult(true); // TODO: Replace with Task.CompletedTask in .NET 4.6+
}
#endif //SUPPORT_ASYNC_CONSUMER
public virtual void Dispose()
{
_readerWriterConsumersLock.Dispose();
_readerWriterAsyncConsumersLock.Dispose();
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Timers;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Console;
using OpenSim.Framework.Statistics;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework;
using System.Runtime;
namespace OpenSim
{
/// <summary>
/// Interactive OpenSim region server
/// </summary>
public class OpenSim : OpenSimBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_startupCommandsFile;
protected string m_shutdownCommandsFile;
protected bool m_gui = false;
protected string m_consoleType = "local";
protected uint m_consolePort = 0;
/// <summary>
/// Prompt to use for simulator command line.
/// </summary>
private string m_consolePrompt;
/// <summary>
/// Regex for parsing out special characters in the prompt.
/// </summary>
private Regex m_consolePromptRegex = new Regex(@"([^\\])\\(\w)", RegexOptions.Compiled);
private string m_timedScript = "disabled";
private Timer m_scriptTimer;
public OpenSim(IConfigSource configSource) : base(configSource)
{
}
protected override void ReadExtraConfigSettings()
{
base.ReadExtraConfigSettings();
IConfig startupConfig = m_config.Source.Configs["Startup"];
IConfig networkConfig = m_config.Source.Configs["Network"];
if (startupConfig != null)
{
m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt");
m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt");
if (String.IsNullOrEmpty(startupConfig.GetString("console", String.Empty)))
m_gui = startupConfig.GetBoolean("gui", false);
else
m_consoleType= startupConfig.GetString("console", String.Empty);
if (networkConfig != null)
m_consolePort = (uint)networkConfig.GetInt("console_port", 0);
m_timedScript = startupConfig.GetString("timer_Script", "disabled");
if (m_logFileAppender != null)
{
if (m_logFileAppender is log4net.Appender.FileAppender)
{
log4net.Appender.FileAppender appender =
(log4net.Appender.FileAppender)m_logFileAppender;
string fileName = startupConfig.GetString("LogFile", String.Empty);
if (!String.IsNullOrEmpty(fileName))
appender.File = fileName;
m_log.InfoFormat("[LOGGING] Logging started to file {0}", appender.File);
}
}
}
if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
{
Util.InitThreadPool(Util.PoolSelection.Default, 20);
Util.InitThreadPool(Util.PoolSelection.LongIO, 16);
}
}
/// <summary>
/// Performs initialization of the scene, such as loading configuration from disk.
/// </summary>
protected override void StartupSpecific()
{
m_log.Info("====================================================================");
m_log.Info("========================= STARTING HALCYON =========================");
m_log.Info("====================================================================");
m_log.InfoFormat("[HALCYON MAIN]: Running in {0} mode",
(ConfigurationSettings.Standalone ? "sandbox" : "grid"));
m_log.InfoFormat("GC: Server mode: {0}, {1}", GCSettings.IsServerGC.ToString(), GCSettings.LatencyMode.ToString());
//m_log.InfoFormat("[HALCYON MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString());
// http://msdn.microsoft.com/en-us/library/bb384202.aspx
//GCSettings.LatencyMode = GCLatencyMode.Batch;
//m_log.InfoFormat("[HALCYON MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString());
if (m_gui) // Driven by external GUI
{
m_console = new CommandConsole("Region");
}
else
{
switch (m_consoleType)
{
case "basic":
m_console = new CommandConsole("Region");
break;
case "rest":
m_console = new RemoteConsole("Region");
((RemoteConsole)m_console).ReadConfig(m_config.Source);
break;
default:
m_console = new LocalConsole("Region");
break;
}
}
MainConsole.Instance = m_console;
RegisterConsoleCommands();
base.StartupSpecific();
if (m_console is RemoteConsole)
{
if (m_consolePort == 0)
{
((RemoteConsole)m_console).SetServer(m_httpServer);
}
else
{
((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort));
}
}
//Run Startup Commands
if (String.IsNullOrEmpty(m_startupCommandsFile))
{
m_log.Info("[STARTUP]: No startup command script specified. Moving on...");
}
else
{
RunCommandScript(m_startupCommandsFile);
}
// Start timer script (run a script every xx seconds)
if (m_timedScript != "disabled")
{
m_scriptTimer = new Timer();
m_scriptTimer.Enabled = true;
m_scriptTimer.Interval = 1200*1000;
m_scriptTimer.Elapsed += RunAutoTimerScript;
}
PrintFileToConsole("startuplogo.txt");
// For now, start at the 'root' level by default
if (m_sceneManager.Scenes.Count == 1) // If there is only one region, select it
ChangeSelectedRegion("region",
new string[] {"change", "region", m_sceneManager.Scenes[0].RegionInfo.RegionName});
else
ChangeSelectedRegion("region", new string[] {"change", "region", "root"});
}
/// <summary>
/// Register standard set of region console commands
/// </summary>
private void RegisterConsoleCommands()
{
MainServer.RegisterHttpConsoleCommands(m_console);
m_console.Commands.AddCommand("base", false, "trust reload",
"trust reload",
"Reloads the trust configuration for the trust manager", HandleTrustReload);
m_console.Commands.AddCommand("region", false, "clear assets",
"clear assets",
"Clear the asset cache", HandleClearAssets);
m_console.Commands.AddCommand("region", false, "force update",
"force update",
"Force the update of all objects on clients",
HandleForceUpdate);
m_console.Commands.AddCommand("region", false, "debug packet",
"debug packet <level>",
"Turn on packet debugging", Debug);
m_console.Commands.AddCommand("region", false, "debug scene",
"debug scene <cripting> <collisions> <physics>",
"Turn on scene debugging", Debug);
m_console.Commands.AddCommand("region", false, "debug crossings",
"debug crossings <level>",
"Turn on crossings debugging (0 or 1)", Debug);
m_console.Commands.AddCommand("region", false, "change region",
"change region <region name>",
"Change current console region", ChangeSelectedRegion);
m_console.Commands.AddCommand("region", false, "save xml",
"save xml",
"Save a region's data in XML format", SaveXml);
m_console.Commands.AddCommand("region", false, "save xml2",
"save xml2",
"Save a region's data in XML2 format", SaveXml2);
m_console.Commands.AddCommand("region", false, "load xml",
"load xml [-newIDs [<x> <y> <z>]]",
"Load a region's data from XML format", LoadXml);
m_console.Commands.AddCommand("region", false, "load xml2",
"load xml2",
"Load a region's data from XML2 format", LoadXml2);
m_console.Commands.AddCommand("region", false, "save prims xml2",
"save prims xml2 [<prim name> <file name>]",
"Save named prim to XML2", SavePrimsXml2);
m_console.Commands.AddCommand("region", false, "load oar",
"load oar [--ignore-errors] <oar name>",
"Load a region's data from OAR archive", LoadOar);
m_console.Commands.AddCommand("region", false, "save oar",
"save oar <oar name> <store_assets>",
"Save a region's data to an OAR archive",
"Store an archive [<store assets> 1 to save assets in the file or 0 to omit]", SaveOar);
m_console.Commands.AddCommand("region", false, "loadexplicit oar",
"loadexplicit oar <region name> <oar name>",
"Load a region's data from OAR archive", LoadExplicitOar);
m_console.Commands.AddCommand("region", false, "saveportable oar",
"saveportable oar <oar filename> [allowed_uuid allowed_uuid ...]",
"Save a region's data to an OAR archive with assets suitable for export from inworldz",
"Store an archive [<store assets> 1 to save assets in the file or 0 to omit]", SavePortableOar);
m_console.Commands.AddCommand("region", false, "saveexplicit oar",
"saveexplicit oar <region name> <oar filename> <store_assets>",
"Save a region's data to an OAR archive",
"Store an archive [<store assets> 1 to save assets in the file or 0 to omit]", SaveExplicitOar);
m_console.Commands.AddCommand("region", false, "edit scale",
"edit scale <name> <x> <y> <z>",
"Change the scale of a named prim", HandleEditScale);
m_console.Commands.AddCommand("region", false, "kick user",
"kick user <first> <last> [message]",
"Kick a user off the simulator", KickUserCommand);
m_console.Commands.AddCommand("region", false, "teleport user",
"teleport user <first> <last> regionName x y z",
"Force-teleport a user to another location", TeleportUserCommand);
m_console.Commands.AddCommand("region", false, "show assets",
"show assets",
"Show asset data", HandleShow);
m_console.Commands.AddCommand("region", false, "show users",
"show users [full]",
"Show user data", HandleShow);
m_console.Commands.AddCommand("region", false, "show remotes",
"show remotes",
"Shows avatar remote presences and their states", HandleShow);
m_console.Commands.AddCommand("region", false, "show users full",
"show users full",
String.Empty, HandleShow);
m_console.Commands.AddCommand("region", false, "show modules",
"show modules",
"Show module data", HandleShow);
m_console.Commands.AddCommand("region", false, "show regions",
"show regions",
"Show region data", HandleShow);
m_console.Commands.AddCommand("region", false, "show queues",
"show queues",
"Show queue data", HandleShow);
m_console.Commands.AddCommand("region", false, "show ratings",
"show ratings",
"Show rating data", HandleShow);
m_console.Commands.AddCommand("region", false, "show owners",
"show owners",
"Show owners of objects", HandleShow);
m_console.Commands.AddCommand("region", false, "show object",
"show object",
"Show information on object specified by UUID or localID", HandleShow);
m_console.Commands.AddCommand("region", false, "show collisions",
"show collisions",
"Collects information about current collisions and shows the data", HandleShow);
m_console.Commands.AddCommand("region", false, "show updates",
"show updates [delta/total]",
"Collects information about objects posting updates", HandleShow);
m_console.Commands.AddCommand("region", false, "nuke",
"nuke",
"Delete all objects owned by the specified UUID", HandleNuke);
m_console.Commands.AddCommand("region", false, "blacklist object owner",
"blacklist object owner",
"Prevent rezzing of all objects with the specified owner UUID", HandleBlacklistOwner);
m_console.Commands.AddCommand("region", false, "blacklist object creator",
"blacklist object creator",
"Prevent rezzing of all objects with the specified creator UUID", HandleBlacklistCreator);
m_console.Commands.AddCommand("region", false, "blacklist object name",
"blacklist object name",
"Prevent rezzing of all objects that start with the the specified partial name", HandleBlacklistName);
m_console.Commands.AddCommand("region", false, "blacklist user",
"blacklist user",
"Prevent region entry and rezzing of all objects based on the user/owner", HandleBlacklistUser);
m_console.Commands.AddCommand("region", false, "blacklist remove",
"blacklist remove",
"Remove a previous blacklist entry (uuid or name)", HandleBlacklistRemove);
m_console.Commands.AddCommand("region", false, "blacklist clear",
"blacklist clear",
"Remove all existing blacklist entries (all types)", HandleBlacklistClear);
m_console.Commands.AddCommand("region", false, "blacklist show",
"blacklist show",
"Display the existing blacklist entries", HandleBlacklistShow);
m_console.Commands.AddCommand("region", false, "backup",
"backup",
"Persist objects to the database now", RunCommand);
m_console.Commands.AddCommand("region", false, "create region",
"create region",
"Create a new region", HandleCreateRegion);
m_console.Commands.AddCommand("region", false, "login enable",
"login enable",
"Enable logins to the simulator", HandleLoginEnable);
m_console.Commands.AddCommand("region", false, "login disable",
"login disable",
"Disable logins to the simulator", HandleLoginDisable);
m_console.Commands.AddCommand("region", false, "login status",
"login status",
"Display status of logins", HandleLoginStatus);
m_console.Commands.AddCommand("region", false, "restart",
"restart",
"Restart all sims in this instance", RunCommand);
m_console.Commands.AddCommand("region", false, "config set",
"config set <section> <field> <value>",
"Set a config option", HandleConfig);
m_console.Commands.AddCommand("region", false, "config get",
"config get <section> <field>",
"Read a config option", HandleConfig);
m_console.Commands.AddCommand("region", false, "config save",
"config save",
"Save current configuration", HandleConfig);
m_console.Commands.AddCommand("region", false, "command-script",
"command-script <script>",
"Run a command script from file", RunCommand);
m_console.Commands.AddCommand("region", false, "remove-region",
"remove-region <name>",
"Remove a region from this simulator", RunCommand);
m_console.Commands.AddCommand("region", false, "delete-region",
"delete-region <name>",
"Delete a region from disk", RunCommand);
m_console.Commands.AddCommand("region", false, "predecode-j2k",
"predecode-j2k [<num threads>]>",
"Precache assets,decode j2k layerdata", RunCommand);
m_console.Commands.AddCommand("region", false, "modules list",
"modules list",
"List modules", HandleModules);
m_console.Commands.AddCommand("region", false, "modules load",
"modules load <name>",
"Load a module", HandleModules);
m_console.Commands.AddCommand("region", false, "modules unload",
"modules unload <name>",
"Unload a module", HandleModules);
m_console.Commands.AddCommand("region", false, "Add-InventoryHost",
"Add-InventoryHost <host>",
String.Empty, RunCommand);
if (ConfigurationSettings.Standalone)
{
m_console.Commands.AddCommand("region", false, "create user",
"create user [<first> [<last> [<pass> [<x> <y> [<email>]]]]]",
"Create a new user", HandleCreateUser);
m_console.Commands.AddCommand("region", false, "reset user password",
"reset user password [<first> [<last> [<password>]]]",
"Reset a user password", HandleResetUserPassword);
}
m_console.Commands.AddCommand("region", false, "get script status",
"get script status [itemid]",
"Returns information about the run state of the given script", GetScriptStatus);
m_console.Commands.AddCommand("region", false, "trace script",
"trace script [itemid]",
"Returns information about the run state of the given script", TraceScript);
m_console.Commands.AddCommand("region", false, "trace disable all",
"trace disable all",
"Disables all script tracing", DisableAllTraces);
}
public override void ShutdownSpecific()
{
if (!String.IsNullOrEmpty(m_shutdownCommandsFile))
{
RunCommandScript(m_shutdownCommandsFile);
}
base.ShutdownSpecific();
}
private void RunAutoTimerScript(object sender, EventArgs e)
{
if (m_timedScript != "disabled")
{
RunCommandScript(m_timedScript);
}
}
#region Console Commands
private void KickUserCommand(string module, string[] cmdparams)
{
if (cmdparams.Length < 4)
return;
string alert = null;
if (cmdparams.Length > 4)
alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4));
IList agents = m_sceneManager.GetCurrentSceneAvatars();
foreach (ScenePresence presence in agents)
{
RegionInfo regionInfo = m_sceneManager.GetRegionInfo(presence.RegionHandle);
if (presence.Firstname.ToLower().Contains(cmdparams[2].ToLower()) &&
presence.Lastname.ToLower().Contains(cmdparams[3].ToLower()))
{
m_console.Notice(
String.Format(
"Kicking user: {0,-16}{1,-16}{2,-37} in region: {3,-16}",
presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName));
// kick client...
if (alert != null)
presence.ControllingClient.Kick(alert);
else
presence.ControllingClient.Kick("\nThe grid manager kicked you out.\n");
// ...and close on our side
presence.Scene.IncomingCloseAgent(presence.UUID);
}
}
m_console.Notice(String.Empty);
}
private void TeleportUserCommand(string module, string[] cmdparams)
{
if (cmdparams.Length != 8)
{
m_console.Notice("teleport user <first> <last> regionName x y z");
return;
}
string destreg = cmdparams[4];
Vector3 destpos = new Vector3(128, 128, 25);
try
{
destpos.X = Convert.ToUInt32(cmdparams[5]);
destpos.Y = Convert.ToUInt32(cmdparams[6]);
destpos.Z = Convert.ToUInt32(cmdparams[7]);
}
catch(Exception)
{
m_console.Notice("teleport user <first> <last> regionName x y z");
return;
}
IList agents = m_sceneManager.GetCurrentSceneAvatars();
foreach (ScenePresence presence in agents)
{
RegionInfo regionInfo = m_sceneManager.GetRegionInfo(presence.RegionHandle);
if (presence.Firstname.ToLower().Contains(cmdparams[2].ToLower()) &&
presence.Lastname.ToLower().Contains(cmdparams[3].ToLower()))
{
m_console.Notice(
String.Format(
"Force-teleporting user: {0,-16}{1,-16}{2,-37} in region: {3,-16}",
presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName));
// force-teleport client...
presence.ControllingClient.SendAlertMessage("The grid manager has teleported you to another location.");
if (destreg != presence.Scene.RegionInfo.RegionName) // diff region?
presence.ControllingClient.SendTeleportLocationStart();
presence.Scene.RequestTeleportLocation(presence.ControllingClient, destreg, destpos, presence.Lookat, (uint)TeleportFlags.ViaLocation);
}
}
}
/// <summary>
/// Run an optional startup list of commands
/// </summary>
/// <param name="fileName"></param>
private void RunCommandScript(string fileName)
{
if (File.Exists(fileName))
{
m_log.Info("[COMMANDFILE]: Running " + fileName);
StreamReader readFile = File.OpenText(fileName);
string currentCommand;
while ((currentCommand = readFile.ReadLine()) != null)
{
if (!String.IsNullOrEmpty(currentCommand))
{
m_log.Info("[COMMANDFILE]: Running '" + currentCommand + "'");
m_console.RunCommand(currentCommand);
}
}
}
}
private static void PrintFileToConsole(string fileName)
{
if (File.Exists(fileName))
{
StreamReader readFile = File.OpenText(fileName);
string currentLine;
while ((currentLine = readFile.ReadLine()) != null)
{
m_log.Info("[!]" + currentLine);
}
}
}
private void HandleTrustReload(string module, string[] args)
{
TrustManager.Instance.ReloadTrustLists();
}
private void HandleClearAssets(string module, string[] args)
{
//NOP
}
private void HandleForceUpdate(string module, string[] args)
{
m_console.Notice("Updating all clients");
m_sceneManager.ForceCurrentSceneClientUpdate();
}
private void HandleEditScale(string module, string[] args)
{
if (args.Length == 6)
{
m_sceneManager.HandleEditCommandOnCurrentScene(args);
}
else
{
m_console.Notice("Argument error: edit scale <prim name> <x> <y> <z>");
}
}
private void HandleCreateRegion(string module, string[] cmd)
{
if (cmd.Length < 4 || !cmd[3].EndsWith(".xml"))
{
m_console.Error("Usage: create region <region name> <region_file.xml>");
return;
}
string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim();
string regionFile = String.Format("{0}/{1}", regionsDir, cmd[3]);
// Allow absolute and relative specifiers
if (cmd[3].StartsWith("/") || cmd[3].StartsWith("\\") || cmd[3].StartsWith(".."))
regionFile = cmd[3];
IScene scene;
CreateRegion(new RegionInfo(cmd[2], regionFile, false, ConfigSource.Source), true, out scene);
}
private void HandleLoginEnable(string module, string[] cmd)
{
ProcessLogin(true);
}
private void HandleLoginDisable(string module, string[] cmd)
{
ProcessLogin(false);
}
private void HandleLoginStatus(string module, string[] cmd)
{
if (m_commsManager.GridService.RegionLoginsEnabled == false)
m_log.Info("[ Login ] Login are disabled ");
else
m_log.Info("[ Login ] Login are enabled");
}
private void HandleConfig(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] cmdparams = args.ToArray();
string n = "CONFIG";
if (cmdparams.Length > 0)
{
switch (cmdparams[0].ToLower())
{
case "set":
if (cmdparams.Length < 4)
{
m_console.Error(n, "SYNTAX: " + n + " SET SECTION KEY VALUE");
}
else
{
// IConfig c = DefaultConfig().Configs[cmdparams[1]];
// if (c == null)
// c = DefaultConfig().AddConfig(cmdparams[1]);
IConfig c;
IConfigSource source = new IniConfigSource();
c = source.AddConfig(cmdparams[1]);
if (c != null)
{
string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3);
c.Set(cmdparams[2], _value);
m_config.Source.Merge(source);
m_console.Error(n, n + " " + n + " " + cmdparams[1] + " " + cmdparams[2] + " " +
_value);
}
}
break;
case "get":
if (cmdparams.Length < 3)
{
m_console.Error(n, "SYNTAX: " + n + " GET SECTION KEY");
m_console.Error(n, "EXAMPLE: " + n + " GET ScriptEngine.DotNetEngine NumberOfScriptThreads");
}
else
{
IConfig c = m_config.Source.Configs[cmdparams[1]]; // DefaultConfig().Configs[cmdparams[1]];
if (c == null)
{
m_console.Notice(n, "Section \"" + cmdparams[1] + "\" does not exist.");
break;
}
else
{
m_console.Notice(n + " GET " + cmdparams[1] + " " + cmdparams[2] + ": " +
c.GetString(cmdparams[2]));
}
}
break;
case "save":
m_console.Notice("Saving configuration file: " + ApplicationBase.iniFilePath);
m_config.Save(ApplicationBase.iniFilePath);
break;
}
}
}
private void HandleModules(string module, string[] cmd)
{
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] cmdparams = args.ToArray();
if (cmdparams.Length > 0)
{
switch (cmdparams[0].ToLower())
{
case "list":
foreach (IRegionModule irm in m_moduleLoader.GetLoadedSharedModules)
{
m_console.Notice("Shared region module: " + irm.Name);
}
break;
case "unload":
if (cmdparams.Length > 1)
{
foreach (IRegionModule rm in new ArrayList(m_moduleLoader.GetLoadedSharedModules))
{
if (rm.Name.ToLower() == cmdparams[1].ToLower())
{
m_console.Notice("Unloading module: " + rm.Name);
m_moduleLoader.UnloadModule(rm);
}
}
}
break;
case "load":
if (cmdparams.Length > 1)
{
foreach (Scene s in new ArrayList(m_sceneManager.Scenes))
{
m_console.Notice("Loading module: " + cmdparams[1]);
m_moduleLoader.LoadRegionModules(cmdparams[1], s);
}
}
break;
}
}
}
/// <summary>
/// Runs commands issued by the server console from the operator
/// </summary>
/// <param name="command">The first argument of the parameter (the command)</param>
/// <param name="cmdparams">Additional arguments passed to the command</param>
public void RunCommand(string module, string[] cmdparams)
{
List<string> args = new List<string>(cmdparams);
if (args.Count < 1)
return;
string command = args[0];
args.RemoveAt(0);
cmdparams = args.ToArray();
switch (command)
{
case "command-script":
if (cmdparams.Length > 0)
{
RunCommandScript(cmdparams[0]);
}
break;
case "backup":
m_sceneManager.BackupCurrentScene();
break;
case "remove-region":
string regRemoveName = CombineParams(cmdparams, 0);
Scene removeScene;
if (m_sceneManager.TryGetScene(regRemoveName, out removeScene))
RemoveRegion(removeScene, false);
else
m_console.Error("no region with that name");
break;
case "delete-region":
string regDeleteName = CombineParams(cmdparams, 0);
Scene killScene;
if (m_sceneManager.TryGetScene(regDeleteName, out killScene))
RemoveRegion(killScene, true);
else
m_console.Error("no region with that name");
break;
case "restart":
m_sceneManager.RestartCurrentScene();
break;
case "predecode-j2k":
if (cmdparams.Length > 0)
{
m_sceneManager.CacheJ2kDecode(Convert.ToInt32(cmdparams[0]));
}
else
{
m_sceneManager.CacheJ2kDecode(1);
}
break;
}
}
/// <summary>
/// Change the currently selected region. The selected region is that operated upon by single region commands.
/// </summary>
/// <param name="cmdParams"></param>
protected void ChangeSelectedRegion(string module, string[] cmdparams)
{
if (cmdparams.Length > 2)
{
string newRegionName = CombineParams(cmdparams, 2);
if (!m_sceneManager.TrySetCurrentScene(newRegionName))
m_console.Error("Couldn't select region " + newRegionName);
}
else
{
m_console.Error("Usage: change region <region name>");
}
string regionName = (m_sceneManager.CurrentScene == null ? "root" : m_sceneManager.CurrentScene.RegionInfo.RegionName);
m_console.Notice(String.Format("Currently selected region is {0}", regionName));
m_console.DefaultPrompt = String.Format("Region ({0}) ", regionName);
m_console.ConsoleScene = m_sceneManager.CurrentScene;
}
/// <summary>
/// Execute switch for some of the create commands
/// </summary>
/// <param name="args"></param>
private void HandleCreateUser(string module, string[] cmd)
{
if (ConfigurationSettings.Standalone)
{
CreateUser(cmd);
}
else
{
m_console.Notice("Create user is not available in grid mode, use the user server.");
}
}
/// <summary>
/// Execute switch for some of the reset commands
/// </summary>
/// <param name="args"></param>
protected void HandleResetUserPassword(string module, string[] cmd)
{
if (ConfigurationSettings.Standalone)
{
ResetUserPassword(cmd);
}
else
{
m_console.Notice("Reset user password is not available in grid mode, use the user-server.");
}
}
/// <summary>
/// Turn on some debugging values for OpenSim.
/// </summary>
/// <param name="args"></param>
protected void Debug(string module, string[] args)
{
if (args.Length == 1)
return;
switch (args[1])
{
case "packet":
if (args.Length > 2)
{
int newDebug;
if (int.TryParse(args[2], out newDebug))
{
m_sceneManager.SetDebugPacketLevelOnCurrentScene(newDebug);
}
else
{
m_console.Error("packet debug should be 0..255");
}
m_console.Notice("New packet debug: " + newDebug.ToString());
}
break;
case "scene":
if (args.Length == 5)
{
if (m_sceneManager.CurrentScene == null)
{
m_console.Notice("Please use 'change region <regioname>' first");
}
else
{
bool scriptingOn = !Convert.ToBoolean(args[2]);
bool collisionsOn = !Convert.ToBoolean(args[3]);
bool physicsOn = !Convert.ToBoolean(args[4]);
m_sceneManager.CurrentScene.SetSceneCoreDebug(scriptingOn, collisionsOn, physicsOn);
m_console.Notice(
"CONSOLE",
String.Format(
"Set debug scene scripting = {0}, collisions = {1}, physics = {2}",
!scriptingOn, !collisionsOn, !physicsOn));
}
}
else
{
m_console.Error("debug scene <scripting> <collisions> <physics> (where inside <> is true/false)");
}
break;
case "crossings":
if (args.Length > 2)
{
int newDebug;
if (int.TryParse(args[2], out newDebug))
{
if ((newDebug >= 0) && (newDebug <= 1))
{
m_sceneManager.SetDebugCrossingsLevelOnCurrentScene(newDebug);
m_console.Notice("New crossings debug: " + newDebug.ToString());
break;
}
}
m_console.Error("crossings debug should be 0 or 1");
}
break;
default:
m_console.Error("Unknown debug");
break;
}
}
// see BaseOpenSimServer
public override void HandleShow(string mod, string[] cmd)
{
base.HandleShow(mod, cmd);
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] showParams = args.ToArray();
switch (showParams[0])
{
case "assets":
bool resetStats = (showParams.Length > 1) && (showParams[1] == "reset");
m_assetCache.ShowState(resetStats);
break;
case "users":
IBotManager botManager = m_sceneManager.CurrentOrFirstScene.RequestModuleInterface<IBotManager>();
IList agents;
bool isFullList = (showParams.Length > 1 && showParams[1] == "full");
if (isFullList)
{
agents = m_sceneManager.GetCurrentScenePresences();
}
else
{
agents = m_sceneManager.GetCurrentSceneAvatars();
}
m_console.Notice(
String.Format("{0,-16}{1,-16}{2,-37}{3}",
"Firstname", "Lastname", "Agent ID", "Type"));
int nRoot = 0;
int nChild = 0;
int nBot = 0;
foreach (ScenePresence presence in agents)
{
bool isBot = false;
if (botManager != null)
isBot = botManager.IsBot(presence.UUID);
if (isFullList || !isBot)
{
m_console.Notice(
String.Format(
"{0,-16}{1,-16}{2,-37}{3}",
presence.Firstname,
presence.Lastname,
presence.UUID,
isBot ? "Bot" : presence.IsChildAgent ? "Child" : "Root"));
if (isBot)
nBot++;
else
if (presence.IsChildAgent)
nChild++;
else
nRoot++;
}
}
if (isFullList)
m_console.Notice(String.Format("Total agents: {0}, Root: {1}, Bot: {2}, Child: {3}", agents.Count, nRoot, nBot, nChild));
else
m_console.Notice(String.Format("Agents connected: {0}", nRoot));
m_console.Notice(String.Empty);
break;
case "remotes":
DoShowRemotes();
break;
case "modules":
m_console.Notice("The currently loaded shared modules are:");
foreach (IRegionModule module in m_moduleLoader.GetLoadedSharedModules)
{
m_console.Notice("Shared Module: " + module.Name);
}
break;
case "regions":
m_sceneManager.ForEachScene(
delegate(Scene scene)
{
m_console.Notice("Region Name: " + scene.RegionInfo.RegionName + " , Region XLoc: " +
scene.RegionInfo.RegionLocX + " , Region YLoc: " +
scene.RegionInfo.RegionLocY + " , Region Port: " +
scene.RegionInfo.InternalEndPoint.Port.ToString());
});
break;
case "queues":
Notice(GetQueuesReport());
break;
case "ratings":
m_sceneManager.ForEachScene(
delegate(Scene scene)
{
string rating = String.Empty;
if (scene.RegionInfo.RegionSettings.Maturity == 1)
{
rating = "MATURE";
}
else if (scene.RegionInfo.RegionSettings.Maturity == 2)
{
rating = "ADULT";
}
else
{
rating = "PG";
}
m_console.Notice("Region Name: " + scene.RegionInfo.RegionName + " , Region Rating: " +
rating);
});
break;
case "owners":
int MinCount = 1;
if (showParams.Length > 1)
{
try { MinCount = Convert.ToInt32(showParams[1]); }
catch {
m_console.Notice("Invalid minimum threshold count for prims.");
break;
}
}
Dictionary<UUID,SceneOwnerCounts> counts = m_sceneManager.GetCurrentSceneOwnerCounts();
m_console.Notice(String.Format("Objects Prims UUID Name {0}",MinCount>1?"(with prim counts above "+MinCount.ToString()+")" : String.Empty));
foreach (KeyValuePair<UUID, SceneOwnerCounts> kvp in counts)
{
SceneOwnerCounts count = kvp.Value;
if (count.TotalPrims >= MinCount)
m_console.Notice(String.Format("{0} {1} {2} {3}", count.TotalObjects, count.TotalPrims, kvp.Key.ToString(), count.OwnerName));
}
break;
case "object":
m_sceneManager.ShowObject(showParams);
break;
case "collisions":
m_sceneManager.ShowCollisions(showParams);
break;
case "updates":
m_sceneManager.ShowUpdates(showParams);
break;
}
}
private void DoShowRemotes()
{
IBotManager botManager = m_sceneManager.CurrentOrFirstScene.RequestModuleInterface<IBotManager>();
IList agents = m_sceneManager.GetCurrentSceneAvatars();
foreach (ScenePresence presence in agents)
{
bool isBot = false;
if (botManager != null)
isBot = botManager.IsBot(presence.UUID);
if (!isBot)
{
m_console.Notice(presence.Name + ":");
List<AvatarRemotePresence> presences = presence.RemotePresences.GetRemotePresenceList();
foreach (var remote in presences)
{
m_console.Notice(
String.Format(
" {0} {1} {2}",
remote.PresenceInfo.RegionInfo.RegionHandle,
remote.PresenceInfo.RegionInfo.ExternalHostName,
remote.State
));
}
}
}
m_console.Notice(String.Empty);
}
public void DisableAllTraces(string mod, string[] cmd)
{
IScriptModule module = m_sceneManager.CurrentOrFirstScene.RequestModuleInterface<IScriptModule>();
if (module != null)
{
module.DisableScriptTraces();
}
}
public void TraceScript(string mod, string[] cmd)
{
}
public void GetScriptStatus(string mod, string[] cmd)
{
if (cmd.Length < 4) return;
UUID itemId;
if (UUID.TryParse(cmd[3], out itemId))
{
IScriptModule module = m_sceneManager.CurrentOrFirstScene.RequestModuleInterface<IScriptModule>();
if (module != null)
{
ScriptRuntimeInformation runtimeInfo = module.GetScriptInformation(itemId);
m_console.Output(String.Format("Script Information for Item {0}", itemId));
m_console.Output(String.Format("RunState: {0}", runtimeInfo.CurrentState));
m_console.Output(String.Format("Memory used: {0}", runtimeInfo.MemoryUsed));
m_console.Output(String.Format("Next Wakeup: {0}", runtimeInfo.NextWakeup));
m_console.Output(String.Format("Current Event: {0}", runtimeInfo.CurrentEvent == null ? "none" : runtimeInfo.CurrentEvent));
m_console.Output(String.Format("Timer Interval: {0}", runtimeInfo.TimerInterval));
m_console.Output(String.Format("Timer Last Scheduled: {0}", runtimeInfo.TimerLastScheduledOn));
m_console.Output(String.Format("Current Function: {0}", runtimeInfo.StackFrameFunctionName == null ? "none" : runtimeInfo.StackFrameFunctionName));
m_console.Output(String.Empty);
}
}
}
// see BaseOpenSimServer
public override void HandleNuke(string mod, string[] cmd)
{
base.HandleNuke(mod, cmd);
List<string> args = new List<string>(cmd);
args.RemoveAt(0);
string[] showParams = args.ToArray();
if (showParams.Length > 0)
{
UUID OwnerID;
if (UUID.TryParse(showParams[0], out OwnerID))
{
m_console.Notice("Deploying nuke...");
m_sceneManager.NukeObjectsOwnedBy(OwnerID);
m_console.Notice("Nuke complete.");
} else
{
m_console.Notice("That does not look like a UUID.");
}
}
else
{
m_console.Notice("You must specify the UUID of the owner.");
}
}
// blacklist object owner <UUID>
public override void HandleBlacklistOwner(string module, string[] cmd)
{
base.HandleBlacklistOwner(module, cmd);
List<string> tokens = new List<string>(cmd);
tokens.RemoveAt(0);
string[] args = tokens.ToArray();
if (args.Length > 2)
{
string param2 = (args.Length > 3) ? args[3] : String.Empty;
SceneManager.BlacklistOp operation = SceneManager.BlacklistOp.Owner;
m_sceneManager.BlacklistOperation(operation, args[2], param2);
}
else
{
m_console.Notice("You must specify the UUID or name of the owner.");
}
}
// blacklist object creator <UUID>
public override void HandleBlacklistCreator(string module, string[] cmd)
{
base.HandleBlacklistCreator(module, cmd);
List<string> tokens = new List<string>(cmd);
tokens.RemoveAt(0);
string[] args = tokens.ToArray();
if (args.Length > 2)
{
string param2 = (args.Length > 3) ? args[3] : String.Empty;
SceneManager.BlacklistOp operation = SceneManager.BlacklistOp.Creator;
SceneManager.BlacklistOperation(operation, args[2], param2);
}
else
{
m_console.Notice("You must specify the UUID or name of the creator.");
}
}
// blacklist object name "<name>"
public override void HandleBlacklistName(string module, string[] cmd)
{
base.HandleBlacklistName(module, cmd);
List<string> tokens = new List<string>(cmd);
tokens.RemoveAt(0);
string[] args = tokens.ToArray();
if (args.Length > 2)
{
SceneManager.BlacklistOp operation = SceneManager.BlacklistOp.Name;
m_sceneManager.BlacklistOperation(operation, args[2], String.Empty);
}
else
{
m_console.Notice("You must specify a starting name portion.");
}
}
// Either: blacklist user <UUID>
// or: blacklist user <First> <Last>
public override void HandleBlacklistUser(string module, string[] cmd)
{
// blacklist object owner <UUID>
base.HandleBlacklistUser(module, cmd);
List<string> tokens = new List<string>(cmd);
tokens.RemoveAt(0);
string[] args = tokens.ToArray();
if (args.Length > 1)
{
string param2 = (args.Length > 2) ? args[2] : String.Empty;
SceneManager.BlacklistOp operation = SceneManager.BlacklistOp.User;
m_sceneManager.BlacklistOperation(operation, args[1], param2);
}
else
{
m_console.Notice("You must specify the UUID or name of the user.");
}
}
// blacklist remove <something>
public override void HandleBlacklistRemove(string module, string[] cmd)
{
base.HandleBlacklistRemove(module, cmd);
List<string> tokens = new List<string>(cmd);
tokens.RemoveAt(0);
string[] args = tokens.ToArray();
if (args.Length > 1)
{
SceneManager.BlacklistOp operation = SceneManager.BlacklistOp.Remove;
m_sceneManager.BlacklistOperation(operation, args[1], String.Empty);
}
else
{
m_console.Notice("You must specify the user (UUID or name).");
}
}
// blacklist clear
public override void HandleBlacklistClear(string module, string[] cmd)
{
base.HandleBlacklistClear(module, cmd);
SceneManager.BlacklistOp operation = SceneManager.BlacklistOp.Clear;
m_sceneManager.BlacklistOperation(operation, String.Empty, String.Empty);
}
// blacklist show
public override void HandleBlacklistShow(string module, string[] cmd)
{
base.HandleBlacklistShow(module, cmd);
SceneManager.BlacklistOp operation = SceneManager.BlacklistOp.Show;
m_sceneManager.BlacklistOperation(operation, String.Empty, String.Empty);
}
private string GetQueuesReport()
{
string report = String.Empty;
m_sceneManager.ForEachScene(delegate(Scene scene)
{
scene.ForEachClient(delegate(IClientAPI client)
{
if (client is IStatsCollector)
{
report = report + client.Name + "\n";
IStatsCollector stats =
(IStatsCollector) client;
report = report + string.Format("{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}\n",
"Send",
"In",
"Out",
"Resend",
"Land",
"Wind",
"Cloud",
"Task",
"Texture",
"Asset");
report = report + stats.Report() +
"\n\n";
}
});
});
return report;
}
/// <summary>
/// Create a new user
/// </summary>
/// <param name="cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param>
protected void CreateUser(string[] cmdparams)
{
string firstName;
string lastName;
string password;
string email;
uint regX = 1000;
uint regY = 1000;
if (cmdparams.Length < 3)
firstName = MainConsole.Instance.CmdPrompt("First name", "Default");
else firstName = cmdparams[2];
if (cmdparams.Length < 4)
lastName = MainConsole.Instance.CmdPrompt("Last name", "User");
else lastName = cmdparams[3];
if (cmdparams.Length < 5)
password = MainConsole.Instance.PasswdPrompt("Password");
else password = cmdparams[4];
if (cmdparams.Length < 6)
regX = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region X", regX.ToString()));
else regX = Convert.ToUInt32(cmdparams[5]);
if (cmdparams.Length < 7)
regY = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region Y", regY.ToString()));
else regY = Convert.ToUInt32(cmdparams[6]);
if (cmdparams.Length < 8)
email = MainConsole.Instance.CmdPrompt("Email", String.Empty);
else email = cmdparams[7];
if (null == m_commsManager.UserService.GetUserProfile(firstName, lastName))
{
m_commsManager.UserAdminService.AddUser(firstName, lastName, password, email, regX, regY);
}
else
{
m_log.ErrorFormat("[CONSOLE]: A user with the name {0} {1} already exists!", firstName, lastName);
}
}
/// <summary>
/// Reset a user password.
/// </summary>
/// <param name="cmdparams"></param>
private void ResetUserPassword(string[] cmdparams)
{
string firstName;
string lastName;
string newPassword;
if (cmdparams.Length < 4)
firstName = MainConsole.Instance.CmdPrompt("First name");
else firstName = cmdparams[3];
if (cmdparams.Length < 5)
lastName = MainConsole.Instance.CmdPrompt("Last name");
else lastName = cmdparams[4];
if (cmdparams.Length < 6)
newPassword = MainConsole.Instance.PasswdPrompt("New password");
else newPassword = cmdparams[5];
m_commsManager.UserAdminService.ResetUserPassword(firstName, lastName, newPassword);
}
protected void SavePrimsXml2(string module, string[] cmdparams)
{
if (cmdparams.Length > 5)
{
m_sceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]);
}
else
{
m_sceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME);
}
}
protected void SaveXml(string module, string[] cmdparams)
{
m_log.Error("[CONSOLE]: PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason.");
if (cmdparams.Length > 0)
{
m_sceneManager.SaveCurrentSceneToXml(cmdparams[2]);
}
else
{
m_sceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME);
}
}
protected void LoadXml(string module, string[] cmdparams)
{
m_log.Error("[CONSOLE]: PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason.");
Vector3 loadOffset = new Vector3(0, 0, 0);
if (cmdparams.Length > 2)
{
bool generateNewIDS = false;
if (cmdparams.Length > 3)
{
if (cmdparams[3] == "-newUID")
{
generateNewIDS = true;
}
if (cmdparams.Length > 4)
{
loadOffset.X = (float) Convert.ToDouble(cmdparams[4]);
if (cmdparams.Length > 5)
{
loadOffset.Y = (float) Convert.ToDouble(cmdparams[5]);
}
if (cmdparams.Length > 6)
{
loadOffset.Z = (float) Convert.ToDouble(cmdparams[6]);
}
m_console.Error("loadOffsets <X,Y,Z> = <" + loadOffset.X + "," + loadOffset.Y + "," +
loadOffset.Z + ">");
}
}
m_sceneManager.LoadCurrentSceneFromXml(cmdparams[0], generateNewIDS, loadOffset);
}
else
{
try
{
m_sceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset);
}
catch (FileNotFoundException)
{
m_console.Error("Default xml not found. Usage: load-xml <filename>");
}
}
}
protected void SaveXml2(string module, string[] cmdparams)
{
if (cmdparams.Length > 2)
{
m_sceneManager.SaveCurrentSceneToXml2(cmdparams[2]);
}
else
{
m_sceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME);
}
}
protected void LoadXml2(string module, string[] cmdparams)
{
if (cmdparams.Length > 2)
{
try
{
m_sceneManager.LoadCurrentSceneFromXml2(cmdparams[2]);
}
catch (FileNotFoundException)
{
m_console.Error("Specified xml not found. Usage: load xml2 <filename>");
}
}
else
{
try
{
m_sceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME);
}
catch (FileNotFoundException)
{
m_console.Error("Default xml not found. Usage: load xml2 <filename>");
}
}
}
/// <summary>
/// Load a whole region from an opensim archive.
/// </summary>
/// <param name="cmdparams"></param>
protected void LoadOar(string module, string[] cmdparams)
{
if (cmdparams.Length > 2)
{
string fileName;
bool ignoreErrors = false;
if (cmdparams.Length > 3 && cmdparams[2] == "--ignore-errors")
{
ignoreErrors = true;
fileName = cmdparams[3];
}
else
{
ignoreErrors = false;
fileName = cmdparams[2];
}
try
{
m_sceneManager.LoadArchiveToCurrentScene(fileName, true, ignoreErrors);
}
catch (FileNotFoundException)
{
m_console.Error("Specified oar not found. Usage: load oar <filename>");
}
}
else
{
try
{
m_sceneManager.LoadArchiveToCurrentScene(DEFAULT_OAR_BACKUP_FILENAME, true, false);
}
catch (FileNotFoundException)
{
m_console.Error("Default oar not found. Usage: load oar <filename>");
}
}
}
/// <summary>
/// Save a region to a file, including all the assets needed to restore it.
/// </summary>
/// <param name="cmdparams"></param>
protected void SaveOar(string module, string[] cmdparams)
{
if (cmdparams.Length == 2)
{
m_sceneManager.SaveCurrentSceneToArchive(DEFAULT_OAR_BACKUP_FILENAME, true);
}
else if (cmdparams.Length == 3)
{
m_sceneManager.SaveCurrentSceneToArchive(cmdparams[2], true);
}
else if (cmdparams.Length == 4)
{
m_sceneManager.SaveCurrentSceneToArchive(cmdparams[2], cmdparams[3] == "1");
}
}
private Scene FindSceneByName(string name)
{
return m_sceneManager.FindSceneByName(name);
}
/// <summary>
/// Load a whole region from an opensim archive.
/// </summary>
/// <param name="cmdparams"></param>
protected void LoadExplicitOar(string module, string[] cmdparams)
{
if (cmdparams.Length != 4)
{
m_console.Error("Usage: loadexplicit oar <region name> <filename>");
return;
}
try
{
Scene targetScene = this.FindSceneByName(cmdparams[2]);
if (targetScene == null)
{
m_console.Error("Could not find requested scene");
return;
}
IRegionArchiverModule archiver = targetScene.RequestModuleInterface<IRegionArchiverModule>();
if (archiver != null)
archiver.DearchiveRegion(cmdparams[3], false, false);
}
catch (FileNotFoundException)
{
m_console.Error("Specified oar not found. Usage: loadexplicit oar <region> <filename>");
}
}
/// <summary>
/// Save a region to a file, including all the assets needed to restore it
/// </summary>
/// <param name="cmdparams"></param>
protected void SavePortableOar(string module, string[] cmdparams)
{
//saveportable oar <oar filename> [creator_uuid creator_uuid ...]
if (cmdparams.Length < 4)
{
m_console.Error("Usage: saveportable oar <oar filename> [creator_uuid creator_uuid ...]");
return;
}
try
{
Scene targetScene = m_sceneManager.Scenes[0];
if (targetScene == null)
{
m_console.Error("Could not find scene");
return;
}
IRegionArchiverModule archiver = targetScene.RequestModuleInterface<IRegionArchiverModule>();
if (archiver != null)
{
List<UUID> userIds = new List<UUID>();
for (int i = 3; i < cmdparams.Length; i++)
{
userIds.Add(UUID.Parse(cmdparams[i]));
}
archiver.ArchiveRegion(cmdparams[2], Guid.Empty, userIds);
}
}
catch (FileNotFoundException)
{
m_console.Error("Specified oar not found. Usage: loadexplicit oar <region> <filename>");
}
}
/// <summary>
/// Save a region to a file, including all the assets needed to restore it.
/// </summary>
/// <param name="cmdparams"></param>
protected void SaveExplicitOar(string module, string[] cmdparams)
{
//saveexplicit oar <region name> <oar filename> <store_assets>
if (cmdparams.Length != 5)
{
m_console.Error("Usage: saveexplicit oar <region name> <oar filename> <store_assets>");
return;
}
m_sceneManager.SaveExplicitOar(cmdparams[2], cmdparams[3], cmdparams[4] == "1");
}
private static string CombineParams(string[] commandParams, int pos)
{
string result = String.Empty;
for (int i = pos; i < commandParams.Length; i++)
{
result += commandParams[i] + " ";
}
result = result.TrimEnd(' ');
return result;
}
#endregion
}
}
| |
using Newtonsoft.Json;
namespace EncompassRest.Company.Users.Rights
{
/// <summary>
/// MiscellaneousRights
/// </summary>
public sealed class MiscellaneousRights : DirtyExtensibleObject
{
private DirtyValue<bool?>? _eFolderAccess;
private DirtyValue<bool?>? _eFolderArchive;
private DirtyValue<bool?>? _eFolderAssignAs;
private DirtyValue<bool?>? _eFolderAttachDoc;
private DirtyValue<bool?>? _eFolderConditionsAddBusinessRuleUnderwriting;
private DirtyValue<bool?>? _eFolderDeleteDoc;
private DirtyValue<bool?>? _eFolderDownloadFaxes;
private DirtyValue<bool?>? _eFolderRequestDoc;
private DirtyValue<bool?>? _eFolderSendDoc;
private DirtyValue<bool?>? _eFolderUFApprover;
private DirtyValue<bool?>? _externalSettingsTPOWCDocs;
private DirtyValue<bool?>? _externalSettingsTPOWCSiteManagement;
private DirtyValue<bool?>? _fannieMaeUCDTransfer;
private DirtyValue<bool?>? _freddieMacCAC;
private DirtyValue<bool?>? _freddieMacLPABatch;
private DirtyValue<bool?>? _globalTabNews;
private DirtyValue<bool?>? _inputFormsShowAllFormsCheckBox;
private DirtyValue<bool?>? _instantMessenger;
private DirtyValue<bool?>? _loanMgmtDownload;
private DirtyValue<bool?>? _loanMgmtDuplicateBlank;
private DirtyValue<bool?>? _loanMgmtUpload;
private DirtyValue<bool?>? _loanTabeFolderDTModifyProtectedDocAndFiles;
private DirtyValue<bool?>? _loanTabeFolderDTNewEditFiles;
private DirtyValue<bool?>? _loanTabOtherExclusiveLock;
private DirtyValue<bool?>? _platFormAccess;
private DirtyValue<bool?>? _settingsTabAffiliatedBusinessArrangementTemplates;
private DirtyValue<bool?>? _settingsTabAllTPOContactInformation;
private DirtyValue<bool?>? _settingsTabAutomatedDisclosures;
private DirtyValue<bool?>? _settingsTabClosingCosts;
private DirtyValue<bool?>? _settingsTabClosingPlanCodes;
private DirtyValue<bool?>? _settingsTabClosingStackingTemplates;
private DirtyValue<bool?>? _settingsTabCompanyDetails;
private DirtyValue<bool?>? _settingsTabCompanyCompanySettingsObsolete;
private DirtyValue<bool?>? _settingsTabCompanyConditionSetup;
private DirtyValue<bool?>? _settingsTabCompanyConfigurableKeyDates;
private DirtyValue<bool?>? _settingsTabCompanyDocumentSetup;
private DirtyValue<bool?>? _settingsTabComplianceReviewSetup;
private DirtyValue<bool?>? _settingsTabConditionForms;
private DirtyValue<bool?>? _settingsTabCurrentLogins;
private DirtyValue<bool?>? _settingsTabCustomPrintForms;
private DirtyValue<bool?>? _settingsTabDataTemplates;
private DirtyValue<bool?>? _settingsTabDocumentSets;
private DirtyValue<bool?>? _settingsTabEDisclosurePlanCodes;
private DirtyValue<bool?>? _settingsTabEDisclosureStackingTemplates;
private DirtyValue<bool?>? _settingsTabExtCompany;
private DirtyValue<bool?>? _settingsTabInputFormSets;
private DirtyValue<bool?>? _settingsTabInsightsSetup;
private DirtyValue<bool?>? _settingsTabItemizationFeeManagement;
private DirtyValue<bool?>? _settingsTabLoanCustomFields;
private DirtyValue<bool?>? _settingsTabLoanErrorInformation;
private DirtyValue<bool?>? _settingsTabLoanPrograms;
private DirtyValue<bool?>? _settingsTabLoanReassignment;
private DirtyValue<bool?>? _settingsTabLoanTemplateSets;
private DirtyValue<bool?>? _settingsTabPrintFormGroups;
private DirtyValue<bool?>? _settingsTabPublicBusinessContactGroups;
private DirtyValue<bool?>? _settingsTabRebuildPipeline;
private DirtyValue<bool?>? _settingsTabSecondaryRoot;
private DirtyValue<bool?>? _settingsTabSettingsReport;
private DirtyValue<bool?>? _settingsTabSettlementServiceProviders;
private DirtyValue<bool?>? _settingsTabSystemAuditTrail;
private DirtyValue<bool?>? _settingsTabTablesFees;
private DirtyValue<bool?>? _settingsTabTaskSets;
private DirtyValue<bool?>? _settingsTabTpoCustomFields;
private DirtyValue<bool?>? _settingsTabTpoFees;
private DirtyValue<bool?>? _settingsTabTpoReassignment;
private DirtyValue<bool?>? _settingsTabTpoSettings;
private DirtyValue<bool?>? _settingsTabTpoWebCenterDocs;
private DirtyValue<bool?>? _settingsTabUnlockLoanFile;
private DirtyValue<bool?>? _thinThickPipelineTabAccess;
private DirtyValue<bool?>? _thinThickTradesTabAccess;
private DirtyValue<bool?>? _tPOAdministrationTabShowAsMgrAdminInBranchesTab;
private DirtyValue<bool?>? _tPOAdministrationTabShowAsMgrAdminInCompanyInfoTab;
private DirtyValue<bool?>? _tPOAdministrationTabViewCmtConfirmations;
private DirtyValue<bool?>? _tradeTabEditTrades;
/// <summary>
/// MiscellaneousRights EFolderAccess
/// </summary>
[JsonProperty("eFolder_Access")]
public bool? EFolderAccess { get => _eFolderAccess; set => SetField(ref _eFolderAccess, value); }
/// <summary>
/// MiscellaneousRights EFolderArchive
/// </summary>
[JsonProperty("eFolder_Archive")]
public bool? EFolderArchive { get => _eFolderArchive; set => SetField(ref _eFolderArchive, value); }
/// <summary>
/// MiscellaneousRights EFolderAssignAs
/// </summary>
[JsonProperty("eFolder_AssignAs")]
public bool? EFolderAssignAs { get => _eFolderAssignAs; set => SetField(ref _eFolderAssignAs, value); }
/// <summary>
/// MiscellaneousRights EFolderAttachDoc
/// </summary>
[JsonProperty("eFolder_AttachDoc")]
public bool? EFolderAttachDoc { get => _eFolderAttachDoc; set => SetField(ref _eFolderAttachDoc, value); }
/// <summary>
/// MiscellaneousRights EFolderConditionsAddBusinessRuleUnderwriting
/// </summary>
[JsonProperty("eFolder_Conditions_AddBusinessRuleUnderwriting")]
public bool? EFolderConditionsAddBusinessRuleUnderwriting { get => _eFolderConditionsAddBusinessRuleUnderwriting; set => SetField(ref _eFolderConditionsAddBusinessRuleUnderwriting, value); }
/// <summary>
/// MiscellaneousRights EFolderDeleteDoc
/// </summary>
[JsonProperty("eFolder_DeleteDoc")]
public bool? EFolderDeleteDoc { get => _eFolderDeleteDoc; set => SetField(ref _eFolderDeleteDoc, value); }
/// <summary>
/// MiscellaneousRights EFolderDownloadFaxes
/// </summary>
[JsonProperty("eFolder_DownloadFaxes")]
public bool? EFolderDownloadFaxes { get => _eFolderDownloadFaxes; set => SetField(ref _eFolderDownloadFaxes, value); }
/// <summary>
/// MiscellaneousRights EFolderRequestDoc
/// </summary>
[JsonProperty("eFolder_RequestDoc")]
public bool? EFolderRequestDoc { get => _eFolderRequestDoc; set => SetField(ref _eFolderRequestDoc, value); }
/// <summary>
/// MiscellaneousRights EFolderSendDoc
/// </summary>
[JsonProperty("eFolder_SendDoc")]
public bool? EFolderSendDoc { get => _eFolderSendDoc; set => SetField(ref _eFolderSendDoc, value); }
/// <summary>
/// MiscellaneousRights EFolderUFApprover
/// </summary>
[JsonProperty("eFolder_UF_Approver")]
public bool? EFolderUFApprover { get => _eFolderUFApprover; set => SetField(ref _eFolderUFApprover, value); }
/// <summary>
/// MiscellaneousRights ExternalSettingsTPOWCDocs
/// </summary>
[JsonProperty("externalSettings_TPOWCDocs")]
public bool? ExternalSettingsTPOWCDocs { get => _externalSettingsTPOWCDocs; set => SetField(ref _externalSettingsTPOWCDocs, value); }
/// <summary>
/// MiscellaneousRights ExternalSettingsTPOWCSiteManagement
/// </summary>
[JsonProperty("externalSettings_TPOWCSiteManagement")]
public bool? ExternalSettingsTPOWCSiteManagement { get => _externalSettingsTPOWCSiteManagement; set => SetField(ref _externalSettingsTPOWCSiteManagement, value); }
/// <summary>
/// MiscellaneousRights FannieMaeUCDTransfer
/// </summary>
[JsonProperty("fannie_Mae_UCD_Transfer")]
public bool? FannieMaeUCDTransfer { get => _fannieMaeUCDTransfer; set => SetField(ref _fannieMaeUCDTransfer, value); }
/// <summary>
/// MiscellaneousRights FreddieMacCAC
/// </summary>
[JsonProperty("freddie_Mac_CAC")]
public bool? FreddieMacCAC { get => _freddieMacCAC; set => SetField(ref _freddieMacCAC, value); }
/// <summary>
/// MiscellaneousRights FreddieMacLPABatch
/// </summary>
[JsonProperty("freddie_Mac_LPA_Batch")]
public bool? FreddieMacLPABatch { get => _freddieMacLPABatch; set => SetField(ref _freddieMacLPABatch, value); }
/// <summary>
/// MiscellaneousRights GlobalTabNews
/// </summary>
[JsonProperty("globalTab_News")]
public bool? GlobalTabNews { get => _globalTabNews; set => SetField(ref _globalTabNews, value); }
/// <summary>
/// MiscellaneousRights InputFormsShowAllFormsCheckBox
/// </summary>
[JsonProperty("inputForms_ShowAllFormsCheckBox")]
public bool? InputFormsShowAllFormsCheckBox { get => _inputFormsShowAllFormsCheckBox; set => SetField(ref _inputFormsShowAllFormsCheckBox, value); }
/// <summary>
/// MiscellaneousRights InstantMessenger
/// </summary>
public bool? InstantMessenger { get => _instantMessenger; set => SetField(ref _instantMessenger, value); }
/// <summary>
/// MiscellaneousRights LoanMgmtDownload
/// </summary>
[JsonProperty("loanMgmt_Download")]
public bool? LoanMgmtDownload { get => _loanMgmtDownload; set => SetField(ref _loanMgmtDownload, value); }
/// <summary>
/// MiscellaneousRights LoanMgmtDuplicateBlank
/// </summary>
[JsonProperty("loanMgmt_Duplicate_Blank")]
public bool? LoanMgmtDuplicateBlank { get => _loanMgmtDuplicateBlank; set => SetField(ref _loanMgmtDuplicateBlank, value); }
/// <summary>
/// MiscellaneousRights LoanMgmtUpload
/// </summary>
[JsonProperty("loanMgmt_Upload")]
public bool? LoanMgmtUpload { get => _loanMgmtUpload; set => SetField(ref _loanMgmtUpload, value); }
/// <summary>
/// MiscellaneousRights LoanTabeFolderDTModifyProtectedDocAndFiles
/// </summary>
[JsonProperty("loanTab_eFolder_DT_ModifyProtectedDocAndFiles")]
public bool? LoanTabeFolderDTModifyProtectedDocAndFiles { get => _loanTabeFolderDTModifyProtectedDocAndFiles; set => SetField(ref _loanTabeFolderDTModifyProtectedDocAndFiles, value); }
/// <summary>
/// MiscellaneousRights LoanTabeFolderDTNewEditFiles
/// </summary>
[JsonProperty("loanTab_eFolder_DT_NewEditFiles")]
public bool? LoanTabeFolderDTNewEditFiles { get => _loanTabeFolderDTNewEditFiles; set => SetField(ref _loanTabeFolderDTNewEditFiles, value); }
/// <summary>
/// MiscellaneousRights LoanTabOtherExclusiveLock
/// </summary>
[JsonProperty("loanTab_Other_ExclusiveLock")]
public bool? LoanTabOtherExclusiveLock { get => _loanTabOtherExclusiveLock; set => SetField(ref _loanTabOtherExclusiveLock, value); }
/// <summary>
/// MiscellaneousRights PlatFormAccess
/// </summary>
[JsonProperty("platForm_Access")]
public bool? PlatFormAccess { get => _platFormAccess; set => SetField(ref _platFormAccess, value); }
/// <summary>
/// MiscellaneousRights SettingsTabAffiliatedBusinessArrangementTemplates
/// </summary>
[JsonProperty("settingsTab_AffiliatedBusinessArrangementTemplates")]
public bool? SettingsTabAffiliatedBusinessArrangementTemplates { get => _settingsTabAffiliatedBusinessArrangementTemplates; set => SetField(ref _settingsTabAffiliatedBusinessArrangementTemplates, value); }
/// <summary>
/// MiscellaneousRights SettingsTabAllTPOContactInformation
/// </summary>
[JsonProperty("settingsTab_AllTPOContactInformation")]
public bool? SettingsTabAllTPOContactInformation { get => _settingsTabAllTPOContactInformation; set => SetField(ref _settingsTabAllTPOContactInformation, value); }
/// <summary>
/// MiscellaneousRights SettingsTabAutomatedDisclosures
/// </summary>
[JsonProperty("settingsTab_AutomatedDisclosures")]
public bool? SettingsTabAutomatedDisclosures { get => _settingsTabAutomatedDisclosures; set => SetField(ref _settingsTabAutomatedDisclosures, value); }
/// <summary>
/// MiscellaneousRights SettingsTabClosingCosts
/// </summary>
[JsonProperty("settingsTab_ClosingCosts")]
public bool? SettingsTabClosingCosts { get => _settingsTabClosingCosts; set => SetField(ref _settingsTabClosingCosts, value); }
/// <summary>
/// MiscellaneousRights SettingsTabClosingPlanCodes
/// </summary>
[JsonProperty("settingsTab_ClosingPlanCodes")]
public bool? SettingsTabClosingPlanCodes { get => _settingsTabClosingPlanCodes; set => SetField(ref _settingsTabClosingPlanCodes, value); }
/// <summary>
/// MiscellaneousRights SettingsTabClosingStackingTemplates
/// </summary>
[JsonProperty("settingsTab_ClosingStackingTemplates")]
public bool? SettingsTabClosingStackingTemplates { get => _settingsTabClosingStackingTemplates; set => SetField(ref _settingsTabClosingStackingTemplates, value); }
/// <summary>
/// MiscellaneousRights SettingsTabCompanyDetails
/// </summary>
[JsonProperty("settingsTab_CompanyDetails")]
public bool? SettingsTabCompanyDetails { get => _settingsTabCompanyDetails; set => SetField(ref _settingsTabCompanyDetails, value); }
/// <summary>
/// MiscellaneousRights SettingsTabCompanyCompanySettingsObsolete
/// </summary>
[JsonProperty("settingsTab_Company_CompanySettings_Obsolete")]
public bool? SettingsTabCompanyCompanySettingsObsolete { get => _settingsTabCompanyCompanySettingsObsolete; set => SetField(ref _settingsTabCompanyCompanySettingsObsolete, value); }
/// <summary>
/// MiscellaneousRights SettingsTabCompanyConditionSetup
/// </summary>
[JsonProperty("settingsTab_Company_ConditionSetup")]
public bool? SettingsTabCompanyConditionSetup { get => _settingsTabCompanyConditionSetup; set => SetField(ref _settingsTabCompanyConditionSetup, value); }
/// <summary>
/// MiscellaneousRights SettingsTabCompanyConfigurableKeyDates
/// </summary>
[JsonProperty("settingsTab_Company_ConfigurableKeyDates")]
public bool? SettingsTabCompanyConfigurableKeyDates { get => _settingsTabCompanyConfigurableKeyDates; set => SetField(ref _settingsTabCompanyConfigurableKeyDates, value); }
/// <summary>
/// MiscellaneousRights SettingsTabCompanyDocumentSetup
/// </summary>
[JsonProperty("settingsTab_Company_DocumentSetup")]
public bool? SettingsTabCompanyDocumentSetup { get => _settingsTabCompanyDocumentSetup; set => SetField(ref _settingsTabCompanyDocumentSetup, value); }
/// <summary>
/// MiscellaneousRights SettingsTabComplianceReviewSetup
/// </summary>
[JsonProperty("settingsTab_ComplianceReviewSetup")]
public bool? SettingsTabComplianceReviewSetup { get => _settingsTabComplianceReviewSetup; set => SetField(ref _settingsTabComplianceReviewSetup, value); }
/// <summary>
/// MiscellaneousRights SettingsTabConditionForms
/// </summary>
[JsonProperty("settingsTab_ConditionForms")]
public bool? SettingsTabConditionForms { get => _settingsTabConditionForms; set => SetField(ref _settingsTabConditionForms, value); }
/// <summary>
/// MiscellaneousRights SettingsTabCurrentLogins
/// </summary>
[JsonProperty("settingsTab_CurrentLogins")]
public bool? SettingsTabCurrentLogins { get => _settingsTabCurrentLogins; set => SetField(ref _settingsTabCurrentLogins, value); }
/// <summary>
/// MiscellaneousRights SettingsTabCustomPrintForms
/// </summary>
[JsonProperty("settingsTab_CustomPrintForms")]
public bool? SettingsTabCustomPrintForms { get => _settingsTabCustomPrintForms; set => SetField(ref _settingsTabCustomPrintForms, value); }
/// <summary>
/// MiscellaneousRights SettingsTabDataTemplates
/// </summary>
[JsonProperty("settingsTab_DataTemplates")]
public bool? SettingsTabDataTemplates { get => _settingsTabDataTemplates; set => SetField(ref _settingsTabDataTemplates, value); }
/// <summary>
/// MiscellaneousRights SettingsTabDocumentSets
/// </summary>
[JsonProperty("settingsTab_DocumentSets")]
public bool? SettingsTabDocumentSets { get => _settingsTabDocumentSets; set => SetField(ref _settingsTabDocumentSets, value); }
/// <summary>
/// MiscellaneousRights SettingsTabEDisclosurePlanCodes
/// </summary>
[JsonProperty("settingsTab_EDisclosurePlanCodes")]
public bool? SettingsTabEDisclosurePlanCodes { get => _settingsTabEDisclosurePlanCodes; set => SetField(ref _settingsTabEDisclosurePlanCodes, value); }
/// <summary>
/// MiscellaneousRights SettingsTabEDisclosureStackingTemplates
/// </summary>
[JsonProperty("settingsTab_EDisclosureStackingTemplates")]
public bool? SettingsTabEDisclosureStackingTemplates { get => _settingsTabEDisclosureStackingTemplates; set => SetField(ref _settingsTabEDisclosureStackingTemplates, value); }
/// <summary>
/// MiscellaneousRights SettingsTabExtCompany
/// </summary>
[JsonProperty("settingsTab_ExtCompany")]
public bool? SettingsTabExtCompany { get => _settingsTabExtCompany; set => SetField(ref _settingsTabExtCompany, value); }
/// <summary>
/// MiscellaneousRights SettingsTabInputFormSets
/// </summary>
[JsonProperty("settingsTab_InputFormSets")]
public bool? SettingsTabInputFormSets { get => _settingsTabInputFormSets; set => SetField(ref _settingsTabInputFormSets, value); }
/// <summary>
/// MiscellaneousRightsSettingsTabInsightsSetup
/// </summary>
[JsonProperty("settingsTab_InsightsSetup")]
public bool? SettingsTabInsightsSetup { get => _settingsTabInsightsSetup; set => SetField(ref _settingsTabInsightsSetup, value); }
/// <summary>
/// MiscellaneousRights SettingsTabItemizationFeeManagement
/// </summary>
[JsonProperty("settingsTab_ItemizationFeeManagement")]
public bool? SettingsTabItemizationFeeManagement { get => _settingsTabItemizationFeeManagement; set => SetField(ref _settingsTabItemizationFeeManagement, value); }
/// <summary>
/// MiscellaneousRights SettingsTabLoanCustomFields
/// </summary>
[JsonProperty("settingsTab_LoanCustomFields")]
public bool? SettingsTabLoanCustomFields { get => _settingsTabLoanCustomFields; set => SetField(ref _settingsTabLoanCustomFields, value); }
/// <summary>
/// MiscellaneousRights SettingsTabLoanErrorInformation
/// </summary>
[JsonProperty("settingsTab_LoanErrorInformation")]
public bool? SettingsTabLoanErrorInformation { get => _settingsTabLoanErrorInformation; set => SetField(ref _settingsTabLoanErrorInformation, value); }
/// <summary>
/// MiscellaneousRights SettingsTabLoanPrograms
/// </summary>
[JsonProperty("settingsTab_LoanPrograms")]
public bool? SettingsTabLoanPrograms { get => _settingsTabLoanPrograms; set => SetField(ref _settingsTabLoanPrograms, value); }
/// <summary>
/// MiscellaneousRights SettingsTabLoanReassignment
/// </summary>
[JsonProperty("settingsTab_LoanReassignment")]
public bool? SettingsTabLoanReassignment { get => _settingsTabLoanReassignment; set => SetField(ref _settingsTabLoanReassignment, value); }
/// <summary>
/// MiscellaneousRights SettingsTabLoanTemplateSets
/// </summary>
[JsonProperty("settingsTab_LoanTemplateSets")]
public bool? SettingsTabLoanTemplateSets { get => _settingsTabLoanTemplateSets; set => SetField(ref _settingsTabLoanTemplateSets, value); }
/// <summary>
/// MiscellaneousRights SettingsTabPrintFormGroups
/// </summary>
[JsonProperty("settingsTab_PrintFormGroups")]
public bool? SettingsTabPrintFormGroups { get => _settingsTabPrintFormGroups; set => SetField(ref _settingsTabPrintFormGroups, value); }
/// <summary>
/// MiscellaneousRights SettingsTabPublicBusinessContactGroups
/// </summary>
[JsonProperty("settingsTab_PublicBusinessContactGroups")]
public bool? SettingsTabPublicBusinessContactGroups { get => _settingsTabPublicBusinessContactGroups; set => SetField(ref _settingsTabPublicBusinessContactGroups, value); }
/// <summary>
/// MiscellaneousRights SettingsTabRebuildPipeline
/// </summary>
[JsonProperty("settingsTab_RebuildPipeline")]
public bool? SettingsTabRebuildPipeline { get => _settingsTabRebuildPipeline; set => SetField(ref _settingsTabRebuildPipeline, value); }
/// <summary>
/// MiscellaneousRights SettingsTabSecondaryRoot
/// </summary>
[JsonProperty("settingsTab_SecondaryRoot")]
public bool? SettingsTabSecondaryRoot { get => _settingsTabSecondaryRoot; set => SetField(ref _settingsTabSecondaryRoot, value); }
/// <summary>
/// MiscellaneousRights SettingsTabSettingsReport
/// </summary>
[JsonProperty("settingsTab_SettingsReport")]
public bool? SettingsTabSettingsReport { get => _settingsTabSettingsReport; set => SetField(ref _settingsTabSettingsReport, value); }
/// <summary>
/// MiscellaneousRights SettingsTabSettlementServiceProviders
/// </summary>
[JsonProperty("settingsTab_SettlementServiceProviders")]
public bool? SettingsTabSettlementServiceProviders { get => _settingsTabSettlementServiceProviders; set => SetField(ref _settingsTabSettlementServiceProviders, value); }
/// <summary>
/// MiscellaneousRights SettingsTabSystemAuditTrail
/// </summary>
[JsonProperty("settingsTab_SystemAuditTrail")]
public bool? SettingsTabSystemAuditTrail { get => _settingsTabSystemAuditTrail; set => SetField(ref _settingsTabSystemAuditTrail, value); }
/// <summary>
/// MiscellaneousRights SettingsTabTablesFees
/// </summary>
[JsonProperty("settingsTab_TablesFees")]
public bool? SettingsTabTablesFees { get => _settingsTabTablesFees; set => SetField(ref _settingsTabTablesFees, value); }
/// <summary>
/// MiscellaneousRights SettingsTabTaskSets
/// </summary>
[JsonProperty("settingsTab_TaskSets")]
public bool? SettingsTabTaskSets { get => _settingsTabTaskSets; set => SetField(ref _settingsTabTaskSets, value); }
/// <summary>
/// MiscellaneousRights SettingsTabTpoCustomFields
/// </summary>
[JsonProperty("settingsTab_TpoCustomFields")]
public bool? SettingsTabTpoCustomFields { get => _settingsTabTpoCustomFields; set => SetField(ref _settingsTabTpoCustomFields, value); }
/// <summary>
/// MiscellaneousRights SettingsTabTpoFees
/// </summary>
[JsonProperty("settingsTab_TpoFees")]
public bool? SettingsTabTpoFees { get => _settingsTabTpoFees; set => SetField(ref _settingsTabTpoFees, value); }
/// <summary>
/// MiscellaneousRights SettingsTabTpoReassignment
/// </summary>
[JsonProperty("settingsTab_TpoReassignment")]
public bool? SettingsTabTpoReassignment { get => _settingsTabTpoReassignment; set => SetField(ref _settingsTabTpoReassignment, value); }
/// <summary>
/// MiscellaneousRights SettingsTabTpoSettings
/// </summary>
[JsonProperty("settingsTab_TpoSettings")]
public bool? SettingsTabTpoSettings { get => _settingsTabTpoSettings; set => SetField(ref _settingsTabTpoSettings, value); }
/// <summary>
/// MiscellaneousRights SettingsTabTpoWebCenterDocs
/// </summary>
[JsonProperty("settingsTab_TpoWebCenterDocs")]
public bool? SettingsTabTpoWebCenterDocs { get => _settingsTabTpoWebCenterDocs; set => SetField(ref _settingsTabTpoWebCenterDocs, value); }
/// <summary>
/// MiscellaneousRights SettingsTabUnlockLoanFile
/// </summary>
[JsonProperty("settingsTab_UnlockLoanFile")]
public bool? SettingsTabUnlockLoanFile { get => _settingsTabUnlockLoanFile; set => SetField(ref _settingsTabUnlockLoanFile, value); }
/// <summary>
/// MiscellaneousRights ThinThickPipelineTabAccess
/// </summary>
[JsonProperty("thinThick_PipelineTab_Access")]
public bool? ThinThickPipelineTabAccess { get => _thinThickPipelineTabAccess; set => SetField(ref _thinThickPipelineTabAccess, value); }
/// <summary>
/// MiscellaneousRights ThinThickTradesTabAccess
/// </summary>
[JsonProperty("thinThick_TradesTab_Access")]
public bool? ThinThickTradesTabAccess { get => _thinThickTradesTabAccess; set => SetField(ref _thinThickTradesTabAccess, value); }
/// <summary>
/// MiscellaneousRights TPOAdministrationTabShowAsMgrAdminInBranchesTab
/// </summary>
[JsonProperty("tPOAdministrationTab_ShowAsMgrAdminInBranchesTab")]
public bool? TPOAdministrationTabShowAsMgrAdminInBranchesTab { get => _tPOAdministrationTabShowAsMgrAdminInBranchesTab; set => SetField(ref _tPOAdministrationTabShowAsMgrAdminInBranchesTab, value); }
/// <summary>
/// MiscellaneousRights TPOAdministrationTabShowAsMgrAdminInCompanyInfoTab
/// </summary>
[JsonProperty("tPOAdministrationTab_ShowAsMgrAdminInCompanyInfoTab")]
public bool? TPOAdministrationTabShowAsMgrAdminInCompanyInfoTab { get => _tPOAdministrationTabShowAsMgrAdminInCompanyInfoTab; set => SetField(ref _tPOAdministrationTabShowAsMgrAdminInCompanyInfoTab, value); }
/// <summary>
/// MiscellaneousRights TPOAdministrationTabViewCmtConfirmations
/// </summary>
[JsonProperty("tPOAdministrationTab_ViewCmtConfirmations")]
public bool? TPOAdministrationTabViewCmtConfirmations { get => _tPOAdministrationTabViewCmtConfirmations; set => SetField(ref _tPOAdministrationTabViewCmtConfirmations, value); }
/// <summary>
/// MiscellaneousRights TradeTabEditTrades
/// </summary>
[JsonProperty("tradeTab_EditTrades")]
public bool? TradeTabEditTrades { get => _tradeTabEditTrades; set => SetField(ref _tradeTabEditTrades, value); }
}
}
| |
// Copyright 2015, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Author: api.anash@gmail.com (Anash P. Oommen)
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.Lib;
using Google.Api.Ads.Dfp.Util.v201502;
using Google.Api.Ads.Dfp.v201502;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Configuration;
using System.Collections;
namespace Google.Api.Ads.Dfp.Tests.v201502 {
/// <summary>
/// A utility class to assist the testing of v201502 services.
/// </summary>
public class TestUtils {
public User GetCurrentUser(DfpUser user) {
return GetUserByEmail(user, new DfpAppConfig().Email);
}
public User GetTrafficker(DfpUser user) {
return GetUserByEmail(user, "dfp.api.trafficker@gmail.com");
}
public User GetSalesperson(DfpUser user) {
return GetUserByEmail(user, "dfp.api.salesperson@gmail.com");
}
public User GetUserByEmail(DfpUser user, string email) {
UserService userService = (UserService) user.GetService(DfpService.v201502.UserService);
// Create a Statement to get all users sorted by name.
Statement statement = new Statement();
statement.query = string.Format("where email = '{0}' LIMIT 1", email);
UserPage page = userService.getUsersByStatement(statement);
if (page.results != null && page.results.Length > 0) {
return page.results[0];
} else {
return null;
}
}
public Role GetRole(DfpUser user, string roleName) {
UserService userService = (UserService)user.GetService(DfpService.v201502.UserService);
// Get all roles.
Role[] roles = userService.getAllRoles();
foreach (Role role in roles) {
if (role.name == roleName) {
return role;
}
}
return null;
}
/// <summary>
/// Create a test company for running further tests.
/// </summary>
/// <returns>A test company for running further tests.</returns>
public Company CreateCompany(DfpUser user, CompanyType companyType) {
CompanyService companyService = (CompanyService) user.GetService(
DfpService.v201502.CompanyService);
Company company = new Company();
company.name = string.Format("Company #{0}", GetTimeStamp());
company.type = companyType;
return companyService.createCompanies(new Company[] {company})[0];
}
public Order CreateOrder(DfpUser user, long advertiserId, long salespersonId,
long traffickerId) {
// Get the OrderService.
OrderService orderService = (OrderService) user.GetService(DfpService.v201502.OrderService);
Order order = new Order();
order.name = string.Format("Order #{0}", GetTimeStamp());
order.advertiserId = advertiserId;
order.salespersonId = salespersonId;
order.traffickerId = traffickerId;
return orderService.createOrders(new Order[] {order})[0];
}
public LineItem CreateLineItem(DfpUser user, long orderId, string adUnitId) {
LineItemService lineItemService =
(LineItemService) user.GetService(DfpService.v201502.LineItemService);
long placementId = CreatePlacement(user, new string[] {adUnitId}).id;
// Create inventory targeting.
InventoryTargeting inventoryTargeting = new InventoryTargeting();
inventoryTargeting.targetedPlacementIds = new long[] {placementId};
// Create geographical targeting.
GeoTargeting geoTargeting = new GeoTargeting();
// Include the US and Quebec, Canada.
Location countryLocation = new Location();
countryLocation.id = 2840L;
Location regionLocation = new Location();
regionLocation.id = 20123L;
geoTargeting.targetedLocations = new Location[] {countryLocation, regionLocation};
// Exclude Chicago and the New York metro area.
Location cityLocation = new Location();
cityLocation.id = 1016367L;
Location metroLocation = new Location();
metroLocation.id = 200501L;
geoTargeting.excludedLocations = new Location[] {cityLocation, metroLocation};
// Exclude domains that are not under the network's control.
UserDomainTargeting userDomainTargeting = new UserDomainTargeting();
userDomainTargeting.domains = new String[] {"usa.gov"};
userDomainTargeting.targeted = false;
// Create day-part targeting.
DayPartTargeting dayPartTargeting = new DayPartTargeting();
dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;
// Target only the weekend in the browser's timezone.
DayPart saturdayDayPart = new DayPart();
saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201502.DayOfWeek.SATURDAY;
saturdayDayPart.startTime = new TimeOfDay();
saturdayDayPart.startTime.hour = 0;
saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;
saturdayDayPart.endTime = new TimeOfDay();
saturdayDayPart.endTime.hour = 24;
saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;
DayPart sundayDayPart = new DayPart();
sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201502.DayOfWeek.SUNDAY;
sundayDayPart.startTime = new TimeOfDay();
sundayDayPart.startTime.hour = 0;
sundayDayPart.startTime.minute = MinuteOfHour.ZERO;
sundayDayPart.endTime = new TimeOfDay();
sundayDayPart.endTime.hour = 24;
sundayDayPart.endTime.minute = MinuteOfHour.ZERO;
dayPartTargeting.dayParts = new DayPart[] {saturdayDayPart, sundayDayPart};
// Create technology targeting.
TechnologyTargeting technologyTargeting = new TechnologyTargeting();
// Create browser targeting.
BrowserTargeting browserTargeting = new BrowserTargeting();
browserTargeting.isTargeted = true;
// Target just the Chrome browser.
Technology browserTechnology = new Technology();
browserTechnology.id = 500072L;
browserTargeting.browsers = new Technology[] {browserTechnology};
technologyTargeting.browserTargeting = browserTargeting;
LineItem lineItem = new LineItem();
lineItem.name = "Line item #" + new TestUtils().GetTimeStamp();
lineItem.orderId = orderId;
lineItem.targeting = new Targeting();
lineItem.targeting.inventoryTargeting = inventoryTargeting;
lineItem.targeting.geoTargeting = geoTargeting;
lineItem.targeting.userDomainTargeting = userDomainTargeting;
lineItem.targeting.dayPartTargeting = dayPartTargeting;
lineItem.targeting.technologyTargeting = technologyTargeting;
lineItem.lineItemType = LineItemType.STANDARD;
lineItem.allowOverbook = true;
// Set the creative rotation type to even.
lineItem.creativeRotationType = CreativeRotationType.EVEN;
// Set the size of creatives that can be associated with this line item.
Size size = new Size();
size.width = 300;
size.height = 250;
size.isAspectRatio = false;
// Create the creative placeholder.
CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
creativePlaceholder.size = size;
lineItem.creativePlaceholders = new CreativePlaceholder[] {creativePlaceholder};
// Set the length of the line item to run.
//lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
lineItem.endDateTime = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1));
// Set the cost per unit to $2.
lineItem.costType = CostType.CPM;
lineItem.costPerUnit = new Money();
lineItem.costPerUnit.currencyCode = "USD";
lineItem.costPerUnit.microAmount = 2000000L;
// Set the number of units bought to 500,000 so that the budget is
// $1,000.
Goal goal = new Goal();
goal.units = 500000L;
goal.unitType = UnitType.IMPRESSIONS;
lineItem.primaryGoal = goal;
return lineItemService.createLineItems(new LineItem[] {lineItem})[0];
}
/// <summary>
/// Create a test company for running further tests.
/// </summary>
/// <returns>A creative for running further tests.</returns>
public Creative CreateCreative(DfpUser user, long advertiserId) {
CreativeService creativeService = (CreativeService)user.GetService(
DfpService.v201502.CreativeService);
// Create creative size.
Size size = new Size();
size.width = 300;
size.height = 250;
// Create an image creative.
ImageCreative imageCreative = new ImageCreative();
imageCreative.name = string.Format("Image creative #{0}", GetTimeStamp());
imageCreative.advertiserId = advertiserId;
imageCreative.destinationUrl = "http://www.google.com";
imageCreative.size = size;
// Create image asset.
CreativeAsset creativeAsset = new CreativeAsset();
creativeAsset.fileName = "image.jpg";
creativeAsset.assetByteArray = MediaUtilities.GetAssetDataFromUrl(
"http://www.google.com/intl/en/adwords/select/images/samples/inline.jpg");
creativeAsset.size = size;
imageCreative.primaryImageAsset = creativeAsset;
return creativeService.createCreatives(new Creative[] {imageCreative})[0];
}
public LineItemCreativeAssociation CreateLica(DfpUser user, long lineItemId, long creativeId) {
LineItemCreativeAssociationService licaService =
(LineItemCreativeAssociationService)user.GetService(
DfpService.v201502.LineItemCreativeAssociationService);
LineItemCreativeAssociation lica = new LineItemCreativeAssociation();
lica.creativeId = creativeId;
lica.lineItemId = lineItemId;
return licaService.createLineItemCreativeAssociations(
new LineItemCreativeAssociation[] {lica})[0];
}
public AdUnit CreateAdUnit(DfpUser user) {
InventoryService inventoryService =
(InventoryService) user.GetService(DfpService.v201502.InventoryService);
AdUnit adUnit = new AdUnit();
adUnit.name = string.Format("Ad_Unit_{0}", GetTimeStamp());
adUnit.parentId = FindRootAdUnit(user).id;
// Set the size of possible creatives that can match this ad unit.
Size size = new Size();
size.width = 300;
size.height = 250;
// Create ad unit size.
AdUnitSize adUnitSize = new AdUnitSize();
adUnitSize.size = size;
adUnitSize.environmentType = EnvironmentType.BROWSER;
adUnit.adUnitSizes = new AdUnitSize[] {adUnitSize};
return inventoryService.createAdUnits(new AdUnit[] {adUnit})[0];
}
public AdUnit FindRootAdUnit(DfpUser user) {
// Get InventoryService.
InventoryService inventoryService =
(InventoryService)user.GetService(DfpService.v201502.InventoryService);
// Create a Statement to only select the root ad unit.
Statement statement = new Statement();
statement.query = "WHERE parentId IS NULL LIMIT 500";
// Get ad units by Statement.
AdUnitPage page = inventoryService.getAdUnitsByStatement(statement);
return page.results[0];
}
public Placement CreatePlacement(DfpUser user, string[] targetedAdUnitIds) {
// Get InventoryService.
PlacementService placementService =
(PlacementService) user.GetService(DfpService.v201502.PlacementService);
Placement placement = new Placement();
placement.name = string.Format("Test placement #{0}", this.GetTimeStamp());
placement.description = "Test placement";
placement.targetedAdUnitIds = targetedAdUnitIds;
return placementService.createPlacements(new Placement[] {placement})[0];
}
public ReportJob CreateReport(DfpUser user) {
// Get ReportService.
ReportService reportService =
(ReportService) user.GetService(DfpService.v201502.ReportService);
ReportJob reportJob = new ReportJob();
reportJob.reportQuery = new ReportQuery();
reportJob.reportQuery.dimensions = new Dimension[] {Dimension.ORDER_ID, Dimension.ORDER_NAME};
reportJob.reportQuery.columns = new Column[] {Column.AD_SERVER_IMPRESSIONS,
Column.AD_SERVER_CLICKS, Column.AD_SERVER_CTR, Column.AD_SERVER_CPM_AND_CPC_REVENUE,
Column.AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM};
reportJob.reportQuery.dateRangeType = DateRangeType.LAST_MONTH;
return reportService.runReportJob(reportJob);
}
/// <summary>
/// Gets the current timestamp as a string.
/// </summary>
/// <returns>The current timestamp as a string.</returns>
public string GetTimeStamp() {
Thread.Sleep(500);
return (System.DateTime.UtcNow - new System.DateTime(1970, 1, 1)).Ticks.
ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class CollectionImportTests
{
[Fact]
public static void ImportNull()
{
X509Certificate2Collection cc2 = new X509Certificate2Collection();
Assert.Throws<ArgumentNullException>(() => cc2.Import((byte[])null));
Assert.Throws<ArgumentNullException>(() => cc2.Import((string)null));
}
[Fact]
public static void ImportEmpty_Pkcs12()
{
using (ImportedCollection ic = Cert.Import(TestData.EmptyPfx))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(0, collection.Count);
}
}
[Fact]
public static void ImportX509DerBytes()
{
using (ImportedCollection ic = Cert.Import(TestData.MsCertificate))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(1, collection.Count);
}
}
[Fact]
public static void ImportX509PemBytes()
{
using (ImportedCollection ic = Cert.Import(TestData.MsCertificatePemBytes))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(1, collection.Count);
}
}
[Fact]
public static void ImportX509DerFile()
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "MS.cer")))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(1, collection.Count);
}
}
[Fact]
public static void ImportX509PemFile()
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "MS.pem")))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(1, collection.Count);
}
}
[Fact]
public static void ImportPkcs7DerBytes_Empty()
{
using (ImportedCollection ic = Cert.Import(TestData.Pkcs7EmptyDerBytes))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(0, collection.Count);
}
}
[Fact]
public static void ImportPkcs7PemBytes_Empty()
{
using (ImportedCollection ic = Cert.Import(TestData.Pkcs7EmptyPemBytes))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(0, collection.Count);
}
}
[Fact]
public static void ImportPkcs7DerFile_Empty()
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "empty.p7b")))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(0, collection.Count);
}
}
[Fact]
public static void ImportPkcs7PemFile_Empty()
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "empty.p7c")))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(0, collection.Count);
}
}
[Fact]
public static void ImportPkcs7DerBytes_Single()
{
using (ImportedCollection ic = Cert.Import(TestData.Pkcs7SingleDerBytes))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(1, collection.Count);
Assert.Equal("D5B5BC1C458A558845BFF51CB4DFF31C", collection[0].SerialNumber);
}
}
[Fact]
public static void ImportPkcs7PemBytes_Single()
{
using (ImportedCollection ic = Cert.Import(TestData.Pkcs7SinglePemBytes))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(1, collection.Count);
Assert.Equal("D5B5BC1C458A558845BFF51CB4DFF31C", collection[0].SerialNumber);
}
}
[Fact]
public static void ImportPkcs7DerFile_Single()
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "singlecert.p7b")))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(1, collection.Count);
Assert.Equal("D5B5BC1C458A558845BFF51CB4DFF31C", collection[0].SerialNumber);
}
}
[Fact]
public static void ImportPkcs7PemFile_Single()
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "singlecert.p7c")))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(1, collection.Count);
Assert.Equal("D5B5BC1C458A558845BFF51CB4DFF31C", collection[0].SerialNumber);
}
}
[Fact]
public static void ImportPkcs7DerBytes_Chain()
{
using (ImportedCollection ic = Cert.Import(TestData.Pkcs7ChainDerBytes))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(3, collection.Count);
}
}
[Fact]
public static void ImportPkcs7PemBytes_Chain()
{
using (ImportedCollection ic = Cert.Import(TestData.Pkcs7ChainPemBytes))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(3, collection.Count);
}
}
[Fact]
public static void ImportPkcs7DerFile_Chain()
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "certchain.p7b")))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(3, collection.Count);
}
}
[Fact]
public static void ImportPkcs7PemFile_Chain()
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "certchain.p7c")))
{
X509Certificate2Collection collection = ic.Collection;
Assert.Equal(3, collection.Count);
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void ImportPkcs12Bytes_Single(X509KeyStorageFlags keyStorageFlags)
{
using (ImportedCollection ic = Cert.Import(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags))
{
X509Certificate2Collection cc2 = ic.Collection;
int count = cc2.Count;
Assert.Equal(1, count);
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void ImportPkcs12Bytes_Single_VerifyContents(X509KeyStorageFlags keyStorageFlags)
{
using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible))
{
using (ImportedCollection ic = Cert.Import(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags))
{
X509Certificate2Collection cc2 = ic.Collection;
int count = cc2.Count;
Assert.Equal(1, count);
using (X509Certificate2 c = cc2[0])
{
// pfxCer was loaded directly, cc2[0] was Imported, two distinct copies.
Assert.NotSame(pfxCer, c);
Assert.Equal(pfxCer, c);
Assert.Equal(pfxCer.Thumbprint, c.Thumbprint);
}
}
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void ImportPkcs12File_Single(X509KeyStorageFlags keyStorageFlags)
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "My.pfx"), TestData.PfxDataPassword, keyStorageFlags))
{
X509Certificate2Collection cc2 = ic.Collection;
int count = cc2.Count;
Assert.Equal(1, count);
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void ImportPkcs12Bytes_Chain(X509KeyStorageFlags keyStorageFlags)
{
using (ImportedCollection ic = Cert.Import(TestData.ChainPfxBytes, TestData.ChainPfxPassword, keyStorageFlags))
{
X509Certificate2Collection certs = ic.Collection;
int count = certs.Count;
Assert.Equal(3, count);
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void ImportPkcs12File_Chain(X509KeyStorageFlags keyStorageFlags)
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, keyStorageFlags))
{
X509Certificate2Collection certs = ic.Collection;
int count = certs.Count;
Assert.Equal(3, count);
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void ImportPkcs12File_Chain_VerifyContents(X509KeyStorageFlags keyStorageFlags)
{
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, keyStorageFlags))
{
X509Certificate2Collection certs = ic.Collection;
int count = certs.Count;
Assert.Equal(3, count);
// Verify that the read ordering is consistent across the platforms
string[] expectedSubjects =
{
"MS Passport Test Sub CA",
"MS Passport Test Root CA",
"test.local",
};
string[] actualSubjects = certs.OfType<X509Certificate2>().
Select(cert => cert.GetNameInfo(X509NameType.SimpleName, false)).
ToArray();
Assert.Equal(expectedSubjects, actualSubjects);
// And verify that we have private keys when we expect them
bool[] expectedHasPrivateKeys =
{
false,
false,
true,
};
bool[] actualHasPrivateKeys = certs.OfType<X509Certificate2>().
Select(cert => cert.HasPrivateKey).
ToArray();
Assert.Equal(expectedHasPrivateKeys, actualHasPrivateKeys);
}
}
#if netcoreapp11
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public static void EphemeralKeySet_OSX()
{
// EphemeralKeySet fails when loading a PFX, and is ignored otherwise.
using (ImportedCollection coll = Cert.Import(TestData.Pkcs7ChainDerBytes, null, X509KeyStorageFlags.EphemeralKeySet))
{
Assert.Equal(3, coll.Collection.Count);
}
Assert.Throws<PlatformNotSupportedException>(
() => new X509Certificate2(TestData.EmptyPfx, string.Empty, X509KeyStorageFlags.EphemeralKeySet));
}
#endif
[Fact]
public static void InvalidStorageFlags()
{
X509Certificate2Collection coll = new X509Certificate2Collection();
byte[] nonEmptyBytes = new byte[1];
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => coll.Import(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => coll.Import(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF));
// No test is performed here for the ephemeral flag failing downlevel, because the live
// binary is always used by default, meaning it doesn't know EphemeralKeySet doesn't exist.
}
#if netcoreapp
[Fact]
public static void InvalidStorageFlags_PersistedEphemeral()
{
const X509KeyStorageFlags PersistedEphemeral =
X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.PersistKeySet;
byte[] nonEmptyBytes = new byte[1];
X509Certificate2Collection coll = new X509Certificate2Collection();
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => coll.Import(nonEmptyBytes, string.Empty, PersistedEphemeral));
AssertExtensions.Throws<ArgumentException>(
"keyStorageFlags",
() => coll.Import(string.Empty, string.Empty, PersistedEphemeral));
}
#endif
public static IEnumerable<object[]> StorageFlags
{
get
{
yield return new object[] { X509KeyStorageFlags.DefaultKeySet };
#if netcoreapp
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
yield return new object[] { X509KeyStorageFlags.EphemeralKeySet };
#endif
}
}
}
}
| |
using System;
using BACnet.Types;
using BACnet.Types.Schemas;
namespace BACnet.Ashrae
{
public abstract partial class ConfirmedServiceAck
{
public abstract Tags Tag { get; }
public bool IsGetAlarmSummary { get { return this.Tag == Tags.GetAlarmSummary; } }
public GetAlarmSummaryAck AsGetAlarmSummary { get { return ((GetAlarmSummaryWrapper)this).Item; } }
public static ConfirmedServiceAck NewGetAlarmSummary(GetAlarmSummaryAck getAlarmSummary)
{
return new GetAlarmSummaryWrapper(getAlarmSummary);
}
public bool IsGetEnrollmentSummary { get { return this.Tag == Tags.GetEnrollmentSummary; } }
public GetEnrollmentSummaryAck AsGetEnrollmentSummary { get { return ((GetEnrollmentSummaryWrapper)this).Item; } }
public static ConfirmedServiceAck NewGetEnrollmentSummary(GetEnrollmentSummaryAck getEnrollmentSummary)
{
return new GetEnrollmentSummaryWrapper(getEnrollmentSummary);
}
public bool IsGetEventInformation { get { return this.Tag == Tags.GetEventInformation; } }
public GetEventInformationAck AsGetEventInformation { get { return ((GetEventInformationWrapper)this).Item; } }
public static ConfirmedServiceAck NewGetEventInformation(GetEventInformationAck getEventInformation)
{
return new GetEventInformationWrapper(getEventInformation);
}
public bool IsAtomicReadFile { get { return this.Tag == Tags.AtomicReadFile; } }
public AtomicReadFileAck AsAtomicReadFile { get { return ((AtomicReadFileWrapper)this).Item; } }
public static ConfirmedServiceAck NewAtomicReadFile(AtomicReadFileAck atomicReadFile)
{
return new AtomicReadFileWrapper(atomicReadFile);
}
public bool IsAtomicWriteFile { get { return this.Tag == Tags.AtomicWriteFile; } }
public AtomicWriteFileAck AsAtomicWriteFile { get { return ((AtomicWriteFileWrapper)this).Item; } }
public static ConfirmedServiceAck NewAtomicWriteFile(AtomicWriteFileAck atomicWriteFile)
{
return new AtomicWriteFileWrapper(atomicWriteFile);
}
public bool IsCreateObject { get { return this.Tag == Tags.CreateObject; } }
public CreateObjectAck AsCreateObject { get { return ((CreateObjectWrapper)this).Item; } }
public static ConfirmedServiceAck NewCreateObject(CreateObjectAck createObject)
{
return new CreateObjectWrapper(createObject);
}
public bool IsReadProperty { get { return this.Tag == Tags.ReadProperty; } }
public ReadPropertyAck AsReadProperty { get { return ((ReadPropertyWrapper)this).Item; } }
public static ConfirmedServiceAck NewReadProperty(ReadPropertyAck readProperty)
{
return new ReadPropertyWrapper(readProperty);
}
public bool IsReadPropertyConditional { get { return this.Tag == Tags.ReadPropertyConditional; } }
public ReadPropertyConditionalAck AsReadPropertyConditional { get { return ((ReadPropertyConditionalWrapper)this).Item; } }
public static ConfirmedServiceAck NewReadPropertyConditional(ReadPropertyConditionalAck readPropertyConditional)
{
return new ReadPropertyConditionalWrapper(readPropertyConditional);
}
public bool IsReadPropertyMultiple { get { return this.Tag == Tags.ReadPropertyMultiple; } }
public ReadPropertyMultipleAck AsReadPropertyMultiple { get { return ((ReadPropertyMultipleWrapper)this).Item; } }
public static ConfirmedServiceAck NewReadPropertyMultiple(ReadPropertyMultipleAck readPropertyMultiple)
{
return new ReadPropertyMultipleWrapper(readPropertyMultiple);
}
public bool IsReadRange { get { return this.Tag == Tags.ReadRange; } }
public ReadRangeAck AsReadRange { get { return ((ReadRangeWrapper)this).Item; } }
public static ConfirmedServiceAck NewReadRange(ReadRangeAck readRange)
{
return new ReadRangeWrapper(readRange);
}
public bool IsConfirmedPrivateTransfer { get { return this.Tag == Tags.ConfirmedPrivateTransfer; } }
public ConfirmedPrivateTransferAck AsConfirmedPrivateTransfer { get { return ((ConfirmedPrivateTransferWrapper)this).Item; } }
public static ConfirmedServiceAck NewConfirmedPrivateTransfer(ConfirmedPrivateTransferAck confirmedPrivateTransfer)
{
return new ConfirmedPrivateTransferWrapper(confirmedPrivateTransfer);
}
public bool IsVtOpen { get { return this.Tag == Tags.VtOpen; } }
public VTOpenAck AsVtOpen { get { return ((VtOpenWrapper)this).Item; } }
public static ConfirmedServiceAck NewVtOpen(VTOpenAck vtOpen)
{
return new VtOpenWrapper(vtOpen);
}
public bool IsVtData { get { return this.Tag == Tags.VtData; } }
public VTDataAck AsVtData { get { return ((VtDataWrapper)this).Item; } }
public static ConfirmedServiceAck NewVtData(VTDataAck vtData)
{
return new VtDataWrapper(vtData);
}
public bool IsAuthenticate { get { return this.Tag == Tags.Authenticate; } }
public AuthenticateAck AsAuthenticate { get { return ((AuthenticateWrapper)this).Item; } }
public static ConfirmedServiceAck NewAuthenticate(AuthenticateAck authenticate)
{
return new AuthenticateWrapper(authenticate);
}
public static readonly ISchema Schema = new ChoiceSchema(false,
new FieldSchema("GetAlarmSummary", 3, Value<GetAlarmSummaryAck>.Schema),
new FieldSchema("GetEnrollmentSummary", 4, Value<GetEnrollmentSummaryAck>.Schema),
new FieldSchema("GetEventInformation", 29, Value<GetEventInformationAck>.Schema),
new FieldSchema("AtomicReadFile", 6, Value<AtomicReadFileAck>.Schema),
new FieldSchema("AtomicWriteFile", 7, Value<AtomicWriteFileAck>.Schema),
new FieldSchema("CreateObject", 10, Value<CreateObjectAck>.Schema),
new FieldSchema("ReadProperty", 12, Value<ReadPropertyAck>.Schema),
new FieldSchema("ReadPropertyConditional", 13, Value<ReadPropertyConditionalAck>.Schema),
new FieldSchema("ReadPropertyMultiple", 14, Value<ReadPropertyMultipleAck>.Schema),
new FieldSchema("ReadRange", 26, Value<ReadRangeAck>.Schema),
new FieldSchema("ConfirmedPrivateTransfer", 18, Value<ConfirmedPrivateTransferAck>.Schema),
new FieldSchema("VtOpen", 21, Value<VTOpenAck>.Schema),
new FieldSchema("VtData", 23, Value<VTDataAck>.Schema),
new FieldSchema("Authenticate", 24, Value<AuthenticateAck>.Schema));
public static ConfirmedServiceAck Load(IValueStream stream)
{
ConfirmedServiceAck ret = null;
Tags tag = (Tags)stream.EnterChoice();
switch(tag)
{
case Tags.GetAlarmSummary:
ret = Value<GetAlarmSummaryWrapper>.Load(stream);
break;
case Tags.GetEnrollmentSummary:
ret = Value<GetEnrollmentSummaryWrapper>.Load(stream);
break;
case Tags.GetEventInformation:
ret = Value<GetEventInformationWrapper>.Load(stream);
break;
case Tags.AtomicReadFile:
ret = Value<AtomicReadFileWrapper>.Load(stream);
break;
case Tags.AtomicWriteFile:
ret = Value<AtomicWriteFileWrapper>.Load(stream);
break;
case Tags.CreateObject:
ret = Value<CreateObjectWrapper>.Load(stream);
break;
case Tags.ReadProperty:
ret = Value<ReadPropertyWrapper>.Load(stream);
break;
case Tags.ReadPropertyConditional:
ret = Value<ReadPropertyConditionalWrapper>.Load(stream);
break;
case Tags.ReadPropertyMultiple:
ret = Value<ReadPropertyMultipleWrapper>.Load(stream);
break;
case Tags.ReadRange:
ret = Value<ReadRangeWrapper>.Load(stream);
break;
case Tags.ConfirmedPrivateTransfer:
ret = Value<ConfirmedPrivateTransferWrapper>.Load(stream);
break;
case Tags.VtOpen:
ret = Value<VtOpenWrapper>.Load(stream);
break;
case Tags.VtData:
ret = Value<VtDataWrapper>.Load(stream);
break;
case Tags.Authenticate:
ret = Value<AuthenticateWrapper>.Load(stream);
break;
default:
throw new Exception();
}
stream.LeaveChoice();
return ret;
}
public static void Save(IValueSink sink, ConfirmedServiceAck value)
{
sink.EnterChoice((byte)value.Tag);
switch(value.Tag)
{
case Tags.GetAlarmSummary:
Value<GetAlarmSummaryWrapper>.Save(sink, (GetAlarmSummaryWrapper)value);
break;
case Tags.GetEnrollmentSummary:
Value<GetEnrollmentSummaryWrapper>.Save(sink, (GetEnrollmentSummaryWrapper)value);
break;
case Tags.GetEventInformation:
Value<GetEventInformationWrapper>.Save(sink, (GetEventInformationWrapper)value);
break;
case Tags.AtomicReadFile:
Value<AtomicReadFileWrapper>.Save(sink, (AtomicReadFileWrapper)value);
break;
case Tags.AtomicWriteFile:
Value<AtomicWriteFileWrapper>.Save(sink, (AtomicWriteFileWrapper)value);
break;
case Tags.CreateObject:
Value<CreateObjectWrapper>.Save(sink, (CreateObjectWrapper)value);
break;
case Tags.ReadProperty:
Value<ReadPropertyWrapper>.Save(sink, (ReadPropertyWrapper)value);
break;
case Tags.ReadPropertyConditional:
Value<ReadPropertyConditionalWrapper>.Save(sink, (ReadPropertyConditionalWrapper)value);
break;
case Tags.ReadPropertyMultiple:
Value<ReadPropertyMultipleWrapper>.Save(sink, (ReadPropertyMultipleWrapper)value);
break;
case Tags.ReadRange:
Value<ReadRangeWrapper>.Save(sink, (ReadRangeWrapper)value);
break;
case Tags.ConfirmedPrivateTransfer:
Value<ConfirmedPrivateTransferWrapper>.Save(sink, (ConfirmedPrivateTransferWrapper)value);
break;
case Tags.VtOpen:
Value<VtOpenWrapper>.Save(sink, (VtOpenWrapper)value);
break;
case Tags.VtData:
Value<VtDataWrapper>.Save(sink, (VtDataWrapper)value);
break;
case Tags.Authenticate:
Value<AuthenticateWrapper>.Save(sink, (AuthenticateWrapper)value);
break;
default:
throw new Exception();
}
sink.LeaveChoice();
}
public enum Tags : byte
{
GetAlarmSummary = 0,
GetEnrollmentSummary = 1,
GetEventInformation = 2,
AtomicReadFile = 3,
AtomicWriteFile = 4,
CreateObject = 5,
ReadProperty = 6,
ReadPropertyConditional = 7,
ReadPropertyMultiple = 8,
ReadRange = 9,
ConfirmedPrivateTransfer = 10,
VtOpen = 11,
VtData = 12,
Authenticate = 13
}
public partial class GetAlarmSummaryWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.GetAlarmSummary; } }
public GetAlarmSummaryAck Item { get; private set; }
public GetAlarmSummaryWrapper(GetAlarmSummaryAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<GetAlarmSummaryAck>.Schema;
public static new GetAlarmSummaryWrapper Load(IValueStream stream)
{
var temp = Value<GetAlarmSummaryAck>.Load(stream);
return new GetAlarmSummaryWrapper(temp);
}
public static void Save(IValueSink sink, GetAlarmSummaryWrapper value)
{
Value<GetAlarmSummaryAck>.Save(sink, value.Item);
}
}
public partial class GetEnrollmentSummaryWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.GetEnrollmentSummary; } }
public GetEnrollmentSummaryAck Item { get; private set; }
public GetEnrollmentSummaryWrapper(GetEnrollmentSummaryAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<GetEnrollmentSummaryAck>.Schema;
public static new GetEnrollmentSummaryWrapper Load(IValueStream stream)
{
var temp = Value<GetEnrollmentSummaryAck>.Load(stream);
return new GetEnrollmentSummaryWrapper(temp);
}
public static void Save(IValueSink sink, GetEnrollmentSummaryWrapper value)
{
Value<GetEnrollmentSummaryAck>.Save(sink, value.Item);
}
}
public partial class GetEventInformationWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.GetEventInformation; } }
public GetEventInformationAck Item { get; private set; }
public GetEventInformationWrapper(GetEventInformationAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<GetEventInformationAck>.Schema;
public static new GetEventInformationWrapper Load(IValueStream stream)
{
var temp = Value<GetEventInformationAck>.Load(stream);
return new GetEventInformationWrapper(temp);
}
public static void Save(IValueSink sink, GetEventInformationWrapper value)
{
Value<GetEventInformationAck>.Save(sink, value.Item);
}
}
public partial class AtomicReadFileWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.AtomicReadFile; } }
public AtomicReadFileAck Item { get; private set; }
public AtomicReadFileWrapper(AtomicReadFileAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<AtomicReadFileAck>.Schema;
public static new AtomicReadFileWrapper Load(IValueStream stream)
{
var temp = Value<AtomicReadFileAck>.Load(stream);
return new AtomicReadFileWrapper(temp);
}
public static void Save(IValueSink sink, AtomicReadFileWrapper value)
{
Value<AtomicReadFileAck>.Save(sink, value.Item);
}
}
public partial class AtomicWriteFileWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.AtomicWriteFile; } }
public AtomicWriteFileAck Item { get; private set; }
public AtomicWriteFileWrapper(AtomicWriteFileAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<AtomicWriteFileAck>.Schema;
public static new AtomicWriteFileWrapper Load(IValueStream stream)
{
var temp = Value<AtomicWriteFileAck>.Load(stream);
return new AtomicWriteFileWrapper(temp);
}
public static void Save(IValueSink sink, AtomicWriteFileWrapper value)
{
Value<AtomicWriteFileAck>.Save(sink, value.Item);
}
}
public partial class CreateObjectWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.CreateObject; } }
public CreateObjectAck Item { get; private set; }
public CreateObjectWrapper(CreateObjectAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<CreateObjectAck>.Schema;
public static new CreateObjectWrapper Load(IValueStream stream)
{
var temp = Value<CreateObjectAck>.Load(stream);
return new CreateObjectWrapper(temp);
}
public static void Save(IValueSink sink, CreateObjectWrapper value)
{
Value<CreateObjectAck>.Save(sink, value.Item);
}
}
public partial class ReadPropertyWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.ReadProperty; } }
public ReadPropertyAck Item { get; private set; }
public ReadPropertyWrapper(ReadPropertyAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<ReadPropertyAck>.Schema;
public static new ReadPropertyWrapper Load(IValueStream stream)
{
var temp = Value<ReadPropertyAck>.Load(stream);
return new ReadPropertyWrapper(temp);
}
public static void Save(IValueSink sink, ReadPropertyWrapper value)
{
Value<ReadPropertyAck>.Save(sink, value.Item);
}
}
public partial class ReadPropertyConditionalWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.ReadPropertyConditional; } }
public ReadPropertyConditionalAck Item { get; private set; }
public ReadPropertyConditionalWrapper(ReadPropertyConditionalAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<ReadPropertyConditionalAck>.Schema;
public static new ReadPropertyConditionalWrapper Load(IValueStream stream)
{
var temp = Value<ReadPropertyConditionalAck>.Load(stream);
return new ReadPropertyConditionalWrapper(temp);
}
public static void Save(IValueSink sink, ReadPropertyConditionalWrapper value)
{
Value<ReadPropertyConditionalAck>.Save(sink, value.Item);
}
}
public partial class ReadPropertyMultipleWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.ReadPropertyMultiple; } }
public ReadPropertyMultipleAck Item { get; private set; }
public ReadPropertyMultipleWrapper(ReadPropertyMultipleAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<ReadPropertyMultipleAck>.Schema;
public static new ReadPropertyMultipleWrapper Load(IValueStream stream)
{
var temp = Value<ReadPropertyMultipleAck>.Load(stream);
return new ReadPropertyMultipleWrapper(temp);
}
public static void Save(IValueSink sink, ReadPropertyMultipleWrapper value)
{
Value<ReadPropertyMultipleAck>.Save(sink, value.Item);
}
}
public partial class ReadRangeWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.ReadRange; } }
public ReadRangeAck Item { get; private set; }
public ReadRangeWrapper(ReadRangeAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<ReadRangeAck>.Schema;
public static new ReadRangeWrapper Load(IValueStream stream)
{
var temp = Value<ReadRangeAck>.Load(stream);
return new ReadRangeWrapper(temp);
}
public static void Save(IValueSink sink, ReadRangeWrapper value)
{
Value<ReadRangeAck>.Save(sink, value.Item);
}
}
public partial class ConfirmedPrivateTransferWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.ConfirmedPrivateTransfer; } }
public ConfirmedPrivateTransferAck Item { get; private set; }
public ConfirmedPrivateTransferWrapper(ConfirmedPrivateTransferAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<ConfirmedPrivateTransferAck>.Schema;
public static new ConfirmedPrivateTransferWrapper Load(IValueStream stream)
{
var temp = Value<ConfirmedPrivateTransferAck>.Load(stream);
return new ConfirmedPrivateTransferWrapper(temp);
}
public static void Save(IValueSink sink, ConfirmedPrivateTransferWrapper value)
{
Value<ConfirmedPrivateTransferAck>.Save(sink, value.Item);
}
}
public partial class VtOpenWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.VtOpen; } }
public VTOpenAck Item { get; private set; }
public VtOpenWrapper(VTOpenAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<VTOpenAck>.Schema;
public static new VtOpenWrapper Load(IValueStream stream)
{
var temp = Value<VTOpenAck>.Load(stream);
return new VtOpenWrapper(temp);
}
public static void Save(IValueSink sink, VtOpenWrapper value)
{
Value<VTOpenAck>.Save(sink, value.Item);
}
}
public partial class VtDataWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.VtData; } }
public VTDataAck Item { get; private set; }
public VtDataWrapper(VTDataAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<VTDataAck>.Schema;
public static new VtDataWrapper Load(IValueStream stream)
{
var temp = Value<VTDataAck>.Load(stream);
return new VtDataWrapper(temp);
}
public static void Save(IValueSink sink, VtDataWrapper value)
{
Value<VTDataAck>.Save(sink, value.Item);
}
}
public partial class AuthenticateWrapper : ConfirmedServiceAck
{
public override Tags Tag { get { return Tags.Authenticate; } }
public AuthenticateAck Item { get; private set; }
public AuthenticateWrapper(AuthenticateAck item)
{
this.Item = item;
}
public static readonly new ISchema Schema = Value<AuthenticateAck>.Schema;
public static new AuthenticateWrapper Load(IValueStream stream)
{
var temp = Value<AuthenticateAck>.Load(stream);
return new AuthenticateWrapper(temp);
}
public static void Save(IValueSink sink, AuthenticateWrapper value)
{
Value<AuthenticateAck>.Save(sink, value.Item);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>CampaignBudget</c> resource.</summary>
public sealed partial class CampaignBudgetName : gax::IResourceName, sys::IEquatable<CampaignBudgetName>
{
/// <summary>The possible contents of <see cref="CampaignBudgetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>.
/// </summary>
CustomerCampaignBudget = 1,
}
private static gax::PathTemplate s_customerCampaignBudget = new gax::PathTemplate("customers/{customer_id}/campaignBudgets/{campaign_budget_id}");
/// <summary>Creates a <see cref="CampaignBudgetName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CampaignBudgetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CampaignBudgetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CampaignBudgetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CampaignBudgetName"/> with the pattern
/// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignBudgetId">The <c>CampaignBudget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CampaignBudgetName"/> constructed from the provided ids.</returns>
public static CampaignBudgetName FromCustomerCampaignBudget(string customerId, string campaignBudgetId) =>
new CampaignBudgetName(ResourceNameType.CustomerCampaignBudget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignBudgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignBudgetId, nameof(campaignBudgetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignBudgetName"/> with pattern
/// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignBudgetId">The <c>CampaignBudget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignBudgetName"/> with pattern
/// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>.
/// </returns>
public static string Format(string customerId, string campaignBudgetId) =>
FormatCustomerCampaignBudget(customerId, campaignBudgetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignBudgetName"/> with pattern
/// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignBudgetId">The <c>CampaignBudget</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignBudgetName"/> with pattern
/// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>.
/// </returns>
public static string FormatCustomerCampaignBudget(string customerId, string campaignBudgetId) =>
s_customerCampaignBudget.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(campaignBudgetId, nameof(campaignBudgetId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignBudgetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="campaignBudgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CampaignBudgetName"/> if successful.</returns>
public static CampaignBudgetName Parse(string campaignBudgetName) => Parse(campaignBudgetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignBudgetName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignBudgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CampaignBudgetName"/> if successful.</returns>
public static CampaignBudgetName Parse(string campaignBudgetName, bool allowUnparsed) =>
TryParse(campaignBudgetName, allowUnparsed, out CampaignBudgetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignBudgetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="campaignBudgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignBudgetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string campaignBudgetName, out CampaignBudgetName result) =>
TryParse(campaignBudgetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignBudgetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignBudgetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignBudgetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string campaignBudgetName, bool allowUnparsed, out CampaignBudgetName result)
{
gax::GaxPreconditions.CheckNotNull(campaignBudgetName, nameof(campaignBudgetName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignBudget.TryParseName(campaignBudgetName, out resourceName))
{
result = FromCustomerCampaignBudget(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(campaignBudgetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CampaignBudgetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignBudgetId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignBudgetId = campaignBudgetId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CampaignBudgetName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/campaignBudgets/{campaign_budget_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignBudgetId">The <c>CampaignBudget</c> ID. Must not be <c>null</c> or empty.</param>
public CampaignBudgetName(string customerId, string campaignBudgetId) : this(ResourceNameType.CustomerCampaignBudget, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignBudgetId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignBudgetId, nameof(campaignBudgetId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>CampaignBudget</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string CampaignBudgetId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCampaignBudget: return s_customerCampaignBudget.Expand(CustomerId, CampaignBudgetId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CampaignBudgetName);
/// <inheritdoc/>
public bool Equals(CampaignBudgetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CampaignBudgetName a, CampaignBudgetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CampaignBudgetName a, CampaignBudgetName b) => !(a == b);
}
public partial class CampaignBudget
{
/// <summary>
/// <see cref="gagvr::CampaignBudgetName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal CampaignBudgetName ResourceNameAsCampaignBudgetName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CampaignBudgetName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::CampaignBudgetName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal CampaignBudgetName CampaignBudgetName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::CampaignBudgetName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// HashJoinQueryOperatorEnumerator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// This enumerator implements the hash-join algorithm as noted earlier.
///
/// Assumptions:
/// This enumerator type won't work properly at all if the analysis engine didn't
/// ensure a proper hash-partition. We expect inner and outer elements with equal
/// keys are ALWAYS in the same partition. If they aren't (e.g. if the analysis is
/// busted) we'll silently drop items on the floor. :(
///
///
/// This is the enumerator class for two operators:
/// - Join
/// - GroupJoin
/// </summary>
/// <typeparam name="TLeftInput"></typeparam>
/// <typeparam name="TLeftKey"></typeparam>
/// <typeparam name="TRightInput"></typeparam>
/// <typeparam name="THashKey"></typeparam>
/// <typeparam name="TOutput"></typeparam>
internal class HashJoinQueryOperatorEnumerator<TLeftInput, TLeftKey, TRightInput, THashKey, TOutput>
: QueryOperatorEnumerator<TOutput, TLeftKey>
{
private readonly QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left (outer) data source. For probing.
private readonly QueryOperatorEnumerator<Pair, int> _rightSource; // Right (inner) data source. For building.
private readonly Func<TLeftInput, TRightInput, TOutput> _singleResultSelector; // Single result selector.
private readonly Func<TLeftInput, IEnumerable<TRightInput>, TOutput> _groupResultSelector; // Group result selector.
private readonly IEqualityComparer<THashKey> _keyComparer; // An optional key comparison object.
private readonly CancellationToken _cancellationToken;
private Mutables _mutables;
private class Mutables
{
internal TLeftInput _currentLeft; // The current matching left element.
internal TLeftKey _currentLeftKey; // The current index of the matching left element.
internal HashLookup<THashKey, Pair> _rightHashLookup; // The hash lookup.
internal ListChunk<TRightInput> _currentRightMatches; // Current right matches (if any).
internal int _currentRightMatchesIndex; // Current index in the set of right matches.
internal int _outputLoopCount;
}
//---------------------------------------------------------------------------------------
// Instantiates a new hash-join enumerator.
//
internal HashJoinQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TLeftKey> leftSource,
QueryOperatorEnumerator<Pair, int> rightSource,
Func<TLeftInput, TRightInput, TOutput> singleResultSelector,
Func<TLeftInput, IEnumerable<TRightInput>, TOutput> groupResultSelector,
IEqualityComparer<THashKey> keyComparer,
CancellationToken cancellationToken)
{
Contract.Assert(leftSource != null);
Contract.Assert(rightSource != null);
Contract.Assert(singleResultSelector != null || groupResultSelector != null);
_leftSource = leftSource;
_rightSource = rightSource;
_singleResultSelector = singleResultSelector;
_groupResultSelector = groupResultSelector;
_keyComparer = keyComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// MoveNext implements all the hash-join logic noted earlier. When it is called first, it
// will execute the entire inner query tree, and build a hash-table lookup. This is the
// Building phase. Then for the first call and all subsequent calls to MoveNext, we will
// incrementally perform the Probing phase. We'll keep getting elements from the outer
// data source, looking into the hash-table we built, and enumerating the full results.
//
// This routine supports both inner and outer (group) joins. An outer join will yield a
// (possibly empty) list of matching elements from the inner instead of one-at-a-time,
// as we do for inner joins.
//
internal override bool MoveNext(ref TOutput currentElement, ref TLeftKey currentKey)
{
Contract.Assert(_singleResultSelector != null || _groupResultSelector != null, "expected a compiled result selector");
Contract.Assert(_leftSource != null);
Contract.Assert(_rightSource != null);
// BUILD phase: If we haven't built the hash-table yet, create that first.
Mutables mutables = _mutables;
if (mutables == null)
{
mutables = _mutables = new Mutables();
#if DEBUG
int hashLookupCount = 0;
int hashKeyCollisions = 0;
#endif
mutables._rightHashLookup = new HashLookup<THashKey, Pair>(_keyComparer);
Pair rightPair = new Pair(default(TRightInput), default(THashKey));
int rightKeyUnused = default(int);
int i = 0;
while (_rightSource.MoveNext(ref rightPair, ref rightKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
TRightInput rightElement = (TRightInput)rightPair.First;
THashKey rightHashKey = (THashKey)rightPair.Second;
// We ignore null keys.
if (rightHashKey != null)
{
#if DEBUG
hashLookupCount++;
#endif
// See if we've already stored an element under the current key. If not, we
// lazily allocate a pair to hold the elements mapping to the same key.
const int INITIAL_CHUNK_SIZE = 2;
Pair currentValue = new Pair(default(TRightInput), default(ListChunk<TRightInput>));
if (!mutables._rightHashLookup.TryGetValue(rightHashKey, ref currentValue))
{
currentValue = new Pair(rightElement, null);
if (_groupResultSelector != null)
{
// For group joins, we also add the element to the list. This makes
// it easier later to yield the list as-is.
currentValue.Second = new ListChunk<TRightInput>(INITIAL_CHUNK_SIZE);
((ListChunk<TRightInput>)currentValue.Second).Add((TRightInput)rightElement);
}
mutables._rightHashLookup.Add(rightHashKey, currentValue);
}
else
{
if (currentValue.Second == null)
{
// Lazily allocate a list to hold all but the 1st value. We need to
// re-store this element because the pair is a value type.
currentValue.Second = new ListChunk<TRightInput>(INITIAL_CHUNK_SIZE);
mutables._rightHashLookup[rightHashKey] = currentValue;
}
((ListChunk<TRightInput>)currentValue.Second).Add((TRightInput)rightElement);
#if DEBUG
hashKeyCollisions++;
#endif
}
}
}
#if DEBUG
TraceHelpers.TraceInfo("ParallelJoinQueryOperator::MoveNext - built hash table [count = {0}, collisions = {1}]",
hashLookupCount, hashKeyCollisions);
#endif
}
// PROBE phase: So long as the source has a next element, return the match.
ListChunk<TRightInput> currentRightChunk = mutables._currentRightMatches;
if (currentRightChunk != null && mutables._currentRightMatchesIndex == currentRightChunk.Count)
{
currentRightChunk = mutables._currentRightMatches = currentRightChunk.Next;
mutables._currentRightMatchesIndex = 0;
}
if (mutables._currentRightMatches == null)
{
// We have to look up the next list of matches in the hash-table.
Pair leftPair = new Pair(default(TLeftInput), default(THashKey));
TLeftKey leftKey = default(TLeftKey);
while (_leftSource.MoveNext(ref leftPair, ref leftKey))
{
if ((mutables._outputLoopCount++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// Find the match in the hash table.
Pair matchValue = new Pair(default(TRightInput), default(ListChunk<TRightInput>));
TLeftInput leftElement = (TLeftInput)leftPair.First;
THashKey leftHashKey = (THashKey)leftPair.Second;
// Ignore null keys.
if (leftHashKey != null)
{
if (mutables._rightHashLookup.TryGetValue(leftHashKey, ref matchValue))
{
// We found a new match. For inner joins, we remember the list in case
// there are multiple value under this same key -- the next iteration will pick
// them up. For outer joins, we will use the list momentarily.
if (_singleResultSelector != null)
{
mutables._currentRightMatches = (ListChunk<TRightInput>)matchValue.Second;
Contract.Assert(mutables._currentRightMatches == null || mutables._currentRightMatches.Count > 0,
"we were expecting that the list would be either null or empty");
mutables._currentRightMatchesIndex = 0;
// Yield the value.
currentElement = _singleResultSelector(leftElement, (TRightInput)matchValue.First);
currentKey = leftKey;
// If there is a list of matches, remember the left values for next time.
if (matchValue.Second != null)
{
mutables._currentLeft = leftElement;
mutables._currentLeftKey = leftKey;
}
return true;
}
}
}
// For outer joins, we always yield a result.
if (_groupResultSelector != null)
{
// Grab the matches, or create an empty list if there are none.
IEnumerable<TRightInput> matches = (ListChunk<TRightInput>)matchValue.Second;
if (matches == null)
{
matches = ParallelEnumerable.Empty<TRightInput>();
}
// Generate the current value.
currentElement = _groupResultSelector(leftElement, matches);
currentKey = leftKey;
return true;
}
}
// If we've reached the end of the data source, we're done.
return false;
}
// Produce the next element and increment our index within the matches.
Contract.Assert(_singleResultSelector != null);
Contract.Assert(mutables._currentRightMatches != null);
Contract.Assert(0 <= mutables._currentRightMatchesIndex && mutables._currentRightMatchesIndex < mutables._currentRightMatches.Count);
currentElement = _singleResultSelector(
mutables._currentLeft, mutables._currentRightMatches._chunk[mutables._currentRightMatchesIndex]);
currentKey = mutables._currentLeftKey;
mutables._currentRightMatchesIndex++;
return true;
}
protected override void Dispose(bool disposing)
{
Contract.Assert(_leftSource != null && _rightSource != null);
_leftSource.Dispose();
_rightSource.Dispose();
}
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Alistair Leslie-Hughes
*
* 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 Microsoft.DirectX.DirectPlay;
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Microsoft.DirectX.DirectPlay
{
public class Server : MarshalByRefObject, IDisposable
{
public GroupMembersList GroupMembers
{
get
{
throw new NotImplementedException ();
}
}
public PlayersGroupsEnumerator Groups
{
get
{
throw new NotImplementedException ();
}
}
public PlayersGroupsEnumerator Players
{
get
{
throw new NotImplementedException ();
}
}
public ApplicationDescription ApplicationDescription
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public Caps Caps
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public event EventHandler Disposing;
public event SendCompleteEventHandler SendComplete;
public event ServerInformationEventHandler ServerInformation;
public event PlayerRemovedFromGroupEventHandler PlayerRemovedFromGroup;
public event ReceiveEventHandler Receive;
public event IndicatedConnectAbortedEventHandler IndicatedConnectAborted;
public event IndicateConnectEventHandler IndicateConnect;
public event GroupInformationEventHandler GroupInformation;
public event FindHostQueryEventHandler FindHostQuery;
public event PlayerDestroyedEventHandler PlayerDestroyed;
public event GroupDestroyedEventHandler GroupDestroyed;
public event GroupCreatedEventHandler GroupCreated;
public event ClientInformationEventHandler ClientInformation;
public event AsyncOperationCompleteEventHandler AsyncOperationComplete;
public event ApplicationDescriptionEventHandler ApplicationDescriptionChanged;
public event PlayerAddedToGroupEventHandler PlayerAddedToGroup;
public event PlayerCreatedEventHandler PlayerCreated;
public override bool Equals(object compare)
{
throw new NotImplementedException ();
}
public static bool operator ==(Server left, Server right)
{
throw new NotImplementedException ();
}
public static bool operator !=(Server left, Server right)
{
throw new NotImplementedException ();
}
public override int GetHashCode()
{
throw new NotImplementedException ();
}
public void Dispose([MarshalAs(UnmanagedType.U1)] bool closeImmediate)
{
throw new NotImplementedException ();
}
public void Dispose()
{
throw new NotImplementedException ();
}
public Server(Microsoft.DirectX.DirectPlay.InitializeFlags flags)
{
}
public Server()
{
}
public void Host(ApplicationDescription applicationDescription, Address[] deviceAddress, object playerContext, HostFlags flags)
{
throw new NotImplementedException ();
}
public void Host(ApplicationDescription applicationDescription, Address deviceAddress, object playerContext, HostFlags flags)
{
throw new NotImplementedException ();
}
public void Host(ApplicationDescription applicationDescription, Address[] deviceAddress, HostFlags flags)
{
throw new NotImplementedException ();
}
public void Host(ApplicationDescription applicationDescription, Address deviceAddress, HostFlags flags)
{
throw new NotImplementedException ();
}
public void Host(ApplicationDescription applicationDescription, Address[] deviceAddress, object playerContext)
{
throw new NotImplementedException ();
}
public void Host(ApplicationDescription applicationDescription, Address deviceAddress, object playerContext)
{
throw new NotImplementedException ();
}
public void Host(ApplicationDescription applicationDescription, Address[] deviceAddress)
{
throw new NotImplementedException ();
}
public void Host(ApplicationDescription applicationDescription, Address deviceAddress)
{
throw new NotImplementedException ();
}
public void CancelAsyncOperation(int asyncHandle)
{
throw new NotImplementedException ();
}
public void CancelAsyncOperation(CancelFlags flags)
{
throw new NotImplementedException ();
}
public void GetSendQueueInformation(int dpnidPlayer, out int numberMessages, out int numberBytes, GetSendQueueInformationFlags flags)
{
throw new NotImplementedException ();
}
public ServiceProviderCaps GetSPCaps(Guid guidServiceProvider)
{
throw new NotImplementedException ();
}
public void SetSPCaps(Guid guidServiceProvider, ServiceProviderCaps value)
{
throw new NotImplementedException ();
}
public void CreateGroup(GroupInformation groupInformation, SyncFlags flags, object groupContext, object asyncContext)
{
throw new NotImplementedException ();
}
public void CreateGroup(GroupInformation groupInformation, out int asyncHandle, SyncFlags flags, object groupContext, object asyncContext)
{
throw new NotImplementedException ();
}
public void CreateGroup(GroupInformation groupInformation, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void CreateGroup(GroupInformation groupInformation, out int asyncHandle, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void DestroyGroup(int groupID, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public void DestroyGroup(int groupID, out int asyncHandle, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public void DestroyGroup(int groupID, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void DestroyGroup(int groupID, out int asyncHandle, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void AddPlayerToGroup(int groupID, int clientID, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public void AddPlayerToGroup(int groupID, int clientID, out int asyncHandle, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public void AddPlayerToGroup(int groupID, int clientID, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void AddPlayerToGroup(int groupID, int clientID, out int asyncHandle, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void RemovePlayerFromGroup(int groupID, int clientID, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public void RemovePlayerFromGroup(int groupID, int clientID, out int asyncHandle, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public void RemovePlayerFromGroup(int groupID, int clientID, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void RemovePlayerFromGroup(int groupID, int clientID, out int asyncHandle, SyncFlags flags)
{
throw new NotImplementedException ();
}
public object GetPlayerContext(int playerID)
{
throw new NotImplementedException ();
}
public object GetGroupContext(int groupID)
{
throw new NotImplementedException ();
}
public Address GetClientAddress(int playerID)
{
throw new NotImplementedException ();
}
public ServiceProviderInformation[] GetServiceProviders([MarshalAs(UnmanagedType.U1)] bool getAll)
{
throw new NotImplementedException ();
}
public ServiceProviderInformation[] GetServiceProviders(Guid guidServiceProvider, [MarshalAs(UnmanagedType.U1)] bool getAll)
{
throw new NotImplementedException ();
}
public ServiceProviderInformation[] GetServiceProviders(Guid guidServiceProvider, Guid guidApplication, [MarshalAs(UnmanagedType.U1)] bool getAll)
{
throw new NotImplementedException ();
}
public void SendTo(int playerID, GCHandle gcbuffer, int bufferSize, int timeOut, out int asyncHandle, SendFlags flags, object context)
{
throw new NotImplementedException ();
}
public void SendTo(int playerID, GCHandle gcbuffer, int bufferSize, int timeOut, SendFlags flags, object context)
{
throw new NotImplementedException ();
}
public void SendTo(int playerID, GCHandle gcbuffer, int bufferSize, int timeOut, SendFlags flags)
{
throw new NotImplementedException ();
}
public void SendTo(int playerID, GCHandle gcbuffer, int bufferSize, int timeOut, out int asyncHandle, SendFlags flags)
{
throw new NotImplementedException ();
}
public void SendTo(int playerID, NetworkPacket sendData, int timeOut, out int asyncHandle, SendFlags flags, object context)
{
throw new NotImplementedException ();
}
public void SendTo(int playerID, NetworkPacket sendData, int timeOut, SendFlags flags, object context)
{
throw new NotImplementedException ();
}
public void SendTo(int playerID, NetworkPacket sendData, int timeOut, SendFlags flags)
{
throw new NotImplementedException ();
}
public void SendTo(int playerID, NetworkPacket sendData, int timeOut, out int asyncHandle, SendFlags flags)
{
throw new NotImplementedException ();
}
public void DestroyClient(int playerID, NetworkPacket destroyData)
{
throw new NotImplementedException ();
}
public void SetServerInformation(PlayerInformation playerInformation, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void SetServerInformation(PlayerInformation playerInformation, out int asyncHandle, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void SetServerInformation(PlayerInformation playerInformation, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public void SetServerInformation(PlayerInformation playerInformation, out int asyncHandle, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public PlayerInformation GetClientInformation(int playerID)
{
throw new NotImplementedException ();
}
public void SetGroupInformation(int groupID, GroupInformation groupInformation, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void SetGroupInformation(int groupID, GroupInformation groupInformation, out int asyncHandle, SyncFlags flags)
{
throw new NotImplementedException ();
}
public void SetGroupInformation(int groupID, GroupInformation groupInformation, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public void SetGroupInformation(int groupID, GroupInformation groupInformation, out int asyncHandle, SyncFlags flags, object asyncContext)
{
throw new NotImplementedException ();
}
public GroupInformation GetGroupInformation(int groupID)
{
throw new NotImplementedException ();
}
public Address[] GetLocalHostAddresses(LocalAddressFlags flags)
{
throw new NotImplementedException ();
}
public ConnectionInformation GetConnectionInformation(int playerID)
{
throw new NotImplementedException ();
}
public void RegisterLobby(int handle, Application lobbiedApplication)
{
throw new NotImplementedException ();
}
public void UnregisterLobby()
{
throw new NotImplementedException ();
}
protected void raise_PlayerCreated(object i1, PlayerCreatedEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_PlayerAddedToGroup(object i1, PlayerAddedToGroupEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_ApplicationDescriptionChanged(object i1, EventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_AsyncOperationComplete(object i1, AsyncOperationCompleteEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_ClientInformation(object i1, ClientInformationEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_GroupCreated(object i1, GroupCreatedEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_GroupDestroyed(object i1, GroupDestroyedEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_PlayerDestroyed(object i1, PlayerDestroyedEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_FindHostQuery(object i1, FindHostQueryEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_GroupInformation(object i1, GroupInformationEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_IndicateConnect(object i1, IndicateConnectEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_IndicatedConnectAborted(object i1, IndicatedConnectAbortedEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_Receive(object i1, Microsoft.DirectX.DirectPlay.ReceiveEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_PlayerRemovedFromGroup(object i1, PlayerRemovedFromGroupEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_ServerInformation(object i1, ServerInformationEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_SendComplete(object i1, SendCompleteEventArgs i2)
{
throw new NotImplementedException ();
}
protected void raise_Disposing(object i1, EventArgs i2)
{
throw new NotImplementedException ();
}
}
}
| |
//! \file ImageMSK.cs
//! \date Sat Oct 17 09:33:34 2015
//! \brief Silky's bitmap mask.
//
// Copyright (C) 2015 by morkt
//
// 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 GameRes.Utility;
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
namespace GameRes.Formats.Silky
{
[Export(typeof(ImageFormat))]
public class RmskFormat : ImageFormat
{
public override string Tag { get { return "RMSK/SILKY'S"; } }
public override string Description { get { return "Silky's bitmap mask format"; } }
public override uint Signature { get { return 0x6B736D52; } } // 'Rmsk'
public RmskFormat ()
{
Extensions = new string[] { "msk" };
}
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (12);
return new ImageMetaData
{
Width = header.ToUInt16 (8),
Height = header.ToUInt16 (10),
OffsetX = header.ToInt16 (4),
OffsetY = header.ToInt16 (6),
BPP = 8,
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
using (var reader = new RmskReader (stream.AsStream, info))
{
reader.Unpack();
return ImageData.CreateFlipped (info, PixelFormats.Gray8, null, reader.Data, (int)info.Width);
}
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("RmskFormat.Write not implemented");
}
}
internal sealed class RmskReader : IDisposable
{
MsbBitStream m_input;
byte[] m_output;
int m_flag;
int m_width;
int m_height;
public byte[] Data { get { return m_output; } }
public RmskReader (Stream input, ImageMetaData info)
{
input.Position = 0xC;
m_flag = input.ReadByte();
if (-1 == m_flag)
throw new EndOfStreamException();
input.Position = 0xE;
m_input = new MsbBitStream (input, true);
m_width = (int)info.Width;
m_height = (int)info.Height;
m_output = new byte[m_width*m_height];
}
public void Unpack ()
{
if (0 == (m_flag & 1))
UnpackV0();
else
UnpackV1();
}
void UnpackV0 ()
{
int line = m_width * (m_height - 1);
for (int h = 0; h < m_height; ++h)
{
int dst = line;
int column = m_width;
while (column > 0)
{
if (0 == m_input.GetNextBit())
{
int src;
int count;
if (1 == m_input.GetNextBit())
{
if (0 == m_input.GetNextBit())
{
src = dst + OffsetTable8[m_input.GetBits (3)];
}
else
{
src = m_width + dst + OffsetTable16[m_input.GetBits (4)];
}
}
else
{
src = dst;
if (1 == m_input.GetNextBit())
{
src += m_width * (m_input.GetNextBit() + 2);
}
else
{
src += m_width * (m_input.GetBits (2) + 4);
}
src += OffsetTable16[m_input.GetBits (4)];
}
if (1 == m_input.GetNextBit())
{
count = m_input.GetNextBit() + 2;
}
else if (1 == m_input.GetNextBit())
{
count = m_input.GetBits (2) + 4;
}
else if (1 == m_input.GetNextBit())
{
count = m_input.GetBits (3) + 8;
}
else if (1 == m_input.GetNextBit())
{
count = m_input.GetBits (6) + 16;
}
else if (1 == m_input.GetNextBit())
{
count = m_input.GetBits (8) + 80;
}
else
{
count = m_input.GetBits (10) + 336;
}
for (int i = 0; i < count; ++i)
{
m_output[dst++] = m_output[src++];
}
column -= count;
}
else
{
m_output[dst++] = (byte)m_input.GetBits (8);
--column;
}
}
line -= m_width;
}
}
void UnpackV1 ()
{
int column = m_width * (m_height - 1);
for (int x = 0; x < m_width; ++x)
{
int dst = column;
int line = m_height;
while (line > 0)
{
if (0 != m_input.GetNextBit())
{
m_output[dst] = (byte)m_input.GetBits (8);
dst -= m_width;
--line;
}
else
{
int src;
if (1 == m_input.GetNextBit())
{
if (0 == m_input.GetNextBit())
{
src = dst - m_width * OffsetTable8[m_input.GetBits (3)];
}
else
{
src = dst - 1 - m_width * OffsetTable16[m_input.GetBits (4)];
}
}
else if (1 == m_input.GetNextBit())
{
int n = dst - 2 - m_input.GetNextBit();
src = n - m_width * OffsetTable16[m_input.GetBits (4)];
}
else
{
int n = dst - 4 - m_input.GetBits (2);
src = n - m_width * OffsetTable16[m_input.GetBits (4)];
}
int count;
if (1 == m_input.GetNextBit())
{
count = m_input.GetBits (1) + 2;
}
else if (1 == m_input.GetNextBit())
{
count = m_input.GetBits (2) + 4;
}
else if (1 == m_input.GetNextBit())
{
count = m_input.GetBits (3) + 8;
}
else if (1 == m_input.GetNextBit())
{
count = m_input.GetBits (6) + 16;
}
else if (1 == m_input.GetNextBit())
{
count = m_input.GetBits (8) + 80;
}
else
{
count = m_input.GetBits (10) + 336;
}
line -= count;
for (int i = 0; i < count; ++i)
{
m_output[dst] = m_output[src];
src -= m_width;
dst -= m_width;
}
}
}
++column;
}
}
static int[] OffsetTable8 = { -1, -2, -4, -6, -8, -12, -16, -20 };
static int[] OffsetTable16 = { -20, -16, -12, -8, -6, -4, -2, -1, 0, 1, 2, 4, 6, 8, 12, 16 };
#region IDisposable Members
bool _disposed = false;
public void Dispose ()
{
if (!_disposed)
{
m_input.Dispose();
_disposed = true;
}
}
#endregion
}
}
| |
#define SQLITE_ASCII
#define SQLITE_DISABLE_LFS
#define SQLITE_ENABLE_OVERSIZE_CELL_CHECK
#define SQLITE_MUTEX_OMIT
#define SQLITE_OMIT_AUTHORIZATION
#define SQLITE_OMIT_DEPRECATED
#define SQLITE_OMIT_GET_TABLE
#define SQLITE_OMIT_INCRBLOB
#define SQLITE_OMIT_LOOKASIDE
#define SQLITE_OMIT_SHARED_CACHE
#define SQLITE_OMIT_UTF16
#define SQLITE_OMIT_WAL
#define SQLITE_OS_WIN
#define SQLITE_SYSTEM_MALLOC
#define VDBE_PROFILE_OFF
#define WINDOWS_MOBILE
#define NDEBUG
#define _MSC_VER
#define YYFALLBACK
using System.Diagnostics;
using System.Text;
namespace Community.CsharpSqlite
{
using sqlite3_int64 = System.Int64;
using i64 = System.Int64;
using sqlite3_uint64 = System.UInt64;
using u32 = System.UInt32;
using System;
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** Memory allocation functions used throughout sqlite.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <stdarg.h>
/*
** Attempt to release up to n bytes of non-essential memory currently
** held by SQLite. An example of non-essential memory is memory used to
** cache database pages that are not currently in use.
*/
static int sqlite3_release_memory( int n )
{
#if SQLITE_ENABLE_MEMORY_MANAGEMENT
int nRet = 0;
nRet += sqlite3PcacheReleaseMemory(n-nRet);
return nRet;
#else
UNUSED_PARAMETER( n );
return SQLITE_OK;
#endif
}
/*
** State information local to the memory allocation subsystem.
*/
//static SQLITE_WSD struct Mem0Global {
public class Mem0Global
{/* Number of free pages for scratch and page-cache memory */
public int nScratchFree;
public int nPageFree;
public sqlite3_mutex mutex; /* Mutex to serialize access */
/*
** The alarm callback and its arguments. The mem0.mutex lock will
** be held while the callback is running. Recursive calls into
** the memory subsystem are allowed, but no new callbacks will be
** issued.
*/
public sqlite3_int64 alarmThreshold;
public dxalarmCallback alarmCallback; // (*alarmCallback)(void*, sqlite3_int64,int);
public object alarmArg;
/*
** Pointers to the end of sqlite3GlobalConfig.pScratch and
** sqlite3GlobalConfig.pPage to a block of memory that records
** which pages are available.
*/
//u32 *aScratchFree;
/*
** True if heap is nearly "full" where "full" is defined by the
** sqlite3_soft_heap_limit() setting.
*/
public bool nearlyFull;
public byte[][][] aByte;
public int[] aByteSize;
public int[] aByte_used;
public int[][] aInt;
public Mem[] aMem;
public BtCursor[] aBtCursor;
public struct memstat
{
public int alloc; // # of allocation requests
public int dealloc; // # of deallocations
public int cached; // # of cache hits
public int next; // # Next slot to use
public int max; // # Max slot used
}
public memstat msByte;
public memstat msInt;
public memstat msMem;
public memstat msBtCursor;
public Mem0Global()
{
}
public Mem0Global( int nScratchFree, int nPageFree, sqlite3_mutex mutex, sqlite3_int64 alarmThreshold, dxalarmCallback alarmCallback, object alarmArg, int Byte_Allocation, int Int_Allocation, int Mem_Allocation, int BtCursor_Allocation )
{
this.nScratchFree = nScratchFree;
this.nPageFree = nPageFree;
this.mutex = mutex;
this.alarmThreshold = alarmThreshold;
this.alarmCallback = alarmCallback;
this.alarmArg = alarmArg;
this.msByte.next = -1;
this.msInt.next = -1;
this.msMem.next = -1;
this.aByteSize = new int[] { 32, 256, 1024, 8192, 0 };
this.aByte_used = new int[] { -1, -1, -1, -1, -1 };
this.aByte = new byte[this.aByteSize.Length][][];
for ( int i = 0; i < this.aByteSize.Length; i++ )
this.aByte[i] = new byte[Byte_Allocation][];
this.aInt = new int[Int_Allocation][];
this.aMem = new Mem[Mem_Allocation <= 4 ? 4 : Mem_Allocation];
this.aBtCursor = new BtCursor[BtCursor_Allocation <= 4 ? 4 : BtCursor_Allocation];
this.nearlyFull = false;
}
}
//mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
//#define mem0 GLOBAL(struct Mem0Global, mem0)
static Mem0Global mem0 = new Mem0Global();
/*
** This routine runs when the memory allocator sees that the
** total memory allocation is about to exceed the soft heap
** limit.
*/
static void softHeapLimitEnforcer(
object NotUsed,
sqlite3_int64 NotUsed2,
int allocSize
)
{
UNUSED_PARAMETER2( NotUsed, NotUsed2 );
sqlite3_release_memory( allocSize );
}
#if !SQLITE_OMIT_DEPRECATED
/*
** Deprecated external interface. Internal/core SQLite code
** should call sqlite3MemoryAlarm.
*/
int sqlite3_memory_alarm(
void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
void *pArg,
sqlite3_int64 iThreshold
){
return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
}
#endif
/*
** Set the soft heap-size limit for the library. Passing a zero or
** negative value indicates no limit.
*/
static sqlite3_int64 sqlite3_soft_heap_limit64( sqlite3_int64 n )
{
sqlite3_int64 priorLimit;
sqlite3_int64 excess;
#if !SQLITE_OMIT_AUTOINIT
sqlite3_initialize();
#endif
sqlite3_mutex_enter( mem0.mutex );
priorLimit = mem0.alarmThreshold;
sqlite3_mutex_leave( mem0.mutex );
if ( n < 0 )
return priorLimit;
if ( n > 0 )
{
sqlite3MemoryAlarm( softHeapLimitEnforcer, 0, n );
}
else
{
sqlite3MemoryAlarm( null, 0, 0 );
}
excess = sqlite3_memory_used() - n;
if ( excess > 0 )
sqlite3_release_memory( (int)( excess & 0x7fffffff ) );
return priorLimit;
}
void sqlite3_soft_heap_limit( int n )
{
if ( n < 0 )
n = 0;
sqlite3_soft_heap_limit64( n );
}
/*
** Initialize the memory allocation subsystem.
*/
static int sqlite3MallocInit()
{
if ( sqlite3GlobalConfig.m.xMalloc == null )
{
sqlite3MemSetDefault();
}
mem0 = new Mem0Global( 0, 0, null, 0, null, null, 1, 1, 8, 8 ); //memset(&mem0, 0, sizeof(mem0));
if ( sqlite3GlobalConfig.bCoreMutex )
{
mem0.mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MEM );
}
if ( sqlite3GlobalConfig.pScratch != null && sqlite3GlobalConfig.szScratch >= 100
&& sqlite3GlobalConfig.nScratch >= 0 )
{
//int i;
sqlite3GlobalConfig.szScratch = ROUNDDOWN8( sqlite3GlobalConfig.szScratch - 4 );
//mem0.aScratchFree = (u32)&((char)sqlite3GlobalConfig.pScratch)
// [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
//for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
//mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
}
else
{
sqlite3GlobalConfig.pScratch = null;
sqlite3GlobalConfig.szScratch = 0;
}
if ( sqlite3GlobalConfig.pPage == null || sqlite3GlobalConfig.szPage < 512
|| sqlite3GlobalConfig.nPage < 1 )
{
sqlite3GlobalConfig.pPage = null;
sqlite3GlobalConfig.szPage = 0;
sqlite3GlobalConfig.nPage = 0;
}
return sqlite3GlobalConfig.m.xInit( sqlite3GlobalConfig.m.pAppData );
}
/*
** Return true if the heap is currently under memory pressure - in other
** words if the amount of heap used is close to the limit set by
** sqlite3_soft_heap_limit().
*/
static bool sqlite3HeapNearlyFull()
{
return mem0.nearlyFull;
}
/*
** Deinitialize the memory allocation subsystem.
*/
static void sqlite3MallocEnd()
{
if ( sqlite3GlobalConfig.m.xShutdown != null )
{
sqlite3GlobalConfig.m.xShutdown( sqlite3GlobalConfig.m.pAppData );
}
mem0 = new Mem0Global();//memset(&mem0, 0, sizeof(mem0));
}
/*
** Return the amount of memory currently checked out.
*/
static sqlite3_int64 sqlite3_memory_used()
{
int n = 0, mx = 0;
sqlite3_int64 res;
sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, 0 );
res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
return res;
}
/*
** Return the maximum amount of memory that has ever been
** checked out since either the beginning of this process
** or since the most recent reset.
*/
static sqlite3_int64 sqlite3_memory_highwater( int resetFlag )
{
int n = 0, mx = 0;
sqlite3_int64 res;
sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, resetFlag );
res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
return res;
}
/*
** Change the alarm callback
*/
static int sqlite3MemoryAlarm(
dxalarmCallback xCallback, //void(*xCallback)(object pArg, sqlite3_int64 used,int N),
object pArg,
sqlite3_int64 iThreshold
)
{
int nUsed;
sqlite3_mutex_enter( mem0.mutex );
mem0.alarmCallback = xCallback;
mem0.alarmArg = pArg;
mem0.alarmThreshold = iThreshold;
nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED );
mem0.nearlyFull = ( iThreshold > 0 && iThreshold <= nUsed );
sqlite3_mutex_leave( mem0.mutex );
return SQLITE_OK;
}
/*
** Trigger the alarm
*/
static void sqlite3MallocAlarm( int nByte )
{
dxalarmCallback xCallback;//void (*xCallback)(void*,sqlite3_int64,int);
sqlite3_int64 nowUsed;
object pArg;// void* pArg;
if ( mem0.alarmCallback == null )
return;
xCallback = mem0.alarmCallback;
nowUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED );
pArg = mem0.alarmArg;
mem0.alarmCallback = null;
sqlite3_mutex_leave( mem0.mutex );
xCallback( pArg, nowUsed, nByte );
sqlite3_mutex_enter( mem0.mutex );
mem0.alarmCallback = xCallback;
mem0.alarmArg = pArg;
}
/*
** Do a memory allocation with statistics and alarms. Assume the
** lock is already held.
*/
static int mallocWithAlarm( int n, ref int[] pp )
{
int nFull;
int[] p;
Debug.Assert( sqlite3_mutex_held( mem0.mutex ) );
nFull = sqlite3GlobalConfig.m.xRoundup( n );
sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, n );
if ( mem0.alarmCallback != null )
{
int nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED );
if ( nUsed >= mem0.alarmThreshold - nFull )
{
mem0.nearlyFull = true;
sqlite3MallocAlarm( nFull );
}
else
{
mem0.nearlyFull = false;
}
}
p = sqlite3GlobalConfig.m.xMallocInt( nFull );
#if SQLITE_ENABLE_MEMORY_MANAGEMENT
if( p==null && mem0.alarmCallback!=null ){
sqlite3MallocAlarm(nFull);
p = sqlite3GlobalConfig.m.xMalloc(nFull);
}
#endif
if ( p != null )
{
nFull = sqlite3MallocSize( p );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nFull );
}
pp = p;
return nFull;
}
static int mallocWithAlarm( int n, ref byte[] pp )
{
int nFull;
byte[] p;
Debug.Assert( sqlite3_mutex_held( mem0.mutex ) );
nFull = sqlite3GlobalConfig.m.xRoundup( n );
sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, n );
if ( mem0.alarmCallback != null )
{
int nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED );
if ( nUsed + nFull >= mem0.alarmThreshold )
{
sqlite3MallocAlarm( nFull );
}
}
p = sqlite3GlobalConfig.m.xMalloc( nFull );
if ( p == null && mem0.alarmCallback != null )
{
sqlite3MallocAlarm( nFull );
p = sqlite3GlobalConfig.m.xMalloc( nFull );
}
if ( p != null )
{
nFull = sqlite3MallocSize( p );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nFull );
sqlite3StatusAdd( SQLITE_STATUS_MALLOC_COUNT, 1 );
}
pp = p;
return nFull;
}
/*
** Allocate memory. This routine is like sqlite3_malloc() except that it
** assumes the memory subsystem has already been initialized.
*/
static Mem sqlite3Malloc( Mem pMem )
{
return sqlite3GlobalConfig.m.xMallocMem( pMem );
}
static int[] sqlite3Malloc( int[] pInt, u32 n )
{
return sqlite3Malloc( pInt, (int)n );
}
static int[] sqlite3Malloc( int[] pInt, int n )
{
int[] p = null;
if ( n < 0 || n >= 0x7fffff00 )
{
/* A memory allocation of a number of bytes which is near the maximum
** signed integer value might cause an integer overflow inside of the
** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
** 255 bytes of overhead. SQLite itself will never use anything near
** this amount. The only way to reach the limit is with sqlite3_malloc() */
p = null;
}
else if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
mallocWithAlarm( n, ref p );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
p = sqlite3GlobalConfig.m.xMallocInt( n );
}
return p;
}
static byte[] sqlite3Malloc( u32 n )
{
return sqlite3Malloc( (int)n );
}
static byte[] sqlite3Malloc( int n )
{
byte[] p = null;
if ( n < 0 || n >= 0x7fffff00 )
{
/* A memory allocation of a number of bytes which is near the maximum
** signed integer value might cause an integer overflow inside of the
** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
** 255 bytes of overhead. SQLite itself will never use anything near
** this amount. The only way to reach the limit is with sqlite3_malloc() */
p = null;
}
else if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
mallocWithAlarm( n, ref p );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
p = sqlite3GlobalConfig.m.xMalloc( n );
}
return p;
}
/*
** This version of the memory allocation is for use by the application.
** First make sure the memory subsystem is initialized, then do the
** allocation.
*/
static byte[] sqlite3_malloc( int n )
{
#if !SQLITE_OMIT_AUTOINIT
if ( sqlite3_initialize() != 0 )
return null;
#endif
return sqlite3Malloc( n );
}
/*
** Each thread may only have a single outstanding allocation from
** xScratchMalloc(). We verify this constraint in the single-threaded
** case by setting scratchAllocOut to 1 when an allocation
** is outstanding clearing it when the allocation is freed.
*/
#if SQLITE_THREADSAFE && !(NDEBUG)
static int scratchAllocOut = 0;
#endif
/*
** Allocate memory that is to be used and released right away.
** This routine is similar to alloca() in that it is not intended
** for situations where the memory might be held long-term. This
** routine is intended to get memory to old large transient data
** structures that would not normally fit on the stack of an
** embedded processor.
*/
static byte[][] sqlite3ScratchMalloc( byte[][] apCell, int n )
{
apCell = sqlite3GlobalConfig.pScratch2;
if ( apCell == null )
apCell = new byte[n < 200 ? 200 : n][];
else if ( apCell.Length < n )
Array.Resize( ref apCell, n );
sqlite3GlobalConfig.pScratch2 = null;
return apCell;
}
static byte[] sqlite3ScratchMalloc( int n )
{
byte[] p = null;
Debug.Assert( n > 0 );
#if SQLITE_THREADSAFE && !(NDEBUG)
/* Verify that no more than two scratch allocation per thread
** is outstanding at one time. (This is only checked in the
** single-threaded case since checking in the multi-threaded case
** would be much more complicated.) */
Debug.Assert( scratchAllocOut <= 1 );
#endif
if ( sqlite3GlobalConfig.szScratch < n )
{
goto scratch_overflow;
}
else
{
sqlite3_mutex_enter( mem0.mutex );
if ( mem0.nScratchFree == 0 )
{
sqlite3_mutex_leave( mem0.mutex );
goto scratch_overflow;
}
else
{
int i;
//i = mem0.aScratchFree[--mem0.nScratchFree];
//i *= sqlite3GlobalConfig.szScratch;
for ( i = 0; i < sqlite3GlobalConfig.pScratch.Length; i++ )
{
if ( sqlite3GlobalConfig.pScratch[i] == null || sqlite3GlobalConfig.pScratch[i].Length < n )
continue;
p = sqlite3GlobalConfig.pScratch[i];// (void)&((char)sqlite3GlobalConfig.pScratch)[i];
sqlite3GlobalConfig.pScratch[i] = null;
break;
}
sqlite3_mutex_leave( mem0.mutex );
if ( p == null )
goto scratch_overflow;
sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_USED, 1 );
sqlite3StatusSet( SQLITE_STATUS_SCRATCH_SIZE, n );
//Debug.Assert( (((u8)p - (u8)0) & 7)==0 );
}
}
#if SQLITE_THREADSAFE && !(NDEBUG)
scratchAllocOut = ( p != null ? 1 : 0 );
#endif
return p;
scratch_overflow:
if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
sqlite3StatusSet( SQLITE_STATUS_SCRATCH_SIZE, n );
n = mallocWithAlarm( n, ref p );
if ( p != null )
sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_OVERFLOW, n );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
p = sqlite3GlobalConfig.m.xMalloc( n );
}
sqlite3MemdebugSetType( p, MEMTYPE_SCRATCH );
#if SQLITE_THREADSAFE && !(NDEBUG)
scratchAllocOut = ( p != null ) ? 1 : 0;
#endif
return p;
}
static void sqlite3ScratchFree( byte[][] p )
{
if ( p != null )
{
if ( sqlite3GlobalConfig.pScratch2 == null || sqlite3GlobalConfig.pScratch2.Length < p.Length )
{
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_SCRATCH ) );
Debug.Assert( sqlite3MemdebugNoType( p, ~MEMTYPE_SCRATCH ) );
sqlite3MemdebugSetType( p, MEMTYPE_HEAP );
if ( sqlite3GlobalConfig.bMemstat )
{
int iSize = sqlite3MallocSize( p );
sqlite3_mutex_enter( mem0.mutex );
sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -iSize );
sqlite3StatusAdd( SQLITE_STATUS_MALLOC_COUNT, -1 );
sqlite3GlobalConfig.pScratch2 = p;// sqlite3GlobalConfig.m.xFree(ref p);
sqlite3_mutex_leave( mem0.mutex );
}
else
{
sqlite3GlobalConfig.pScratch2 = p;//sqlite3GlobalConfig.m.xFree(ref p);
}
}
else // larger Scratch 2 already in use, let the C# GC handle
{
//int i;
//i = (int)((u8)p - (u8)sqlite3GlobalConfig.pScratch);
//i /= sqlite3GlobalConfig.szScratch;
//Debug.Assert(i >= 0 && i < sqlite3GlobalConfig.nScratch);
//sqlite3_mutex_enter(mem0.mutex);
//Debug.Assert(mem0.nScratchFree < (u32)sqlite3GlobalConfig.nScratch);
//mem0.aScratchFree[mem0.nScratchFree++] = i;
//sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
//sqlite3_mutex_leave(mem0.mutex);
#if SQLITE_THREADSAFE && !(NDEBUG)
/* Verify that no more than two scratch allocation per thread
** is outstanding at one time. (This is only checked in the
** single-threaded case since checking in the multi-threaded case
** would be much more complicated.) */
Debug.Assert( scratchAllocOut >= 1 && scratchAllocOut <= 2 );
scratchAllocOut = 0;
#endif
}
//if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
// /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
// ScratchFreeslot *pSlot;
// pSlot = (ScratchFreeslot)p;
// sqlite3_mutex_enter(mem0.mutex);
// pSlot->pNext = mem0.pScratchFree;
// mem0.pScratchFree = pSlot;
// mem0.nScratchFree++;
// Debug.Assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
// sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
// sqlite3_mutex_leave(mem0.mutex);
//}else{
// /* Release memory back to the heap */
// Debug.Assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
// Debug.Assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
// sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
// if( sqlite3GlobalConfig.bMemstat ){
// int iSize = sqlite3MallocSize(p);
// sqlite3_mutex_enter(mem0.mutex);
// sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
// sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
// sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
// sqlite3GlobalConfig.m.xFree(p);
// sqlite3_mutex_leave(mem0.mutex);
// }else{
// sqlite3GlobalConfig.m.xFree(p);
// }
p = null;
}
}
/*
** TRUE if p is a lookaside memory allocation from db
*/
#if !SQLITE_OMIT_LOOKASIDE
static int isLookaside(sqlite3 db, object *p){
return p && p>=db.lookaside.pStart && p<db.lookaside.pEnd;
}
#else
//#define isLookaside(A,B) 0
static bool isLookaside( sqlite3 db, object p )
{
return false;
}
#endif
/*
** Return the size of a memory allocation previously obtained from
** sqlite3Malloc() or sqlite3_malloc().
*/
//int sqlite3MallocSize(void* p)
//{
// Debug.Assert(sqlite3MemdebugHasType(p, MEMTYPE_HEAP));
// Debug.Assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
// return sqlite3GlobalConfig.m.xSize(p);
//}
static int sqlite3MallocSize( byte[][] p )
{
return p.Length * p[0].Length;
}
static int sqlite3MallocSize( int[] p )
{
return p.Length;
}
static int sqlite3MallocSize( byte[] p )
{
return sqlite3GlobalConfig.m.xSize( p );
}
static int sqlite3DbMallocSize( sqlite3 db, byte[] p )
{
Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) );
if ( db != null && isLookaside( db, p ) )
{
return db.lookaside.sz;
}
else
{
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_DB ) );
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_LOOKASIDE | MEMTYPE_HEAP ) );
Debug.Assert( db != null || sqlite3MemdebugNoType( p, MEMTYPE_LOOKASIDE ) );
return sqlite3GlobalConfig.m.xSize( p );
}
}
/*
** Free memory previously obtained from sqlite3Malloc().
*/
static void sqlite3_free( ref byte[] p )
{
if ( p == null )
return;
Debug.Assert( sqlite3MemdebugNoType( p, MEMTYPE_DB ) );
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_HEAP ) );
if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize( p ) );
sqlite3StatusAdd( SQLITE_STATUS_MALLOC_COUNT, -1 );
sqlite3GlobalConfig.m.xFree( ref p );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
sqlite3GlobalConfig.m.xFree( ref p );
}
p = null;
}
static void sqlite3_free( ref Mem p )
{
if ( p == null )
return;
if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
//sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize( p ) );
sqlite3GlobalConfig.m.xFreeMem( ref p );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
sqlite3GlobalConfig.m.xFreeMem( ref p );
}
p = null;
}
/*
** Free memory that might be associated with a particular database
** connection.
*/
static void sqlite3DbFree( sqlite3 db, ref byte[] p )
{
Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) );
if ( db != null )
{
//if ( db.pnBytesFreed != 0 )
//{
#if SQLITE_OMIT_LOOKASIDE
//db.pnBytesFreed += 1;
#else
db.pnBytesFreed += sqlite3DbMallocSize( db, p );
#endif
return;
//}
#if !SQLITE_OMIT_LOOKASIDE
if( isLookaside(db, p) ){
LookasideSlot *pBuf = (LookasideSlot)p;
pBuf.pNext = db.lookaside.pFree;
db.lookaside.pFree = pBuf;
db.lookaside.nOut--;
}else
#endif
//{
// Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_DB ) );
// Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_LOOKASIDE | MEMTYPE_HEAP ) );
// Debug.Assert( db != null || sqlite3MemdebugNoType( p, MEMTYPE_LOOKASIDE ) );
// sqlite3MemdebugSetType( p, MEMTYPE_HEAP );
// sqlite3_free( ref p );
//}
}
}
/*
** Change the size of an existing memory allocation
*/
static byte[] sqlite3Realloc( byte[] pOld, int nBytes )
{
int nOld, nNew, nDiff;
byte[] pNew;
if ( pOld == null )
{
pOld = sqlite3Malloc( nBytes );
return pOld;
}
if ( nBytes < 0 )
{
sqlite3_free( ref pOld );
return null;
}
if ( nBytes >= 0x7fffff00 )
{
/* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
return null;
}
nOld = sqlite3MallocSize( pOld );
nNew = sqlite3GlobalConfig.m.xRoundup( nBytes );
if ( nOld == nNew )
{
pNew = pOld;
}
else if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, nBytes );
nDiff = nNew - nOld;
if ( sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ) >=
mem0.alarmThreshold - nDiff )
{
sqlite3MallocAlarm( nDiff );
}
Debug.Assert( sqlite3MemdebugHasType( pOld, MEMTYPE_HEAP ) );
Debug.Assert( sqlite3MemdebugNoType( pOld, ~MEMTYPE_HEAP ) );
pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew );
if ( pNew == null && mem0.alarmCallback != null )
{
sqlite3MallocAlarm( nBytes );
pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew );
}
if ( pNew != null )
{
nNew = sqlite3MallocSize( pNew );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nNew - nOld );
}
sqlite3_mutex_leave( mem0.mutex );
}
else
{
pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew );
}
return pNew;
}
/*
** The public interface to sqlite3Realloc. Make sure that the memory
** subsystem is initialized prior to invoking sqliteRealloc.
*/
static byte[] sqlite3_realloc( byte[] pOld, int n )
{
#if !SQLITE_OMIT_AUTOINIT
if ( sqlite3_initialize() != 0 )
return null;
#endif
return sqlite3Realloc( pOld, n );
}
/*
** Allocate and zero memory.
*/
static byte[] sqlite3MallocZero( int n )
{
byte[] p = sqlite3Malloc( n );
if ( p != null )
{
Array.Clear( p, 0, n );// memset(p, 0, n);
}
return p;
}
/*
** Allocate and zero memory. If the allocation fails, make
** the mallocFailed flag in the connection pointer.
*/
static Mem sqlite3DbMallocZero( sqlite3 db, Mem m )
{
return new Mem();
}
static byte[] sqlite3DbMallocZero( sqlite3 db, int n )
{
byte[] p = sqlite3DbMallocRaw( db, n );
if ( p != null )
{
Array.Clear( p, 0, n );// memset(p, 0, n);
}
return p;
}
/*
** Allocate and zero memory. If the allocation fails, make
** the mallocFailed flag in the connection pointer.
**
** If db!=0 and db->mallocFailed is true (indicating a prior malloc
** failure on the same database connection) then always return 0.
** Hence for a particular database connection, once malloc starts
** failing, it fails consistently until mallocFailed is reset.
** This is an important assumption. There are many places in the
** code that do things like this:
**
** int *a = (int)sqlite3DbMallocRaw(db, 100);
** int *b = (int)sqlite3DbMallocRaw(db, 200);
** if( b ) a[10] = 9;
**
** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
** that all prior mallocs (ex: "a") worked too.
*/
static byte[] sqlite3DbMallocRaw( sqlite3 db, int n )
{
byte[] p;
Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) );
Debug.Assert( db == null || db.pnBytesFreed == 0 );
#if !SQLITE_OMIT_LOOKASIDE
if( db ){
LookasideSlot *pBuf;
if( db->mallocFailed ){
return 0;
}
if( db->lookaside.bEnabled ){
if( n>db->lookaside.sz ){
db->lookaside.anStat[1]++;
}else if( (pBuf = db->lookaside.pFree)==0 ){
db->lookaside.anStat[2]++;
}else{
db->lookaside.pFree = pBuf->pNext;
db->lookaside.nOut++;
db->lookaside.anStat[0]++;
if( db->lookaside.nOut>db->lookaside.mxOut ){
db->lookaside.mxOut = db->lookaside.nOut;
}
return (void)pBuf;
}
}
}
#else
//if( db && db->mallocFailed ){
// return 0;
//}
#endif
p = sqlite3Malloc( n );
//if( null==p && db ){
// db->mallocFailed = 1;
//}
#if !SQLITE_OMIT_LOOKASIDE
sqlite3MemdebugSetType(p, MEMTYPE_DB |
((db !=null && db.lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
#endif
return p;
}
/*
** Resize the block of memory pointed to by p to n bytes. If the
** resize fails, set the mallocFailed flag in the connection object.
*/
static byte[] sqlite3DbRealloc( sqlite3 db, byte[] p, int n )
{
byte[] pNew = null;
Debug.Assert( db != null );
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
//if( db->mallocFailed==0 ){
if ( p == null )
{
return sqlite3DbMallocRaw( db, n );
}
#if !SQLITE_OMIT_LOOKASIDE
if( isLookaside(db, p) ){
if( n<=db->lookaside.sz ){
return p;
}
pNew = sqlite3DbMallocRaw(db, n);
if( pNew ){
memcpy(pNew, p, db->lookaside.sz);
sqlite3DbFree(db, ref p);
}
}else
#else
{
{
#endif
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_DB ) );
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_LOOKASIDE | MEMTYPE_HEAP ) );
sqlite3MemdebugSetType( p, MEMTYPE_HEAP );
pNew = sqlite3_realloc( p, n );
//if( null==pNew ){
//sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
// db->mallocFailed = 1;
//}
#if !SQLITE_OMIT_LOOKASIDE
sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
(db.lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
#endif
}
}
return pNew;
}
/*
** Attempt to reallocate p. If the reallocation fails, then free p
** and set the mallocFailed flag in the database connection.
*/
static byte[] sqlite3DbReallocOrFree( sqlite3 db, byte[] p, int n )
{
byte[] pNew;
pNew = sqlite3DbRealloc( db, p, n );
if ( null == pNew )
{
sqlite3DbFree( db, ref p );
}
return pNew;
}
/*
** Make a copy of a string in memory obtained from sqliteMalloc(). These
** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
** is because when memory debugging is turned on, these two functions are
** called via macros that record the current file and line number in the
** ThreadData structure.
*/
//char *sqlite3DbStrDup(sqlite3 db, string z){
// string zNew;
// size_t n;
// if( z==0 ){
// return 0;
// }
// n = sqlite3Strlen30(z) + 1;
// Debug.Assert( (n&0x7fffffff)==n );
// zNew = sqlite3DbMallocRaw(db, (int)n);
// if( zNew ){
// memcpy(zNew, z, n);
// }
// return zNew;
//}
//char *sqlite3DbStrNDup(sqlite3 db, string z, int n){
// string zNew;
// if( z==0 ){
// return 0;
// }
// Debug.Assert( (n&0x7fffffff)==n );
// zNew = sqlite3DbMallocRaw(db, n+1);
// if( zNew ){
// memcpy(zNew, z, n);
// zNew[n] = 0;
// }
// return zNew;
//}
/*
** Create a string from the zFromat argument and the va_list that follows.
** Store the string in memory obtained from sqliteMalloc() and make pz
** point to that string.
*/
static void sqlite3SetString( ref string pz, sqlite3 db, string zFormat, params string[] ap )
{
//va_list ap;
lock ( lock_va_list )
{
string z;
va_start( ap, zFormat );
z = sqlite3VMPrintf( db, zFormat, ap );
va_end( ref ap );
sqlite3DbFree( db, ref pz );
pz = z;
}
}
/*
** This function must be called before exiting any API function (i.e.
** returning control to the user) that has called sqlite3_malloc or
** sqlite3_realloc.
**
** The returned value is normally a copy of the second argument to this
** function. However, if a malloc() failure has occurred since the previous
** invocation SQLITE_NOMEM is returned instead.
**
** If the first argument, db, is not NULL and a malloc() error has occurred,
** then the connection error-code (the value returned by sqlite3_errcode())
** is set to SQLITE_NOMEM.
*/
static int sqlite3ApiExit( int zero, int rc )
{
sqlite3 db = null;
return sqlite3ApiExit( db, rc );
}
static int sqlite3ApiExit( sqlite3 db, int rc )
{
/* If the db handle is not NULL, then we must hold the connection handle
** mutex here. Otherwise the read (and possible write) of db.mallocFailed
** is unsafe, as is the call to sqlite3Error().
*/
Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) );
if ( /*db != null && db.mallocFailed != 0 || */ rc == SQLITE_IOERR_NOMEM )
{
sqlite3Error( db, SQLITE_NOMEM, "" );
//db.mallocFailed = 0;
rc = SQLITE_NOMEM;
}
return rc & ( db != null ? db.errMask : 0xff );
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Contacts Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KPCDataSet : EduHubDataSet<KPC>
{
/// <inheritdoc />
public override string Name { get { return "KPC"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KPCDataSet(EduHubContext Context)
: base(Context)
{
Index_KPCKEY = new Lazy<Dictionary<string, KPC>>(() => this.ToDictionary(i => i.KPCKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KPC" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KPC" /> fields for each CSV column header</returns>
internal override Action<KPC, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KPC, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "KPCKEY":
mapper[i] = (e, v) => e.KPCKEY = v;
break;
case "SURNAME":
mapper[i] = (e, v) => e.SURNAME = v;
break;
case "FIRST_NAME":
mapper[i] = (e, v) => e.FIRST_NAME = v;
break;
case "SECOND_NAME":
mapper[i] = (e, v) => e.SECOND_NAME = v;
break;
case "GENDER":
mapper[i] = (e, v) => e.GENDER = v;
break;
case "ADDRESS01":
mapper[i] = (e, v) => e.ADDRESS01 = v;
break;
case "ADDRESS02":
mapper[i] = (e, v) => e.ADDRESS02 = v;
break;
case "ADDRESS03":
mapper[i] = (e, v) => e.ADDRESS03 = v;
break;
case "STATE":
mapper[i] = (e, v) => e.STATE = v;
break;
case "POST":
mapper[i] = (e, v) => e.POST = v;
break;
case "BUS_PHONE":
mapper[i] = (e, v) => e.BUS_PHONE = v;
break;
case "HOME_PHONE":
mapper[i] = (e, v) => e.HOME_PHONE = v;
break;
case "MOBILE":
mapper[i] = (e, v) => e.MOBILE = v;
break;
case "EMAIL":
mapper[i] = (e, v) => e.EMAIL = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KPC" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KPC" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KPC" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KPC}"/> of entities</returns>
internal override IEnumerable<KPC> ApplyDeltaEntities(IEnumerable<KPC> Entities, List<KPC> DeltaEntities)
{
HashSet<string> Index_KPCKEY = new HashSet<string>(DeltaEntities.Select(i => i.KPCKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.KPCKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_KPCKEY.Remove(entity.KPCKEY);
if (entity.KPCKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, KPC>> Index_KPCKEY;
#endregion
#region Index Methods
/// <summary>
/// Find KPC by KPCKEY field
/// </summary>
/// <param name="KPCKEY">KPCKEY value used to find KPC</param>
/// <returns>Related KPC entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KPC FindByKPCKEY(string KPCKEY)
{
return Index_KPCKEY.Value[KPCKEY];
}
/// <summary>
/// Attempt to find KPC by KPCKEY field
/// </summary>
/// <param name="KPCKEY">KPCKEY value used to find KPC</param>
/// <param name="Value">Related KPC entity</param>
/// <returns>True if the related KPC entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByKPCKEY(string KPCKEY, out KPC Value)
{
return Index_KPCKEY.Value.TryGetValue(KPCKEY, out Value);
}
/// <summary>
/// Attempt to find KPC by KPCKEY field
/// </summary>
/// <param name="KPCKEY">KPCKEY value used to find KPC</param>
/// <returns>Related KPC entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KPC TryFindByKPCKEY(string KPCKEY)
{
KPC value;
if (Index_KPCKEY.Value.TryGetValue(KPCKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KPC table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KPC]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KPC](
[KPCKEY] varchar(10) NOT NULL,
[SURNAME] varchar(20) NULL,
[FIRST_NAME] varchar(15) NULL,
[SECOND_NAME] varchar(15) NULL,
[GENDER] varchar(1) NULL,
[ADDRESS01] varchar(30) NULL,
[ADDRESS02] varchar(30) NULL,
[ADDRESS03] varchar(30) NULL,
[STATE] varchar(3) NULL,
[POST] varchar(4) NULL,
[BUS_PHONE] varchar(20) NULL,
[HOME_PHONE] varchar(20) NULL,
[MOBILE] varchar(20) NULL,
[EMAIL] varchar(MAX) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KPC_Index_KPCKEY] PRIMARY KEY CLUSTERED (
[KPCKEY] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="KPCDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="KPCDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KPC"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KPC"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KPC> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_KPCKEY = new List<string>();
foreach (var entity in Entities)
{
Index_KPCKEY.Add(entity.KPCKEY);
}
builder.AppendLine("DELETE [dbo].[KPC] WHERE");
// Index_KPCKEY
builder.Append("[KPCKEY] IN (");
for (int index = 0; index < Index_KPCKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// KPCKEY
var parameterKPCKEY = $"@p{parameterIndex++}";
builder.Append(parameterKPCKEY);
command.Parameters.Add(parameterKPCKEY, SqlDbType.VarChar, 10).Value = Index_KPCKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KPC data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KPC data set</returns>
public override EduHubDataSetDataReader<KPC> GetDataSetDataReader()
{
return new KPCDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KPC data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KPC data set</returns>
public override EduHubDataSetDataReader<KPC> GetDataSetDataReader(List<KPC> Entities)
{
return new KPCDataReader(new EduHubDataSetLoadedReader<KPC>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KPCDataReader : EduHubDataSetDataReader<KPC>
{
public KPCDataReader(IEduHubDataSetReader<KPC> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 17; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // KPCKEY
return Current.KPCKEY;
case 1: // SURNAME
return Current.SURNAME;
case 2: // FIRST_NAME
return Current.FIRST_NAME;
case 3: // SECOND_NAME
return Current.SECOND_NAME;
case 4: // GENDER
return Current.GENDER;
case 5: // ADDRESS01
return Current.ADDRESS01;
case 6: // ADDRESS02
return Current.ADDRESS02;
case 7: // ADDRESS03
return Current.ADDRESS03;
case 8: // STATE
return Current.STATE;
case 9: // POST
return Current.POST;
case 10: // BUS_PHONE
return Current.BUS_PHONE;
case 11: // HOME_PHONE
return Current.HOME_PHONE;
case 12: // MOBILE
return Current.MOBILE;
case 13: // EMAIL
return Current.EMAIL;
case 14: // LW_DATE
return Current.LW_DATE;
case 15: // LW_TIME
return Current.LW_TIME;
case 16: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // SURNAME
return Current.SURNAME == null;
case 2: // FIRST_NAME
return Current.FIRST_NAME == null;
case 3: // SECOND_NAME
return Current.SECOND_NAME == null;
case 4: // GENDER
return Current.GENDER == null;
case 5: // ADDRESS01
return Current.ADDRESS01 == null;
case 6: // ADDRESS02
return Current.ADDRESS02 == null;
case 7: // ADDRESS03
return Current.ADDRESS03 == null;
case 8: // STATE
return Current.STATE == null;
case 9: // POST
return Current.POST == null;
case 10: // BUS_PHONE
return Current.BUS_PHONE == null;
case 11: // HOME_PHONE
return Current.HOME_PHONE == null;
case 12: // MOBILE
return Current.MOBILE == null;
case 13: // EMAIL
return Current.EMAIL == null;
case 14: // LW_DATE
return Current.LW_DATE == null;
case 15: // LW_TIME
return Current.LW_TIME == null;
case 16: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // KPCKEY
return "KPCKEY";
case 1: // SURNAME
return "SURNAME";
case 2: // FIRST_NAME
return "FIRST_NAME";
case 3: // SECOND_NAME
return "SECOND_NAME";
case 4: // GENDER
return "GENDER";
case 5: // ADDRESS01
return "ADDRESS01";
case 6: // ADDRESS02
return "ADDRESS02";
case 7: // ADDRESS03
return "ADDRESS03";
case 8: // STATE
return "STATE";
case 9: // POST
return "POST";
case 10: // BUS_PHONE
return "BUS_PHONE";
case 11: // HOME_PHONE
return "HOME_PHONE";
case 12: // MOBILE
return "MOBILE";
case 13: // EMAIL
return "EMAIL";
case 14: // LW_DATE
return "LW_DATE";
case 15: // LW_TIME
return "LW_TIME";
case 16: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "KPCKEY":
return 0;
case "SURNAME":
return 1;
case "FIRST_NAME":
return 2;
case "SECOND_NAME":
return 3;
case "GENDER":
return 4;
case "ADDRESS01":
return 5;
case "ADDRESS02":
return 6;
case "ADDRESS03":
return 7;
case "STATE":
return 8;
case "POST":
return 9;
case "BUS_PHONE":
return 10;
case "HOME_PHONE":
return 11;
case "MOBILE":
return 12;
case "EMAIL":
return 13;
case "LW_DATE":
return 14;
case "LW_TIME":
return 15;
case "LW_USER":
return 16;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#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;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;
using Infrastructure.Common;
using Xunit;
public static class CommunicationObjectTest
{
[WcfFact]
public static void CommunicationObject_Sync_Open_Close_Methods_Called()
{
MockCommunicationObject mco = new MockCommunicationObject();
List<string> openMethodsCalled = new List<string>();
List<string> closeMethodsCalled = new List<string>();
TimeSpan timeout = TimeSpan.FromSeconds(30);
// *** SETUP *** \\
MockCommunicationObject.InterceptAllOpenMethods(mco, openMethodsCalled);
MockCommunicationObject.InterceptAllCloseMethods(mco, closeMethodsCalled);
// *** EXECUTE *** \\
mco.Open(timeout);
mco.Close(timeout);
// *** VALIDATE *** \\
string expectedOpens = "OnOpening,OnOpen,OnOpened";
string actualOpens = String.Join(",", openMethodsCalled);
Assert.True(String.Equals(expectedOpens, actualOpens, StringComparison.Ordinal),
String.Format("Expected open methods to be '{0}' but actual was '{1}'.",
expectedOpens, actualOpens));
string expectedCloses = "OnClosing,OnClose,OnClosed";
string actualCloses = String.Join(",", closeMethodsCalled);
Assert.True(String.Equals(expectedCloses, actualCloses, StringComparison.Ordinal),
String.Format("Expected close methods to be '{0}' but actual was '{1}'.",
expectedCloses, actualCloses));
}
[WcfFact]
public static void CommunicationObject_Async_Open_Close_Methods_Called()
{
MockCommunicationObject mco = new MockCommunicationObject();
List<string> openMethodsCalled = new List<string>();
List<string> closeMethodsCalled = new List<string>();
TimeSpan timeout = TimeSpan.FromSeconds(30);
// *** SETUP *** \\
MockCommunicationObject.InterceptAllOpenMethods(mco, openMethodsCalled);
MockCommunicationObject.InterceptAllCloseMethods(mco, closeMethodsCalled);
// *** EXECUTE *** \\
IAsyncResult openAr = mco.BeginOpen(timeout, callback: null, state: null);
mco.OpenAsyncResult.Complete();
mco.EndOpen(openAr);
IAsyncResult closeAr = mco.BeginClose(timeout, callback: null, state: null);
mco.CloseAsyncResult.Complete();
mco.EndClose(closeAr);
// *** VALIDATE *** \\
string expectedOpens = "OnOpening,OnBeginOpen,OnOpened";
string actualOpens = String.Join(",", openMethodsCalled);
Assert.True(String.Equals(expectedOpens, actualOpens, StringComparison.Ordinal),
String.Format("Expected open methods to be '{0}' but actual was '{1}'.",
expectedOpens, actualOpens));
string expectedCloses = "OnClosing,OnBeginClose,OnClosed";
string actualCloses = String.Join(",", closeMethodsCalled);
Assert.True(String.Equals(expectedCloses, actualCloses, StringComparison.Ordinal),
String.Format("Expected close methods to be '{0}' but actual was '{1}'.",
expectedCloses, actualCloses));
}
[WcfFact]
public static void CommunicationObject_Abort_Close_Methods_Called()
{
MockCommunicationObject mco = new MockCommunicationObject();
List<string> closeMethodsCalled = new List<string>();
TimeSpan timeout = TimeSpan.FromSeconds(30);
// *** SETUP *** \\
MockCommunicationObject.InterceptAllCloseMethods(mco, closeMethodsCalled);
// *** EXECUTE *** \\
mco.Open(timeout);
mco.Abort();
// *** VALIDATE *** \\
string expectedCloses = "OnClosing,OnAbort,OnClosed";
string actualCloses = String.Join(",", closeMethodsCalled);
Assert.True(String.Equals(expectedCloses, actualCloses, StringComparison.Ordinal),
String.Format("Expected close methods to be '{0}' but actual was '{1}'.",
expectedCloses, actualCloses));
Assert.True(mco.State == CommunicationState.Closed,
String.Format("Expected final state to be 'Closed' but actual was '{0}", mco.State));
}
[WcfFact]
public static void CommunicationObject_Sync_Open_Close_Events_Fire()
{
MockCommunicationObject mco = new MockCommunicationObject();
List<string> openEventsFired = new List<string>();
List<string> closeEventsFired = new List<string>();
TimeSpan timeout = TimeSpan.FromSeconds(30);
// *** SETUP *** \\
MockCommunicationObject.InterceptAllOpenEvents(mco, openEventsFired);
MockCommunicationObject.InterceptAllCloseEvents(mco, closeEventsFired);
// *** EXECUTE *** \\
mco.Open(timeout);
mco.Close(timeout);
// *** VALIDATE *** \\
string expectedOpens = "Opening,Opened";
string actualOpens = String.Join(",", openEventsFired);
Assert.True(String.Equals(expectedOpens, actualOpens, StringComparison.Ordinal),
String.Format("Expected open events to be '{0}' but actual was '{1}'.",
expectedOpens, actualOpens));
string expectedCloses = "Closing,Closed";
string actualCloses = String.Join(",", closeEventsFired);
Assert.True(String.Equals(expectedCloses, actualCloses, StringComparison.Ordinal),
String.Format("Expected close events to be '{0}' but actual was '{1}'.",
expectedCloses, actualCloses));
}
[WcfFact]
public static void CommunicationObject_Async_Open_Close_Events_Fire()
{
MockCommunicationObject mco = new MockCommunicationObject();
List<string> openEventsFired = new List<string>();
List<string> closeEventsFired = new List<string>();
TimeSpan timeout = TimeSpan.FromMinutes(30);
// *** SETUP *** \\
MockCommunicationObject.InterceptAllOpenEvents(mco, openEventsFired);
MockCommunicationObject.InterceptAllCloseEvents(mco, closeEventsFired);
// *** EXECUTE *** \\
IAsyncResult openAr = mco.BeginOpen(timeout, callback: null, state: null);
mco.OpenAsyncResult.Complete();
mco.EndOpen(openAr);
IAsyncResult closeAr = mco.BeginClose(timeout, callback: null, state: null);
mco.CloseAsyncResult.Complete();
mco.EndClose(closeAr);
// *** VALIDATE *** \\
string expectedOpens = "Opening,Opened";
string actualOpens = String.Join(",", openEventsFired);
Assert.True(String.Equals(expectedOpens, actualOpens, StringComparison.Ordinal),
String.Format("Expected open events to be '{0}' but actual was '{1}'.",
expectedOpens, actualOpens));
string expectedCloses = "Closing,Closed";
string actualCloses = String.Join(",", closeEventsFired);
Assert.True(String.Equals(expectedCloses, actualCloses, StringComparison.Ordinal),
String.Format("Expected close events to be '{0}' but actual was '{1}'.",
expectedCloses, actualCloses));
}
[WcfFact]
public static void CommunicationObject_Sync_Open_Close_States_Transition()
{
MockCommunicationObject mco = new MockCommunicationObject();
TimeSpan timeout = TimeSpan.FromSeconds(30);
CommunicationStateData data = new CommunicationStateData();
// *** SETUP *** \\
MockCommunicationObject.InterceptAllStateChanges(mco, data);
// *** EXECUTE *** \\
mco.Open(timeout);
mco.Close(timeout);
// *** VALIDATE *** \\
Assert.True(data.StateAfterCreate == CommunicationState.Created,
String.Format("CommunicationState after creation was '{0}' but expected 'Created'",
data.StateAfterCreate));
Assert.True(data.StateEnterOnOpening == CommunicationState.Opening,
String.Format("CommunicationState entering OnOpening was '{0}' but expected 'Opening'",
data.StateEnterOnOpening));
Assert.True(data.StateLeaveOnOpening == CommunicationState.Opening,
String.Format("CommunicationState leaving OnOpening was '{0}' but expected 'Opening'",
data.StateLeaveOnOpening));
Assert.True(data.StateEnterOnOpen == CommunicationState.Opening,
String.Format("CommunicationState entering OnOpen was '{0}' but expected 'Opening'",
data.StateEnterOnOpen));
Assert.True(data.StateLeaveOnOpen == CommunicationState.Opening,
String.Format("CommunicationState leaving OnOpen was '{0}' but expected 'Opening'",
data.StateLeaveOnOpen));
Assert.True(data.StateEnterOnOpened == CommunicationState.Opening,
String.Format("CommunicationState entering OnOpened was '{0}' but expected 'Opening'",
data.StateEnterOnOpened));
Assert.True(data.StateLeaveOnOpened == CommunicationState.Opened,
String.Format("CommunicationState leaving OnOpened was '{0}' but expected 'Opened'",
data.StateLeaveOnOpened));
Assert.True(data.StateEnterOnClosing == CommunicationState.Closing,
String.Format("CommunicationState entering OnClosing was '{0}' but expected 'Closing'",
data.StateEnterOnClosing));
Assert.True(data.StateLeaveOnClosing == CommunicationState.Closing,
String.Format("CommunicationState leaving OnClosing was '{0}' but expected 'Closing'",
data.StateLeaveOnClosing));
Assert.True(data.StateEnterOnClose == CommunicationState.Closing,
String.Format("CommunicationState entering OnClose was '{0}' but expected 'Closing'",
data.StateEnterOnClose));
Assert.True(data.StateLeaveOnClose == CommunicationState.Closing,
String.Format("CommunicationState leaving OnClose was '{0}' but expected 'Closing'",
data.StateLeaveOnClose));
Assert.True(data.StateEnterOnClosed == CommunicationState.Closing,
String.Format("CommunicationState entering OnClosed was '{0}' but expected 'Closing'",
data.StateEnterOnClosed));
Assert.True(data.StateLeaveOnClosed == CommunicationState.Closed,
String.Format("CommunicationState leaving OnClosed was '{0}' but expected 'Closed'",
data.StateLeaveOnClosed));
}
[WcfFact]
public static void CommunicationObject_Async_Open_Close_States_Transition()
{
MockCommunicationObject mco = new MockCommunicationObject();
TimeSpan timeout = TimeSpan.FromMinutes(5);
CommunicationStateData data = new CommunicationStateData();
// *** SETUP *** \\
MockCommunicationObject.InterceptAllStateChanges(mco, data);
// *** EXECUTE *** \\
IAsyncResult openAr = mco.BeginOpen(timeout, callback: null, state: null);
mco.OpenAsyncResult.Complete();
mco.EndOpen(openAr);
IAsyncResult closeAr = mco.BeginClose(timeout, callback: null, state: null);
mco.CloseAsyncResult.Complete();
mco.EndClose(closeAr);
// *** VALIDATE *** \\
Assert.True(data.StateAfterCreate == CommunicationState.Created,
String.Format("CommunicationState after creation was '{0}' but expected 'Created'",
data.StateAfterCreate));
Assert.True(data.StateEnterOnOpening == CommunicationState.Opening,
String.Format("CommunicationState entering OnOpening was '{0}' but expected 'Opening'",
data.StateEnterOnOpening));
Assert.True(data.StateLeaveOnOpening == CommunicationState.Opening,
String.Format("CommunicationState leaving OnOpening was '{0}' but expected 'Opening'",
data.StateLeaveOnOpening));
Assert.True(data.StateEnterOnBeginOpen == CommunicationState.Opening,
String.Format("CommunicationState entering OnBeginOpen was '{0}' but expected 'Opening'",
data.StateEnterOnBeginOpen));
Assert.True(data.StateLeaveOnBeginOpen == CommunicationState.Opening,
String.Format("CommunicationState leaving OnBeginOpen was '{0}' but expected 'Opening'",
data.StateLeaveOnBeginOpen));
Assert.True(data.StateEnterOnOpened == CommunicationState.Opening,
String.Format("CommunicationState entering OnOpened was '{0}' but expected 'Opening'",
data.StateEnterOnOpened));
Assert.True(data.StateLeaveOnOpened == CommunicationState.Opened,
String.Format("CommunicationState leaving OnOpened was '{0}' but expected 'Opened'",
data.StateLeaveOnOpened));
Assert.True(data.StateEnterOnClosing == CommunicationState.Closing,
String.Format("CommunicationState entering OnClosing was '{0}' but expected 'Closing'",
data.StateEnterOnClosing));
Assert.True(data.StateLeaveOnClosing == CommunicationState.Closing,
String.Format("CommunicationState leaving OnClosing was '{0}' but expected 'Closing'",
data.StateLeaveOnClosing));
Assert.True(data.StateEnterOnBeginClose == CommunicationState.Closing,
String.Format("CommunicationState entering OnBeginClose was '{0}' but expected 'Closing'",
data.StateEnterOnBeginClose));
Assert.True(data.StateLeaveOnBeginClose == CommunicationState.Closing,
String.Format("CommunicationState leaving OnClose was '{0}' but expected 'Closing'",
data.StateLeaveOnBeginClose));
Assert.True(data.StateEnterOnClosed == CommunicationState.Closing,
String.Format("CommunicationState entering OnClosed was '{0}' but expected 'Closing'",
data.StateEnterOnClosed));
Assert.True(data.StateLeaveOnClosed == CommunicationState.Closed,
String.Format("CommunicationState leaving OnClosed was '{0}' but expected 'Closed'",
data.StateLeaveOnClosed));
}
[WcfFact]
public static void CommunicationObject_Sync_Open_Propagates_Exception()
{
MockCommunicationObject mco = new MockCommunicationObject();
TimeSpan timeout = TimeSpan.FromSeconds(30);
string exceptionMessage = "Expected exception";
// *** SETUP *** \\
mco.OnOpenOverride = (t) =>
{
throw new InvalidOperationException(exceptionMessage);
};
// *** EXECUTE *** \\
InvalidOperationException actualException = Assert.Throws<InvalidOperationException>(() =>
{
mco.Open(timeout);
});
// *** VALIDATE *** \\
Assert.True(String.Equals(exceptionMessage, actualException.Message),
String.Format("Expected exception message '{0}' but actual was '{1}'",
exceptionMessage, actualException.Message));
}
[WcfFact]
public static void CommunicationObject_Sync_Close_Propagates_Exception()
{
MockCommunicationObject mco = new MockCommunicationObject();
TimeSpan timeout = TimeSpan.FromSeconds(30);
string exceptionMessage = "Expected exception";
// *** SETUP *** \\
mco.OnCloseOverride = (t) =>
{
throw new InvalidOperationException(exceptionMessage);
};
// *** EXECUTE *** \\
mco.Open(timeout);
InvalidOperationException actualException = Assert.Throws<InvalidOperationException>(() =>
{
mco.Close(timeout);
});
// *** VALIDATE *** \\
Assert.True(String.Equals(exceptionMessage, actualException.Message),
String.Format("Expected exception message '{0}' but actual was '{1}'",
exceptionMessage, actualException.Message));
}
[WcfFact]
public static void CommunicationObject_Async_Open_Propagates_Exception()
{
MockCommunicationObject mco = new MockCommunicationObject();
TimeSpan timeout = TimeSpan.FromSeconds(30);
string exceptionMessage = "Expected exception";
// *** SETUP *** \\
mco.OnBeginOpenOverride = (TimeSpan t, AsyncCallback c, object s) =>
{
throw new InvalidOperationException(exceptionMessage);
};
// *** EXECUTE *** \\
InvalidOperationException actualException = Assert.Throws<InvalidOperationException>(() =>
{
IAsyncResult openAr = mco.BeginOpen(timeout, callback: null, state: null);
mco.OpenAsyncResult.Complete();
mco.EndOpen(openAr);
});
// *** VALIDATE *** \\
Assert.True(String.Equals(exceptionMessage, actualException.Message),
String.Format("Expected exception message '{0}' but actual was '{1}'",
exceptionMessage, actualException.Message));
}
[WcfFact]
public static void CommunicationObject_Async_Close_Propagates_Exception()
{
MockCommunicationObject mco = new MockCommunicationObject();
TimeSpan timeout = TimeSpan.FromSeconds(30);
string exceptionMessage = "Expected exception";
// *** SETUP *** \\
mco.OnBeginCloseOverride = (TimeSpan t, AsyncCallback c, object s) =>
{
throw new InvalidOperationException(exceptionMessage);
};
// *** EXECUTE *** \\
IAsyncResult openAr = mco.BeginOpen(timeout, callback: null, state: null);
mco.OpenAsyncResult.Complete();
mco.EndOpen(openAr);
InvalidOperationException actualException = Assert.Throws<InvalidOperationException>(() =>
{
IAsyncResult closeAr = mco.BeginClose(timeout, callback: null, state: null);
mco.CloseAsyncResult.Complete();
mco.EndClose(closeAr);
});
// *** VALIDATE *** \\
Assert.True(String.Equals(exceptionMessage, actualException.Message),
String.Format("Expected exception message '{0}' but actual was '{1}'",
exceptionMessage, actualException.Message));
}
}
| |
using System.Diagnostics;
using System;
using System.Management;
using System.Collections;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Web.UI.Design;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ACSGhana.Web.Framework
{
namespace UI
{
namespace Controls
{
sealed class commonScript
{
static public void WritePopupRoutines(System.Web.UI.Page Page)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb = new System.Text.StringBuilder();
sb.AppendLine("var __popup_panel;");
sb.AppendLine("function __popup_clear() {");
sb.AppendLine(" if (__popup_panel != null ) ");
sb.AppendLine(" {");
sb.AppendLine(" document.getElementById(__popup_panel).style.display=\'none\';");
sb.AppendLine(" __popup_panel=null;");
// sb.AppendLine(" document.onclick=null;")
sb.AppendLine(" }");
sb.AppendLine("}");
sb.AppendLine("function __popup_losefocus(panel)");
sb.AppendLine("{");
sb.AppendLine(" if (!panel.contains(document.activeElement))");
sb.AppendLine(" {");
sb.AppendLine(" panel.style.display=\'none\';");
sb.AppendLine(" }");
sb.AppendLine("}");
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "PopupRoutines", sb.ToString(), true);
}
}
public class DatePicker : WebControl, INamingContainer
{
private Calendar _innerCal;
private System.Web.UI.WebControls.TextBox _innerTbx;
private string errorText = null;
private bool _panelvisible = false;
public DatePicker() : base(System.Web.UI.HtmlTextWriterTag.Div)
{
}
public DateTime SelectedDate
{
get
{
EnsureChildControls();
DateTime d;
try
{
d = DateTime.Parse(_innerTbx.Text);
errorText = null;
_innerCal.SelectedDate = d;
}
catch
{
errorText = "Date needs to be specified as mm/dd/yyyy";
}
return d;
}
set
{
EnsureChildControls();
_innerCal.SelectedDate = value;
_innerTbx.Text = value.ToShortDateString();
}
}
protected override void CreateChildControls()
{
base.CreateChildControls();
_innerTbx = new System.Web.UI.WebControls.TextBox();
this.Controls.Add(_innerTbx);
_innerCal = new Calendar();
_innerCal.SelectionChanged += new System.EventHandler(_innerCal_SelectionChanged);
_innerCal.VisibleMonthChanged += new System.Web.UI.WebControls.MonthChangedEventHandler(_innerCal_MonthChanged);
Controls.Add(_innerCal);
}
protected override System.Web.UI.HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}
protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
if (this.Width.IsEmpty)
{
this.Width = new Unit(150);
}
base.AddAttributesToRender(writer);
}
private string ImagesPath
{
get
{
string strSitePath = (HttpContext.Current.Request.ApplicationPath != "/" ? HttpContext.Current.Request.ApplicationPath : "").ToString();
return strSitePath + "images/";
}
}
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
_innerTbx.Attributes.Add("Align", "AbsMiddle");
_innerTbx.Width = new Unit(100);
//_innerTbx.Height = New Unit(20)
_innerTbx.RenderControl(writer);
string innerid = this.UniqueID + "_inner";
writer.AddAttribute("Align", "AbsMiddle");
writer.AddAttribute("src", ImagesPath + "dropdownbtn.gif");
writer.AddAttribute("onClick", "__datepicker_showpopup(\'" + innerid + "\')");
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
if (errorText != null)
{
writer.AddStyleAttribute("color", "red");
writer.AddStyleAttribute("display", "block");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.Write(errorText);
writer.RenderEndTag();
}
writer.AddStyleAttribute("position", "relative");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
writer.AddStyleAttribute("position", "absolute");
writer.AddStyleAttribute("left", "0px");
writer.AddStyleAttribute("top", "0px");
writer.AddStyleAttribute("z-index", "100");
string panelvisible;
if (_panelvisible)
{
panelvisible = "block";
}
else
{
panelvisible = "none";
}
writer.AddStyleAttribute("display", panelvisible);
writer.AddStyleAttribute("background-color", "white");
writer.AddAttribute("id", innerid);
writer.AddAttribute("onfocusout", "__popup_losefocus(this)");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
_innerCal.RenderControl(writer);
writer.RenderEndTag();
writer.RenderEndTag();
}
protected override void OnPreRender(System.EventArgs e)
{
base.OnPreRender(e);
commonScript.WritePopupRoutines(Page);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
if (_panelvisible)
{
sb.AppendLine("__popup_panel = \'" + this.UniqueID + "_inner\';");
}
sb.AppendLine("function __datepicker_showpopup(name)");
sb.AppendLine("{");
sb.AppendLine(" if (__popup_panel != null)");
sb.AppendLine(" {");
sb.AppendLine(" document.getElementById(__popup_panel).style.display=\'none\';");
sb.AppendLine(" }");
sb.AppendLine(" __popup_panel=name;");
sb.AppendLine(" var panel=document.getElementById(__popup_panel);");
sb.AppendLine(" panel.style.display=\'block\';");
sb.AppendLine(" var links=panel.getElementsByTagName(\'A\');");
sb.AppendLine(" links[0].focus();");
// sb.AppendLine(" document.onclick=__popup_clear();")
sb.AppendLine(" window.event.cancelBubble=true;");
sb.AppendLine("}");
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "popup", sb.ToString(), true);
Page.MaintainScrollPositionOnPostBack = true;
}
private void _innerCal_SelectionChanged(object sender, System.EventArgs e)
{
EnsureChildControls();
_innerTbx.Text = _innerCal.SelectedDate.ToShortDateString();
}
//keep the panel for another
private void _innerCal_MonthChanged(object sender, MonthChangedEventArgs e)
{
_panelvisible = true;
}
}
}
}
}
| |
// 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.Security;
namespace System.Runtime
{
[Fx.Tag.SynchronizationObject(Blocking = false)]
// A simple synchronized pool would simply lock a stack and push/pop on return/take.
//
// This implementation tries to reduce locking by exploiting the case where an item
// is taken and returned by the same thread, which turns out to be common in our
// scenarios.
//
// Initially, all the quota is allocated to a global (non-thread-specific) pool,
// which takes locks. As different threads take and return values, we record their IDs,
// and if we detect that a thread is taking and returning "enough" on the same thread,
// then we decide to "promote" the thread. When a thread is promoted, we decrease the
// quota of the global pool by one, and allocate a thread-specific entry for the thread
// to store it's value. Once this entry is allocated, the thread can take and return
// it's value from that entry without taking any locks. Not only does this avoid
// locks, but it affinitizes pooled items to a particular thread.
//
// There are a couple of additional things worth noting:
//
// It is possible for a thread that we have reserved an entry for to exit. This means
// we will still have a entry allocated for it, but the pooled item stored there
// will never be used. After a while, we could end up with a number of these, and
// as a result we would begin to exhaust the quota of the overall pool. To mitigate this
// case, we throw away the entire per-thread pool, and return all the quota back to
// the global pool if we are unable to promote a thread (due to lack of space). Then
// the set of active threads will be re-promoted as they take and return items.
//
// You may notice that the code does not immediately promote a thread, and does not
// immediately throw away the entire per-thread pool when it is unable to promote a
// thread. Instead, it uses counters (based on the number of calls to the pool)
// and a threshold to figure out when to do these operations. In the case where the
// pool to misconfigured to have too few items for the workload, this avoids constant
// promoting and rebuilding of the per thread entries.
//
// You may also notice that we do not use interlocked methods when adjusting statistics.
// Since the statistics are a heuristic as to how often something is happening, they
// do not need to be perfect.
//
internal class SynchronizedPool<T> where T : class
{
private const int maxPendingEntries = 128;
private const int maxPromotionFailures = 64;
private const int maxReturnsBeforePromotion = 64;
private const int maxThreadItemsPerProcessor = 16;
private Entry[] _entries;
private GlobalPool _globalPool;
private int _maxCount;
private PendingEntry[] _pending;
private int _promotionFailures;
public SynchronizedPool(int maxCount)
{
int threadCount = maxCount;
int maxThreadCount = maxThreadItemsPerProcessor + SynchronizedPoolHelper.ProcessorCount;
if (threadCount > maxThreadCount)
{
threadCount = maxThreadCount;
}
_maxCount = maxCount;
_entries = new Entry[threadCount];
_pending = new PendingEntry[4];
_globalPool = new GlobalPool(maxCount);
}
private object ThisLock
{
get
{
return this;
}
}
public void Clear()
{
Entry[] entries = _entries;
for (int i = 0; i < entries.Length; i++)
{
entries[i].value = null;
}
_globalPool.Clear();
}
private void HandlePromotionFailure(int thisThreadID)
{
int newPromotionFailures = _promotionFailures + 1;
if (newPromotionFailures >= maxPromotionFailures)
{
lock (ThisLock)
{
_entries = new Entry[_entries.Length];
_globalPool.MaxCount = _maxCount;
}
PromoteThread(thisThreadID);
}
else
{
_promotionFailures = newPromotionFailures;
}
}
private bool PromoteThread(int thisThreadID)
{
lock (ThisLock)
{
for (int i = 0; i < _entries.Length; i++)
{
int threadID = _entries[i].threadID;
if (threadID == thisThreadID)
{
return true;
}
else if (threadID == 0)
{
_globalPool.DecrementMaxCount();
_entries[i].threadID = thisThreadID;
return true;
}
}
}
return false;
}
private void RecordReturnToGlobalPool(int thisThreadID)
{
PendingEntry[] localPending = _pending;
for (int i = 0; i < localPending.Length; i++)
{
int threadID = localPending[i].threadID;
if (threadID == thisThreadID)
{
int newReturnCount = localPending[i].returnCount + 1;
if (newReturnCount >= maxReturnsBeforePromotion)
{
localPending[i].returnCount = 0;
if (!PromoteThread(thisThreadID))
{
HandlePromotionFailure(thisThreadID);
}
}
else
{
localPending[i].returnCount = newReturnCount;
}
break;
}
else if (threadID == 0)
{
break;
}
}
}
private void RecordTakeFromGlobalPool(int thisThreadID)
{
PendingEntry[] localPending = _pending;
for (int i = 0; i < localPending.Length; i++)
{
int threadID = localPending[i].threadID;
if (threadID == thisThreadID)
{
return;
}
else if (threadID == 0)
{
lock (localPending)
{
if (localPending[i].threadID == 0)
{
localPending[i].threadID = thisThreadID;
return;
}
}
}
}
if (localPending.Length >= maxPendingEntries)
{
_pending = new PendingEntry[localPending.Length];
}
else
{
PendingEntry[] newPending = new PendingEntry[localPending.Length * 2];
Array.Copy(localPending, newPending, localPending.Length);
_pending = newPending;
}
}
public bool Return(T value)
{
int thisThreadID = Environment.CurrentManagedThreadId;
if (thisThreadID == 0)
{
return false;
}
if (ReturnToPerThreadPool(thisThreadID, value))
{
return true;
}
return ReturnToGlobalPool(thisThreadID, value);
}
private bool ReturnToPerThreadPool(int thisThreadID, T value)
{
Entry[] entries = _entries;
for (int i = 0; i < entries.Length; i++)
{
int threadID = entries[i].threadID;
if (threadID == thisThreadID)
{
if (entries[i].value == null)
{
entries[i].value = value;
return true;
}
else
{
return false;
}
}
else if (threadID == 0)
{
break;
}
}
return false;
}
private bool ReturnToGlobalPool(int thisThreadID, T value)
{
RecordReturnToGlobalPool(thisThreadID);
return _globalPool.Return(value);
}
public T Take()
{
int thisThreadID = Environment.CurrentManagedThreadId;
if (thisThreadID == 0)
{
return null;
}
T value = TakeFromPerThreadPool(thisThreadID);
if (value != null)
{
return value;
}
return TakeFromGlobalPool(thisThreadID);
}
private T TakeFromPerThreadPool(int thisThreadID)
{
Entry[] entries = _entries;
for (int i = 0; i < entries.Length; i++)
{
int threadID = entries[i].threadID;
if (threadID == thisThreadID)
{
T value = entries[i].value;
if (value != null)
{
entries[i].value = null;
return value;
}
else
{
return null;
}
}
else if (threadID == 0)
{
break;
}
}
return null;
}
private T TakeFromGlobalPool(int thisThreadID)
{
RecordTakeFromGlobalPool(thisThreadID);
return _globalPool.Take();
}
private struct Entry
{
public int threadID;
public T value;
}
private struct PendingEntry
{
public int returnCount;
public int threadID;
}
internal static class SynchronizedPoolHelper
{
public static readonly int ProcessorCount = GetProcessorCount();
[Fx.Tag.SecurityNote(Critical = "Asserts in order to get the processor count from the environment", Safe = "This data isn't actually protected so it's ok to leak")]
[SecuritySafeCritical]
private static int GetProcessorCount()
{
return Environment.ProcessorCount;
}
}
[Fx.Tag.SynchronizationObject(Blocking = false)]
internal class GlobalPool
{
private Stack<T> _items;
private int _maxCount;
public GlobalPool(int maxCount)
{
_items = new Stack<T>();
_maxCount = maxCount;
}
public int MaxCount
{
get
{
return _maxCount;
}
set
{
lock (ThisLock)
{
while (_items.Count > value)
{
_items.Pop();
}
_maxCount = value;
}
}
}
private object ThisLock
{
get
{
return this;
}
}
public void DecrementMaxCount()
{
lock (ThisLock)
{
if (_items.Count == _maxCount)
{
_items.Pop();
}
_maxCount--;
}
}
public T Take()
{
if (_items.Count > 0)
{
lock (ThisLock)
{
if (_items.Count > 0)
{
return _items.Pop();
}
}
}
return null;
}
public bool Return(T value)
{
if (_items.Count < this.MaxCount)
{
lock (ThisLock)
{
if (_items.Count < this.MaxCount)
{
_items.Push(value);
return true;
}
}
}
return false;
}
public void Clear()
{
lock (ThisLock)
{
_items.Clear();
}
}
}
}
}
| |
using System;
using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* Implements the Counter with Cipher Block Chaining mode (CCM) detailed in
* NIST Special Publication 800-38C.
* <p>
* <b>Note</b>: this mode is a packet mode - it needs all the data up front.
* </p>
*/
public class CcmBlockCipher
: IAeadBlockCipher
{
private static readonly int BlockSize = 16;
private readonly IBlockCipher cipher;
private readonly byte[] macBlock;
private bool forEncryption;
private byte[] nonce;
private byte[] initialAssociatedText;
private int macSize;
private ICipherParameters keyParam;
private readonly MemoryStream associatedText = new MemoryStream();
private readonly MemoryStream data = new MemoryStream();
/**
* Basic constructor.
*
* @param cipher the block cipher to be used.
*/
public CcmBlockCipher(
IBlockCipher cipher)
{
this.cipher = cipher;
this.macBlock = new byte[BlockSize];
if (cipher.GetBlockSize() != BlockSize)
throw new ArgumentException("cipher required with a block size of " + BlockSize + ".");
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public virtual IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
public virtual void Init(
bool forEncryption,
ICipherParameters parameters)
{
this.forEncryption = forEncryption;
ICipherParameters cipherParameters;
if (parameters is AeadParameters)
{
AeadParameters param = (AeadParameters) parameters;
nonce = param.GetNonce();
initialAssociatedText = param.GetAssociatedText();
macSize = param.MacSize / 8;
cipherParameters = param.Key;
}
else if (parameters is ParametersWithIV)
{
ParametersWithIV param = (ParametersWithIV) parameters;
nonce = param.GetIV();
initialAssociatedText = null;
macSize = macBlock.Length / 2;
cipherParameters = param.Parameters;
}
else
{
throw new ArgumentException("invalid parameters passed to CCM");
}
// NOTE: Very basic support for key re-use, but no performance gain from it
if (cipherParameters != null)
{
keyParam = cipherParameters;
}
if (nonce == null || nonce.Length < 7 || nonce.Length > 13)
{
throw new ArgumentException("nonce must have length from 7 to 13 octets");
}
Reset();
}
public virtual string AlgorithmName
{
get { return cipher.AlgorithmName + "/CCM"; }
}
public virtual int GetBlockSize()
{
return cipher.GetBlockSize();
}
public virtual void ProcessAadByte(byte input)
{
associatedText.WriteByte(input);
}
public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len)
{
// TODO: Process AAD online
associatedText.Write(inBytes, inOff, len);
}
public virtual int ProcessByte(
byte input,
byte[] outBytes,
int outOff)
{
data.WriteByte(input);
return 0;
}
public virtual int ProcessBytes(
byte[] inBytes,
int inOff,
int inLen,
byte[] outBytes,
int outOff)
{
Check.DataLength(inBytes, inOff, inLen, "Input buffer too short");
data.Write(inBytes, inOff, inLen);
return 0;
}
public virtual int DoFinal(
byte[] outBytes,
int outOff)
{
int len = ProcessPacket(data.GetBuffer(), 0, (int)data.Position, outBytes, outOff);
Reset();
return len;
}
public virtual void Reset()
{
cipher.Reset();
associatedText.SetLength(0);
data.SetLength(0);
}
/**
* Returns a byte array containing the mac calculated as part of the
* last encrypt or decrypt operation.
*
* @return the last mac calculated.
*/
public virtual byte[] GetMac()
{
return Arrays.CopyOfRange(macBlock, 0, macSize);
}
public virtual int GetUpdateOutputSize(
int len)
{
return 0;
}
public virtual int GetOutputSize(
int len)
{
int totalData = (int)data.Length + len;
if (forEncryption)
{
return totalData + macSize;
}
return totalData < macSize ? 0 : totalData - macSize;
}
/**
* Process a packet of data for either CCM decryption or encryption.
*
* @param in data for processing.
* @param inOff offset at which data starts in the input array.
* @param inLen length of the data in the input array.
* @return a byte array containing the processed input..
* @throws IllegalStateException if the cipher is not appropriately set up.
* @throws InvalidCipherTextException if the input data is truncated or the mac check fails.
*/
public virtual byte[] ProcessPacket(byte[] input, int inOff, int inLen)
{
byte[] output;
if (forEncryption)
{
output = new byte[inLen + macSize];
}
else
{
if (inLen < macSize)
throw new InvalidCipherTextException("data too short");
output = new byte[inLen - macSize];
}
ProcessPacket(input, inOff, inLen, output, 0);
return output;
}
/**
* Process a packet of data for either CCM decryption or encryption.
*
* @param in data for processing.
* @param inOff offset at which data starts in the input array.
* @param inLen length of the data in the input array.
* @param output output array.
* @param outOff offset into output array to start putting processed bytes.
* @return the number of bytes added to output.
* @throws IllegalStateException if the cipher is not appropriately set up.
* @throws InvalidCipherTextException if the input data is truncated or the mac check fails.
* @throws DataLengthException if output buffer too short.
*/
public virtual int ProcessPacket(byte[] input, int inOff, int inLen, byte[] output, int outOff)
{
// TODO: handle null keyParam (e.g. via RepeatedKeySpec)
// Need to keep the CTR and CBC Mac parts around and reset
if (keyParam == null)
throw new InvalidOperationException("CCM cipher unitialized.");
int n = nonce.Length;
int q = 15 - n;
if (q < 4)
{
int limitLen = 1 << (8 * q);
if (inLen >= limitLen)
throw new InvalidOperationException("CCM packet too large for choice of q.");
}
byte[] iv = new byte[BlockSize];
iv[0] = (byte)((q - 1) & 0x7);
nonce.CopyTo(iv, 1);
IBlockCipher ctrCipher = new SicBlockCipher(cipher);
ctrCipher.Init(forEncryption, new ParametersWithIV(keyParam, iv));
int outputLen;
int inIndex = inOff;
int outIndex = outOff;
if (forEncryption)
{
outputLen = inLen + macSize;
Check.OutputLength(output, outOff, outputLen, "Output buffer too short.");
CalculateMac(input, inOff, inLen, macBlock);
byte[] encMac = new byte[BlockSize];
ctrCipher.ProcessBlock(macBlock, 0, encMac, 0); // S0
while (inIndex < (inOff + inLen - BlockSize)) // S1...
{
ctrCipher.ProcessBlock(input, inIndex, output, outIndex);
outIndex += BlockSize;
inIndex += BlockSize;
}
byte[] block = new byte[BlockSize];
Array.Copy(input, inIndex, block, 0, inLen + inOff - inIndex);
ctrCipher.ProcessBlock(block, 0, block, 0);
Array.Copy(block, 0, output, outIndex, inLen + inOff - inIndex);
Array.Copy(encMac, 0, output, outOff + inLen, macSize);
}
else
{
if (inLen < macSize)
throw new InvalidCipherTextException("data too short");
outputLen = inLen - macSize;
Check.OutputLength(output, outOff, outputLen, "Output buffer too short.");
Array.Copy(input, inOff + outputLen, macBlock, 0, macSize);
ctrCipher.ProcessBlock(macBlock, 0, macBlock, 0);
for (int i = macSize; i != macBlock.Length; i++)
{
macBlock[i] = 0;
}
while (inIndex < (inOff + outputLen - BlockSize))
{
ctrCipher.ProcessBlock(input, inIndex, output, outIndex);
outIndex += BlockSize;
inIndex += BlockSize;
}
byte[] block = new byte[BlockSize];
Array.Copy(input, inIndex, block, 0, outputLen - (inIndex - inOff));
ctrCipher.ProcessBlock(block, 0, block, 0);
Array.Copy(block, 0, output, outIndex, outputLen - (inIndex - inOff));
byte[] calculatedMacBlock = new byte[BlockSize];
CalculateMac(output, outOff, outputLen, calculatedMacBlock);
if (!Arrays.ConstantTimeAreEqual(macBlock, calculatedMacBlock))
throw new InvalidCipherTextException("mac check in CCM failed");
}
return outputLen;
}
private int CalculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock)
{
IMac cMac = new CbcBlockCipherMac(cipher, macSize * 8);
cMac.Init(keyParam);
//
// build b0
//
byte[] b0 = new byte[16];
if (HasAssociatedText())
{
b0[0] |= 0x40;
}
b0[0] |= (byte)((((cMac.GetMacSize() - 2) / 2) & 0x7) << 3);
b0[0] |= (byte)(((15 - nonce.Length) - 1) & 0x7);
Array.Copy(nonce, 0, b0, 1, nonce.Length);
int q = dataLen;
int count = 1;
while (q > 0)
{
b0[b0.Length - count] = (byte)(q & 0xff);
q >>= 8;
count++;
}
cMac.BlockUpdate(b0, 0, b0.Length);
//
// process associated text
//
if (HasAssociatedText())
{
int extra;
int textLength = GetAssociatedTextLength();
if (textLength < ((1 << 16) - (1 << 8)))
{
cMac.Update((byte)(textLength >> 8));
cMac.Update((byte)textLength);
extra = 2;
}
else // can't go any higher than 2^32
{
cMac.Update((byte)0xff);
cMac.Update((byte)0xfe);
cMac.Update((byte)(textLength >> 24));
cMac.Update((byte)(textLength >> 16));
cMac.Update((byte)(textLength >> 8));
cMac.Update((byte)textLength);
extra = 6;
}
if (initialAssociatedText != null)
{
cMac.BlockUpdate(initialAssociatedText, 0, initialAssociatedText.Length);
}
if (associatedText.Position > 0)
{
cMac.BlockUpdate(associatedText.GetBuffer(), 0, (int)associatedText.Position);
}
extra = (extra + textLength) % 16;
if (extra != 0)
{
for (int i = extra; i < 16; ++i)
{
cMac.Update((byte)0x00);
}
}
}
//
// add the text
//
cMac.BlockUpdate(data, dataOff, dataLen);
return cMac.DoFinal(macBlock, 0);
}
private int GetAssociatedTextLength()
{
return (int)associatedText.Length + ((initialAssociatedText == null) ? 0 : initialAssociatedText.Length);
}
private bool HasAssociatedText()
{
return GetAssociatedTextLength() > 0;
}
}
}
| |
// 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!
namespace Google.Apis.Kgsearch.v1
{
/// <summary>The Kgsearch Service.</summary>
public class KgsearchService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public KgsearchService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public KgsearchService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Entities = new EntitiesResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "kgsearch";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://kgsearch.googleapis.com/";
#else
"https://kgsearch.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://kgsearch.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Gets the Entities resource.</summary>
public virtual EntitiesResource Entities { get; }
}
/// <summary>A base abstract class for Kgsearch requests.</summary>
public abstract class KgsearchBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new KgsearchBaseServiceRequest instance.</summary>
protected KgsearchBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes Kgsearch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "entities" collection of methods.</summary>
public class EntitiesResource
{
private const string Resource = "entities";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public EntitiesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Searches Knowledge Graph for entities that match the constraints. A list of matched entities will be
/// returned in response, which will be in JSON-LD format and compatible with http://schema.org
/// </summary>
public virtual SearchRequest Search()
{
return new SearchRequest(service);
}
/// <summary>
/// Searches Knowledge Graph for entities that match the constraints. A list of matched entities will be
/// returned in response, which will be in JSON-LD format and compatible with http://schema.org
/// </summary>
public class SearchRequest : KgsearchBaseServiceRequest<Google.Apis.Kgsearch.v1.Data.SearchResponse>
{
/// <summary>Constructs a new Search request.</summary>
public SearchRequest(Google.Apis.Services.IClientService service) : base(service)
{
InitParameters();
}
/// <summary>
/// The list of entity id to be used for search instead of query string. To specify multiple ids in the HTTP
/// request, repeat the parameter in the URL as in ...?ids=A&amp;ids=B
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("ids", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Ids { get; set; }
/// <summary>Enables indenting of json results.</summary>
[Google.Apis.Util.RequestParameterAttribute("indent", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Indent { get; set; }
/// <summary>The list of language codes (defined in ISO 693) to run the query with, e.g. 'en'.</summary>
[Google.Apis.Util.RequestParameterAttribute("languages", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Languages { get; set; }
/// <summary>Limits the number of entities to be returned.</summary>
[Google.Apis.Util.RequestParameterAttribute("limit", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> Limit { get; set; }
/// <summary>Enables prefix match against names and aliases of entities</summary>
[Google.Apis.Util.RequestParameterAttribute("prefix", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Prefix { get; set; }
/// <summary>The literal query string for search.</summary>
[Google.Apis.Util.RequestParameterAttribute("query", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Query { get; set; }
/// <summary>
/// Restricts returned entities with these types, e.g. Person (as defined in http://schema.org/Person). If
/// multiple types are specified, returned entities will contain one or more of these types.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("types", Google.Apis.Util.RequestParameterType.Query)]
public virtual Google.Apis.Util.Repeatable<string> Types { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "search";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/entities:search";
/// <summary>Initializes Search parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("ids", new Google.Apis.Discovery.Parameter
{
Name = "ids",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("indent", new Google.Apis.Discovery.Parameter
{
Name = "indent",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("languages", new Google.Apis.Discovery.Parameter
{
Name = "languages",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("limit", new Google.Apis.Discovery.Parameter
{
Name = "limit",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prefix", new Google.Apis.Discovery.Parameter
{
Name = "prefix",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("query", new Google.Apis.Discovery.Parameter
{
Name = "query",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("types", new Google.Apis.Discovery.Parameter
{
Name = "types",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Kgsearch.v1.Data
{
/// <summary>
/// Response message includes the context and a list of matching results which contain the detail of associated
/// entities.
/// </summary>
public class SearchResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The local context applicable for the response. See more details at
/// http://www.w3.org/TR/json-ld/#context-definitions.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("@context")]
public virtual object Context { get; set; }
/// <summary>The schema type of top-level JSON-LD object, e.g. ItemList.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("@type")]
public virtual object Type { get; set; }
/// <summary>The item list of search results.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("itemListElement")]
public virtual System.Collections.Generic.IList<object> ItemListElement { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace FunctionHacker.Classes
{
public class PEOptHeader
{
public bool _is64;
PEOptHeader32 _opt32;
PEOptHeader64 _opt64;
// Wrapper for PEOptHeader32 and PEOptHeader64
public UInt32 signature //decimal number 267.
{ get { return (_is64 ? _opt64.Magic : _opt32.signature); } }
public byte MajorLinkerVersion
{ get { return (_is64 ? _opt64.MajorLinkerVersion : _opt32.MajorLinkerVersion); } }
public byte MinorLinkerVersion
{ get { return (_is64 ? _opt64.MinorLinkerVersion : _opt32.MinorLinkerVersion); } }
public UInt32 SizeOfCode
{ get { return (_is64 ? _opt64.SizeOfCode : _opt32.SizeOfCode); } }
public UInt32 SizeOfInitializedData
{ get { return (_is64 ? _opt64.SizeOfInitializedData : _opt32.SizeOfInitializedData); } }
public UInt32 SizeOfUninitializedData
{ get { return (_is64 ? _opt64.SizeOfUninitializedData : _opt32.SizeOfUninitializedData); } }
public UInt32 AddressOfEntryPoint //The RVA of the code entry point
{ get { return (_is64 ? _opt64.AddressOfEntryPoint : _opt32.AddressOfEntryPoint); } }
public UInt32 BaseOfCode
{ get { return (_is64 ? _opt64.BaseOfCode : _opt32.BaseOfCode); } }
public UInt64 BaseOfData
{ get { return (_is64 ? _opt64.ImageBase : _opt32.BaseOfData); } }
public UInt64 ImageBase
{ get { return (_is64 ? _opt64.ImageBase : _opt32.ImageBase); } }
public UInt32 SectionAlignment
{ get { return (_is64 ? _opt64.SectionAlignment : _opt32.SectionAlignment); } }
public UInt32 FileAlignment
{ get { return (_is64 ? _opt64.FileAlignment : _opt32.FileAlignment); } }
public UInt16 MajorOSVersion
{ get { return (_is64 ? _opt64.MajorOperatingSystemVersion : _opt32.MajorOSVersion); } }
public UInt16 MinorOSVersion
{ get { return (_is64 ? _opt64.MinorOperatingSystemVersion : _opt32.MinorOSVersion); } }
public UInt16 MajorImageVersion
{ get { return (_is64 ? _opt64.MajorImageVersion : _opt32.MajorImageVersion); } }
public UInt16 MinorImageVersion
{ get { return (_is64 ? _opt64.MinorImageVersion : _opt32.MinorImageVersion); } }
public UInt16 MajorSubsystemVersion
{ get { return (_is64 ? _opt64.MajorSubsystemVersion : _opt32.MajorSubsystemVersion); } }
public UInt16 MinorSubsystemVersion
{ get { return (_is64 ? _opt64.MinorSubsystemVersion : _opt32.MinorSubsystemVersion); } }
public UInt32 Reserved
{ get { return (_is64 ? _opt64.Win32VersionValue : _opt32.Reserved); } }
public UInt32 SizeOfImage
{ get { return (_is64 ? _opt64.SizeOfImage : _opt32.SizeOfImage); } }
public UInt32 SizeOfHeaders
{ get { return (_is64 ? _opt64.SizeOfHeaders : _opt32.SizeOfHeaders); } }
public UInt32 Checksum
{ get { return (_is64 ? _opt64.CheckSum : _opt32.Checksum); } }
public UInt16 Subsystem
{ get { return (_is64 ? _opt64.Subsystem : _opt32.Subsystem); } }
public UInt16 DLLCharacteristics
{ get { return (_is64 ? _opt64.DllCharacteristics : _opt32.DLLCharacteristics); } }
public UInt64 SizeOfStackReserve
{ get { return (_is64 ? _opt64.SizeOfStackReserve : _opt32.SizeOfStackReserve); } }
public UInt64 SizeOfStackCommit
{ get { return (_is64 ? _opt64.SizeOfStackCommit : _opt32.SizeOfStackCommit); } }
public UInt64 SizeOfHeapReserve
{ get { return (_is64 ? _opt64.SizeOfHeapReserve : _opt32.SizeOfHeapReserve); } }
public UInt64 SizeOfHeapCommit
{ get { return (_is64 ? _opt64.SizeOfHeapCommit : _opt32.SizeOfHeapCommit); } }
public UInt32 LoaderFlags
{ get { return (_is64 ? _opt64.LoaderFlags : _opt32.LoaderFlags); } }
public UInt32 NumberOfRvaAndSizes
{ get { return (_is64 ? _opt64.NumberOfRvaAndSizes : _opt32.NumberOfRvaAndSizes); } }
public data_directory DataDirectory1_export
{ get { return (_is64 ? _opt64.DataDirectory1_export : _opt32.DataDirectory1_export); } }
public data_directory DataDirectory2_import
{ get { return (_is64 ? _opt64.DataDirectory2_import : _opt32.DataDirectory2_import); } }
public data_directory DataDirectory3
{ get { return (_is64 ? _opt64.DataDirectory3 : _opt32.DataDirectory3); } }
public data_directory DataDirectory4
{ get { return (_is64 ? _opt64.DataDirectory4 : _opt32.DataDirectory4); } }
public data_directory DataDirectory5
{ get { return (_is64 ? _opt64.DataDirectory5 : _opt32.DataDirectory5); } }
public data_directory DataDirectory6
{ get { return (_is64 ? _opt64.DataDirectory6 : _opt32.DataDirectory6); } }
public data_directory DataDirectory7
{ get { return (_is64 ? _opt64.DataDirectory7 : _opt32.DataDirectory7); } }
public data_directory DataDirectory8
{ get { return (_is64 ? _opt64.DataDirectory8 : _opt32.DataDirectory8); } }
public data_directory DataDirectory9
{ get { return (_is64 ? _opt64.DataDirectory9 : _opt32.DataDirectory9); } }
public data_directory DataDirectory10
{ get { return (_is64 ? _opt64.DataDirectory10 : _opt32.DataDirectory10); } }
public data_directory DataDirectory11
{ get { return (_is64 ? _opt64.DataDirectory11 : _opt32.DataDirectory11); } }
public data_directory DataDirectory12
{ get { return (_is64 ? _opt64.DataDirectory12 : _opt32.DataDirectory12); } }
public data_directory DataDirectory13
{ get { return (_is64 ? _opt64.DataDirectory13 : _opt32.DataDirectory13); } }
public data_directory DataDirectory14
{ get { return (_is64 ? _opt64.DataDirectory14 : _opt32.DataDirectory14); } }
public data_directory DataDirectory15
{ get { return (_is64 ? _opt64.DataDirectory15 : _opt32.DataDirectory15); } }
public data_directory DataDirectory16
{ get { return (_is64 ? _opt64.DataDirectory16 : _opt32.DataDirectory16); } }
public PEOptHeader(ref byte[] data, int index, int size)
{
if (size == Marshal.SizeOf(typeof(PEOptHeader64)))
{
// Parse 64 bit version
_is64 = true;
_opt64 = (PEOptHeader64)oMemoryFunctions.RawDataToObject(ref data, typeof(PEOptHeader64));
}
else if (size == Marshal.SizeOf(typeof(PEOptHeader32)))
{
// Parse 32 bit version
_is64 = false;
_opt32 = (PEOptHeader32)oMemoryFunctions.RawDataToObject(ref data, typeof(PEOptHeader32));
}
else
{
// ERROR
throw new Exception("ERROR: Invalid pe optional header size of " + size.ToString() + ". Expected " + Marshal.SizeOf(typeof(PEOptHeader64)).ToString() + " or " + Marshal.SizeOf(typeof(PEOptHeader32)).ToString() + ".");
}
}
}
public struct ADDRESS_RANGE
{
public uint start;
public uint size;
public ADDRESS_RANGE(uint address, uint size)
{
this.start = address;
this.size = size;
}
public bool isValid(uint address)
{
if (address >= start && address < start + size)
return false;
return true;
}
}
public class HeaderReader
{
public uint codeLength;
public uint codeStartAddress;
public COFFHeader coffHeader;
public IMAGE_DOS_HEADER dosHeader;
public Hashtable exports;
public List<IMPORT_FUNCTION> importTable;
public PEOptHeader optHeader;
public bool success;
public List<ADDRESS_RANGE> invalidCodeAddresses;
public List<section> sections;
public UInt64 BaseAddress;
public UInt64 Size;
/// <summary>
/// Check all invalid code ranges to see if this pointer is invalid for a code region.
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public bool isValidCodePointer(uint address)
{
foreach (ADDRESS_RANGE range in invalidCodeAddresses)
if (!range.isValid(address))
return false;
return true;
}
public static bool IsWin64(System.Diagnostics.Process process)
{
UInt64 address = (UInt64)process.MainModule.BaseAddress;
// Read in the Image Dos Header
byte[] headerData = oMemoryFunctions.ReadMemory(process, (ulong)address, (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
IMAGE_DOS_HEADER dosHeader = (IMAGE_DOS_HEADER)oMemoryFunctions.RawDataToObject(ref headerData, typeof(IMAGE_DOS_HEADER));
// Load the PE Address
UInt64 PE_header = 0;
if (dosHeader.e_magic == 0x5A4D)
{
// Load the PE header address
PE_header = dosHeader.e_lfanew + address;
}
else
{
PE_header = address;
}
// Read in the PE token
byte[] PE_Token = oMemoryFunctions.ReadMemory(process, (ulong)PE_header, 4);
if (!(PE_Token[0] == 'P' & PE_Token[1] == 'E' & PE_Token[2] == 0 & PE_Token[3] == 0))
{
// Problem, we are not pointing at a correct PE header. Abort.
throw new Exception("Failed to read PE header from block " + address.ToString("X") + " with PE header located at " + PE_header.ToString() + ".");
}
// Input the COFFHeader
byte[] coffHeader_rawData = oMemoryFunctions.ReadMemory(process, (ulong)(PE_header + 4), (uint)Marshal.SizeOf(typeof(COFFHeader)));
COFFHeader coffHeader = (COFFHeader)oMemoryFunctions.RawDataToObject(ref coffHeader_rawData, typeof(COFFHeader));
return ((MACHINE)coffHeader.Machine) == MACHINE.IMAGE_FILE_MACHINE_IA64 || ((MACHINE)coffHeader.Machine) == MACHINE.IMAGE_FILE_MACHINE_AMD64;
}
/// <summary>
/// This checks whether the specified heap is
/// a valid pe header.
/// </summary>
/// <param name="process"></param>
/// <param name="address"></param>
/// <returns></returns>
public static bool isPeHeader(System.Diagnostics.Process process, UInt64 address)
{
// Read in the Image Dos Header
byte[] headerData = oMemoryFunctions.ReadMemory(process, (ulong)address,
(uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
IMAGE_DOS_HEADER dosHeader = (IMAGE_DOS_HEADER)oMemoryFunctions.RawDataToObject(ref headerData, typeof(IMAGE_DOS_HEADER));
// Load the PE Address
UInt64 PE_header = 0;
if (dosHeader.e_magic == 0x5A4D)
{
// Load the PE header address
PE_header = dosHeader.e_lfanew + address;
}
else
{
PE_header = address;
return false;
}
if (PE_header <= 0x7FFFFFFF)
{
// Read in the PE token
byte[] PE_Token = oMemoryFunctions.ReadMemory(process, (ulong)PE_header, 4);
if (!(PE_Token[0] == 'P' & PE_Token[1] == 'E' & PE_Token[2] == 0 & PE_Token[3] == 0))
{
// Problem, we are not pointing at a correct PE header. Abort.
return false;
}
// Input the COFFHeader
byte[] coffHeader_rawData = oMemoryFunctions.ReadMemory(process, (ulong)(PE_header + 4), (uint)Marshal.SizeOf(typeof(COFFHeader)));
COFFHeader coffHeader = (COFFHeader)oMemoryFunctions.RawDataToObject(ref coffHeader_rawData, typeof(COFFHeader));
// Read in the PEOptHeader if it exists
if (coffHeader.SizeOfOptionalHeader != 0 && coffHeader.SizeOfOptionalHeader < 0x1000)
{
// Read in the optHeader
byte[] optHeader_rawData = oMemoryFunctions.ReadMemory(process, (ulong)(PE_header + 4 + (uint)Marshal.SizeOf(typeof(COFFHeader))), coffHeader.SizeOfOptionalHeader);
PEOptHeader optHeader = new PEOptHeader(ref optHeader_rawData, 0, optHeader_rawData.Length);
// Confirm that it loaded correctly
if ((optHeader.signature & 0xffff) != 0x10b && (optHeader.signature & 0xffff) != 0x20b)
{
return false;
}
if (optHeader.SizeOfCode == 0)
return false;
}
else
{
// No COFFHeader found
return false;
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// This function loads the header and PE header at the
/// specified address in memory.
/// </summary>
/// <param name="process"></param>
/// <param name="address"></param>
public HeaderReader(System.Diagnostics.Process process, UInt64 address)
{
this.BaseAddress = address;
codeStartAddress = 0;
codeLength = 0;
invalidCodeAddresses = new List<ADDRESS_RANGE>(10);
sections = new List<section>(10);
exports = new Hashtable(10);
// Read in the Image Dos Header
importTable = new List<IMPORT_FUNCTION>(0);
byte[] headerData = oMemoryFunctions.ReadMemory(process, (ulong)address, (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
dosHeader = (IMAGE_DOS_HEADER)oMemoryFunctions.RawDataToObject(ref headerData, typeof(IMAGE_DOS_HEADER));
// Load the PE Address
UInt64 PE_header = 0;
if (dosHeader.e_magic == 0x5A4D)
{
// Load the PE header address
PE_header = dosHeader.e_lfanew + address;
}
else
{
PE_header = address;
}
// Read in the PE token
byte[] PE_Token = oMemoryFunctions.ReadMemory(process, (ulong)PE_header, 4);
if (!(PE_Token[0] == 'P' & PE_Token[1] == 'E' & PE_Token[2] == 0 & PE_Token[3] == 0))
{
// Problem, we are not pointing at a correct PE header. Abort.
Console.WriteLine("Failed to read PE header from block " + address.ToString("X") + " with PE header located at " + PE_header.ToString() + ".");
return;
}
// Input the COFFHeader
byte[] coffHeader_rawData = oMemoryFunctions.ReadMemory(process, (ulong)(PE_header + 4), (uint)Marshal.SizeOf(typeof(COFFHeader)));
coffHeader = (COFFHeader)oMemoryFunctions.RawDataToObject(ref coffHeader_rawData, typeof(COFFHeader));
// Read in the PEOptHeader if it exists
if (coffHeader.SizeOfOptionalHeader != 0 && coffHeader.SizeOfOptionalHeader < 0x1000)
{
// Read in the optHeader
byte[] optHeader_rawData = oMemoryFunctions.ReadMemory(process, (ulong)(PE_header + 4 + (uint)Marshal.SizeOf(typeof(COFFHeader))), coffHeader.SizeOfOptionalHeader);
optHeader = new PEOptHeader(ref optHeader_rawData, 0, coffHeader.SizeOfOptionalHeader);
// Confirm that it loaded correctly
if ((optHeader.signature & 0xffff) != 0x10b && (optHeader.signature & 0xffff) != 0x20b)
{
Console.WriteLine("Failed to read optHeader; Expected signature does not match read in signature of " + optHeader.signature.ToString() + ".");
return;
}
if (optHeader._is64)
return; // Do not process 64bit headers
// Load the sections
UInt64 sectionAddress = PE_header + 4 + (UInt64)Marshal.SizeOf(typeof(COFFHeader)) + coffHeader.SizeOfOptionalHeader;
sections = new List<section>(coffHeader.NumberOfSections);
for (int i = 0; i < coffHeader.NumberOfSections; i++)
{
sections.Add(new section(process, sectionAddress));
sectionAddress += (uint)Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER));
}
// Add all the directories as invalid code ranges
try
{
if (optHeader.DataDirectory1_export.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory1_export.VirtualAddress),
optHeader.DataDirectory1_export.Size));
if (optHeader.DataDirectory2_import.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory2_import.VirtualAddress),
optHeader.DataDirectory2_import.Size));
if (optHeader.DataDirectory3.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory3.VirtualAddress),
optHeader.DataDirectory3.Size));
if (optHeader.DataDirectory4.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory4.VirtualAddress),
optHeader.DataDirectory4.Size));
if (optHeader.DataDirectory5.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory5.VirtualAddress),
optHeader.DataDirectory5.Size));
if (optHeader.DataDirectory6.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory6.VirtualAddress),
optHeader.DataDirectory6.Size));
if (optHeader.DataDirectory7.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory7.VirtualAddress),
optHeader.DataDirectory7.Size));
if (optHeader.DataDirectory8.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory8.VirtualAddress),
optHeader.DataDirectory8.Size));
if (optHeader.DataDirectory9.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory9.VirtualAddress),
optHeader.DataDirectory9.Size));
if (optHeader.DataDirectory10.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory10.VirtualAddress),
optHeader.DataDirectory10.Size));
if (optHeader.DataDirectory11.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory11.VirtualAddress),
optHeader.DataDirectory11.Size));
if (optHeader.DataDirectory12.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory12.VirtualAddress),
optHeader.DataDirectory12.Size));
if (optHeader.DataDirectory13.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory13.VirtualAddress),
optHeader.DataDirectory13.Size));
if (optHeader.DataDirectory14.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory14.VirtualAddress),
optHeader.DataDirectory14.Size));
if (optHeader.DataDirectory15.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory15.VirtualAddress),
optHeader.DataDirectory15.Size));
if (optHeader.DataDirectory16.Size > 0)
invalidCodeAddresses.Add(
new ADDRESS_RANGE(
oMemoryFunctions.AddressAdd(address, optHeader.DataDirectory16.VirtualAddress),
optHeader.DataDirectory16.Size));
}
catch
{
// Ignore exceptions, this is not cretical.
}
// Extract the names of the functions and corresponding table entries
Int64 importTableAddress = (Int64)optHeader.DataDirectory2_import.VirtualAddress + (Int64)address;
loadImportTable(process, (uint)importTableAddress, optHeader.DataDirectory2_import.Size, (uint)address);
// Extract the names of the functions and corresponding table entries
Int64 exportTableAddress = (Int64)optHeader.DataDirectory1_export.VirtualAddress + (Int64)address;
// Read in the first _IMAGE_EXPORT_DIRECTORY structure
byte[] export_directory_rawData = oMemoryFunctions.ReadMemory(process, (ulong)exportTableAddress, (uint)Marshal.SizeOf(typeof(_IMAGE_EXPORT_DIRECTORY)));
_IMAGE_EXPORT_DIRECTORY export_directory = (_IMAGE_EXPORT_DIRECTORY)oMemoryFunctions.RawDataToObject(ref export_directory_rawData, typeof(_IMAGE_EXPORT_DIRECTORY));
exports = new Hashtable(20);
UInt64 functionNameArray = (UInt64)export_directory.AddressOfNames + address;
string exportName = oMemoryFunctions.ReadString(process, (UInt64)export_directory.Name + address, oMemoryFunctions.STRING_TYPE.ascii);
UInt64 functionOrdinalArray = (UInt64)export_directory.AddressOfNameOrdinal + address;
UInt64 functionAddressArray = (UInt64)export_directory.AddressOfFunctions + address;
for (int i = 0; i < export_directory.NumberOfNames; i++)
{
int ordinal_relative = (int)oMemoryFunctions.ReadMemoryUShort(process, functionOrdinalArray + (UInt64)i * 2);
int ordinal = ordinal_relative + (int)export_directory.Base;
if (ordinal_relative < export_directory.NumberOfFunctions)
{
// Continue with importing this function
string name = "";
if (i < export_directory.NumberOfNames)
name = oMemoryFunctions.ReadString(process, (UInt64)oMemoryFunctions.ReadMemoryDword(process, functionNameArray + (UInt64)i * 4) + address, oMemoryFunctions.STRING_TYPE.ascii);
else
name = "oridinal" + ordinal.ToString();
// Lookup the function rva now
try
{
UInt64 offset = (UInt64)oMemoryFunctions.ReadMemoryDword(process, functionAddressArray + (UInt64)ordinal_relative * 4);
// Check to see if this is a forwarded export
if (offset < optHeader.DataDirectory1_export.VirtualAddress ||
offset > optHeader.DataDirectory1_export.VirtualAddress + optHeader.DataDirectory1_export.Size)
{
// Lookup privilege of heap to confirm it requests execute privileges. We only want to list exported functions, not variables.
foreach (section exp in sections)
{
if (exp.Contains(offset))
{
if (exp.IsExecutable())
{
// Add this exported function
export new_export = new export(offset + address,
name,
ordinal);
if (!exports.ContainsKey(new_export.Address))
{
exports.Add(new_export.Address, new_export);
}
break;
}
break;
}
}
}
else
{
// Forwarded export. Ignore it.
}
}
catch (Exception e)
{
Console.WriteLine("Warning, failed to parse PE header export directory entry for name '" + name + "'.");
}
}
}
}
else
{
// No COFFHeader found
Console.WriteLine("Warning, no COFFHeader found for address " + address.ToString("X") + ".");
return;
}
}
private void loadImportTable(Process process, uint importTableAddress, uint length, uint baseAddress)
{
// Read in the first import descriptor structure
byte[] image_import_descriptor_rawData = oMemoryFunctions.ReadMemory(process, importTableAddress, (uint)Marshal.SizeOf(typeof(image_import_descriptor)));
image_import_descriptor descriptor = (image_import_descriptor)oMemoryFunctions.RawDataToObject(ref image_import_descriptor_rawData, typeof(image_import_descriptor));
List<image_import_by_name> imports = new List<image_import_by_name>(0);
while (descriptor.FirstThunk != 0 || descriptor.OriginalFirstThunk != 0 || descriptor.Name != 0)
{
// Process this descriptor
imports.Add(new image_import_by_name(process, descriptor, (ulong)baseAddress));
// Read next descriptor
image_import_descriptor_rawData = oMemoryFunctions.ReadMemory(process, oMemoryFunctions.AddressAdd(importTableAddress, (ulong)(imports.Count * Marshal.SizeOf(typeof(image_import_descriptor)))), (uint)Marshal.SizeOf(typeof(image_import_descriptor)));
descriptor = (image_import_descriptor)oMemoryFunctions.RawDataToObject(ref image_import_descriptor_rawData, typeof(image_import_descriptor));
}
// Now lets process the array of descriptors
foreach (image_import_by_name dllDescriptor in imports)
{
for (int i = 0; i < dllDescriptor.ImportTableAddresses.Count; i++)
{
// Process this function import
try
{
IMPORT_FUNCTION newImport = new IMPORT_FUNCTION();
newImport.name = dllDescriptor.Names[i];
newImport.memoryAddress = (uint)dllDescriptor.ImportTableAddresses[i];
newImport.targetAddress = oMemoryFunctions.ReadMemoryDword(process,
(ulong)newImport.memoryAddress);
importTable.Add(newImport);
}
catch
{
// Not a critical error
}
}
}
}
public static bool isPeHeader(System.Diagnostics.Process process, ulong p, MEMORY_PROTECT memoryProtection)
{
// We don't want to set off a page guard exception!
if (memoryProtection.ToString().ToUpper().Contains("GUARD"))
return false;
else
return isPeHeader(process, p);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct IMAGE_EXPORT_DIRECTORY
{
public UInt32 Characteristics;
public UInt32 TimeDateStamp;
public UInt16 MajorVersion;
public UInt16 MinorVersion;
public UInt32 Name;
public UInt32 Base;
public UInt32 NumberOfFunctions;
public UInt32 NumberOfNames;
public UInt32 AddressOfFunctions; // RVA from base of image
public UInt32 AddressOfNames; // RVA from base of image
public UInt32 AddressOfNameOrdinals; // RVA from base of image
}
public struct IMPORT_FUNCTION
{
public UInt64 memoryAddress;
public UInt64 targetAddress;
public string name;
}
public struct IMAGE_DOS_HEADER
{
// DOS .EXE header
public UInt16 e_magic; // Magic number, should be value to value to 0x54AD
public UInt16 e_cblp; // Bytes on last page of file
public UInt16 e_cp; // Pages in file
public UInt16 e_crlc; // Relocations
public UInt16 e_cparhdr; // Size of header in paragraphs
public UInt16 e_minalloc; // Minimum extra paragraphs needed
public UInt16 e_maxalloc; // Maximum extra paragraphs needed
public UInt16 e_ss; // Initial (relative) SS value
public UInt16 e_sp; // Initial SP value
public UInt16 e_csum; // Checksum
public UInt16 e_ip; // Initial IP value
public UInt16 e_cs; // Initial (relative) CS value
public UInt16 e_lfarlc; // File address of relocation table
public UInt16 e_ovno; // Overlay number
public UInt16 e_res_1; // Reserved words
public UInt16 e_res_2; // Reserved words
public UInt16 e_res_3; // Reserved words
public UInt16 e_res_4; // Reserved words
public UInt16 e_oemid; // OEM identifier (for e_oeminfo)
public UInt16 e_oeminfo; // OEM information; e_oemid specific
public UInt16 e_res2_1; // Reserved words
public UInt16 e_res2_2; // Reserved words
public UInt16 e_res2_3; // Reserved words
public UInt16 e_res2_4; // Reserved words
public UInt16 e_res2_5; // Reserved words
public UInt16 e_res2_6; // Reserved words
public UInt16 e_res2_7; // Reserved words
public UInt16 e_res2_8; // Reserved words
public UInt16 e_res2_9; // Reserved words
public UInt16 e_res2_10; // Reserved words
public UInt32 e_lfanew; // Offset of PE header
}
public struct COFFHeader
{
public UInt16 Machine;
public UInt16 NumberOfSections;
public UInt32 TimeDateStamp;
public UInt32 PointerToSymbolTable;
public UInt32 NumberOfSymbols;
public UInt16 SizeOfOptionalHeader;
public UInt16 Characteristics;
}
public enum MACHINE
{
IMAGE_FILE_MACHINE_I386 = 0x014c,
IMAGE_FILE_MACHINE_AMD64 = 0x8664,
IMAGE_FILE_MACHINE_IA64 = 0x0200,
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PEOptHeader32
{
public UInt16 signature; //decimal number 267.
public byte MajorLinkerVersion;
public byte MinorLinkerVersion;
public UInt32 SizeOfCode;
public UInt32 SizeOfInitializedData;
public UInt32 SizeOfUninitializedData;
public UInt32 AddressOfEntryPoint; //The RVA of the code entry point
public UInt32 BaseOfCode;
public UInt32 BaseOfData;
public UInt32 ImageBase;
public UInt32 SectionAlignment;
public UInt32 FileAlignment;
public UInt16 MajorOSVersion;
public UInt16 MinorOSVersion;
public UInt16 MajorImageVersion;
public UInt16 MinorImageVersion;
public UInt16 MajorSubsystemVersion;
public UInt16 MinorSubsystemVersion;
public UInt32 Reserved;
public UInt32 SizeOfImage;
public UInt32 SizeOfHeaders;
public UInt32 Checksum;
public UInt16 Subsystem;
public UInt16 DLLCharacteristics;
public UInt32 SizeOfStackReserve;
public UInt32 SizeOfStackCommit;
public UInt32 SizeOfHeapReserve;
public UInt32 SizeOfHeapCommit;
public UInt32 LoaderFlags;
public UInt32 NumberOfRvaAndSizes;
public data_directory DataDirectory1_export;
//Can have any number of elements, matching the number in NumberOfRvaAndSizes.
public data_directory DataDirectory2_import;
public data_directory DataDirectory3;
public data_directory DataDirectory4;
public data_directory DataDirectory5;
public data_directory DataDirectory6;
public data_directory DataDirectory7;
public data_directory DataDirectory8;
public data_directory DataDirectory9;
public data_directory DataDirectory10;
public data_directory DataDirectory11;
public data_directory DataDirectory12;
public data_directory DataDirectory13;
public data_directory DataDirectory14;
public data_directory DataDirectory15;
public data_directory DataDirectory16;
}
[StructLayout(LayoutKind.Explicit)]
public struct PEOptHeader64
{
[FieldOffset(0)]
public UInt32 Magic;
[FieldOffset(2)]
public byte MajorLinkerVersion;
[FieldOffset(3)]
public byte MinorLinkerVersion;
[FieldOffset(4)]
public UInt32 SizeOfCode;
[FieldOffset(8)]
public UInt32 SizeOfInitializedData;
[FieldOffset(12)]
public UInt32 SizeOfUninitializedData;
[FieldOffset(16)]
public UInt32 AddressOfEntryPoint;
[FieldOffset(20)]
public UInt32 BaseOfCode;
[FieldOffset(24)]
public UInt64 ImageBase;
[FieldOffset(32)]
public UInt32 SectionAlignment;
[FieldOffset(36)]
public UInt32 FileAlignment;
[FieldOffset(40)]
public UInt16 MajorOperatingSystemVersion;
[FieldOffset(42)]
public UInt16 MinorOperatingSystemVersion;
[FieldOffset(44)]
public UInt16 MajorImageVersion;
[FieldOffset(46)]
public UInt16 MinorImageVersion;
[FieldOffset(48)]
public UInt16 MajorSubsystemVersion;
[FieldOffset(50)]
public UInt16 MinorSubsystemVersion;
[FieldOffset(52)]
public UInt32 Win32VersionValue;
[FieldOffset(56)]
public UInt32 SizeOfImage;
[FieldOffset(60)]
public UInt32 SizeOfHeaders;
[FieldOffset(64)]
public UInt32 CheckSum;
[FieldOffset(68)]
public UInt16 Subsystem;
[FieldOffset(70)]
public UInt16 DllCharacteristics;
[FieldOffset(72)]
public UInt64 SizeOfStackReserve;
[FieldOffset(80)]
public UInt64 SizeOfStackCommit;
[FieldOffset(88)]
public UInt64 SizeOfHeapReserve;
[FieldOffset(96)]
public UInt64 SizeOfHeapCommit;
[FieldOffset(104)]
public UInt32 LoaderFlags;
[FieldOffset(108)]
public UInt32 NumberOfRvaAndSizes;
[FieldOffset(112)]
public data_directory DataDirectory1_export;
[FieldOffset(120)]
public data_directory DataDirectory2_import;
[FieldOffset(128)]
public data_directory DataDirectory3;
[FieldOffset(136)]
public data_directory DataDirectory4;
[FieldOffset(144)]
public data_directory DataDirectory5;
[FieldOffset(152)]
public data_directory DataDirectory6;
[FieldOffset(160)]
public data_directory DataDirectory7;
[FieldOffset(168)]
public data_directory DataDirectory8;
[FieldOffset(176)]
public data_directory DataDirectory9;
[FieldOffset(184)]
public data_directory DataDirectory10;
[FieldOffset(192)]
public data_directory DataDirectory11;
[FieldOffset(200)]
public data_directory DataDirectory12;
[FieldOffset(208)]
public data_directory DataDirectory13;
[FieldOffset(216)]
public data_directory DataDirectory14;
[FieldOffset(224)]
public data_directory DataDirectory15;
[FieldOffset(232)]
public data_directory DataDirectory16;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct data_directory
{
public UInt32 VirtualAddress;
public UInt32 Size;
}
public struct image_import_descriptor
{
public int OriginalFirstThunk;
public int TimeDateStamp;
public int ForwarderChain;
public int Name;
public int FirstThunk;
}
public struct _IMAGE_EXPORT_DIRECTORY
{
public UInt32 Characteristics;
public UInt32 TimeDateStamp;
public UInt16 MajorVersion;
public UInt16 MinorVersion;
public UInt32 Name;
public UInt32 Base;
public UInt32 NumberOfFunctions;
public UInt32 NumberOfNames;
public UInt32 AddressOfFunctions;
public UInt32 AddressOfNames;
public UInt32 AddressOfNameOrdinal;
}
[StructLayout(LayoutKind.Explicit)]
public struct IMAGE_SECTION_HEADER
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public char[] Name;
[FieldOffset(8)]
public UInt32 VirtualSize;
[FieldOffset(12)]
public UInt32 VirtualAddress;
[FieldOffset(16)]
public UInt32 SizeOfRawData;
[FieldOffset(20)]
public UInt32 PointerToRawData;
[FieldOffset(24)]
public UInt32 PointerToRelocations;
[FieldOffset(28)]
public UInt32 PointerToLinenumbers;
[FieldOffset(32)]
public UInt16 NumberOfRelocations;
[FieldOffset(34)]
public UInt16 NumberOfLinenumbers;
[FieldOffset(36)]
public DataSectionFlags Characteristics;
public string Section
{
get { return new string(Name); }
}
}
[Flags]
public enum DataSectionFlags : uint
{
/// <summary>
/// Reserved for future use.
/// </summary>
TypeReg = 0x00000000,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeDsect = 0x00000001,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeNoLoad = 0x00000002,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeGroup = 0x00000004,
/// <summary>
/// The section should not be padded to the next boundary. This flag is obsolete and is replaced by IMAGE_SCN_ALIGN_1BYTES. This is valid only for object files.
/// </summary>
TypeNoPadded = 0x00000008,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeCopy = 0x00000010,
/// <summary>
/// The section contains executable code.
/// </summary>
ContentCode = 0x00000020,
/// <summary>
/// The section contains initialized data.
/// </summary>
ContentInitializedData = 0x00000040,
/// <summary>
/// The section contains uninitialized data.
/// </summary>
ContentUninitializedData = 0x00000080,
/// <summary>
/// Reserved for future use.
/// </summary>
LinkOther = 0x00000100,
/// <summary>
/// The section contains comments or other information. The .drectve section has this type. This is valid for object files only.
/// </summary>
LinkInfo = 0x00000200,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeOver = 0x00000400,
/// <summary>
/// The section will not become part of the image. This is valid only for object files.
/// </summary>
LinkRemove = 0x00000800,
/// <summary>
/// The section contains COMDAT data. For more information, see section 5.5.6, COMDAT Sections (Object Only). This is valid only for object files.
/// </summary>
LinkComDat = 0x00001000,
/// <summary>
/// Reset speculative exceptions handling bits in the TLB entries for this section.
/// </summary>
NoDeferSpecExceptions = 0x00004000,
/// <summary>
/// The section contains data referenced through the global pointer (GP).
/// </summary>
RelativeGP = 0x00008000,
/// <summary>
/// Reserved for future use.
/// </summary>
MemPurgeable = 0x00020000,
/// <summary>
/// Reserved for future use.
/// </summary>
Memory16Bit = 0x00020000,
/// <summary>
/// Reserved for future use.
/// </summary>
MemoryLocked = 0x00040000,
/// <summary>
/// Reserved for future use.
/// </summary>
MemoryPreload = 0x00080000,
/// <summary>
/// Align data on a 1-byte boundary. Valid only for object files.
/// </summary>
Align1Bytes = 0x00100000,
/// <summary>
/// Align data on a 2-byte boundary. Valid only for object files.
/// </summary>
Align2Bytes = 0x00200000,
/// <summary>
/// Align data on a 4-byte boundary. Valid only for object files.
/// </summary>
Align4Bytes = 0x00300000,
/// <summary>
/// Align data on an 8-byte boundary. Valid only for object files.
/// </summary>
Align8Bytes = 0x00400000,
/// <summary>
/// Align data on a 16-byte boundary. Valid only for object files.
/// </summary>
Align16Bytes = 0x00500000,
/// <summary>
/// Align data on a 32-byte boundary. Valid only for object files.
/// </summary>
Align32Bytes = 0x00600000,
/// <summary>
/// Align data on a 64-byte boundary. Valid only for object files.
/// </summary>
Align64Bytes = 0x00700000,
/// <summary>
/// Align data on a 128-byte boundary. Valid only for object files.
/// </summary>
Align128Bytes = 0x00800000,
/// <summary>
/// Align data on a 256-byte boundary. Valid only for object files.
/// </summary>
Align256Bytes = 0x00900000,
/// <summary>
/// Align data on a 512-byte boundary. Valid only for object files.
/// </summary>
Align512Bytes = 0x00A00000,
/// <summary>
/// Align data on a 1024-byte boundary. Valid only for object files.
/// </summary>
Align1024Bytes = 0x00B00000,
/// <summary>
/// Align data on a 2048-byte boundary. Valid only for object files.
/// </summary>
Align2048Bytes = 0x00C00000,
/// <summary>
/// Align data on a 4096-byte boundary. Valid only for object files.
/// </summary>
Align4096Bytes = 0x00D00000,
/// <summary>
/// Align data on an 8192-byte boundary. Valid only for object files.
/// </summary>
Align8192Bytes = 0x00E00000,
/// <summary>
/// The section contains extended relocations.
/// </summary>
LinkExtendedRelocationOverflow = 0x01000000,
/// <summary>
/// The section can be discarded as needed.
/// </summary>
MemoryDiscardable = 0x02000000,
/// <summary>
/// The section cannot be cached.
/// </summary>
MemoryNotCached = 0x04000000,
/// <summary>
/// The section is not pageable.
/// </summary>
MemoryNotPaged = 0x08000000,
/// <summary>
/// The section can be shared in memory.
/// </summary>
MemoryShared = 0x10000000,
/// <summary>
/// The section can be executed as code.
/// </summary>
MemoryExecute = 0x20000000,
/// <summary>
/// The section can be read.
/// </summary>
MemoryRead = 0x40000000,
/// <summary>
/// The section can be written to.
/// </summary>
MemoryWrite = 0x80000000
}
public class export
{
public UInt64 Address;
public string Name;
public int Ordinal;
public export(UInt64 address, string name, int ordinal)
{
this.Address = address;
this.Ordinal = ordinal;
if (name.Trim() == "")
this.Name = "Ordinal " + ordinal;
else
this.Name = name;
}
}
public class section
{
public IMAGE_SECTION_HEADER SectionHeader;
public section(System.Diagnostics.Process process, UInt64 address)
{
// Parse the section struct
byte[] headerData = oMemoryFunctions.ReadMemory(process, (ulong)address, (uint)Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)));
SectionHeader = (IMAGE_SECTION_HEADER)oMemoryFunctions.RawDataToObject(ref headerData, typeof(IMAGE_SECTION_HEADER));
}
public string Name
{
get { return SectionHeader.Section; }
}
public DataSectionFlags Characteristics
{
get { return SectionHeader.Characteristics; }
}
public bool Contains(UInt64 rva)
{
return rva >= SectionHeader.VirtualAddress && rva - SectionHeader.VirtualAddress < SectionHeader.VirtualSize;
}
public bool IsExecutable()
{
return (((uint)SectionHeader.Characteristics) & (uint)DataSectionFlags.MemoryExecute) > 0;
}
}
public class image_import_by_name
{
public List<uint> AddressOfData;
public List<string> Names;
public List<UInt64> ImportTableAddresses;
public image_import_by_name(System.Diagnostics.Process process, image_import_descriptor descriptor, UInt64 baseAddress)
{
AddressOfData = new List<uint>(0);
ImportTableAddresses = new List<UInt64>(0);
Names = new List<string>(0);
// Read the AddressOfData array in
if (descriptor.OriginalFirstThunk != 0 && descriptor.FirstThunk != 0)
{
// Read in the descriptor table with names
int i = 0;
uint newAddress = oMemoryFunctions.ReadMemoryDword(process,
(ulong)descriptor.OriginalFirstThunk +
(ulong)baseAddress + (ulong)i * 4);
while (newAddress != 0)
{
// Add this new address
AddressOfData.Add(newAddress & 0x7fffffff);
// Add the string corresponding to this new function
if ((newAddress & 0x80000000) > 0)
{
// Export by ordinal
newAddress = newAddress & 0x7fffffff;
Names.Add("ordinal 0x" +
oMemoryFunctions.ReadMemoryUShort(process, (UInt64)newAddress + baseAddress).
ToString("X"));
}
else if (newAddress > 0)
{
// Export by name
Names.Add(oMemoryFunctions.ReadMemoryString(process, (UInt64)newAddress + baseAddress + 2, 256));
}
else
{
// There is no name or ordinal given, probably obfuscated?
Names.Add("obfuscated?");
}
// Add the pe table address corresponding to this function
ImportTableAddresses.Add((UInt64)descriptor.FirstThunk + (UInt64)baseAddress + (UInt64)i * 4);
// Read in the next value
i++;
newAddress = oMemoryFunctions.ReadMemoryDword(process,
(ulong)descriptor.OriginalFirstThunk +
(ulong)baseAddress + (ulong)i * 4);
}
}
else
{
// Read in the descriptor table without names
int i = 0;
ulong addressThunk = (ulong)(descriptor.OriginalFirstThunk != 0
? descriptor.OriginalFirstThunk
: descriptor.FirstThunk);
if (addressThunk == 0)
return; // We have no imports that we can read in.
uint newAddress = oMemoryFunctions.ReadMemoryDword(process,
addressThunk +
(ulong)baseAddress + (ulong)i * 4);
while (newAddress != 0)
{
// Add this new address
AddressOfData.Add(newAddress & 0x7fffffff);
Names.Add("");
ImportTableAddresses.Add((UInt64)addressThunk + (UInt64)baseAddress + (UInt64)i * 4);
// Read in the next value
i++;
newAddress = oMemoryFunctions.ReadMemoryDword(process,
addressThunk +
(ulong)baseAddress + (ulong)i * 4);
}
}
}
}
}
| |
namespace SPALM.SPSF.Library.CustomWizardPages
{
using System.ComponentModel;
using System.Windows.Forms;
partial class FeatureSelectionPage : SPSFBaseWizardPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.panel2 = new System.Windows.Forms.Panel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.checkBox_Hidden = new System.Windows.Forms.CheckBox();
this.textBox_FeatureTitle = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.checkBox_CreateReceiver = new System.Windows.Forms.CheckBox();
this.comboBox_Scopes = new System.Windows.Forms.ComboBox();
this.textBox_FeatureName = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox_FeatureDescription = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.infoPanel.SuspendLayout();
this.panel2.SuspendLayout();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
this.SuspendLayout();
//
// infoPanel
//
this.infoPanel.Controls.Add(this.panel1);
this.infoPanel.Location = new System.Drawing.Point(0, 41);
this.infoPanel.Size = new System.Drawing.Size(500, 309);
this.infoPanel.Controls.SetChildIndex(this.panel1, 0);
//
// panel1
//
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(500, 205);
this.panel1.TabIndex = 9;
//
// panel2
//
this.panel2.Controls.Add(this.groupBox1);
this.panel2.Controls.Add(this.comboBox1);
this.panel2.Controls.Add(this.label1);
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(495, 298);
this.panel2.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.checkBox_Hidden);
this.groupBox1.Controls.Add(this.textBox_FeatureTitle);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.checkBox_CreateReceiver);
this.groupBox1.Controls.Add(this.comboBox_Scopes);
this.groupBox1.Controls.Add(this.textBox_FeatureName);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.textBox_FeatureDescription);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Location = new System.Drawing.Point(3, 54);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(489, 236);
this.groupBox1.TabIndex = 8;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "New feature settings";
this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter);
//
// checkBox_Hidden
//
this.checkBox_Hidden.AutoSize = true;
this.checkBox_Hidden.Location = new System.Drawing.Point(10, 203);
this.checkBox_Hidden.Name = "checkBox_Hidden";
this.checkBox_Hidden.Size = new System.Drawing.Size(96, 17);
this.checkBox_Hidden.TabIndex = 12;
this.checkBox_Hidden.Text = "Hidden feature";
this.checkBox_Hidden.UseVisualStyleBackColor = true;
this.checkBox_Hidden.CheckedChanged += new System.EventHandler(this.checkBox_CreateReceiver_CheckedChanged);
//
// textBox_FeatureTitle
//
this.textBox_FeatureTitle.Location = new System.Drawing.Point(10, 74);
this.textBox_FeatureTitle.Name = "textBox_FeatureTitle";
this.textBox_FeatureTitle.Size = new System.Drawing.Size(469, 20);
this.textBox_FeatureTitle.TabIndex = 11;
this.textBox_FeatureTitle.TextChanged += new System.EventHandler(this.textBox_FeatureDescription_TextChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(7, 58);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(27, 13);
this.label5.TabIndex = 10;
this.label5.Text = "Title";
//
// checkBox_CreateReceiver
//
this.checkBox_CreateReceiver.AutoSize = true;
this.checkBox_CreateReceiver.Location = new System.Drawing.Point(10, 180);
this.checkBox_CreateReceiver.Name = "checkBox_CreateReceiver";
this.checkBox_CreateReceiver.Size = new System.Drawing.Size(139, 17);
this.checkBox_CreateReceiver.TabIndex = 9;
this.checkBox_CreateReceiver.Text = "Create FeatureReceiver";
this.checkBox_CreateReceiver.UseVisualStyleBackColor = true;
this.checkBox_CreateReceiver.CheckedChanged += new System.EventHandler(this.checkBox_CreateReceiver_CheckedChanged);
//
// comboBox_Scopes
//
this.comboBox_Scopes.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox_Scopes.FormattingEnabled = true;
this.comboBox_Scopes.Location = new System.Drawing.Point(10, 153);
this.comboBox_Scopes.Name = "comboBox_Scopes";
this.comboBox_Scopes.Size = new System.Drawing.Size(469, 21);
this.comboBox_Scopes.TabIndex = 7;
this.comboBox_Scopes.SelectedIndexChanged += new System.EventHandler(this.comboBox_Scopes_SelectedIndexChanged);
//
// textBox_FeatureName
//
this.textBox_FeatureName.Location = new System.Drawing.Point(10, 33);
this.textBox_FeatureName.Name = "textBox_FeatureName";
this.textBox_FeatureName.Size = new System.Drawing.Size(469, 20);
this.textBox_FeatureName.TabIndex = 5;
this.textBox_FeatureName.TextChanged += new System.EventHandler(this.textBox_FeatureDescription_TextChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(7, 17);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(35, 13);
this.label2.TabIndex = 2;
this.label2.Text = "Name";
//
// textBox_FeatureDescription
//
this.textBox_FeatureDescription.Location = new System.Drawing.Point(10, 113);
this.textBox_FeatureDescription.Name = "textBox_FeatureDescription";
this.textBox_FeatureDescription.Size = new System.Drawing.Size(469, 20);
this.textBox_FeatureDescription.TabIndex = 6;
this.textBox_FeatureDescription.TextChanged += new System.EventHandler(this.textBox_FeatureDescription_TextChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(7, 97);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(60, 13);
this.label3.TabIndex = 3;
this.label3.Text = "Description";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(7, 136);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(38, 13);
this.label4.TabIndex = 4;
this.label4.Text = "Scope";
//
// comboBox1
//
this.comboBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBox1.BackColor = System.Drawing.SystemColors.Window;
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(2, 19);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(490, 21);
this.comboBox1.TabIndex = 1;
this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(-1, 2);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(106, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Select parent feature";
//
// FeatureSelectionPage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.panel2);
this.Headline = "Parent Feature";
this.InfoRTBoxSize = new System.Drawing.Size(550, 50);
this.InfoRTBoxText = "Select an existing feature or create a new feature.";
this.Name = "FeatureSelectionPage";
this.Size = new System.Drawing.Size(500, 350);
this.StepTitle = "Parent Feature";
this.Controls.SetChildIndex(this.infoPanel, 0);
this.Controls.SetChildIndex(this.panel2, 0);
this.infoPanel.ResumeLayout(false);
this.infoPanel.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Panel panel1;
private Panel panel2;
private ComboBox comboBox1;
private Label label1;
private Label label2;
private TextBox textBox_FeatureDescription;
private TextBox textBox_FeatureName;
private Label label4;
private Label label3;
private GroupBox groupBox1;
private ComboBox comboBox_Scopes;
private CheckBox checkBox_CreateReceiver;
private TextBox textBox_FeatureTitle;
private Label label5;
private CheckBox checkBox_Hidden;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// 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 Xunit;
using System.IO;
using System.Xml;
using System.Data.SqlTypes;
using System.Globalization;
using System.Xml.Serialization;
namespace System.Data.Tests.SqlTypes
{
public class SqlCharsTest
{
private CultureInfo _originalCulture;
// Test constructor
[Fact]
public void SqlCharsItem()
{
SqlChars chars = new SqlChars();
try
{
Assert.Equal(0, chars[0]);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(SqlNullValueException), ex.GetType());
}
char[] b = null;
chars = new SqlChars(b);
try
{
Assert.Equal(0, chars[0]);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(SqlNullValueException), ex.GetType());
}
b = new char[10];
chars = new SqlChars(b);
Assert.Equal(0, chars[0]);
try
{
Assert.Equal(0, chars[-1]);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType());
}
try
{
Assert.Equal(0, chars[10]);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType());
}
}
[Fact]
public void SqlCharsLength()
{
char[] b = null;
SqlChars chars = new SqlChars();
try
{
Assert.Equal(0, chars.Length);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(SqlNullValueException), ex.GetType());
}
chars = new SqlChars(b);
try
{
Assert.Equal(0, chars.Length);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(SqlNullValueException), ex.GetType());
}
b = new char[10];
chars = new SqlChars(b);
Assert.Equal(10, chars.Length);
}
[Fact]
public void SqlCharsMaxLength()
{
char[] b = null;
SqlChars chars = new SqlChars();
Assert.Equal(chars.MaxLength, -1);
chars = new SqlChars(b);
Assert.Equal(chars.MaxLength, -1);
b = new char[10];
chars = new SqlChars(b);
Assert.Equal(10, chars.MaxLength);
}
[Fact]
public void SqlCharsNull()
{
char[] b = null;
SqlChars chars = SqlChars.Null;
Assert.True(chars.IsNull);
}
[Fact]
public void SqlCharsStorage()
{
char[] b = null;
SqlChars chars = new SqlChars();
try
{
Assert.Equal(StorageState.Buffer, chars.Storage);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(SqlNullValueException), ex.GetType());
}
chars = new SqlChars(b);
try
{
Assert.Equal(StorageState.Buffer, chars.Storage);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(SqlNullValueException), ex.GetType());
}
b = new char[10];
chars = new SqlChars(b);
Assert.Equal(StorageState.Buffer, chars.Storage);
}
[Fact]
public void SqlCharsValue()
{
char[] b1 = new char[10];
SqlChars chars = new SqlChars(b1);
char[] b2 = chars.Value;
Assert.Equal(b1[0], b2[0]);
b2[0] = '1';
Assert.Equal(0, b1[0]);
Assert.Equal('1', b2[0]);
}
[Fact]
public void SqlCharsSetLength()
{
char[] b1 = new char[10];
SqlChars chars = new SqlChars();
try
{
chars.SetLength(20);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(SqlTypeException), ex.GetType());
}
chars = new SqlChars(b1);
Assert.Equal(10, chars.Length);
try
{
chars.SetLength(-1);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType());
}
try
{
chars.SetLength(11);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(ArgumentOutOfRangeException), ex.GetType());
}
chars.SetLength(2);
Assert.Equal(2, chars.Length);
}
[Fact]
public void SqlCharsSetNull()
{
char[] b1 = new char[10];
SqlChars chars = new SqlChars(b1);
Assert.Equal(10, chars.Length);
chars.SetNull();
try
{
Assert.Equal(10, chars.Length);
Assert.False(true);
}
catch (Exception ex)
{
Assert.Equal(typeof(SqlNullValueException), ex.GetType());
}
Assert.True(chars.IsNull);
}
[Fact]
public void GetXsdTypeTest()
{
XmlQualifiedName qualifiedName = SqlChars.GetXsdType(null);
Assert.Equal("string", qualifiedName.Name);
}
internal void ReadWriteXmlTestInternal(string xml,
string testval,
string unit_test_id)
{
SqlString test;
SqlString test1;
XmlSerializer ser;
StringWriter sw;
XmlTextWriter xw;
StringReader sr;
XmlTextReader xr;
test = new SqlString(testval);
ser = new XmlSerializer(typeof(SqlString));
sw = new StringWriter();
xw = new XmlTextWriter(sw);
ser.Serialize(xw, test);
Assert.Equal(xml, sw.ToString());
sr = new StringReader(xml);
xr = new XmlTextReader(sr);
test1 = (SqlString)ser.Deserialize(xr);
Assert.Equal(testval, test1.Value);
}
[Fact]
public void ReadWriteXmlTest()
{
string xml1 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><string>This is a test string</string>";
string xml2 = "<?xml version=\"1.0\" encoding=\"utf-16\"?><string>a</string>";
string strtest1 = "This is a test string";
char strtest2 = 'a';
ReadWriteXmlTestInternal(xml1, strtest1, "BA01");
ReadWriteXmlTestInternal(xml2, strtest2.ToString(), "BA02");
}
/* Read tests */
[Fact]
public void Read_SuccessTest1()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars(c1);
char[] c2 = new char[10];
chars.Read(0, c2, 0, (int)chars.Length);
Assert.Equal(chars.Value[5], c2[5]);
}
[Fact]
public void Read_NullBufferTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars(c1);
char[] c2 = null;
Assert.Throws<ArgumentNullException>(() => chars.Read(0, c2, 0, 10));
}
[Fact]
public void Read_InvalidCountTest1()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars(c1);
char[] c2 = new char[5];
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Read(0, c2, 0, 10));
}
[Fact]
public void Read_NegativeOffsetTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars(c1);
char[] c2 = new char[5];
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Read(-1, c2, 0, 4));
}
[Fact]
public void Read_NegativeOffsetInBufferTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars(c1);
char[] c2 = new char[5];
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Read(0, c2, -1, 4));
}
[Fact]
public void Read_InvalidOffsetInBufferTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars(c1);
char[] c2 = new char[5];
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Read(0, c2, 8, 4));
}
[Fact]
public void Read_NullInstanceValueTest()
{
char[] c2 = new char[5];
SqlChars chars = new SqlChars();
Assert.Throws<SqlNullValueException>(() => chars.Read(0, c2, 8, 4));
}
[Fact]
public void Read_SuccessTest2()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars(c1);
char[] c2 = new char[10];
chars.Read(5, c2, 0, 10);
Assert.Equal(chars.Value[5], c2[0]);
Assert.Equal(chars.Value[9], c2[4]);
}
[Fact]
public void Read_NullBufferAndInstanceValueTest()
{
char[] c2 = null;
SqlChars chars = new SqlChars();
Assert.Throws<SqlNullValueException>(() => chars.Read(0, c2, 8, 4));
}
[Fact]
public void Read_NegativeCountTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars(c1);
char[] c2 = new char[5];
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Read(0, c2, 0, -1));
}
[Fact]
public void Read_InvalidCountTest2()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars(c1);
char[] c2 = new char[5];
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Read(0, c2, 3, 4));
}
[Fact]
public void Write_SuccessTest1()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[10];
SqlChars chars = new SqlChars(c2);
chars.Write(0, c1, 0, c1.Length);
Assert.Equal(chars.Value[0], c1[0]);
}
[Fact]
public void Write_NegativeOffsetTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[10];
SqlChars chars = new SqlChars(c2);
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Write(-1, c1, 0, c1.Length));
}
[Fact]
public void Write_InvalidOffsetTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[10];
SqlChars chars = new SqlChars(c2);
Assert.Throws<SqlTypeException>(() => chars.Write(chars.Length + 5, c1, 0, c1.Length));
}
[Fact]
public void Write_NegativeOffsetInBufferTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[10];
SqlChars chars = new SqlChars(c2);
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Write(0, c1, -1, c1.Length));
}
[Fact]
public void Write_InvalidOffsetInBufferTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[10];
SqlChars chars = new SqlChars(c2);
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Write(0, c1, c1.Length + 5, c1.Length));
}
[Fact]
public void Write_InvalidCountTest1()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[10];
SqlChars chars = new SqlChars(c2);
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Write(0, c1, 0, c1.Length + 5));
}
[Fact]
public void Write_InvalidCountTest2()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[10];
SqlChars chars = new SqlChars(c2);
Assert.Throws<SqlTypeException>(() => chars.Write(8, c1, 0, c1.Length));
}
[Fact]
public void Write_NullBufferTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = null;
SqlChars chars = new SqlChars(c1);
Assert.Throws<ArgumentNullException>(() => chars.Write(0, c2, 0, 10));
}
[Fact]
public void Write_NullInstanceValueTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
SqlChars chars = new SqlChars();
Assert.Throws<SqlTypeException>(() => chars.Write(0, c1, 0, 10));
}
[Fact]
public void Write_NullBufferAndInstanceValueTest()
{
char[] c1 = null;
SqlChars chars = new SqlChars();
Assert.Throws<ArgumentNullException>(() => chars.Write(0, c1, 0, 10));
}
[Fact]
public void Write_SuccessTest2()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[20];
SqlChars chars = new SqlChars(c2);
chars.Write(8, c1, 0, 10);
Assert.Equal(chars.Value[8], c1[0]);
Assert.Equal(chars.Value[17], c1[9]);
}
[Fact]
public void Write_NegativeCountTest()
{
char[] c1 = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
char[] c2 = new char[10];
SqlChars chars = new SqlChars(c2);
Assert.Throws<ArgumentOutOfRangeException>(() => chars.Write(0, c1, 0, -1));
}
}
}
| |
namespace android.location
{
[global::MonoJavaBridge.JavaClass()]
public partial class Location : java.lang.Object, android.os.Parcelable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Location(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.location.Location.staticClass, "toString", "()Ljava/lang/String;", ref global::android.location.Location._m0) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual void set(android.location.Location arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "set", "(Landroid/location/Location;)V", ref global::android.location.Location._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m2;
public virtual void reset()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "reset", "()V", ref global::android.location.Location._m2);
}
private static global::MonoJavaBridge.MethodId _m3;
public virtual void setTime(long arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "setTime", "(J)V", ref global::android.location.Location._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new long Time
{
get
{
return getTime();
}
set
{
setTime(value);
}
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual long getTime()
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.location.Location.staticClass, "getTime", "()J", ref global::android.location.Location._m4);
}
public new global::java.lang.String Provider
{
get
{
return getProvider();
}
set
{
setProvider(value);
}
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual global::java.lang.String getProvider()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.location.Location.staticClass, "getProvider", "()Ljava/lang/String;", ref global::android.location.Location._m5) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m6;
public static double convert(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.location.Location._m6.native == global::System.IntPtr.Zero)
global::android.location.Location._m6 = @__env.GetStaticMethodIDNoThrow(global::android.location.Location.staticClass, "convert", "(Ljava/lang/String;)D");
return @__env.CallStaticDoubleMethod(android.location.Location.staticClass, global::android.location.Location._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public static global::java.lang.String convert(double arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.location.Location._m7.native == global::System.IntPtr.Zero)
global::android.location.Location._m7 = @__env.GetStaticMethodIDNoThrow(global::android.location.Location.staticClass, "convert", "(DI)Ljava/lang/String;");
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.location.Location.staticClass, global::android.location.Location._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m8;
public virtual void dump(android.util.Printer arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "dump", "(Landroid/util/Printer;Ljava/lang/String;)V", ref global::android.location.Location._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void dump(global::android.util.PrinterDelegate arg0, java.lang.String arg1)
{
dump((global::android.util.PrinterDelegateWrapper)arg0, arg1);
}
private static global::MonoJavaBridge.MethodId _m9;
public virtual void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.location.Location._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m10;
public virtual int describeContents()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.location.Location.staticClass, "describeContents", "()I", ref global::android.location.Location._m10);
}
public new global::android.os.Bundle Extras
{
get
{
return getExtras();
}
set
{
setExtras(value);
}
}
private static global::MonoJavaBridge.MethodId _m11;
public virtual global::android.os.Bundle getExtras()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.os.Bundle>(this, global::android.location.Location.staticClass, "getExtras", "()Landroid/os/Bundle;", ref global::android.location.Location._m11) as android.os.Bundle;
}
public new double Latitude
{
get
{
return getLatitude();
}
set
{
setLatitude(value);
}
}
private static global::MonoJavaBridge.MethodId _m12;
public virtual double getLatitude()
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::android.location.Location.staticClass, "getLatitude", "()D", ref global::android.location.Location._m12);
}
private static global::MonoJavaBridge.MethodId _m13;
public virtual void setLatitude(double arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "setLatitude", "(D)V", ref global::android.location.Location._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new double Longitude
{
get
{
return getLongitude();
}
set
{
setLongitude(value);
}
}
private static global::MonoJavaBridge.MethodId _m14;
public virtual double getLongitude()
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::android.location.Location.staticClass, "getLongitude", "()D", ref global::android.location.Location._m14);
}
private static global::MonoJavaBridge.MethodId _m15;
public virtual void setLongitude(double arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "setLongitude", "(D)V", ref global::android.location.Location._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m16;
public virtual void setExtras(android.os.Bundle arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "setExtras", "(Landroid/os/Bundle;)V", ref global::android.location.Location._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m17;
public virtual void setAccuracy(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "setAccuracy", "(F)V", ref global::android.location.Location._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public new float Accuracy
{
get
{
return getAccuracy();
}
set
{
setAccuracy(value);
}
}
private static global::MonoJavaBridge.MethodId _m18;
public virtual float getAccuracy()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.location.Location.staticClass, "getAccuracy", "()F", ref global::android.location.Location._m18);
}
private static global::MonoJavaBridge.MethodId _m19;
public static void distanceBetween(double arg0, double arg1, double arg2, double arg3, float[] arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.location.Location._m19.native == global::System.IntPtr.Zero)
global::android.location.Location._m19 = @__env.GetStaticMethodIDNoThrow(global::android.location.Location.staticClass, "distanceBetween", "(DDDD[F)V");
@__env.CallStaticVoidMethod(android.location.Location.staticClass, global::android.location.Location._m19, 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));
}
private static global::MonoJavaBridge.MethodId _m20;
public virtual float distanceTo(android.location.Location arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.location.Location.staticClass, "distanceTo", "(Landroid/location/Location;)F", ref global::android.location.Location._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m21;
public virtual float bearingTo(android.location.Location arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.location.Location.staticClass, "bearingTo", "(Landroid/location/Location;)F", ref global::android.location.Location._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m22;
public virtual void setProvider(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "setProvider", "(Ljava/lang/String;)V", ref global::android.location.Location._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m23;
public virtual bool hasAltitude()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.location.Location.staticClass, "hasAltitude", "()Z", ref global::android.location.Location._m23);
}
public new double Altitude
{
get
{
return getAltitude();
}
set
{
setAltitude(value);
}
}
private static global::MonoJavaBridge.MethodId _m24;
public virtual double getAltitude()
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::android.location.Location.staticClass, "getAltitude", "()D", ref global::android.location.Location._m24);
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual void setAltitude(double arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "setAltitude", "(D)V", ref global::android.location.Location._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual void removeAltitude()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "removeAltitude", "()V", ref global::android.location.Location._m26);
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual bool hasSpeed()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.location.Location.staticClass, "hasSpeed", "()Z", ref global::android.location.Location._m27);
}
public new float Speed
{
get
{
return getSpeed();
}
set
{
setSpeed(value);
}
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual float getSpeed()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.location.Location.staticClass, "getSpeed", "()F", ref global::android.location.Location._m28);
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual void setSpeed(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "setSpeed", "(F)V", ref global::android.location.Location._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m30;
public virtual void removeSpeed()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "removeSpeed", "()V", ref global::android.location.Location._m30);
}
private static global::MonoJavaBridge.MethodId _m31;
public virtual bool hasBearing()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.location.Location.staticClass, "hasBearing", "()Z", ref global::android.location.Location._m31);
}
public new float Bearing
{
get
{
return getBearing();
}
set
{
setBearing(value);
}
}
private static global::MonoJavaBridge.MethodId _m32;
public virtual float getBearing()
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.location.Location.staticClass, "getBearing", "()F", ref global::android.location.Location._m32);
}
private static global::MonoJavaBridge.MethodId _m33;
public virtual void setBearing(float arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "setBearing", "(F)V", ref global::android.location.Location._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
public virtual void removeBearing()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "removeBearing", "()V", ref global::android.location.Location._m34);
}
private static global::MonoJavaBridge.MethodId _m35;
public virtual bool hasAccuracy()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.location.Location.staticClass, "hasAccuracy", "()Z", ref global::android.location.Location._m35);
}
private static global::MonoJavaBridge.MethodId _m36;
public virtual void removeAccuracy()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.location.Location.staticClass, "removeAccuracy", "()V", ref global::android.location.Location._m36);
}
private static global::MonoJavaBridge.MethodId _m37;
public Location(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.location.Location._m37.native == global::System.IntPtr.Zero)
global::android.location.Location._m37 = @__env.GetMethodIDNoThrow(global::android.location.Location.staticClass, "<init>", "(Ljava/lang/String;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.location.Location.staticClass, global::android.location.Location._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m38;
public Location(android.location.Location arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.location.Location._m38.native == global::System.IntPtr.Zero)
global::android.location.Location._m38 = @__env.GetMethodIDNoThrow(global::android.location.Location.staticClass, "<init>", "(Landroid/location/Location;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.location.Location.staticClass, global::android.location.Location._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int FORMAT_DEGREES
{
get
{
return 0;
}
}
public static int FORMAT_MINUTES
{
get
{
return 1;
}
}
public static int FORMAT_SECONDS
{
get
{
return 2;
}
}
internal static global::MonoJavaBridge.FieldId _CREATOR2612;
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.location.Location.staticClass, _CREATOR2612)) as android.os.Parcelable_Creator;
}
}
static Location()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.location.Location.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/location/Location"));
global::android.location.Location._CREATOR2612 = @__env.GetStaticFieldIDNoThrow(global::android.location.Location.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Scrumfish.WebApi.v2.ApiSite.Areas.HelpPage.ModelDescriptions;
using Scrumfish.WebApi.v2.ApiSite.Areas.HelpPage.Models;
namespace Scrumfish.WebApi.v2.ApiSite.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// <copyright file="By.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
/// <summary>
/// Provides a mechanism by which to find elements within a document.
/// </summary>
/// <remarks>It is possible to create your own locating mechanisms for finding documents.
/// In order to do this,subclass this class and override the protected methods. However,
/// it is expected that that all subclasses rely on the basic finding mechanisms provided
/// through static methods of this class. An example of this can be found in OpenQA.Support.ByIdOrName
/// </remarks>
[Serializable]
public class By
{
private string description = "OpenQA.Selenium.By";
private string mechanism = string.Empty;
private string criteria = string.Empty;
private Func<ISearchContext, IWebElement> findElementMethod;
private Func<ISearchContext, ReadOnlyCollection<IWebElement>> findElementsMethod;
/// <summary>
/// Initializes a new instance of the <see cref="By"/> class.
/// </summary>
protected By()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="By"/> class using the given functions to find elements.
/// </summary>
/// <param name="findElementMethod">A function that takes an object implementing <see cref="ISearchContext"/>
/// and returns the found <see cref="IWebElement"/>.</param>
/// <param name="findElementsMethod">A function that takes an object implementing <see cref="ISearchContext"/>
/// and returns a <see cref="ReadOnlyCollection{T}"/> of the found<see cref="IWebElement">IWebElements</see>.
/// <see cref="IWebElement">IWebElements</see>/>.</param>
protected By(Func<ISearchContext, IWebElement> findElementMethod, Func<ISearchContext, ReadOnlyCollection<IWebElement>> findElementsMethod)
{
this.findElementMethod = findElementMethod;
this.findElementsMethod = findElementsMethod;
}
/// <summary>
/// Gets the value of the mechanism for this <see cref="By"/> class instance.
/// </summary>
public string Mechanism
{
get { return this.mechanism; }
}
/// <summary>
/// Gets the value of the criteria for this <see cref="By"/> class instance.
/// </summary>
public string Criteria
{
get { return this.criteria; }
}
/// <summary>
/// Gets or sets the value of the description for this <see cref="By"/> class instance.
/// </summary>
protected string Description
{
get { return this.description; }
set { this.description = value; }
}
/// <summary>
/// Gets or sets the method used to find a single element matching specified criteria.
/// </summary>
protected Func<ISearchContext, IWebElement> FindElementMethod
{
get { return this.findElementMethod; }
set { this.findElementMethod = value; }
}
/// <summary>
/// Gets or sets the method used to find all elements matching specified criteria.
/// </summary>
protected Func<ISearchContext, ReadOnlyCollection<IWebElement>> FindElementsMethod
{
get { return this.findElementsMethod; }
set { this.findElementsMethod = value; }
}
/// <summary>
/// Determines if two <see cref="By"/> instances are equal.
/// </summary>
/// <param name="one">One instance to compare.</param>
/// <param name="two">The other instance to compare.</param>
/// <returns><see langword="true"/> if the two instances are equal; otherwise, <see langword="false"/>.</returns>
public static bool operator ==(By one, By two)
{
// If both are null, or both are same instance, return true.
if (object.ReferenceEquals(one, two))
{
return true;
}
// If one is null, but not both, return false.
if (((object)one == null) || ((object)two == null))
{
return false;
}
return one.Equals(two);
}
/// <summary>
/// Determines if two <see cref="By"/> instances are unequal.
/// </summary>s
/// <param name="one">One instance to compare.</param>
/// <param name="two">The other instance to compare.</param>
/// <returns><see langword="true"/> if the two instances are not equal; otherwise, <see langword="false"/>.</returns>
public static bool operator !=(By one, By two)
{
return !(one == two);
}
/// <summary>
/// Gets a mechanism to find elements by their ID.
/// </summary>
/// <param name="idToFind">The ID to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Id(string idToFind)
{
if (idToFind == null)
{
throw new ArgumentNullException("idToFind", "Cannot find elements with a null id attribute.");
}
By by = new By();
by.description = "By.Id: " + idToFind;
by.mechanism = "css selector";
string selector = By.EscapeCssSelector(idToFind);
by.criteria = "#" + selector;
by.findElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(by.mechanism, by.criteria);
if (string.IsNullOrEmpty(selector))
{
// Finding multiple elements with an empty ID will return
// an empty list. However, finding by a CSS selector of '#'
// throws an exception, even in the multiple elements case,
// which means we need to short-circuit that behavior.
by.findElementsMethod = (ISearchContext context) => new List<IWebElement>().AsReadOnly();
}
else
{
by.findElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(by.mechanism, by.criteria);
}
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their link text.
/// </summary>
/// <param name="linkTextToFind">The link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By LinkText(string linkTextToFind)
{
if (linkTextToFind == null)
{
throw new ArgumentNullException("linkTextToFind", "Cannot find elements when link text is null.");
}
By by = new By();
by.description = "By.LinkText: " + linkTextToFind;
by.mechanism = "link text";
by.criteria = linkTextToFind;
by.findElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(by.mechanism, by.criteria);
by.findElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(by.mechanism, by.criteria);
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their name.
/// </summary>
/// <param name="nameToFind">The name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Name(string nameToFind)
{
if (nameToFind == null)
{
throw new ArgumentNullException("nameToFind", "Cannot find elements when name text is null.");
}
By by = new By();
by.description = "By.Name: " + nameToFind;
by.mechanism = "css selector";
by.criteria = "*[name =\"" + By.EscapeCssSelector(nameToFind) + "\"]";
by.findElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(by.mechanism, by.criteria);
by.findElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(by.mechanism, by.criteria);
return by;
}
/// <summary>
/// Gets a mechanism to find elements by an XPath query.
/// When searching within a WebElement using xpath be aware that WebDriver follows standard conventions:
/// a search prefixed with "//" will search the entire document, not just the children of this current node.
/// Use ".//" to limit your search to the children of this WebElement.
/// </summary>
/// <param name="xpathToFind">The XPath query to use.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By XPath(string xpathToFind)
{
if (xpathToFind == null)
{
throw new ArgumentNullException("xpathToFind", "Cannot find elements when the XPath expression is null.");
}
By by = new By();
by.description = "By.XPath: " + xpathToFind;
by.mechanism = "xpath";
by.criteria = xpathToFind;
by.findElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(by.mechanism, by.criteria);
by.findElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(by.mechanism, by.criteria);
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their CSS class.
/// </summary>
/// <param name="classNameToFind">The CSS class to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
/// <remarks>If an element has many classes then this will match against each of them.
/// For example if the value is "one two onone", then the following values for the
/// className parameter will match: "one" and "two".</remarks>
public static By ClassName(string classNameToFind)
{
if (classNameToFind == null)
{
throw new ArgumentNullException("classNameToFind", "Cannot find elements when the class name expression is null.");
}
By by = new By();
by.description = "By.ClassName[Contains]: " + classNameToFind;
by.mechanism = "css selector";
by.criteria = "." + By.EscapeCssSelector(classNameToFind);
if (by.criteria.Contains(" "))
{
// Finding elements by class name with whitespace is not allowed.
// However, converting the single class name to a valid CSS selector
// by prepending a '.' may result in a still-valid, but incorrect
// selector. Thus, we short-ciruit that behavior here.
throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
}
by.findElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(by.mechanism, by.criteria);
by.findElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(by.mechanism, by.criteria);
return by;
}
/// <summary>
/// Gets a mechanism to find elements by a partial match on their link text.
/// </summary>
/// <param name="partialLinkTextToFind">The partial link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By PartialLinkText(string partialLinkTextToFind)
{
if (partialLinkTextToFind == null)
{
throw new ArgumentNullException("partialLinkTextToFind", "Cannot find elements when partial link text is null.");
}
By by = new By();
by.description = "By.PartialLinkText: " + partialLinkTextToFind;
by.mechanism = "partial link text";
by.criteria = partialLinkTextToFind;
by.findElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(by.mechanism, by.criteria);
by.findElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(by.mechanism, by.criteria);
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their tag name.
/// </summary>
/// <param name="tagNameToFind">The tag name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By TagName(string tagNameToFind)
{
if (tagNameToFind == null)
{
throw new ArgumentNullException("tagNameToFind", "Cannot find elements when name tag name is null.");
}
By by = new By();
by.description = "By.TagName: " + tagNameToFind;
by.mechanism = "css selector";
by.criteria = tagNameToFind;
by.findElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(by.mechanism, by.criteria);
by.findElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(by.mechanism, by.criteria);
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their cascading style sheet (CSS) selector.
/// </summary>
/// <param name="cssSelectorToFind">The CSS selector to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By CssSelector(string cssSelectorToFind)
{
if (cssSelectorToFind == null)
{
throw new ArgumentNullException("cssSelectorToFind", "Cannot find elements when name CSS selector is null.");
}
By by = new By();
by.description = "By.CssSelector: " + cssSelectorToFind;
by.mechanism = "css selector";
by.criteria = cssSelectorToFind;
by.findElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(by.mechanism, by.criteria);
by.findElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(by.mechanism, by.criteria);
return by;
}
/// <summary>
/// Finds the first element matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
public virtual IWebElement FindElement(ISearchContext context)
{
return this.findElementMethod(context);
}
/// <summary>
/// Finds all elements matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElements(ISearchContext context)
{
return this.findElementsMethod(context);
}
/// <summary>
/// Gets a string representation of the finder.
/// </summary>
/// <returns>The string displaying the finder content.</returns>
public override string ToString()
{
return this.description;
}
/// <summary>
/// Determines whether the specified <see cref="object">Object</see> is equal
/// to the current <see cref="object">Object</see>.
/// </summary>
/// <param name="obj">The <see cref="object">Object</see> to compare with the
/// current <see cref="object">Object</see>.</param>
/// <returns><see langword="true"/> if the specified <see cref="object">Object</see>
/// is equal to the current <see cref="object">Object</see>; otherwise,
/// <see langword="false"/>.</returns>
public override bool Equals(object obj)
{
var other = obj as By;
// TODO(dawagner): This isn't ideal
return other != null && this.description.Equals(other.description);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>A hash code for the current <see cref="object">Object</see>.</returns>
public override int GetHashCode()
{
return this.description.GetHashCode();
}
/// <summary>
/// Escapes invalid characters in a CSS selector.
/// </summary>
/// <param name="selector">The selector to escape.</param>
/// <returns>The selector with invalid characters escaped.</returns>
internal static string EscapeCssSelector(string selector)
{
string escaped = Regex.Replace(selector, @"([ '""\\#.:;,!?+<>=~*^$|%&@`{}\-/\[\]\(\)])", @"\$1");
if (selector.Length > 0 && char.IsDigit(selector[0]))
{
escaped = @"\" + (30 + int.Parse(selector.Substring(0, 1), CultureInfo.InvariantCulture)).ToString(CultureInfo.InvariantCulture) + " " + selector.Substring(1);
}
return escaped;
}
}
}
| |
// 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 Test.Cryptography;
namespace System.Security.Cryptography.Pkcs.Tests
{
internal static class Certificates
{
public static readonly CertLoader RSAKeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer1Cer, RawData.s_RSAKeyTransfer1Pfx, "1111");
public static readonly CertLoader RSAKeyTransfer2 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer2Cer, RawData.s_RSAKeyTransfer2Pfx, "1111");
public static readonly CertLoader RSAKeyTransfer3 = new CertLoaderFromRawData(RawData.s_RSAKeyTransfer3Cer, RawData.s_RSAKeyTransfer3Pfx, "1111");
public static readonly CertLoader RSAKeyTransferCapi1 = new CertLoaderFromRawData(RawData.s_RSAKeyTransferCapi1Cer, RawData.s_RSAKeyTransferCapi1Pfx, "1111");
public static readonly CertLoader RSASha256KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSASha256KeyTransfer1Cer, RawData.s_RSASha256KeyTransfer1Pfx, "1111");
public static readonly CertLoader RSASha384KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSASha384KeyTransfer1Cer, RawData.s_RSASha384KeyTransfer1Pfx, "1111");
public static readonly CertLoader RSASha512KeyTransfer1 = new CertLoaderFromRawData(RawData.s_RSASha512KeyTransfer1Cer, RawData.s_RSASha512KeyTransfer1Pfx, "1111");
public static readonly CertLoader DHKeyAgree1 = new CertLoaderFromRawData(RawData.s_DHKeyAgree1Cer);
public static readonly CertLoader RSA2048SignatureOnly = new CertLoaderFromRawData(RawData.s_Rsa2048SignatureOnlyCer, RawData.s_Rsa2048SignatureOnlyPfx, "12345");
public static readonly CertLoader Dsa1024 = new CertLoaderFromRawData(RawData.s_dsa1024Cert, RawData.s_dsa1024Pfx, "1234");
public static readonly CertLoader ECDsaP256Win = new CertLoaderFromRawData(RawData.ECDsaP256_DigitalSignature_Cert, RawData.ECDsaP256_DigitalSignature_Pfx_Windows, "Test");
// Note: the raw data is its own (nested) class to avoid problems with static field initialization ordering.
private static class RawData
{
public static byte[] s_RSAKeyTransfer1Cer =
("308201c830820131a003020102021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657231301e170d3136303431323136323534375a170d31373034313232"
+ "32323534375a301a311830160603550403130f5253414b65795472616e736665723130819f300d06092a864886f70d010101"
+ "050003818d00308189028181009eaab63f5629db5ac0bd74300b43ba61f49189ccc30c001fa96bd3b139f45732cd3c37e422"
+ "ccbb2c598a4c6b3977a516a36ff850a5e914331f7445e86973f5a6cbb590105e933306e240eab6db72d08430cd7316e99481"
+ "a272adef0f2479d0b7c58e89e072364d660fdad1b51a603ff4549a82e8dc914df82bcc6c6c232985450203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d01010505000381810048c83e6f45d73a111c67e8f9f9c2d646292b"
+ "75cec52ef0f9ae3e1639504aa1759512c46527fcf5476897d3fb6fc515ff1646f8f8bc09f84ea6e2ad04242d3fb9b190b816"
+ "86b73d334e8b3afa7fb8eb31483efc0c7ccb0f8c1ca94d8be4f0daade4498501d02e6f92dd7b2f4401550896eb511ef14417"
+ "cbb5a1b360d67998d334").HexToByteArray();
// password = "1111"
public static byte[] s_RSAKeyTransfer1Pfx =
("308205d20201033082058e06092a864886f70d010701a082057f0482057b308205773082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e040818fdedadbb31b101020207d0048202806aa390fa9a4cb071a0daf25765ed69efe039896036c0f0edfc03ebe35d2a"
+ "f2f6a5bc9efd907f3b64ae15ac7f61d830e48810aa096ee37fe442b7bfbceeb92e22c25bd5484baf91460be29e06648485db"
+ "7b10ea92d17983c4d22067396c12e4598541ab989d7beb38bf8a0213fd7c9d49ecd46d319bbb58b1423504cd4145e1b33978"
+ "41306c5ace9eab42d408e05101911adc684e63a8c8c9579ce929e48ce2393af1a63c3180c52bd87475e3edb9763dff731ede"
+ "38fc8043dee375001a59e7d6eec5d686d509efee38ef0e7bddcd7ba0477f6f38ff7172ceaeef94ff56ad4b9533241f404d58"
+ "c2b5d54f1ab8250c56b1a70f57b7fffc640b7037408b8f830263befc031ffe7dbc6bef23f02c1e6e2b541be12009bfb11297"
+ "02fc0559e54d264df9b0d046c73ad1b25056231e5d3c4015bdc4f0a9af70ac28b7241233ecc845ce14484779102a45da2560"
+ "c354ec3e01f26d0e0b9a8b650f811d2ffeba95ec1e5cf6be2d060788c1b18ea4ec8f41e46da734c1216044a10a3e171620ed"
+ "79f7e9dd36972c89d91111c68fd60a94d2aa2a3dbbde0383c7c367f77b70a218ddf9fb4ed7abf94c233ffb2797d9ca3802ed"
+ "77868d3ab5651abb90e4de9ea74854b13603859b308689d770a62b5821e5a5650ecb23ca2894ad7901c7e1d2f22ef97e9092"
+ "f0791e886487a59d380d98c0368d3f2f261e0139714b02010e61aa073ee782b1fe5b6f79d070ef1412a13270138330a2e308"
+ "599e1e7829be9f983202ac0dc1c38d38587defe2741903af35227e4f979a68adef86a8459be4a2d74e5de7f94e114a8ea7e4"
+ "0ea2af6b8a93a747377bdd8ddd83c086bb20ca49854efb931ee689b319f984e5377f5a0f20d0a613326d749af00675c6bc06"
+ "0be528ef90ec6a9b2f9b3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082022706092a864886f70d010701a0820218048202"
+ "14308202103082020c060b2a864886f70d010c0a0103a08201e4308201e0060a2a864886f70d01091601a08201d0048201cc"
+ "308201c830820131a003020102021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657231301e170d3136303431323136323534375a170d31373034313232"
+ "32323534375a301a311830160603550403130f5253414b65795472616e736665723130819f300d06092a864886f70d010101"
+ "050003818d00308189028181009eaab63f5629db5ac0bd74300b43ba61f49189ccc30c001fa96bd3b139f45732cd3c37e422"
+ "ccbb2c598a4c6b3977a516a36ff850a5e914331f7445e86973f5a6cbb590105e933306e240eab6db72d08430cd7316e99481"
+ "a272adef0f2479d0b7c58e89e072364d660fdad1b51a603ff4549a82e8dc914df82bcc6c6c232985450203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d01010505000381810048c83e6f45d73a111c67e8f9f9c2d646292b"
+ "75cec52ef0f9ae3e1639504aa1759512c46527fcf5476897d3fb6fc515ff1646f8f8bc09f84ea6e2ad04242d3fb9b190b816"
+ "86b73d334e8b3afa7fb8eb31483efc0c7ccb0f8c1ca94d8be4f0daade4498501d02e6f92dd7b2f4401550896eb511ef14417"
+ "cbb5a1b360d67998d3343115301306092a864886f70d0109153106040401000000303b301f300706052b0e03021a0414c4c0"
+ "4e0c0b0a20e50d58cb5ce565ba7c192d5d3f041479b53fc5f1f1f493a02cf113d563a247462e8726020207d0").HexToByteArray();
public static byte[] s_RSAKeyTransfer2Cer =
("308201c830820131a00302010202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657232301e170d3136303332353231323334325a170d31373033323630"
+ "33323334325a301a311830160603550403130f5253414b65795472616e736665723230819f300d06092a864886f70d010101"
+ "050003818d0030818902818100ea5a3834bfb863ae481b696ea7010ba4492557a160a102b3b4d11c120a7128f20b656ebbd2"
+ "4b426f1a6d40be0a55ca1b53ebdca202d258eebb20d5c662819182e64539360461dd3b5dda4085f10250fc5249cf023976b8"
+ "db2bc5f5e628fdb0f26e1b11e83202cbcfc9750efd6bb4511e6211372b60a97adb984779fdae21ce070203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d0101050500038181004dc6f9fd6054ae0361d28d2d781be590fa8f"
+ "5685fedfc947e315db12a4c47e220601e8c810e84a39b05b7a89f87425a06c0202ad48b3f2713109f5815e6b5d61732dac45"
+ "41da152963e700a6f37faf7678f084a9fb4fe88f7b2cbc6cdeb0b9fdcc6a8a16843e7bc281a71dc6eb8bbc4092d299bf7599"
+ "a3492c99c9a3acf41b29").HexToByteArray();
// password = "1111"
public static byte[] s_RSAKeyTransfer2Pfx =
("308205d20201033082058e06092a864886f70d010701a082057f0482057b308205773082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e04080338620310d29656020207d0048202804a94d3b1a1bf43efe3726aa9f0abc90c44585d2f0aee0864b4d574cd2cc1"
+ "dca4a353b102779e072ed6072d3c083b83974e74069b353ba8ac8be113228e0225993f5ecb7293ab1a6941bef75f7bcb0e3b"
+ "e6902832be46b976e94c6a0bc6865822ff07371551d206e300558da67cf972d89c3d181beb86d02f5523baa8351b88992654"
+ "a4c507e136dd32120530585a25424fe40f9962b910e08fb55f582c3764946ba7f6d92520decfc9faa2d5e180f9824e5ed4c8"
+ "c57e549a27950e7a875f2ed450035a69de6d95ec7bd9e30b65b8563fdd52809a4a1fc960f75c817c72f98afb000e8a8a33be"
+ "f62e458c2db97b464121489bf3c54de45e05f9c3e06c21892735e3f2d9353a71febcd6a73a0af3c3fc0922ea71bdc483ed7e"
+ "5653740c107cfd5e101e1609c20061f864671ccb45c8b5b5b7b48436797afe19de99b5027faf4cead0fd69d1987bbda5a0a4"
+ "0141495998d368d3a4747fc370205eed9fc28e530d2975ca4084c297a544441cf46c39fb1f0f42c65b99a6c9c970746012ad"
+ "c2be15fbbc803d5243f73fdec50bdee0b74297bd30ca3ea3a1dc623db6a199e93e02053bd1a6ca1a00a5c6090de1fa10cdd5"
+ "b5541bd5f5f92ff60a139c50deff8768e7b242018611efd2cce0d9441f3c8b207906345a985617ba5e98e7883c9b925ba17d"
+ "c4fadddbbe025cecd24bb9b95cae573a8a24ceb635eb9f663e74b0084a88f4e8e0d2baf767be3abe5b873695989a0edac7bd"
+ "092de79c3b6427dcbedee0512918fc3f7a45cd6898701673c9ed9f2f873abb8aa64cec7b8d350e8c780c645e50ce607a1afd"
+ "bcefba6cf5cebbc766d1e61d78fbef7680b38dd0f32133ceb39c6c9cabd0b33af9f7ef73c94854b57cf68e61997b61393a0b"
+ "6fc37f8834157e0c9fba3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082022706092a864886f70d010701a0820218048202"
+ "14308202103082020c060b2a864886f70d010c0a0103a08201e4308201e0060a2a864886f70d01091601a08201d0048201cc"
+ "308201c830820131a00302010202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657232301e170d3136303332353231323334325a170d31373033323630"
+ "33323334325a301a311830160603550403130f5253414b65795472616e736665723230819f300d06092a864886f70d010101"
+ "050003818d0030818902818100ea5a3834bfb863ae481b696ea7010ba4492557a160a102b3b4d11c120a7128f20b656ebbd2"
+ "4b426f1a6d40be0a55ca1b53ebdca202d258eebb20d5c662819182e64539360461dd3b5dda4085f10250fc5249cf023976b8"
+ "db2bc5f5e628fdb0f26e1b11e83202cbcfc9750efd6bb4511e6211372b60a97adb984779fdae21ce070203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d0101050500038181004dc6f9fd6054ae0361d28d2d781be590fa8f"
+ "5685fedfc947e315db12a4c47e220601e8c810e84a39b05b7a89f87425a06c0202ad48b3f2713109f5815e6b5d61732dac45"
+ "41da152963e700a6f37faf7678f084a9fb4fe88f7b2cbc6cdeb0b9fdcc6a8a16843e7bc281a71dc6eb8bbc4092d299bf7599"
+ "a3492c99c9a3acf41b293115301306092a864886f70d0109153106040401000000303b301f300706052b0e03021a04143cdb"
+ "6a36dfd2288ba4e3771766d7a5289c04419704146c84193dc4f3778f21197d11ff994d8bf4822049020207d0").HexToByteArray();
public static byte[] s_RSAKeyTransfer3Cer =
("308201c830820131a00302010202104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657233301e170d3136303332353231323335355a170d31373033323630"
+ "33323335355a301a311830160603550403130f5253414b65795472616e736665723330819f300d06092a864886f70d010101"
+ "050003818d0030818902818100bbc6fe8702a4e92eadb9b0f41577c0fffc731411c6f87c27c9ef7c2e2113d4269574f44f2e"
+ "90382bd193eb2f57564cf00092172d91a003e7252a544958b30aab6402e6fba7e442e973d1902e383f6bc4a4d8a00e60b3f3"
+ "3a032bdf6bedb56acb0d08669b71dd7b35f5d39d9914f5e111e1cd1559eb741a3075d673c39e7850a50203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d01010505000381810058abccbf69346360351d55817a61a6091b0b"
+ "022607caeb44edb6f05a91f169903608d7391b245ac0dcbe052e16a91ac1f8d9533f19f6793f15cb6681b2cbaa0d8e83d77b"
+ "5207e7c70d843deda8754af8ef1029e0b68c35d88c30d7da2f85d1a20dd4099facf373341b50a8a213f735421062e1477459"
+ "6e27a32e23b3f3fcfec3").HexToByteArray();
// password = "1111"
public static byte[] s_RSAKeyTransfer3Pfx =
("308205d20201033082058e06092a864886f70d010701a082057f0482057b308205773082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e0408a9197ad512c316b5020207d004820280b1c213fa87f3906cde3502249830a01d1d636d0058bd8d6172222544c35a"
+ "9676f390a5ef1d52f13fae2f04fe2ca1bcb9914296f97fdf729a52e0c3472c9f7ae72bd746f0a66b0c9363fae0328ad063fa"
+ "45d35cc2679c85e970c7420ad036012ce553ef47ed8fe594917739aab1123be435a0ca88ac4b85cf3d341d4aeb2c6816d8fc"
+ "a2e9611224b42f0ca00bde4f25db460200f25fe99ed4fd0236e4d00c48085aec4734f0bce7e6c8fea08b11a2a7214f4a18c0"
+ "fa4b732c8dae5c5857f2edec27fa94eb17ac05d1d05b321b01c1368231ff89c46c6378abf67cb751156370bbcc35591e0028"
+ "d4ace5158048d9d25b00e028b7766f1c74ade9603a211aad241fc3b7599a2b15f86846dfdc106f49cf56491b3f6ff451d641"
+ "400f38fabcdb74a4423828b041901fa5d8c528ebf1cc6169b08eb14b2d457acb6970a11ccaa8fbc3b37b6454803b07b1916e"
+ "2ad3533f2b72721625c11f39a457033744fde3745c3d107a3f1e14118e04db41ca8970a383e8706bcf8ba5439a4cb360b250"
+ "4fcae3dbfb54af0154f9b813ad552f2bdbc2a9eb61d38ae5e6917990cbeb1c5292845637c5fed477dabbed4198a2978640ba"
+ "7db22c85322115fa9027ad418a61e2e31263da3776398faaaab818aae6423c873bd393f558fa2fc05115b4983d35ecfeae13"
+ "601519a53c7a77b5688aeddc6f210a65303eeb0dbd7e3a5ec94d7552cf4cbe7acebf5e4e10abaccd2e990f1cf217b98ad9b5"
+ "06820f7769a7c5e61d95462918681c2b111faf29f13e3615c4c5e75426dbcd903c483590434e8ab1965dc620e7d8bebea36f"
+ "53f1bc0807933b0ef9d8cc1b36b96aff8288e9a8d1bba24af562dfeb497b9a58083b71d76dacd6f2ce67cb2593c6f06472ef"
+ "e508012c34f40d87e0be3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082022706092a864886f70d010701a0820218048202"
+ "14308202103082020c060b2a864886f70d010c0a0103a08201e4308201e0060a2a864886f70d01091601a08201d0048201cc"
+ "308201c830820131a00302010202104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d0101050500301a3118"
+ "30160603550403130f5253414b65795472616e7366657233301e170d3136303332353231323335355a170d31373033323630"
+ "33323335355a301a311830160603550403130f5253414b65795472616e736665723330819f300d06092a864886f70d010101"
+ "050003818d0030818902818100bbc6fe8702a4e92eadb9b0f41577c0fffc731411c6f87c27c9ef7c2e2113d4269574f44f2e"
+ "90382bd193eb2f57564cf00092172d91a003e7252a544958b30aab6402e6fba7e442e973d1902e383f6bc4a4d8a00e60b3f3"
+ "3a032bdf6bedb56acb0d08669b71dd7b35f5d39d9914f5e111e1cd1559eb741a3075d673c39e7850a50203010001a30f300d"
+ "300b0603551d0f040403020520300d06092a864886f70d01010505000381810058abccbf69346360351d55817a61a6091b0b"
+ "022607caeb44edb6f05a91f169903608d7391b245ac0dcbe052e16a91ac1f8d9533f19f6793f15cb6681b2cbaa0d8e83d77b"
+ "5207e7c70d843deda8754af8ef1029e0b68c35d88c30d7da2f85d1a20dd4099facf373341b50a8a213f735421062e1477459"
+ "6e27a32e23b3f3fcfec33115301306092a864886f70d0109153106040401000000303b301f300706052b0e03021a0414cd11"
+ "0833d653f2e18d2afb2de74689ff0446ec7d0414f2ca1c390db19317697044b9012ef6864e0f05cc020207d0").HexToByteArray();
public static byte[] s_RSAKeyTransferCapi1Cer =
("3082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e03021d0500301e311c301a0603"
+ "55040313135253414b65795472616e736665724361706931301e170d3135303431353037303030305a170d32353034313530"
+ "37303030305a301e311c301a060355040313135253414b65795472616e73666572436170693130819f300d06092a864886f7"
+ "0d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03e301c37d9bff6d75b6eb6671ba"
+ "9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6c9d2b4e283ea3535923f398a31"
+ "2a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4111299f99424408d0203010001"
+ "a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e311c301a060355040313135253"
+ "414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca300906052b0e03021d050003818100"
+ "81e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c5931662d9ecd8b1e7b81749e48468167"
+ "e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957d653b5c78e5291e4401045576f"
+ "6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a429646").HexToByteArray();
// Password = "1111"
//
// Built by:
//
// makecert -r -len 1024 -n "CN=RSAKeyTransferCapi1" -b 04/15/2015 -e 04/15/2025 RSAKeyTransferCapi1.cer -sv RSAKeyTransferCapi1.pvk -sky exchange
// pvk2pfx.exe -pvk RSAKeyTransferCapi1.pvk -spc RSAKeyTransferCapi1.cer -pfx RSAKeyTransferCapi1.pfx -po 1111
//
public static byte[] s_RSAKeyTransferCapi1Pfx =
("30820626020103308205e206092a864886f70d010701a08205d3048205cf308205cb3082035806092a864886f70d010701a0"
+ "82034904820345308203413082033d060b2a864886f70d010c0a0102a08202b6308202b2301c060a2a864886f70d010c0103"
+ "300e0408dbd82a9abd7c1a2b020207d004820290768873985e74c2ece506531d348d8b43f2ae8524a2bcc737eeb778fac1ee"
+ "b21f82deb7cf1ba54bc9a865be8294de23e6648ffb881ae2f0132265c6dacd60ae55df1497abc3eb9181f47cb126261ea66f"
+ "d22107bbcdb8825251c60c5179ef873cb7e047782a4a255e3e9d2e0dd33f04cde92f9d268e8e4daf8ba74e54d8b279a0e811"
+ "9a3d0152608c51331bbdd23ff65da492f85809e1d7f37af9ae00dca796030a19e517e7fe2572d4502d4738fd5394ee369216"
+ "fb64cf84beab33860855e23204156dcf774fac18588f1c1ca1a576f276e9bfbf249449842f193020940a35f163378a2ce7da"
+ "37352d5b0c7c3ac5eb5f21ed1921a0076523b2e66a101655bb78d4ecc22472ac0151b7e8051633747d50377258ab19dcb22e"
+ "e09820876607d3291b55bba73d713d6689486b310507316b4f227383e4869628ad31f0b431145d45f4f38f325772c866a20e"
+ "0b442088cbf663e92e8ee82dd495fba8d40345474a384bb3b80b49ca1d66eef5321235135dcc0a5425e4bf3b8ce5c2469e2a"
+ "c0f8d53aab276361d9a2ff5c974c6e6b66126158676331fe7f74643fd1e215b22d7799846651350ed0f1f21a67ac6b3bfd62"
+ "7defb235ef8732d772d1c4bea2ae80c165f0182f547ea7a3f3366288f74c030689988a9838c27b10a48737a620d8220f68b4"
+ "ea8d8eb26298d5359d54a59c6be6716cefc12c929e17bb71c57c560659a7757ba8ac08ae90794474e50f0e87a22e2b7c3ebd"
+ "061390928bf48c6c6200c225f7025eab20f5f6fee5dc41682b2d4a607c8c81964b7d52651e5a62a41f4e8ea3982c294a4aee"
+ "8a67dc36a8b34b29509a4868c259dc205d1e8a3b6259a76a147f002f3bfbc8378e8edd230a34f9cd5f13ce6651b10394709d"
+ "5092bb6a70d8c2816f1c0e44cd45dfa7c2d94aa32112d79cb44a3174301306092a864886f70d010915310604040100000030"
+ "5d06092b060104018237110131501e4e004d006900630072006f0073006f006600740020005300740072006f006e00670020"
+ "00430072007900700074006f0067007200610070006800690063002000500072006f007600690064006500723082026b0609"
+ "2a864886f70d010701a082025c048202583082025430820250060b2a864886f70d010c0a0103a082022830820224060a2a86"
+ "4886f70d01091601a0820214048202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906"
+ "052b0e03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135"
+ "3037303030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243"
+ "6170693130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2b"
+ "c27b03e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec8"
+ "6aa8f6c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a3"
+ "36baa4111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa1"
+ "20301e311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4c"
+ "ca300906052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c"
+ "5931662d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075"
+ "d11957d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a429646311530130609"
+ "2a864886f70d0109153106040401000000303b301f300706052b0e03021a041463c18f4fec17cf06262e8acd744e18b8ab7b"
+ "8f280414134ec4a25653b142c3d3f9999830f2ac66ef513b020207d0").HexToByteArray();
public static byte[] s_RSASha256KeyTransfer1Cer =
("308201d43082013da003020102021072c6c7734916468c4d608253da017676300d06092a864886f70d01010b05003020311e"
+ "301c060355040313155253415368613235364b65795472616e7366657231301e170d3136303431383130353934365a170d31"
+ "37303431383136353934365a3020311e301c060355040313155253415368613235364b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100cad046de3a7f6dc78fc5a4e01d1f7d90db596f586334d5708a"
+ "ecb8e52d6bb912c0b5ec9633a82b4abac4c2860c766f2fdf1c905c4a72a54adfd041adabe5f2afd1e2ad88615970e818dc3d"
+ "4d00bb6c4ce94c5eb4e3efedd80d14c3d295ea471ae430cbb20b071582f1396369fbe90c14aa5f85b8e3b14011d81fbd41ec"
+ "b1495d0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010b050003818100baed2a5ae2d1"
+ "1ee4209c0694c790e72e3e8ad310b2506b277d7c001b09f660d48dba846ac5bbef97653613adf53d7624fc9b2b337f25cb33"
+ "74227900cfefbe2fdac92b4f769cf2bf3befb485f282a85bfb09454b797ce5286de560c219fb0dd6fce0442adbfef4f767e9"
+ "ac81cf3e9701baf81efc73a0ed88576adff12413b827").HexToByteArray();
// password = "1111"
public static byte[] s_RSASha256KeyTransfer1Pfx =
("308205de0201033082059a06092a864886f70d010701a082058b04820587308205833082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e040829e4911057aa5fb6020207d00482028052e016e1e339ca6a648ab1e152813899bd2ec0de1e34804c33e109cf2136"
+ "d42edc0d5ff8a005939ec38d4284aa0cfda295e801b701855c3c129e9311dc80b3538ba76d3164d48d83a73949d695f42294"
+ "75469f262c807767bc5c12bb83b2c4857fa9f8c7c519143136ba93ab93e17ad4b0b63cf6449708e6128425b00eaeae6bc5b6"
+ "7ff092673c9aabbbb63e90424295f0ae828bcd00f5ad85fe8384711ca5fffd4cbfe57ddbc3e5bb1df19e6fd7640fbd8d4516"
+ "f8d2d5ec84baca72ac42b50e77be0055dfdbbbe9c6de42c06fc86de8fbfc6231db89b30065d534e76aa851833b6c9c651288"
+ "c12f87ba12ae429e9bec0b22297c666046355ebd5a54dc7f13a55e0ebd53c768f69eee57d6041263f5bdf1c4c5b2b55dfb9b"
+ "38171aaed0d21fd5a41e0ef760db42f373c9007e1df47fd79ba9b41528c9c02dffdd04472265763ae94f4e05b86976a2c459"
+ "093d8e6bb0d0c5da5994fe3edbdf843b67e8e4c4daf59351788bf8b96da116aecbb95d52bf727ff10ca41340112f0bcb41e0"
+ "b8373a6e55727c745b77cf1944b74fa447ed0a6d93b8e43fd6e4b4b3e0d49d03ee2ee12d15519406c49a4c1be70de5171c93"
+ "d056e9f47b8a96d50f01873be4c596590f1247a2f2822dea9339fa87dd49545b559e0225ab738ecc0b054155749670d412be"
+ "472d13dfb0a8c8f56b3c0be1aa0d9195ba937b0c2119c702a0be1f83e1b4a77375ed1654e3dcf6b8ce119db3ac7cd440369a"
+ "b0b964e0b526b865680015cc3046a20badeaca4543ce65042ff5eb691e93232754a7b34fd8b6833c2625fdfdc59d80b3dcb4"
+ "ce70d1833ecf6344bb7331e46b71bb1592b6d814370548ee2b2f4df207696be87d2e1e0c5dc0ca528e5a231802cbb7853968"
+ "beb6ceb1b3a2998ecd313174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082023306092a864886f70d010701a0820224048202"
+ "203082021c30820218060b2a864886f70d010c0a0103a08201f0308201ec060a2a864886f70d01091601a08201dc048201d8"
+ "308201d43082013da003020102021072c6c7734916468c4d608253da017676300d06092a864886f70d01010b05003020311e"
+ "301c060355040313155253415368613235364b65795472616e7366657231301e170d3136303431383130353934365a170d31"
+ "37303431383136353934365a3020311e301c060355040313155253415368613235364b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100cad046de3a7f6dc78fc5a4e01d1f7d90db596f586334d5708a"
+ "ecb8e52d6bb912c0b5ec9633a82b4abac4c2860c766f2fdf1c905c4a72a54adfd041adabe5f2afd1e2ad88615970e818dc3d"
+ "4d00bb6c4ce94c5eb4e3efedd80d14c3d295ea471ae430cbb20b071582f1396369fbe90c14aa5f85b8e3b14011d81fbd41ec"
+ "b1495d0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010b050003818100baed2a5ae2d1"
+ "1ee4209c0694c790e72e3e8ad310b2506b277d7c001b09f660d48dba846ac5bbef97653613adf53d7624fc9b2b337f25cb33"
+ "74227900cfefbe2fdac92b4f769cf2bf3befb485f282a85bfb09454b797ce5286de560c219fb0dd6fce0442adbfef4f767e9"
+ "ac81cf3e9701baf81efc73a0ed88576adff12413b8273115301306092a864886f70d0109153106040401000000303b301f30"
+ "0706052b0e03021a0414282ee1780ac2a08b2783b1f8f7c855fb1a53ce9e04143fad59471323dc979f3bf29b927e54eca677"
+ "7576020207d0").HexToByteArray();
public static byte[] s_RSASha384KeyTransfer1Cer =
("308201d43082013da00302010202103c724fb7a0159a9345caac9e3df5f136300d06092a864886f70d01010c05003020311e"
+ "301c060355040313155253415368613338344b65795472616e7366657231301e170d3136303431383131303530365a170d31"
+ "37303431383137303530365a3020311e301c060355040313155253415368613338344b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100e6b46b0e6f4f6df724081e11f201b9fbb07f2b6db2b868f607"
+ "68e2b5b843f690ca5e8d48f439d8b181ace2fb27dfa07eff0324642d6c9129e2d95e136702f6c31fe3ccf3aa87ba9f1b6f7b"
+ "acd07156ff3dd2a7f4c70356fb94b0adbde6819383c19bbefb4a6d1d6491a770d5f9feb11bcb3e5ac99cb153984dee0910e4"
+ "b57f8f0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010c0500038181003842cc95a680"
+ "c8a31534a461d061a4706a0aba52b7a1c709c2f1e3b94acf6dc0930b74e63e3babf3c5b11c8f8a888722d9f23c7e0a8c9b09"
+ "90ebcdbce563b8d4209efc1b04750f46c8c6117ccb96b26b5f02b0b5f961ab01b0c3b4cdb2530cbc5dcf37786712a3476ce7"
+ "32c5c544c328db5ebc3a338b18fe32aedaffedd973ef").HexToByteArray();
// password = "1111"
public static byte[] s_RSASha384KeyTransfer1Pfx =
("308205de0201033082059a06092a864886f70d010701a082058b04820587308205833082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e040856d7d59810ce8b17020207d00482028082012797edb5f74429bb6b91dd1e24aa32a19b89d92fd486e826773a7a11"
+ "03a9b49d98c6b7e97d411d19b44cd79559964f31cb6f0443c70d687c390d31c656ee3887391ae1735c142d891ec8337c5dc4"
+ "d6b5a4f09400a4cc35dd8dbde831f7625b7afedf4990294988b0b32b2889c97cd85c2568ffef332be83232449dd4083a43d4"
+ "89e654520eb922239379b5e9f5dfc1e64972339dee27dfdd874e2ee2b85f941f3b313ab881571c3a5a9b292d8c82d79d74a0"
+ "2d78dd5cfce366b3a914b61b861b35948757d137e5d53589a0fa2f1b4d06ee6b4aa4b8d3f526b059637b236ceb2de128d7bd"
+ "f91c12612d09e1cb4bed1b5e336fb56424b68dcc6d6cd5d90f666047c8b181526a60622027d322db0172046c23e84a3c725e"
+ "45ce774df037cafb74b359c3ec6874dce98673d9f7581f54dcb6e3c40583de2de6aaf6739bba878362e9bfab331cab2eb22d"
+ "3b130dec4eedf55a7ed8d5960e9f037209f9c1ef584c6dd5de17245d0da62c54420dc862b6648418d2aa9797f86a2cd0ecf6"
+ "abcbeb16907d8f44021690682a4e1286cd3f9aea4866108b3c968cf4b80a39c60436079617346861662e01a5419d8cebe2c6"
+ "e186141e42baf7cfc596270dbab8db03da9bd501daa426e24aa2d8ccf4d4512a8dce3ae8954be69b5c3a70fac587ac91ad97"
+ "fb427c8118659b710b57183c4fd16ffd276834e2fe45d74e175f3f5077783cdd7668b4e87217512ceb7f3e64715ba22bbab7"
+ "0d1b3485820c16304758cf1dd0b806d801f1185bb14d12f2c147ec65b95088077dec23498ebe40a952727c559c7af5cf20f1"
+ "f491f4123db093dc1a67014c3db46c11c7d5833b15167c91138eba6b4badf869aefba5fbea523a5ad02bb676db6039e7aabd"
+ "44f0702d59cf3d1ad9bb3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082023306092a864886f70d010701a0820224048202"
+ "203082021c30820218060b2a864886f70d010c0a0103a08201f0308201ec060a2a864886f70d01091601a08201dc048201d8"
+ "308201d43082013da00302010202103c724fb7a0159a9345caac9e3df5f136300d06092a864886f70d01010c05003020311e"
+ "301c060355040313155253415368613338344b65795472616e7366657231301e170d3136303431383131303530365a170d31"
+ "37303431383137303530365a3020311e301c060355040313155253415368613338344b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100e6b46b0e6f4f6df724081e11f201b9fbb07f2b6db2b868f607"
+ "68e2b5b843f690ca5e8d48f439d8b181ace2fb27dfa07eff0324642d6c9129e2d95e136702f6c31fe3ccf3aa87ba9f1b6f7b"
+ "acd07156ff3dd2a7f4c70356fb94b0adbde6819383c19bbefb4a6d1d6491a770d5f9feb11bcb3e5ac99cb153984dee0910e4"
+ "b57f8f0203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010c0500038181003842cc95a680"
+ "c8a31534a461d061a4706a0aba52b7a1c709c2f1e3b94acf6dc0930b74e63e3babf3c5b11c8f8a888722d9f23c7e0a8c9b09"
+ "90ebcdbce563b8d4209efc1b04750f46c8c6117ccb96b26b5f02b0b5f961ab01b0c3b4cdb2530cbc5dcf37786712a3476ce7"
+ "32c5c544c328db5ebc3a338b18fe32aedaffedd973ef3115301306092a864886f70d0109153106040401000000303b301f30"
+ "0706052b0e03021a041429bd86de50f91b8f804b2097b1d9167ca56577f40414b8714b8172fa1baa384bed57e3ddb6d1851a"
+ "f5e9020207d0").HexToByteArray();
public static byte[] s_RSASha512KeyTransfer1Cer =
("308201d43082013da00302010202102f5d9d58a5f41b844650aa233e68f105300d06092a864886f70d01010d05003020311e"
+ "301c060355040313155253415368613531324b65795472616e7366657231301e170d3136303431383131303532355a170d31"
+ "37303431383137303532355a3020311e301c060355040313155253415368613531324b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100b2eca20240da8486b1a933ade62ad8781ef30d4434ebbc9b3f"
+ "c9c550d0f9a75f4345b5520f3d0bafa63b8037785d1e8cbd3efe9a22513dc8b82bcd1d44bf26bd2c292205ca3e793ff1cb09"
+ "e0df4afefb542362bc148ea2b76053d06754b4a37a535afe63b048282f8fb6bd8cf5dc5b47b7502760587f84d9995acbf1f3"
+ "4a3ca10203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010d050003818100493d857684d2"
+ "7468dd09926d20933254c7c79645f7b466e7b4a90a583cedba1c3b3dbf4ccf1c2506eb392dcf15f53f964f3c3b519132a38e"
+ "b966d3ea397fe25457b8a703fb43ddab1c52272d6a12476df1df1826c90fb679cebc4c04efc764fd8ce3277305c3bcdf1637"
+ "91784d778663194097180584e5e8ab69039908bf6f86").HexToByteArray();
// password = "1111"
public static byte[] s_RSASha512KeyTransfer1Pfx =
("308205de0201033082059a06092a864886f70d010701a082058b04820587308205833082034806092a864886f70d010701a0"
+ "82033904820335308203313082032d060b2a864886f70d010c0a0102a08202a6308202a2301c060a2a864886f70d010c0103"
+ "300e04083a0e344b65dd4e27020207d00482028014464df9f07d2cb37a28607570130de5877e829e759040976866afc831db"
+ "4d2741734ae53ea5eb80c1080dae7b0a2acddabd3d47b1ed5f3051455429308f3b7b0b48c5a4dbc5d718534472c746ce62f1"
+ "bbb8c5d178c1d3e91efdbd4f56569517bcadf3c81dbe4c34746194e47bcf46b74cd1880d7bd12d9b819b462fbcf6f51f3972"
+ "2858c9b9af8975bfefd7f007928b39e11d50b612761d03e566b992f92e9c9873d138c937fc43fe971db4c8e57b51aeef4ed0"
+ "022ec76c3bb4bd9f2395b99585449303a6d68183edf6e5dda1885531bee10b7cf6509390f4ee6a37ed2931d658548bd6390f"
+ "a7094fdf017166309074c00581d2b7dcaaee657f9c48e08edf636004dc5e60486dd022c45058700fe682472b371380948792"
+ "74c2a20dd9e07e149e7ab52157db748160ad81f91019297baa58ce68656b0b2f7c9ac88b3da6920c2a5eab7bcc2629974f8a"
+ "6c8bf33629af05e4e34d5d24393448e9751b7708f5915b0fd97a5af4dd5a37d71b18b6526316cbc65b1c6af8a6779acbc470"
+ "2381f027bdb118cb84e9005b02a8bd2d02365d280cffb04831f877de7bd3d3287f11beed8978a5389e2b28317eb90569781f"
+ "94f66f672736a09b4a7caeaaefd1909f2d20255df51512dbd08ec6125455d932b626bdfd3c4f669148fa783671f90b59ceff"
+ "560c338f92cbe8bf7fbab4db3e9b943effac747eb34f06bd72aee961ed31742caa2a9934a5fe4685677ecbca6fb1b1c0b642"
+ "b4f71d55d0e2cb1dc10ce845514090cc117a875c4d10c0ce367e31091144eacd7e600792d61d036bde020e3bb9a004a7dd1a"
+ "cf03541b6fff3bcef4c30df05d98b75688320685261b2b34813407b20a7c92a04eeb46cb7e618a6ee32154728ba6735668f4"
+ "11abece4ba07426a394b3174301306092a864886f70d0109153106040401000000305d06092b060104018237110131501e4e"
+ "004d006900630072006f0073006f0066007400200053006f0066007400770061007200650020004b00650079002000530074"
+ "006f0072006100670065002000500072006f007600690064006500723082023306092a864886f70d010701a0820224048202"
+ "203082021c30820218060b2a864886f70d010c0a0103a08201f0308201ec060a2a864886f70d01091601a08201dc048201d8"
+ "308201d43082013da00302010202102f5d9d58a5f41b844650aa233e68f105300d06092a864886f70d01010d05003020311e"
+ "301c060355040313155253415368613531324b65795472616e7366657231301e170d3136303431383131303532355a170d31"
+ "37303431383137303532355a3020311e301c060355040313155253415368613531324b65795472616e736665723130819f30"
+ "0d06092a864886f70d010101050003818d0030818902818100b2eca20240da8486b1a933ade62ad8781ef30d4434ebbc9b3f"
+ "c9c550d0f9a75f4345b5520f3d0bafa63b8037785d1e8cbd3efe9a22513dc8b82bcd1d44bf26bd2c292205ca3e793ff1cb09"
+ "e0df4afefb542362bc148ea2b76053d06754b4a37a535afe63b048282f8fb6bd8cf5dc5b47b7502760587f84d9995acbf1f3"
+ "4a3ca10203010001a30f300d300b0603551d0f040403020520300d06092a864886f70d01010d050003818100493d857684d2"
+ "7468dd09926d20933254c7c79645f7b466e7b4a90a583cedba1c3b3dbf4ccf1c2506eb392dcf15f53f964f3c3b519132a38e"
+ "b966d3ea397fe25457b8a703fb43ddab1c52272d6a12476df1df1826c90fb679cebc4c04efc764fd8ce3277305c3bcdf1637"
+ "91784d778663194097180584e5e8ab69039908bf6f863115301306092a864886f70d0109153106040401000000303b301f30"
+ "0706052b0e03021a041401844058f6e177051a87eedcc55cc4fa8d567ff10414669cb82c9cc3ceb4d3ca9f65bd57ba829616"
+ "60d9020207d0").HexToByteArray();
public static byte[] s_DHKeyAgree1Cer =
("3082041930820305a00302010202100ae59b0cb8119f8942eda74163413a02300906052b0e03021d0500304f314d304b0603"
+ "5504031e44004d0061006e006100670065006400200050004b00430053002300370020005400650073007400200052006f00"
+ "6f007400200041007500740068006f0072006900740079301e170d3136303431333132313630315a170d3339313233313233"
+ "353935395a301f311d301b06035504031314446648656c6c654b657941677265656d656e7431308201b63082012b06072a86"
+ "48ce3e02013082011e02818100b2f221e2b4649401f817557771e4f2ca1c1309caab3fa4d85b03dc1ea13c8395665eb4d05a"
+ "212b33e1d727403fec46d30ef3c3fd58cd5b621d7d30912f2360676f16b206aa419dba39b95267b42f14f6500b1729de2d94"
+ "ef182ed0f3042fd3850a7398808c48f3501fca0e929cec7a9594e98bccb093c21ca9b7dbdfcdd733110281805e0bed02dd17"
+ "342f9f96d186d2cc9e6ff57f5345b44bfeeb0da936b37bca62e2e508d9635a216616abe777c3fa64021728e7aa42cfdae521"
+ "01c6a390c3eb618226d8060ceacdbc59fa43330ad41e34a604b1c740959b534f00bd6cf0f35b62d1f8de68d8f37389cd435d"
+ "764b4abec5fc39a1e936cdf52a8b73e0f4f37dda536902150093ced62909a4ac3aeca9982f68d1eed34bf055b30381840002"
+ "81804f7e72a0e0ed4aae8e498131b0f23425537b9a28b15810a3c1ff6f1439647f4e55dcf73e72a7573ce609a5fb5c5dc3dc"
+ "daa883b334780c232ea12b3af2f88226775db48f4b800c9ab1b54e7a26c4c0697bbd5e09355e3b4ac8005a89c65027e1d0d7"
+ "091b6aec8ede5dc72e9bb0d3597915d50da58221673ad8a74e76b2a79f25a38194308191300c0603551d130101ff04023000"
+ "3081800603551d010479307780109713ac709a6e2cc6aa54b098e5557cd8a151304f314d304b06035504031e44004d006100"
+ "6e006100670065006400200050004b00430053002300370020005400650073007400200052006f006f007400200041007500"
+ "740068006f00720069007400798210d581eafe596cd7a34d453011f4a4b6f0300906052b0e03021d05000382010100357fbe"
+ "079401e111bf80db152752766983c756eca044610f8baab67427dc9b5f37df736da806e91a562939cf876a0998c1232f31b9"
+ "9cf38f0e34d39c7e8a2cc04ed897bfdc91f7f292426063ec3ec5490e35c52a7f98ba86a4114976c45881373dacc95ad3e684"
+ "7e1e28bb58e4f7cfc7138a56ce75f01a8050194159e1878bd90f9f580f63c6dd41e2d15cd80dc0a8db61101df9009d891ec2"
+ "28f70f3a0a37358e7917fc94dfeb6e7cb176e8f5dbfa1ace2af6c0a4306e22eb3051e7705306152ce87328b24f7f153d565b"
+ "73aef677d25ae8657f81ca1cd5dd50404b70b9373eadcd2d276e263105c00607a86f0c10ab26d1aafd986313a36c70389a4d"
+ "1a8e88").HexToByteArray();
public static byte[] s_Rsa2048SignatureOnlyCer = (
"3082032C30820214A003020102020900E0D8AB6819D7306E300D06092A864886" +
"F70D01010B05003038313630340603550403132D54776F2074686F7573616E64" +
"20666F7274792065696768742062697473206F662052534120676F6F646E6573" +
"73301E170D3137313130333233353131355A170D313831313033323335313135" +
"5A3038313630340603550403132D54776F2074686F7573616E6420666F727479" +
"2065696768742062697473206F662052534120676F6F646E6573733082012230" +
"0D06092A864886F70D01010105000382010F003082010A028201010096C114A5" +
"898D09133EF859F89C1D848BA8CB5258793E05B92D499C55EEFACE274BBBC268" +
"03FB813B9C11C6898153CC1745DED2C4D2672F807F0B2D957BC4B65EBC9DDE26" +
"E2EA7B2A6FE9A7C4D8BD1EF6032B8F0BB6AA33C8B57248B3D5E3901D8A38A283" +
"D7E25FF8E6F522381EE5484234CFF7B30C174635418FA89E14C468AD89DCFCBB" +
"B535E5AF53510F9EA7F9DA8C1B53375B6DAB95A291439A5648726EE1012E4138" +
"8E100691642CF6917F5569D8351F2782F435A579014E8448EEA0C4AECAFF2F47" +
"6799D88457E2C8BCB56E5E128782B4FE26AFF0720D91D52CCAFE344255808F52" +
"71D09F784F787E8323182080915BE0AE15A71D66476D0F264DD084F302030100" +
"01A3393037301D0603551D0E04160414745B5F12EF962E84B897E246D399A2BA" +
"DEA9C5AC30090603551D1304023000300B0603551D0F040403020780300D0609" +
"2A864886F70D01010B0500038201010087A15DF37FBD6E9DED7A8FFF25E60B73" +
"1F635469BA01DD14BC03B2A24D99EFD8B894E9493D63EC88C496CB04B33DF252" +
"22544F23D43F4023612C4D97B719C1F9431E4DB7A580CDF66A3E5F0DAF89A267" +
"DD187ABFFB08361B1F79232376AA5FC5AD384CC2F98FE36C1CEA0B943E1E3961" +
"190648889C8ABE8397A5A338843CBFB1D8B212BE46685ACE7B80475CC7C97FC0" +
"377936ABD5F664E9C09C463897726650711A1110FA9866BC1C278D95E5636AB9" +
"6FAE95CCD67FD572A8C727E2C03E7B242457318BEC1BE52CA5BD9454A0A41140" +
"AE96ED1C56D220D1FD5DD3B1B4FB2AA0E04FC94F7E3C7D476F29896224556395" +
"3AD7225EDCEAC8B8509E49292E62D8BF").HexToByteArray();
public static byte[] s_Rsa2048SignatureOnlyPfx = (
"308209E3020103308209A306092A864886F70D010701A0820994048209903082" +
"098C308205BD06092A864886F70D010701A08205AE048205AA308205A6308205" +
"A2060B2A864886F70D010C0A0102A08204FE308204FA301C060A2A864886F70D" +
"010C0103300E04083EF905F0EA26FBF7020207D0048204D82297B5546DA6CC49" +
"BD8C1444E3FE1845A2C9E9BDB8B83E78235DF4ADF7A97496A62D31D4EEEB76B0" +
"71C0B183ACC3663272F88CF4F31E2E00D76357C0A051B8D6E0BB0BCF4CCDD064" +
"CCBAF546EABA80DA56CD11FE952C61154792559D65F26B0476CF7A5FDB8CC794" +
"B89F6ACD50003459054FE82C48D8791B226A0EEEC01F048AC3CE716C9F3BB313" +
"D64BEBBF0037D83133DD9C15D04F15BB11652D793B613A68AFE580245724E5D1" +
"110040B332B5C39BE04086BA4DFC58E905BC2FE8B3C696181E2879AF197EE24D" +
"91D8AD67013F14C4864C8D0FB19C134B766CF3E48B8C9E363A11EB19F1E82E74" +
"D25EDD96517D64A94314B40C11651030D561E742E63856E8D1A3EE9FDFD6CF64" +
"7140CFC354AE7EA1D14C157C2985F82D54296F7D3DE456AF7513F5F30A0421E4" +
"3A9DAD6DF8A2BF69005B35CA8066F80755D848DA73EF03BC0CC129C5799911D9" +
"3A1ED43F8E76732AF56FD62DC6D0B0DBA6AAC6DCDE77D0E8AC9F6A5EB5A02B61" +
"BC477706D4F1873240AB45E0291EF21E6034D48F1AE8EB139DE7ACD8B8A821E6" +
"70B395C3EC4B0E75C34BF0067F052FCED835CAC1F17C3FBEA2FC9FD281FCDE21" +
"D5B27CF31A07E90164A979ACEF0E1C67DBA6C33082E9B189D4BDA2D2D504776F" +
"455843437BDF10D4AF48639EC03344BCC36EFEA7CDE08D7F94DDEAF98BCB5D65" +
"207AE0C349EECE3032DE19F3B337F29A3457AA0AAF4306FA8301619AB01B7235" +
"BE16CB93728E142DAA6C1CBBCC5BD82D913596994DA40FB916CF2DB5FBCC20CF" +
"E893DC62BBC5FC59E00BC0A704A9DB25BBF9291971F2377FC1A20F2C954869DB" +
"6FFCC90C625AABE97ED4CF7C0209D39AD780003C437152D636ACB3B484C46885" +
"DC1584733D2153A3F9B968F12CDD5937CDF9DD2581D72EE67C83AE2530197AA7" +
"C6110613BEFF0B75E586C28394EA8EBCF7F9DB133295B33DC86C8DBA92BF8BD1" +
"ADCAF8D2CD2E018B08D59FF1C30A13484AB11468F7DCEB1FE53A6DAF309B0510" +
"7772CB735314A5B2F053E60A653F0496BCB9CADF5E50339A4D2EF2382056B768" +
"558EB9230D996C636E6D29664F92F70A088DE3EE4EC4BBD8A9C4C98C7892D122" +
"28806622B87E581A321AD835B8F4B964A17B5BE6D9DA50133D494732A41884E2" +
"9E891FE2D40ACCFD585C8BF626C1E8A412D2EE7CDE060E2CCDA826BF79D80F1B" +
"F6B8400473BCE0C19D03ACF55D1FAA994C04A8CD11D49743B1F45F48DFFDD701" +
"18B5FA82ECDF67714F5DE5D3D3DDDCB76ED0EA6A6E151665A4AA351DB1A99F8C" +
"7502D3795C2C358CCA589C390C1F4810615130B91BA42A85E77FA37197E1B083" +
"FE1246B067C6444D49B369D45B130A6D7B463C3F0459EB41D68009CABD2F5C60" +
"49DB706FA742C9773FB5791AF123FBE485E05F87759ADD25281BE337B6095EC3" +
"4EFF9FC692798FB4217EF4B2B59902D930F28181933FAA278C041123CAE3CA63" +
"6DFD3AD4E04EB751A30D50C26288EA4D01C7B323E4FD6387F88E020BC433BF60" +
"C4406398C44EA5C7A6EB24134B0811E4F94DFAF5553172306FA5543C254E7E04" +
"DEEC84DBF9FAF7BFEA8D61E094CBB18DD45C5BAB9199DD719F9A305E205605CC" +
"671DCD566FEBA2C8F4C1A445625C4F42D1CFE32087F095591798D1D48DA46DE9" +
"230F5102B56A1EF879D48936D5331D6B3D9F1B564CF08FD3C641CFF3B02CB4FC" +
"8995E5EC5DD1D183704940C02DEA7430FD594E54800DCC74B7732731C63FBBA2" +
"A2F6DC031174390A74781D352B09FB4F318190301306092A864886F70D010915" +
"3106040401000000307906092B0601040182371101316C1E6A004D0069006300" +
"72006F0073006F0066007400200045006E00680061006E006300650064002000" +
"520053004100200061006E006400200041004500530020004300720079007000" +
"74006F0067007200610070006800690063002000500072006F00760069006400" +
"650072308203C706092A864886F70D010706A08203B8308203B4020100308203" +
"AD06092A864886F70D010701301C060A2A864886F70D010C0106300E04087CB7" +
"E0256AD1AD80020207D0808203800C21CEBEF9F3765F11A188B56702050E3DCA" +
"78AA27123654D066399DD56E62187C89A30940B5B63493950EEFA06C04B5CAF0" +
"329143AF30EE0B47406E49D4E6241817986F864780B743B58F03DF13523F5C01" +
"C889046356623AFA816B163E57A36672FAC9CA72294B2A17F75F5ADB1A4CBDB7" +
"B3F5C33C643DA0CC00CB79E54FAB25D1881B81C03BA5762BAA551A7E8BA38144" +
"353B07285B288BC2747F75B7AF249040C338CFC585D0B1CECFED46BCAE7FAF09" +
"60BB3EE996E30E626CB544A38393BC7DFDB7A27A21A6CF09332B544F448DF5B3" +
"31E000F7CCD5CE5C8E8765A2339919C713352FCD30FA52B994C25EA95E548C4B" +
"5EC23B3BDEC7342D0676B9227D3405758DBA5BD09F9253791FAA03F158F04848" +
"D5073DD240F466F57770353528B3AE83A626F33D05BD1BBB4E28CB067FFAA97D" +
"B4C79EEAAFB4B30BE738C1AA5DB1830B3968CDF6BAF778494AE40EF003DCDA54" +
"486E9952EB44628385E149C348E0E431928B85608622B994CF43433DA9C19482" +
"360121560E53E85FE7CBB7C31E27AD335BC247F284EAC3CA94C30DBB4DF2AB02" +
"DF1154626838240213D910D5B7476A025CA7565CECBA0051320FC7EECD6C74FF" +
"505566F75804D1E2BD2B0181B235CE911EAD9260C0799C817F956AE290E00EF0" +
"997F7B6BD059B315915D580CF0C019A23A6D4993F6E8B8106A1AB6CE1991B609" +
"1B42B6D33EE01EC96CB475430365E9C710C5EB4C6010260D12108022449F7E6D" +
"1A2F28838304DB2A60B9FF714FC887579A4CDC139DAF30A18D3910D82313CCB1" +
"FA43A8930E0F10DE24652AC1E5B797084BEBDB8AB5FA6DCE03E44ABF35EDEB1A" +
"FFEAD3F7C9CB342CCA2882D945EB52C20DC595FA10161866EB9426281CF13341" +
"311B59FDE8E69F9B853117740D92F4AC1B2E4597D41B8A097E1DAA688FFF1C5C" +
"846DF96CA75224EC26F4FF328164F5D1EC06B697211BDB42E6C97EB294A5798C" +
"0FCE6104C950A5207F74EC0DED8AEE10463EF2D9ACD7473D2BE48EBBF0A550B9" +
"AA19A465147B378B078229E8804918136633D7FCE5340AC61A1418D7D9BB18D1" +
"98B7B7866C4D7DC562B1F93F3F322484BDDCEB23680B8EB9904EC783D5CD7177" +
"CFE9CA9D1893104E97760E871DE0907D4BDF6263E7BB0F47414AF31E377C7447" +
"B881E68AE3E80D06597F12D5EF5ED861D055D494D89F04A70800DA3FD4E53877" +
"87FBEED7B772E3A24E7F4832A956FEC0C81847C68373ED4760ABF542F77DC794" +
"249519BDDF5F846EB8C5078BCC053037301F300706052B0E03021A0414461F5B" +
"19C6933240012EFEB95F734C648CCD13460414FA1743400686D25BA1CB28D736" +
"F2B1ED97699EA4").HexToByteArray();
public static byte[] s_dsa1024Pfx = (
"308206EE020103308206B406092A864886F70D010701A08206A5048206A13082" +
"069D3082043706092A864886F70D010706A0820428308204240201003082041D" +
"06092A864886F70D010701301C060A2A864886F70D010C0106300E04084AF212" +
"89D5D7E2E702020800808203F0DECCF218AC91F26BAB026998AB77C7629D20DB" +
"E2FB7022A3C4A1CECD743C0F932E944AE229DAFB61AD76C4DEB6995DF4F4BA01" +
"2DBAD5C63A4C846E0807FCA0BC4A162CDFBAB4B3C4D304F473B3ACC1D268436E" +
"F537DAE97ECC3C634C8DF2A294CC23E904A169F369021A0C024A03DE98A65B0F" +
"3F14D6910525D76AD98B91E67BB7398E245CF48A4D2A5603CFCCF4E547D7EDAB" +
"669D9A8597C6839119EB9FD932D1E4BA8B45D3317186CDA2EFF247BCFD64A5CA" +
"ED604BF7033E423CC21CEC6454FE3B74E03A26C51A1C3519CE339FBE9F10B81D" +
"DF6A0AAB4F8166D90B6F52B3439AB4B5273D0A506E3E01869F8FEBD1521EF8E5" +
"BFB357FA630E3C988926EF3ACC0A0F4176FE8A93337C1A5C6DEAB5758EC2F07C" +
"11E8B2495ECDE58D12312CCCA2E8B2EE8564B533D18C7A26A9290394C2A9942C" +
"295EBB0317F5695103627519567960908323FFE6560AD054C97800218A52F37A" +
"DDE4E7F18EF3BF3718A9D7BF57B700DBEB5AB86598C9604A4546995E34DBABBB" +
"6A9FB483A3C2DFE6046DFD54F2D7AC61C062AF04B7FBAC395C5DD19408D6926A" +
"93B896BFB92DA6F7F5A4E54EDBE2CFBB56576878150676ADB0D37E0177B91E0D" +
"F09D7B37769E66842DD40C7B1422127F152A165BC9669168885BA0243C9641B4" +
"48F68575AA6AB9247A49A61AC3C683EE057B7676B9610CF9100096FC46BDC8B9" +
"BAA03535815D5E98BA3ABC1E18E39B50A8AF8D81E30F2DFD6AF5D0F9FC3636AB" +
"69E128C793571723A79E42FC7C1BD7F39BD45FBE9C39EEB010005435BEC19844" +
"2058033D2601B83124BD369DADB831317E0B2C28CE7535A2E89D8A0E5E34E252" +
"3B0FCEC34FF26A2B80566F4D86F958F70106BF3322FA70A3312E48EAA130246A" +
"07412E93FDE91F633F758BC49311F6CBBAEC5D2F22AFCD696F72BC22E7DE6C00" +
"3275DFEC47E3848226FE9DBA184EA711E051B267C584749F897EFE7EAFD02F1D" +
"BF3FD8E882474CA1F45509EF2E7B82F35B677CB88ED42AF729848EE2B424B0CE" +
"2E9AAC945BABA550C20D5B25075A30FE70D8CAA5A527A35F1DF17BCCB91930C1" +
"7120C625667120E0806C2B51EDFF540F928BD555FB48DBCB83CCCE0C385E78C8" +
"65BE715AE6F8BE472E5FC187EBE3FEFD8D7FE62D4DB2EE61F42D24D81FAA9179" +
"0FB17E8EBC8E219B6F9E039F5AB3BC4870821D474B36C8F8D0583D9DC06E4383" +
"D03424420B8C8B26276877166A0F51E22F0D8FA60A070CFBD47EAFBC717C879C" +
"B5A1EA69C4C2A38F26A1EEF96A0C32BFCECCE4EA97E90A425066B1DD0891353F" +
"766EB9F2BFA2563A815DAF3639EBB147E1E8757A6BFAB902C4A8F037AD47E03F" +
"AF2E019FCF6CA7430BDFEA4B45B28ED746BB90E09BEF7B370A75E7924BBA0920" +
"25FE654A9A197A5B8BBBE43DC7C892FF14E75A37EB97FC489AB121A43E308202" +
"5E06092A864886F70D010701A082024F0482024B3082024730820243060B2A86" +
"4886F70D010C0A0102A082017630820172301C060A2A864886F70D010C010330" +
"0E0408ECB4D1550DA52C6302020800048201509322DC0193DD9E79ADAFD38827" +
"AD6DE9299327DDDF6E9DF4FB70D53A64951E4B814E90D2A19B3F4B8E39A2F851" +
"A3E5E9B9EB947DD248A3E5F5EB458F3323D4656709E97C6BD59238C4D1F26AB6" +
"7D73235FAE7780D98705957B6650AC0DE3E2D46E22455D0A105D138F16A84839" +
"14EDDF5C518B748558704ED3AE4A8C4914F667BBDE07978E4A4FC66194F6B86B" +
"AB9F558EDE890C25DFB97C59653906CC573B5DEB62165CFF8A5F4F8059A478EB" +
"F6FED75F1DACDC612C2E271E25A7083E15D33697270FD442D79FFCB25DB135F9" +
"8E580DC9CE14F73C3B847931AF821C77718455F595CA15B86386F3FCC5962262" +
"5FC916DDB4A08479DCB49FF7444333FA99FBB22F1AEC1876CF1E099F7A4ECA85" +
"A325A8623E071EEA9359194EEE712F73076C5EB72AA243D0C0978B934BC8596F" +
"8353FD3CA859EEA457C6175E82AE5854CC7B6598A1E980332F56AB1EE1208277" +
"4A91A63181B9302306092A864886F70D01091531160414E6335FA7097AB6DE4A" +
"1CDB0C678D7A929883FB6430819106092B06010401823711013181831E818000" +
"4D006900630072006F0073006F0066007400200045006E00680061006E006300" +
"650064002000440053005300200061006E006400200044006900660066006900" +
"65002D00480065006C006C006D0061006E002000430072007900700074006F00" +
"67007200610070006800690063002000500072006F0076006900640065007230" +
"313021300906052B0E03021A0500041466FD3518CEBBD69877BA663C9E8D7092" +
"8E8A98F30408DFB5AE610308BCF802020800").HexToByteArray();
public static byte[] s_dsa1024Cert = (
"3082038D3082034AA003020102020900AB740A714AA83C92300B060960864801" +
"650304030230818D310B3009060355040613025553311330110603550408130A" +
"57617368696E67746F6E3110300E060355040713075265646D6F6E64311E301C" +
"060355040A13154D6963726F736F667420436F72706F726174696F6E3120301E" +
"060355040B13172E4E4554204672616D65776F726B2028436F72654658293115" +
"30130603550403130C313032342D62697420445341301E170D31353131323531" +
"34343030335A170D3135313232353134343030335A30818D310B300906035504" +
"0613025553311330110603550408130A57617368696E67746F6E3110300E0603" +
"55040713075265646D6F6E64311E301C060355040A13154D6963726F736F6674" +
"20436F72706F726174696F6E3120301E060355040B13172E4E4554204672616D" +
"65776F726B2028436F7265465829311530130603550403130C313032342D6269" +
"7420445341308201B73082012C06072A8648CE3804013082011F02818100AEE3" +
"309FC7C9DB750D4C3797D333B3B9B234B462868DB6FFBDED790B7FC8DDD574C2" +
"BD6F5E749622507AB2C09DF5EAAD84859FC0706A70BB8C9C8BE22B4890EF2325" +
"280E3A7F9A3CE341DBABEF6058D063EA6783478FF8B3B7A45E0CA3F7BAC9995D" +
"CFDDD56DF168E91349130F719A4E717351FAAD1A77EAC043611DC5CC5A7F0215" +
"00D23428A76743EA3B49C62EF0AA17314A85415F0902818100853F830BDAA738" +
"465300CFEE02418E6B07965658EAFDA7E338A2EB1531C0E0CA5EF1A12D9DDC7B" +
"550A5A205D1FF87F69500A4E4AF5759F3F6E7F0C48C55396B738164D9E35FB50" +
"6BD50E090F6A497C70E7E868C61BD4477C1D62922B3DBB40B688DE7C175447E2" +
"E826901A109FAD624F1481B276BF63A665D99C87CEE9FD063303818400028180" +
"25B8E7078E149BAC352667623620029F5E4A5D4126E336D56F1189F9FF71EA67" +
"1B844EBD351514F27B69685DDF716B32F102D60EA520D56F544D19B2F08F5D9B" +
"DDA3CBA3A73287E21E559E6A07586194AFAC4F6E721EDCE49DE0029627626D7B" +
"D30EEB337311DB4FF62D7608997B6CC32E9C42859820CA7EF399590D5A388C48" +
"A330302E302C0603551D110425302387047F0000018710000000000000000000" +
"0000000000000182096C6F63616C686F7374300B060960864801650304030203" +
"3000302D021500B9316CC7E05C9F79197E0B41F6FD4E3FCEB72A8A0214075505" +
"CCAECB18B7EF4C00F9C069FA3BC78014DE").HexToByteArray();
// Password: "Test"
internal static readonly byte[] ECDsaP256_DigitalSignature_Pfx_Windows = (
"308204470201033082040306092A864886F70D010701A08203F4048203F03082" +
"03EC3082016D06092A864886F70D010701A082015E0482015A30820156308201" +
"52060B2A864886F70D010C0A0102A081CC3081C9301C060A2A864886F70D010C" +
"0103300E0408EC154269C5878209020207D00481A80BAA4AF8660E6FAB7B050B" +
"8EF604CFC378652B54FE005DC3C7E2F12E5EFC7FE2BB0E1B3828CAFE752FD64C" +
"7CA04AF9FBC5A1F36E30D7D299C52BF6AE65B54B9240CC37C04E7E06330C24E9" +
"6D19A67B7015A6BF52C172FFEA719B930DBE310EEBC756BDFF2DF2846EE973A6" +
"6C63F4E9130083D64487B35C1941E98B02B6D5A92972293742383C62CCAFB996" +
"EAD71A1DF5D0380EFFF25BA60B233A39210FD7D55A9B95CD8A440DF666317430" +
"1306092A864886F70D0109153106040401000000305D06092B06010401823711" +
"0131501E4E004D006900630072006F0073006F0066007400200053006F006600" +
"7400770061007200650020004B00650079002000530074006F00720061006700" +
"65002000500072006F007600690064006500723082027706092A864886F70D01" +
"0706A0820268308202640201003082025D06092A864886F70D010701301C060A" +
"2A864886F70D010C0106300E0408175CCB1790C48584020207D080820230E956" +
"E38768A035D8EA911283A63F2E5B6E5B73231CFC4FFD386481DE24B7BB1B0995" +
"D614A0D1BD086215CE0054E01EF9CF91B7D80A4ACB6B596F1DFD6CBCA71476F6" +
"10C0D6DD24A301E4B79BA6993F15D34A8ADB7115A8605E797A2C6826A4379B65" +
"90B56CA29F7C36997119257A827C3CA0EC7F8F819536208C650E324C8F884794" +
"78705F833155463A4EFC02B5D5E2608B83F3CAF6C9BB97C1BBBFC6C5584BDCD3" +
"9C46A3944915B3845C41429C7792EB4FA3A7EDECCD801F31A4B6EF57D808AEEA" +
"AF3D1F55F378EF8EF9632CED16EDA3EFBE4A9D5C5F608CA90A9AC8D3F86462AC" +
"219BFFD0B8A87DDD22CF029230369B33FC2B488B5F82702EFC3F270F912EAD2E" +
"2402D99F8324164C5CD5959F22DEC0D1D212345B4B3F62848E7D9CFCE2224B61" +
"976C107E1B218B4B7614FF65BCCA388F85D6920270D4C588DEED323C416D014F" +
"5F648CC2EE941855EB3C889DCB9A345ED11CAE94041A86ED23E5789137A3DE22" +
"5F4023D260BB686901F2149B5D7E37102FFF5282995892BDC2EAB48BD5DA155F" +
"72B1BD05EE3EDD32160AC852E5B47CA9AEACE24946062E9D7DCDA642F945C9E7" +
"C98640DFAC7A2B88E76A560A0B4156611F9BE8B3613C71870F035062BD4E3D9F" +
"D896CF373CBFBFD31410972CDE50739FFB8EC9180A52D7F5415EBC997E5A4221" +
"349B4BB7D53614630EEEA729A74E0C0D20726FDE5814321D6C265A7DC6BA24CA" +
"F2FCE8C8C162733D58E02E08921E70EF838B95C96A5818489782563AE8A2A85F" +
"64A95EB350FF8EF6D625AD031BCD303B301F300706052B0E03021A0414C8D96C" +
"ED140F5CA3CB92BEFCA32C690804576ABF0414B59D4FECA9944D40EEFDE7FB96" +
"196D167B0FA511020207D0").HexToByteArray();
internal static readonly byte[] ECDsaP256_DigitalSignature_Cert = (
"308201583081FFA003020102021035428F3B3C5107AD49E776D6E74C4DC8300A" +
"06082A8648CE3D04030230153113301106035504030C0A454344534120546573" +
"74301E170D3135303530313030333730335A170D313630353031303035373033" +
"5A30153113301106035504030C0A454344534120546573743059301306072A86" +
"48CE3D020106082A8648CE3D030107034200047590F69CA114E92927E034C997" +
"B7C882A8C992AC00CEFB4EB831901536F291E1B515263BCD20E1EA32496FDAC8" +
"4E2D8D1B703266A9088F6EAF652549D9BB63D5A331302F300E0603551D0F0101" +
"FF040403020388301D0603551D0E0416041411218A92C5EB12273B3C5CCFB822" +
"0CCCFDF387DB300A06082A8648CE3D040302034800304502201AFE595E19F1AE" +
"4B6A4B231E8851926438C55B5DDE632E6ADF13C1023A65898E022100CBDF434F" +
"DD197D8B594E8026E44263BADE773C2BEBD060CC4109484A498E7C7E").HexToByteArray();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NUnit.Framework;
using Should;
#if !SILVERLIGHT
using NUnit.Framework.SyntaxHelpers;
#endif
namespace AutoMapper.UnitTests
{
[TestFixture]
public class CollectionMapping
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
Mapper.Reset();
}
[TearDown]
public void TearDown()
{
}
#endregion
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
}
public class MasterWithList
{
private IList<Detail> _details = new List<Detail>();
public int Id { get; set; }
public IList<Detail> Details
{
get { return _details; }
set { _details = value; }
}
}
public class MasterWithCollection
{
public MasterWithCollection(ICollection<Detail> details)
{
Details = details;
}
public int Id { get; set; }
public ICollection<Detail> Details { get; set; }
}
public class MasterWithNoExistingCollection
{
public int Id { get; set; }
public HashSet<Detail> Details { get; set; }
}
public class Detail
{
public int Id { get; set; }
}
public class MasterDto
{
public int Id { get; set; }
public DetailDto[] Details { get; set; }
}
public class DetailDto
{
public int Id { get; set; }
}
private static void FillCollection<TSource, TDestination, TSourceItem, TDestinationItem>(
TSource s, TDestination d,
Func<TSource, IEnumerable<TSourceItem>> getSourceEnum,
Func<TDestination, ICollection<TDestinationItem>> getDestinationColl)
{
ICollection<TDestinationItem> collection = getDestinationColl(d);
collection.Clear();
foreach (TSourceItem sourceItem in getSourceEnum(s))
{
collection.Add(Mapper.Map<TSourceItem, TDestinationItem>(sourceItem));
}
}
[Test]
public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_list()
{
Mapper.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, o => o.UseDestinationValue());
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new List<Detail>());
ICollection<Detail> originalCollection = master.Details;
Mapper.Map(dto, master);
Assert.That(master.Details, Is.SameAs(originalCollection));
Assert.That(master.Details.Count, Is.EqualTo(originalCollection.Count));
}
[Test]
public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_set()
{
Mapper.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, o => o.UseDestinationValue());
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new HashSet<Detail>());
ICollection<Detail> originalCollection = master.Details;
Mapper.Map(dto, master);
Assert.That(master.Details, Is.SameAs(originalCollection));
Assert.That(master.Details.Count, Is.EqualTo(originalCollection.Count));
}
[Test]
public void Should_keep_and_fill_destination_collection_when_collection_is_implemented_as_set_with_aftermap()
{
Mapper.CreateMap<MasterDto, MasterWithCollection>()
.ForMember(d => d.Details, o => o.Ignore())
.AfterMap((s, d) => FillCollection(s, d, ss => ss.Details, dd => dd.Details));
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new HashSet<Detail>());
ICollection<Detail> originalCollection = master.Details;
Mapper.Map(dto, master);
Assert.That(master.Details, Is.SameAs(originalCollection));
Assert.That(master.Details.Count, Is.EqualTo(originalCollection.Count));
}
[Test]
public void Should_keep_and_fill_destination_list()
{
Mapper.CreateMap<MasterDto, MasterWithList>()
.ForMember(d => d.Details, o => o.UseDestinationValue());
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithList();
IList<Detail> originalCollection = master.Details;
Mapper.Map(dto, master);
Assert.That(master.Details, Is.SameAs(originalCollection));
Assert.That(master.Details.Count, Is.EqualTo(originalCollection.Count));
}
[Test]
public void Should_replace_destination_collection()
{
Mapper.CreateMap<MasterDto, MasterWithCollection>();
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithCollection(new List<Detail>());
ICollection<Detail> originalCollection = master.Details;
Mapper.Map(dto, master);
Assert.That(master.Details, Is.Not.SameAs(originalCollection));
}
[Test]
public void Should_be_able_to_map_to_a_collection_type_that_implements_ICollection_of_T()
{
Mapper.CreateMap<MasterDto, MasterWithNoExistingCollection>();
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = Mapper.Map<MasterDto, MasterWithNoExistingCollection>(dto);
master.Details.Count.ShouldEqual(2);
}
[Test]
public void Should_replace_destination_list()
{
Mapper.CreateMap<MasterDto, MasterWithList>();
Mapper.CreateMap<DetailDto, Detail>();
var dto = new MasterDto
{
Id = 1,
Details = new[]
{
new DetailDto {Id = 2},
new DetailDto {Id = 3},
}
};
var master = new MasterWithList();
IList<Detail> originalCollection = master.Details;
Mapper.Map(dto, master);
Assert.That(master.Details, Is.Not.SameAs(originalCollection));
}
#if SILVERLIGHT
public class HashSet<T> : Collection<T>
{
}
#endif
}
}
| |
// <copyright file="SignaturePadView.cs" company="">
// All rights reserved.
// </copyright>
using Android.Content;
using Android.Graphics;
using Android.Util;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Anuracode.Forms.Controls.Renderers
{
/// <summary>
/// Signature pad view.
/// </summary>
public class SignaturePad : RelativeLayout
{
/// <summary>
/// The color of the signature line.
/// </summary>
/// <value>The color of the signature line.</value>
protected Color signatureLineColor;
/// <summary>
/// Random seed.
/// </summary>
private static Random rndId = new Random();
/// <summary>
/// Background color.
/// </summary>
private Color backgroundColor;
/// <summary>
/// Canvas view.
/// </summary>
private SignatureCanvasView canvasView;
/// <summary>
/// Context to use.
/// </summary>
private Context context;
/// <summary>
/// Current points.
/// </summary>
private List<System.Drawing.PointF> currentPoints;
/// <summary>
/// Used to determine rectangle that needs to be redrawn.
/// </summary>
private RectF dirtyRect;
/// <summary>
/// Clear image view.
/// </summary>
private ClearingImageView imageView;
/// <summary>
/// Current path.
/// </summary>
private Path internalCurrentPath;
/// <summary>
/// Paoint to use.
/// </summary>
private Paint internalPaint;
/// <summary>
/// Last x.
/// </summary>
private float lastX;
/// <summary>
/// Last y.
/// </summary>
private float lastY;
/// <summary>
/// Label sign.
/// </summary>
private TextView lblSign;
/// <summary>
/// Paths to use.
/// </summary>
private List<Path> paths;
/// <summary>
/// Points to use.
/// </summary>
private List<System.Drawing.PointF[]> points;
/// <summary>
/// View signature.
/// </summary>
private View signatureLine;
/// <summary>
/// Gets or sets the color of the strokes for the signature.
/// </summary>
private Color strokeColor;
/// <summary>
/// Gets or sets the width in pixels of the strokes for the signature.
/// </summary>
private float strokeWidth;
/// <summary>
/// Bitmap buffer off by default since memory is a limited resource.
/// </summary>
private bool useBitmapBuffer = false;
/// <summary>
/// Label for the x.
/// </summary>
private TextView xLabel;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="context">Context to use.</param>
public SignaturePad(Context context)
: base(context)
{
this.context = context;
Initialize();
}
/// <summary>
/// Constructor with attributes.
/// </summary>
/// <param name="context">Context to use.</param>
/// <param name="attrs">Attributes to use.</param>
public SignaturePad(Context context, IAttributeSet attrs)
: base(context, attrs)
{
this.context = context;
Initialize();
}
/// <summary>
/// Constructor with attributes.
/// </summary>
/// <param name="context">Context to use.</param>
/// <param name="attrs">Attributes to use.</param>
/// <param name="defStyle">Style to use.</param>
public SignaturePad(Context context, IAttributeSet attrs, int defStyle) :
base(context, attrs, defStyle)
{
this.context = context;
Initialize();
}
/// <summary>
/// Background color.
/// </summary>
public Color BackgroundColor
{
get
{
return backgroundColor;
}
set
{
backgroundColor = value;
SetBackgroundColor(backgroundColor);
}
}
/// <summary>
/// Gets the background image view.
/// </summary>
/// <value>The background image view.</value>
public ImageView BackgroundImageView { get; private set; }
/// <summary>
/// The caption displayed under the signature line.
/// </summary>
/// <remarks>
/// Text value defaults to 'Sign here.'
/// </remarks>
/// <value>The caption.</value>
public TextView Caption
{
get
{
return lblSign;
}
set
{
lblSign = value;
}
}
/// <summary>
/// Property to check if its blank.
/// </summary>
public bool IsBlank
{
get
{
return points == null || points.Count() == 0 || !(points.Where(p => p.Any()).Any());
}
}
/// <summary>
/// Create an array containing all of the points used to draw the signature. Uses null
/// to indicate a new line.
/// </summary>
public System.Drawing.PointF[] Points
{
get
{
if (points == null || points.Count() == 0)
return new System.Drawing.PointF[0];
IEnumerable<System.Drawing.PointF> pointsList = points[0];
for (var i = 1; i < points.Count; i++)
{
pointsList = pointsList.Concat(new[] { System.Drawing.PointF.Empty });
pointsList = pointsList.Concat(points[i]);
}
return pointsList.ToArray();
}
}
/// <summary>
/// Delegate when the is blank changed.
/// </summary>
public Action RaiseIsBlankChangedDelegate { get; set; }
/// <summary>
/// Gets the horizontal line that goes in the lower part of the pad.
/// </summary>
/// <value>The signature line.</value>
public View SignatureLine
{
get
{
return signatureLine;
}
}
/// <summary>
/// The color of the signature line.
/// </summary>
/// <value>The color of the signature line.</value>
public Color SignatureLineColor
{
get
{
return signatureLineColor;
}
set
{
signatureLineColor = value;
signatureLine.SetBackgroundColor(value);
}
}
/// <summary>
/// The prompt displayed at the beginning of the signature line.
/// </summary>
/// <remarks>
/// Text value defaults to 'X'.
/// </remarks>
/// <value>The signature prompt.</value>
public TextView SignaturePrompt
{
get
{
return xLabel;
}
set
{
xLabel = value;
}
}
/// <summary>
/// Gets or sets the color of the strokes for the signature.
/// </summary>
public Color StrokeColor
{
get
{
return strokeColor;
}
set
{
strokeColor = value;
if (paint != null)
paint.Color = strokeColor;
if (!IsBlank)
DrawStrokes();
}
}
/// <summary>
/// Gets or sets the width in pixels of the strokes for the signature.
/// </summary>
public float StrokeWidth
{
get
{
return strokeWidth;
}
set
{
strokeWidth = value;
if (paint != null)
{
paint.StrokeWidth = strokeWidth;
}
if (!IsBlank)
{
DrawStrokes();
}
}
}
/// <summary>
/// Bitmap buffer off by default since memory is a limited resource.
/// </summary>
public bool UseBitmapBuffer
{
get
{
return useBitmapBuffer;
}
set
{
useBitmapBuffer = value;
if (useBitmapBuffer)
{
DrawStrokes();
}
else
{
imageView.SetImageBitmap(null);
}
}
}
/// <summary>
/// Current path.
/// </summary>
protected Path currentPath
{
get
{
return internalCurrentPath;
}
set
{
canvasView.Path = internalCurrentPath = value;
}
}
/// <summary>
/// Point to use.
/// </summary>
protected Paint paint
{
get
{
return internalPaint;
}
set
{
canvasView.Paint = internalPaint = value;
}
}
/// <summary>
/// Delete the current signature.
/// </summary>
public void Clear()
{
paths = new List<Path>();
points = new List<System.Drawing.PointF[]>();
currentPoints = new List<System.Drawing.PointF>();
currentPath = new Path();
imageView.SetImageBitmap(null);
GC.Collect();
canvasView.Invalidate();
Invalidate();
NotifyIsBlankChanged();
}
/// <summary>
/// Draw canvas.
/// </summary>
/// <param name="canvas">Canvas to use.</param>
public override void Draw(Canvas canvas)
{
base.Draw(canvas);
if (!UseBitmapBuffer)
{
//Bitmap not in use: redraw all of the paths.
DrawStrokesOnCanvas(canvas, this.strokeColor, Color.Transparent, false);
}
}
/// <summary>
/// Create a UIImage of the currently drawn signature.
/// </summary>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
public Bitmap GetImage(bool shouldCrop = true, bool keepAspectRatio = true)
{
return GetImage(strokeColor, Color.Transparent, new System.Drawing.SizeF(Width, Height), 1, shouldCrop, keepAspectRatio);
}
/// <summary>
/// Create a image of the currently drawn signature.
/// </summary>
/// <param name="size">Size to use.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
public Bitmap GetImage(System.Drawing.SizeF size, bool shouldCrop = true, bool keepAspectRatio = true)
{
return GetImage(strokeColor, Color.Transparent, size, GetScaleFromSize(size, Width, Height), shouldCrop, keepAspectRatio);
}
/// <summary>
/// Create a UIImage of the currently drawn signature.
/// </summary>
/// <param name="scale">Scale to use.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
public Bitmap GetImage(float scale, bool shouldCrop = true, bool keepAspectRatio = true)
{
return GetImage(
strokeColor,
Color.Transparent,
GetSizeFromScale(scale, Width, Height),
scale,
shouldCrop,
keepAspectRatio);
}
/// <summary>
/// Create a UIImage of the currently drawn signature.
/// </summary>
/// <param name="strokeColor">Color to use.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
public Bitmap GetImage(Color strokeColor, bool shouldCrop = true, bool keepAspectRatio = true)
{
return GetImage(
strokeColor,
Color.Transparent,
new System.Drawing.SizeF(Width, Height),
1,
shouldCrop,
keepAspectRatio);
}
/// <summary>
/// Create a UIImage of the currently drawn signature.
/// </summary>
/// <param name="strokeColor">Color to use.</param>
/// <param name="size">Size to use.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
public Bitmap GetImage(Color strokeColor, System.Drawing.SizeF size, bool shouldCrop = true, bool keepAspectRatio = true)
{
return GetImage(
strokeColor,
Color.Transparent,
size,
GetScaleFromSize(size, Width, Height),
shouldCrop,
keepAspectRatio);
}
/// <summary>
/// Create a UIImage of the currently drawn signature.
/// </summary>
/// <param name="strokeColor">Color to use.</param>
/// <param name="scale">Scale to use.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
public Bitmap GetImage(Color strokeColor, float scale, bool shouldCrop = true, bool keepAspectRatio = true)
{
return GetImage(
strokeColor,
Color.Transparent,
GetSizeFromScale(scale, Width, Height),
scale,
shouldCrop,
keepAspectRatio);
}
/// <summary>
/// Create a UIImage of the currently drawn signature.
/// </summary>
/// <param name="strokeColor">Color to use.</param>
/// <param name="fillColor">Fill color.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
public Bitmap GetImage(Color strokeColor, Color fillColor, bool shouldCrop = true, bool keepAspectRatio = true)
{
return GetImage(
strokeColor,
fillColor,
new System.Drawing.SizeF(Width, Height),
1,
shouldCrop,
keepAspectRatio);
}
/// <summary>
/// Create a UIImage of the currently drawn signature.
/// </summary>
/// <param name="strokeColor">Color to use.</param>
/// <param name="fillColor">Fill color.</param>
/// <param name="size">Size to use.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
public Bitmap GetImage(Color strokeColor, Color fillColor, System.Drawing.SizeF size,
bool shouldCrop = true, bool keepAspectRatio = true)
{
return GetImage(
strokeColor,
fillColor,
size,
GetScaleFromSize(size, Width, Height),
shouldCrop,
keepAspectRatio);
}
/// <summary>
/// Create a UIImage of the currently drawn signature.
/// </summary>
/// <param name="strokeColor">Color to use.</param>
/// <param name="fillColor">Fill color.</param>
/// <param name="scale">Scale to use.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
public Bitmap GetImage(Color strokeColor, Color fillColor, float scale, bool shouldCrop = true, bool keepAspectRatio = true)
{
return GetImage(
strokeColor,
fillColor,
GetSizeFromScale(scale, Width, Height),
scale,
shouldCrop,
keepAspectRatio);
}
/// <summary>
/// Get the points in string format.
/// </summary>
/// <returns>String with the point.</returns>
public async Task<string> GetPointsStringAsync()
{
await Task.FromResult(0);
string result = null;
List<List<DrawPoint>> linesList = new List<List<DrawPoint>>();
// The first child is always the current drawing path, and should be ignored.
if ((points != null) && (points.Count > 1))
{
List<DrawPoint> pointLine;
System.Drawing.PointF[] line;
System.Drawing.PointF point;
for (int i = 0; i < points.Count; i++)
{
line = points[i];
if ((line != null) && (line.Length > 0))
{
pointLine = new List<DrawPoint>();
for (int j = 0; j < line.Length; j++)
{
point = line[j];
pointLine.Add(new DrawPoint(point.X, point.Y));
}
linesList.Add(pointLine);
}
}
result = await SignatureSerializer.SerializeAsync(linesList);
}
return result;
}
/// <summary>
/// Allow the user to import an array of points to be used to draw a signature in the view, with new
/// lines indicated by a System.Drawing.PointF.Empty in the array.
/// </summary>
/// <param name="loadedPoints">Point to use.</param>
public void LoadPoints(System.Drawing.PointF[] loadedPoints)
{
if (loadedPoints == null || loadedPoints.Count() == 0)
{
return;
}
var startIndex = 0;
var emptyIndex = loadedPoints.ToList().IndexOf(System.Drawing.PointF.Empty);
if (emptyIndex == -1)
{
emptyIndex = loadedPoints.Count();
}
//Clear any existing paths or points.
paths = new List<Path>();
points = new List<System.Drawing.PointF[]>();
do
{
//Create a new path and set the line options
currentPath = new Path();
currentPoints = new List<System.Drawing.PointF>();
//Move to the first point and add that point to the current_points array.
currentPath.MoveTo(loadedPoints[startIndex].X, loadedPoints[startIndex].Y);
currentPoints.Add(loadedPoints[startIndex]);
//Iterate through the array until an empty point (or the end of the array) is reached,
//adding each point to the current_path and to the current_points array.
for (var i = startIndex + 1; i < emptyIndex; i++)
{
currentPath.LineTo(loadedPoints[i].X, loadedPoints[i].Y);
currentPoints.Add(loadedPoints[i]);
}
//Add the current_path and current_points list to their respective Lists before
//starting on the next line to be drawn.
paths.Add(currentPath);
points.Add(currentPoints.ToArray());
//Obtain the indices for the next line to be drawn.
startIndex = emptyIndex + 1;
if (startIndex < loadedPoints.Count() - 1)
{
emptyIndex = loadedPoints.ToList().IndexOf(System.Drawing.PointF.Empty, startIndex);
if (emptyIndex == -1)
{
emptyIndex = loadedPoints.Count();
}
}
else
{
emptyIndex = startIndex;
}
} while (startIndex < emptyIndex);
DrawStrokes();
//Display the clear button.
Invalidate();
NotifyIsBlankChanged();
}
/// <summary>
/// On touch event.
/// </summary>
/// <param name="e">Arguments of the event.</param>
/// <returns>Flag to use.</returns>
public override bool OnTouchEvent(MotionEvent e)
{
float touchX = e.GetX();
float touchY = e.GetY();
System.Drawing.PointF touch = new System.Drawing.PointF(touchX, touchY);
switch (e.Action)
{
case MotionEventActions.Down:
lastX = touchX;
lastY = touchY;
//Create a new path and move to the touched point.
currentPath = new Path();
currentPath.MoveTo(touchX, touchY);
//Clear the list of points then add the touched point
currentPoints.Clear();
currentPoints.Add(touch);
return true;
case MotionEventActions.Move:
HandleTouch(e);
canvasView.Invalidate(
(int)(dirtyRect.Left - 1),
(int)(dirtyRect.Top - 1),
(int)(dirtyRect.Right + 1),
(int)(dirtyRect.Bottom + 1));
break;
case MotionEventActions.Up:
HandleTouch(e);
currentPath = SmoothedPathWithGranularity(0, out currentPoints);
// Add the current path and points to their respective lists.
paths.Add(currentPath);
points.Add(currentPoints.ToArray());
DrawStrokes();
canvasView.Invalidate();
NotifyIsBlankChanged();
break;
default:
return false;
}
lastX = touchX;
lastY = touchY;
return true;
}
/// <summary>
/// Generate id.
/// </summary>
/// <returns>New Id.</returns>
protected int GenerateId()
{
int id;
for (; ; )
{
id = rndId.Next(1, 0x00FFFFFF);
if (FindViewById<View>(id) != null)
{
continue;
}
return id;
}
}
/// <summary>
/// Notify the is blank changed.
/// </summary>
protected void NotifyIsBlankChanged()
{
if (RaiseIsBlankChangedDelegate != null)
{
RaiseIsBlankChangedDelegate();
}
}
/// <summary>
/// Draw strokes.
/// </summary>
private void DrawStrokes()
{
if (UseBitmapBuffer)
{
//Get an image of the current signature and display it so that the entire set of paths
//doesn't have to be redrawn every time.
this.imageView.SetImageBitmap(this.GetImage(false));
}
else
{
Invalidate();
}
}
/// <summary>
/// Draw strokes on canvas.
/// </summary>
/// <param name="canvas">Canvas to use.</param>
/// <param name="strokeColor">Stroke color.</param>
/// <param name="fillColor">Fill color.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="croppedRectangle">Crop rectangle.</param>
private void DrawStrokesOnCanvas(Canvas canvas, Color strokeColor, Color fillColor, bool shouldCrop, RectF croppedRectangle = null)
{
canvas.DrawColor(fillColor);
paint.Color = strokeColor;
foreach (var path in paths)
{
var tempPath = path;
if (shouldCrop)
{
tempPath = new Path(path);
var translate = new Matrix();
translate.SetTranslate(-croppedRectangle.Left, -croppedRectangle.Top);
tempPath.Transform(translate);
}
canvas.DrawPath(tempPath, paint);
tempPath = null;
}
paint.Color = this.strokeColor;
}
/// <summary>
/// Get cropped rectange.
/// </summary>
/// <param name="cachedPoints">Chached points.</param>
/// <returns>Rectangle for the crop.</returns>
private RectF GetCroppedRectangle(System.Drawing.PointF[] cachedPoints)
{
var xMin = cachedPoints.Where(point => !point.IsEmpty).Min(point => point.X) - strokeWidth / 2;
var xMax = cachedPoints.Where(point => !point.IsEmpty).Max(point => point.X) + strokeWidth / 2;
var yMin = cachedPoints.Where(point => !point.IsEmpty).Min(point => point.Y) - strokeWidth / 2;
var yMax = cachedPoints.Where(point => !point.IsEmpty).Max(point => point.Y) + strokeWidth / 2;
xMin = Math.Max(xMin, 0);
xMax = Math.Min(xMax, Width);
yMin = Math.Max(yMin, 0);
yMax = Math.Min(yMax, Height);
return new RectF(xMin, yMin, xMax, yMax);
}
/// <summary>
/// Create a UIImage of the currently drawn signature.
/// </summary>
/// <param name="strokeColor">Color to use.</param>
/// <param name="fillColor">Fill color.</param>
/// <param name="size">Size to use.</param>
/// <param name="scale">Scale to use.</param>
/// <param name="shouldCrop">Should crop.</param>
/// <param name="keepAspectRatio">Keep ratio.</param>
/// <returns>New bitmap.</returns>
private Bitmap GetImage(
Color strokeColor,
Color fillColor,
System.Drawing.SizeF size,
float scale,
bool shouldCrop = true,
bool keepAspectRatio = true)
{
if (size.Width == 0 || size.Height == 0 || scale <= 0)
{
return null;
}
float uncroppedScale;
RectF croppedRectangle = new RectF();
System.Drawing.PointF[] cachedPoints;
if (shouldCrop && (cachedPoints = Points).Any())
{
croppedRectangle = GetCroppedRectangle(cachedPoints);
if (croppedRectangle.Left >= 5)
croppedRectangle.Left -= 5;
if (croppedRectangle.Right <= size.Width - 5)
croppedRectangle.Right += 5;
if (croppedRectangle.Top >= 5)
croppedRectangle.Top -= 5;
if (croppedRectangle.Bottom <= size.Height - 5)
croppedRectangle.Bottom += 5;
float scaleX = (croppedRectangle.Right - croppedRectangle.Left) / Width;
float scaleY = (croppedRectangle.Bottom - croppedRectangle.Top) / Height;
uncroppedScale = 1 / Math.Max(scaleX, scaleY);
}
else
{
uncroppedScale = scale;
}
Bitmap image;
if (keepAspectRatio)
{
image = Bitmap.CreateBitmap((int)size.Width, (int)size.Height, Bitmap.Config.Argb8888);
}
else
{
image = Bitmap.CreateBitmap((int)(croppedRectangle.Width() * uncroppedScale), (int)(croppedRectangle.Height() * uncroppedScale), Bitmap.Config.Argb8888);
}
Canvas canvas = new Canvas(image);
canvas.Scale(uncroppedScale, uncroppedScale);
DrawStrokesOnCanvas(canvas, strokeColor, fillColor, shouldCrop, croppedRectangle);
return image;
}
/// <summary>
/// Get scale from size.
/// </summary>
/// <param name="size">Size to use.</param>
/// <param name="width">Width to use.</param>
/// <param name="height">Height to use.</param>
/// <returns>Scale to use.</returns>
private float GetScaleFromSize(System.Drawing.SizeF size, float width, float height)
{
float scaleX = size.Width / width;
float scaleY = size.Height / height;
return Math.Min(scaleX, scaleY);
}
/// <summary>
/// Get size from scale.
/// </summary>
/// <param name="scale">Scale to use.</param>
/// <param name="inWidth">Width to use.</param>
/// <param name="inHeight">Height to use.</param>
/// <returns>New size.</returns>
private System.Drawing.SizeF GetSizeFromScale(float scale, float inWidth, float inHeight)
{
float width = inWidth * scale;
float height = inHeight * scale;
return new System.Drawing.SizeF(width, height);
}
/// <summary>
/// Iterate through the touch history since the last touch event and add them to the path and points list.
/// </summary>
/// <param name="e">Arguments to use.</param>
private void HandleTouch(MotionEvent e)
{
float touchX = e.GetX();
float touchY = e.GetY();
System.Drawing.PointF touch = new System.Drawing.PointF(touchX, touchY);
ResetBounds(touchX, touchY);
for (var i = 0; i < e.HistorySize; i++)
{
float historicalX = e.GetHistoricalX(i);
float historicalY = e.GetHistoricalY(i);
System.Drawing.PointF historical = new System.Drawing.PointF(historicalX, historicalY);
UpdateBounds(historicalX, historicalY);
currentPath.LineTo(historicalX, historicalY);
currentPoints.Add(historical);
}
currentPath.LineTo(touchX, touchY);
currentPoints.Add(touch);
}
/// <summary>
/// Initialize view.
/// </summary>
private void Initialize()
{
BackgroundColor = Color.Black;
strokeColor = Color.White;
StrokeWidth = 2f;
canvasView = new SignatureCanvasView(this.context);
canvasView.LayoutParameters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FillParent, RelativeLayout.LayoutParams.FillParent);
// Set the attributes for painting the lines on the screen.
paint = new Paint();
paint.Color = strokeColor;
paint.StrokeWidth = StrokeWidth;
paint.SetStyle(Paint.Style.Stroke);
paint.StrokeJoin = Paint.Join.Round;
paint.StrokeCap = Paint.Cap.Round;
paint.AntiAlias = true;
#region Add Subviews
RelativeLayout.LayoutParams layout;
BackgroundImageView = new ImageView(this.context);
BackgroundImageView.Id = GenerateId();
AddView(BackgroundImageView);
// Add an image that covers the entire signature view, used to display already drawn
// elements instead of having to redraw them every time the user touches the screen.
imageView = new ClearingImageView(context);
imageView.SetBackgroundColor(Color.Transparent);
imageView.LayoutParameters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FillParent, RelativeLayout.LayoutParams.FillParent);
AddView(imageView);
lblSign = new TextView(context);
lblSign.Id = GenerateId();
lblSign.SetIncludeFontPadding(true);
lblSign.Text = "Sign Here";
layout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent);
layout.AlignWithParent = true;
layout.BottomMargin = 6;
layout.AddRule(LayoutRules.AlignBottom);
layout.AddRule(LayoutRules.CenterHorizontal);
lblSign.LayoutParameters = layout;
lblSign.SetPadding(0, 0, 0, 6);
AddView(lblSign);
// Display the base line for the user to sign on.
signatureLine = new View(context);
signatureLine.Id = GenerateId();
signatureLine.SetBackgroundColor(Color.Gray);
layout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, 1);
layout.SetMargins(10, 0, 10, 5);
layout.AddRule(LayoutRules.Above, lblSign.Id);
signatureLine.LayoutParameters = layout;
AddView(signatureLine);
// Display the X on the left hand side of the line where the user signs.
xLabel = new TextView(context);
xLabel.Id = GenerateId();
xLabel.Text = "X";
xLabel.SetTypeface(null, TypefaceStyle.Bold);
layout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent);
layout.LeftMargin = 11;
layout.AddRule(LayoutRules.Above, signatureLine.Id);
xLabel.LayoutParameters = layout;
AddView(xLabel);
AddView(canvasView);
#endregion Add Subviews
paths = new List<Path>();
points = new List<System.Drawing.PointF[]>();
currentPoints = new List<System.Drawing.PointF>();
dirtyRect = new RectF();
}
/// <summary>
/// Set the bounds for the rectangle that will need to be redrawn to show the drawn path.
/// </summary>
/// <param name="touchX">Touch X.</param>
/// <param name="touchY">Touch Y.</param>
private void ResetBounds(float touchX, float touchY)
{
if (touchX < lastX)
{
dirtyRect.Left = touchX;
}
if (touchX > lastX)
{
dirtyRect.Right = touchX;
}
if (touchY < lastY)
{
dirtyRect.Top = touchY;
}
if (touchY > lastY)
{
dirtyRect.Bottom = touchY;
}
}
/// <summary>
/// Smooth points.
/// </summary>
/// <param name="granularity">Granularity to use.</param>
/// <param name="smoothedPoints">Points smoothed.</param>
/// <returns>Path to use.</returns>
private Path SmoothedPathWithGranularity(int granularity, out List<System.Drawing.PointF> smoothedPoints)
{
List<System.Drawing.PointF> pointsArray = currentPoints;
smoothedPoints = new List<System.Drawing.PointF>();
//Not enough points to smooth effectively, so return the original path and points.
if (pointsArray.Count < 4)
{
smoothedPoints = pointsArray;
return currentPath;
}
//Create a new bezier path to hold the smoothed path.
Path smoothedPath = new Path();
//Duplicate the first and last points as control points.
pointsArray.Insert(0, pointsArray[0]);
pointsArray.Add(pointsArray[pointsArray.Count - 1]);
//Add the first point
smoothedPath.MoveTo(pointsArray[0].X, pointsArray[0].Y);
smoothedPoints.Add(pointsArray[0]);
for (var index = 1; index < pointsArray.Count - 2; index++)
{
System.Drawing.PointF p0 = pointsArray[index - 1];
System.Drawing.PointF p1 = pointsArray[index];
System.Drawing.PointF p2 = pointsArray[index + 1];
System.Drawing.PointF p3 = pointsArray[index + 2];
//Add n points starting at p1 + dx/dy up until p2 using Catmull-Rom splines
for (var i = 1; i < granularity; i++)
{
float t = (float)i * (1f / (float)granularity);
float tt = t * t;
float ttt = tt * t;
//Intermediate point
System.Drawing.PointF mid = new System.Drawing.PointF();
mid.X = 0.5f * (2f * p1.X + (p2.X - p0.X) * t +
(2f * p0.X - 5f * p1.X + 4f * p2.X - p3.X) * tt +
(3f * p1.X - p0.X - 3f * p2.X + p3.X) * ttt);
mid.Y = 0.5f * (2 * p1.Y + (p2.Y - p0.Y) * t +
(2 * p0.Y - 5 * p1.Y + 4 * p2.Y - p3.Y) * tt +
(3 * p1.Y - p0.Y - 3 * p2.Y + p3.Y) * ttt);
smoothedPath.LineTo(mid.X, mid.Y);
smoothedPoints.Add(mid);
}
//Add p2
smoothedPath.LineTo(p2.X, p2.Y);
smoothedPoints.Add(p2);
}
//Add the last point
System.Drawing.PointF last = pointsArray[pointsArray.Count - 1];
smoothedPath.LineTo(last.X, last.Y);
smoothedPoints.Add(last);
return smoothedPath;
}
/// <summary>
/// Update the bounds for the rectangle to be redrawn if necessary for the given point.
/// </summary>
/// <param name="touchX">Touch X.</param>
/// <param name="touchY">Touch Y.</param>
private void UpdateBounds(float touchX, float touchY)
{
if (touchX < dirtyRect.Left)
{
dirtyRect.Left = touchX;
}
else if (touchX > dirtyRect.Right)
{
dirtyRect.Right = touchX;
}
if (touchY < dirtyRect.Top)
{
dirtyRect.Top = touchY;
}
else if (touchY > dirtyRect.Bottom)
{
dirtyRect.Bottom = touchY;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.YamlSerialization.ObjectGraphTraversalStrategies
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
#if !NetCore
using System.Globalization;
#endif
using System.Reflection;
using System.Reflection.Emit;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using Microsoft.DocAsCode.YamlSerialization.Helpers;
using Microsoft.DocAsCode.YamlSerialization.ObjectDescriptors;
using IObjectGraphVisitor = System.Object;
using IObjectGraphVisitorContext = System.Object;
/// <summary>
/// An implementation of <see cref="IObjectGraphTraversalStrategy"/> that traverses
/// readable properties, collections and dictionaries.
/// </summary>
public class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy
{
private static MethodInfo TraverseGenericDictionaryHelperMethod { get; } =
typeof(FullObjectGraphTraversalStrategy).GetMethod(nameof(TraverseGenericDictionaryHelper));
protected YamlSerializer Serializer { get; }
private readonly int _maxRecursion;
private readonly ITypeInspector _typeDescriptor;
private readonly ITypeResolver _typeResolver;
private INamingConvention _namingConvention;
private readonly Dictionary<Tuple<Type, Type>, Action<IObjectDescriptor, IObjectGraphVisitor, int, IObjectGraphVisitorContext>> _behaviorCache =
new Dictionary<Tuple<Type, Type>, Action<IObjectDescriptor, IObjectGraphVisitor, int, IObjectGraphVisitorContext>>();
private readonly Dictionary<Tuple<Type, Type, Type>, Action<FullObjectGraphTraversalStrategy, object, IObjectGraphVisitor, int, INamingConvention, IObjectGraphVisitorContext>> _traverseGenericDictionaryCache =
new Dictionary<Tuple<Type, Type, Type>, Action<FullObjectGraphTraversalStrategy, object, IObjectGraphVisitor, int, INamingConvention, IObjectGraphVisitorContext>>();
public FullObjectGraphTraversalStrategy(YamlSerializer serializer, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention)
{
if (maxRecursion <= 0)
{
throw new ArgumentOutOfRangeException("maxRecursion", maxRecursion, "maxRecursion must be greater than 1");
}
Serializer = serializer;
_typeDescriptor = typeDescriptor ?? throw new ArgumentNullException("typeDescriptor");
_typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver");
_maxRecursion = maxRecursion;
_namingConvention = namingConvention;
}
void IObjectGraphTraversalStrategy.Traverse<TContext>(IObjectDescriptor graph, IObjectGraphVisitor<TContext> visitor, TContext context)
{
Traverse(graph, visitor, 0, context);
}
protected virtual void Traverse<TContext>(IObjectDescriptor value, IObjectGraphVisitor<TContext> visitor, int currentDepth, TContext context)
{
if (++currentDepth > _maxRecursion)
{
throw new InvalidOperationException("Too much recursion when traversing the object graph");
}
if (!visitor.Enter(value, context))
{
return;
}
var typeCode = Type.GetTypeCode(value.Type);
switch (typeCode)
{
case TypeCode.Boolean:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
case TypeCode.String:
case TypeCode.Char:
case TypeCode.DateTime:
visitor.VisitScalar(value, context);
break;
case TypeCode.DBNull:
visitor.VisitScalar(new BetterObjectDescriptor(null, typeof(object), typeof(object)), context);
break;
case TypeCode.Empty:
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "TypeCode.{0} is not supported.", typeCode));
default:
if (value.Value == null || value.Type == typeof(TimeSpan))
{
visitor.VisitScalar(value, context);
break;
}
var underlyingType = Nullable.GetUnderlyingType(value.Type);
if (underlyingType != null)
{
// This is a nullable type, recursively handle it with its underlying type.
// Note that if it contains null, the condition above already took care of it
Traverse(new BetterObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, currentDepth, context);
}
else
{
TraverseObject(value, visitor, currentDepth, context);
}
break;
}
}
protected virtual void TraverseObject<TContext>(IObjectDescriptor value, IObjectGraphVisitor<TContext> visitor, int currentDepth, TContext context)
{
var key = Tuple.Create(value.Type, typeof(TContext));
if (!_behaviorCache.TryGetValue(key, out var action))
{
if (typeof(IDictionary).IsAssignableFrom(value.Type))
{
action = TraverseDictionary<TContext>;
}
else
{
var dictionaryType = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IDictionary<,>));
if (dictionaryType != null)
{
action = (v, vi, d, c) => TraverseGenericDictionary<TContext>(v, dictionaryType, vi, d, c);
}
else if (typeof(IEnumerable).IsAssignableFrom(value.Type))
{
action = TraverseList<TContext>;
}
else
{
action = TraverseProperties<TContext>;
}
}
_behaviorCache[key] = action;
}
action(value, visitor, currentDepth, context);
}
protected virtual void TraverseDictionary<TContext>(IObjectDescriptor dictionary, object visitor, int currentDepth, object context)
{
var v = (IObjectGraphVisitor<TContext>)visitor;
var c = (TContext)context;
v.VisitMappingStart(dictionary, typeof(object), typeof(object), c);
foreach (DictionaryEntry entry in (IDictionary)dictionary.Value)
{
var key = GetObjectDescriptor(entry.Key, typeof(object));
var value = GetObjectDescriptor(entry.Value, typeof(object));
if (v.EnterMapping(key, value, c))
{
Traverse(key, v, currentDepth, c);
Traverse(value, v, currentDepth, c);
}
}
v.VisitMappingEnd(dictionary, c);
}
private void TraverseGenericDictionary<TContext>(IObjectDescriptor dictionary, Type dictionaryType, IObjectGraphVisitor visitor, int currentDepth, IObjectGraphVisitorContext context)
{
var v = (IObjectGraphVisitor<TContext>)visitor;
var c = (TContext)context;
var entryTypes = dictionaryType.GetGenericArguments();
// dictionaryType is IDictionary<TKey, TValue>
v.VisitMappingStart(dictionary, entryTypes[0], entryTypes[1], c);
var key = Tuple.Create(entryTypes[0], entryTypes[1], typeof(TContext));
if (!_traverseGenericDictionaryCache.TryGetValue(key, out var action))
{
action = GetTraverseGenericDictionaryHelper(entryTypes[0], entryTypes[1], typeof(TContext));
_traverseGenericDictionaryCache[key] = action;
}
action(this, dictionary.Value, v, currentDepth, _namingConvention ?? new NullNamingConvention(), c);
v.VisitMappingEnd(dictionary, c);
}
private static Action<FullObjectGraphTraversalStrategy, object, IObjectGraphVisitor, int, INamingConvention, IObjectGraphVisitorContext> GetTraverseGenericDictionaryHelper(Type tkey, Type tvalue, Type tcontext)
{
var dm = new DynamicMethod(string.Empty, typeof(void), new[] { typeof(FullObjectGraphTraversalStrategy), typeof(object), typeof(IObjectGraphVisitor), typeof(int), typeof(INamingConvention), typeof(IObjectGraphVisitorContext) });
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Castclass, typeof(IDictionary<,>).MakeGenericType(tkey, tvalue));
il.Emit(OpCodes.Ldarg_2);
il.Emit(OpCodes.Ldarg_3);
il.Emit(OpCodes.Ldarg_S, (byte)4);
il.Emit(OpCodes.Ldarg_S, (byte)5);
il.Emit(OpCodes.Call, TraverseGenericDictionaryHelperMethod.MakeGenericMethod(tkey, tvalue, tcontext));
il.Emit(OpCodes.Ret);
return (Action<FullObjectGraphTraversalStrategy, object, IObjectGraphVisitor, int, INamingConvention, IObjectGraphVisitorContext>)dm.CreateDelegate(typeof(Action<FullObjectGraphTraversalStrategy, object, IObjectGraphVisitor, int, INamingConvention, IObjectGraphVisitorContext>));
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static void TraverseGenericDictionaryHelper<TKey, TValue, TContext>(
FullObjectGraphTraversalStrategy self,
IDictionary<TKey, TValue> dictionary,
IObjectGraphVisitor visitor,
int currentDepth,
INamingConvention namingConvention,
IObjectGraphVisitorContext context)
{
var v = (IObjectGraphVisitor<TContext>)visitor;
var c = (TContext)context;
var isDynamic = dictionary.GetType().FullName.Equals("System.Dynamic.ExpandoObject");
foreach (var entry in dictionary)
{
var keyString = isDynamic ? namingConvention.Apply(entry.Key.ToString()) : entry.Key.ToString();
var key = self.GetObjectDescriptor(keyString, typeof(TKey));
var value = self.GetObjectDescriptor(entry.Value, typeof(TValue));
if (v.EnterMapping(key, value, c))
{
self.Traverse(key, v, currentDepth, c);
self.Traverse(value, v, currentDepth, c);
}
}
}
private void TraverseList<TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth, IObjectGraphVisitorContext context)
{
var v = (IObjectGraphVisitor<TContext>)visitor;
var c = (TContext)context;
var enumerableType = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IEnumerable<>));
var itemType = enumerableType != null ?
enumerableType.GetGenericArguments()[0]
: typeof(object);
v.VisitSequenceStart(value, itemType, c);
foreach (var item in (IEnumerable)value.Value)
{
Traverse(GetObjectDescriptor(item, itemType), v, currentDepth, c);
}
v.VisitSequenceEnd(value, c);
}
protected virtual void TraverseProperties<TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, int currentDepth, IObjectGraphVisitorContext context)
{
var v = (IObjectGraphVisitor<TContext>)visitor;
var c = (TContext)context;
v.VisitMappingStart(value, typeof(string), typeof(object), c);
foreach (var propertyDescriptor in _typeDescriptor.GetProperties(value.Type, value.Value))
{
var propertyValue = propertyDescriptor.Read(value.Value);
if (v.EnterMapping(propertyDescriptor, propertyValue, c))
{
Traverse(new BetterObjectDescriptor(propertyDescriptor.Name, typeof(string), typeof(string)), v, currentDepth, c);
Traverse(propertyValue, v, currentDepth, c);
}
}
v.VisitMappingEnd(value, c);
}
private IObjectDescriptor GetObjectDescriptor(object value, Type staticType)
{
return new BetterObjectDescriptor(value, _typeResolver.Resolve(staticType, value), staticType);
}
}
}
| |
using System;
/// <summary>
/// UIntPtr.Equals(Object)
/// Returns a value indicating whether this instance is equal to a specified object.
/// This method is not CLS-compliant.
/// </summary>
public unsafe class UIntPtrEquals
{
public static int Main()
{
UIntPtrEquals testObj = new UIntPtrEquals();
TestLibrary.TestFramework.BeginTestCase("for method: UIntPtr.Equals(Object)");
if(testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_ID = "P001";
const string c_TEST_DESC = "PosTest1: UIntPtr.Zero vs UIntPtr(0)";
string errorDesc;
UIntPtr srcUIntPtr, expUIntPtr;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
expUIntPtr = new UIntPtr();
srcUIntPtr = UIntPtr.Zero;
actualResult = srcUIntPtr.Equals(expUIntPtr);
if (!actualResult)
{
errorDesc = "Source UIntPtr value does not equal" + expUIntPtr + " as expected: Actual(" + srcUIntPtr + ")";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_ID = "P002";
const string c_TEST_DESC = "PosTest2: UIntPtr.Zero vs non-zero UIntPtr";
string errorDesc;
UIntPtr srcUIntPtr, expUIntPtr;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
expUIntPtr = new UIntPtr((UInt32)TestLibrary.Generator.GetInt32(-55) + 1);
srcUIntPtr = UIntPtr.Zero;
actualResult = !srcUIntPtr.Equals(expUIntPtr);
if (!actualResult)
{
errorDesc = "Source UIntPtr value does not equal" + expUIntPtr + " as expected: Actual(" + srcUIntPtr + ")";
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_ID = "P003";
const string c_TEST_DESC = "PosTest3: two UIntPtrs with random value";
string errorDesc;
UIntPtr uiPtrA, uiPtrB;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
UInt32 uiA = (UInt32)TestLibrary.Generator.GetInt32(-55);
UInt32 uiB = (UInt32)TestLibrary.Generator.GetInt32(-55);
uiPtrA = new UIntPtr(uiA);
uiPtrB = new UIntPtr(uiB);
actualResult = uiPtrA.Equals(uiPtrB);
actualResult = !((uiA == uiB) ^ actualResult);
if (!actualResult)
{
errorDesc = "UIntPtr " + uiPtrA + " vs UIntPtr " + uiPtrB + " is " + actualResult +
", that differs from UInt32 " + uiA + " vs UInt32 " + uiB;
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_ID = "P004";
const string c_TEST_DESC = "PosTest4: UIntPtr vs UInt32";
string errorDesc;
UIntPtr srcUIntPtr;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
UInt32 ui = (UInt32)TestLibrary.Generator.GetInt32(-55);
srcUIntPtr = new UIntPtr(ui);
actualResult = !srcUIntPtr.Equals(ui);
if (!actualResult)
{
errorDesc = "UIntPtr " + srcUIntPtr + " should not equal UInt" + ui;
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
const string c_TEST_ID = "P005";
const string c_TEST_DESC = "PosTest5: UIntPtr vs Object";
string errorDesc;
UIntPtr srcUIntPtr;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
object obj = new object();
srcUIntPtr = new UIntPtr();
actualResult = !srcUIntPtr.Equals(obj);
if (!actualResult)
{
errorDesc = "UIntPtr " + srcUIntPtr + " should not equal object" + obj;
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
[System.Security.SecuritySafeCritical]
public bool PosTest6()
{
bool retVal = true;
const string c_TEST_ID = "P006";
const string c_TEST_DESC = "PosTest6: UIntPtr vs IntPtr";
string errorDesc;
UIntPtr uiPtr;
IntPtr iPtr;
bool actualResult;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
void * ptr = (void *)TestLibrary.Generator.GetInt32(-55);
uiPtr = new UIntPtr(ptr);
iPtr = new IntPtr(ptr);
actualResult = !uiPtr.Equals(iPtr);
if (!actualResult)
{
errorDesc = "UIntPtr " + uiPtr + " should not equal IntPtr " + iPtr;
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2014-2015 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;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
#if !UNITY
#if XAMIOS || XAMDROID
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // XAMIOS || XAMDROID
#endif // !UNITY
using System.Reflection;
using MsgPack.Serialization.DefaultSerializers;
using MsgPack.Serialization.Reflection;
namespace MsgPack.Serialization.ReflectionSerializers
{
/// <summary>
/// Helper static methods for reflection serializers.
/// </summary>
internal static class ReflectionSerializerHelper
{
public static MessagePackSerializer<T> CreateReflectionEnumMessagePackSerializer<T>( SerializationContext context )
{
#if !UNITY
return
ReflectionExtensions.CreateInstancePreservingExceptionType<MessagePackSerializer<T>>(
typeof( ReflectionEnumMessagePackSerializer<> ).MakeGenericType( typeof( T ) ),
context
);
#else
return MessagePackSerializer.Wrap<T>( context, new ReflectionEnumMessagePackSerializer( context, typeof( T ) ) );
#endif // !UNITY
}
#if !UNITY
public static MessagePackSerializer<T> CreateCollectionSerializer<T>(
#else
public static IMessagePackSingleObjectSerializer CreateCollectionSerializer<T>(
#endif // !UNITY
SerializationContext context,
Type targetType,
CollectionTraits traits,
PolymorphismSchema schema
)
{
switch ( traits.DetailedCollectionType )
{
case CollectionDetailedKind.Array:
{
return ArraySerializer.Create<T>( context, schema );
}
case CollectionDetailedKind.GenericList:
#if !NETFX_35 && !UNITY
case CollectionDetailedKind.GenericSet:
#endif // !NETFX_35 && !UNITY
case CollectionDetailedKind.GenericCollection:
{
return
#if !UNITY
( MessagePackSerializer<T> )
ReflectionExtensions.CreateInstancePreservingExceptionType<IVariantReflectionSerializerFactory>(
typeof( CollectionSerializerFactory<,> ).MakeGenericType( typeof( T ), traits.ElementType )
).Create( context, targetType, schema );
#else
new ReflectionCollectionMessagePackSerializer( context, typeof( T ), targetType, traits, schema );
#endif // !UNITY
}
case CollectionDetailedKind.GenericEnumerable:
{
return
#if !UNITY
( MessagePackSerializer<T> )
ReflectionExtensions.CreateInstancePreservingExceptionType<IVariantReflectionSerializerFactory>(
typeof( EnumerableSerializerFactory<,> ).MakeGenericType( typeof( T ), traits.ElementType )
).Create( context, targetType, schema );
#else
new ReflectionEnumerableMessagePackSerializer( context, typeof( T ), targetType, traits, schema );
#endif // !Enumerable
}
case CollectionDetailedKind.GenericDictionary:
{
var genericArgumentOfKeyValuePair = traits.ElementType.GetGenericArguments();
return
#if !UNITY
( MessagePackSerializer<T> )
ReflectionExtensions.CreateInstancePreservingExceptionType<IVariantReflectionSerializerFactory>(
typeof( DictionarySerializerFactory<,,> ).MakeGenericType(
typeof( T ),
genericArgumentOfKeyValuePair[ 0 ],
genericArgumentOfKeyValuePair[ 1 ]
)
).Create( context, targetType, schema );
#else
new ReflectionDictionaryMessagePackSerializer(
context,
typeof( T ),
targetType,
genericArgumentOfKeyValuePair[ 0 ],
genericArgumentOfKeyValuePair[ 1 ],
traits,
schema
);
#endif // !UNITY
}
case CollectionDetailedKind.NonGenericList:
{
return
#if !UNITY
( MessagePackSerializer<T> )
ReflectionExtensions.CreateInstancePreservingExceptionType<IVariantReflectionSerializerFactory>(
typeof( NonGenericListSerializerFactory<> ).MakeGenericType( typeof( T ) )
).Create( context, targetType, schema );
#else
new ReflectionNonGenericListMessagePackSerializer( context, typeof( T ), targetType, schema );
#endif // !UNITY
}
case CollectionDetailedKind.NonGenericCollection:
{
return
#if !UNITY
( MessagePackSerializer<T> )
ReflectionExtensions.CreateInstancePreservingExceptionType<IVariantReflectionSerializerFactory>(
typeof( NonGenericCollectionSerializerFactory<> ).MakeGenericType( typeof( T ), traits.ElementType )
).Create( context, targetType, schema );
#else
new ReflectionNonGenericCollectionMessagePackSerializer( context, typeof( T ), targetType, schema );
#endif // !UNITY
}
case CollectionDetailedKind.NonGenericEnumerable:
{
return
#if !UNITY
( MessagePackSerializer<T> )
ReflectionExtensions.CreateInstancePreservingExceptionType<IVariantReflectionSerializerFactory>(
typeof( NonGenericEnumerableSerializerFactory<> ).MakeGenericType( typeof( T ), traits.ElementType )
).Create( context, targetType, schema );
#else
new ReflectionNonGenericEnumerableMessagePackSerializer( context, typeof( T ), targetType, schema );
#endif // !UNITY
}
case CollectionDetailedKind.NonGenericDictionary:
{
return
#if !UNITY
( MessagePackSerializer<T> )
ReflectionExtensions.CreateInstancePreservingExceptionType<IVariantReflectionSerializerFactory>(
typeof( NonGenericDictionarySerializerFactory<> ).MakeGenericType( typeof( T ) )
).Create( context, targetType, schema );
#else
new ReflectionNonGenericDictionaryMessagePackSerializer( context, typeof( T ), targetType, schema );
#endif // !UNITY
}
default:
{
return null;
}
}
}
#if !UNITY
public static Action<TCollection, TItem> GetAddItem<TCollection, TItem>( Type targetType )
#else
public static Action<object, object> GetAddItem( Type targetType )
#endif // !UNITY
{
var addMethod = targetType.GetCollectionTraits().AddMethod;
if ( addMethod == null )
{
throw new NotSupportedException(
String.Format(
CultureInfo.CurrentCulture,
"Reflection based serializer only supports collection types which implement interface to add new item such as '{0}' and '{1}'",
typeof( ICollection<> ).GetFullName(),
typeof( IList )
)
);
}
// CreateDelegate causes AOT error.
// So use reflection in AOT environment.
#if ( !UNITY && !XAMIOS ) || AOT_CHECK
try
{
return addMethod.CreateDelegate( typeof( Action<TCollection, TItem> ) ) as Action<TCollection, TItem>;
}
catch ( ArgumentException )
{
#endif // ( !UNITY && !XAMIOS ) || AOT_CHECK
return ( collection, item ) => addMethod.InvokePreservingExceptionType( collection, item );
#if ( !UNITY && !XAMIOS ) || AOT_CHECK
}
#endif // ( !UNITY && !XAMIOS ) || AOT_CHECK
}
public static void GetMetadata(
IList<SerializingMember> members,
SerializationContext context,
out Func<object, object>[] getters,
out Action<object, object>[] setters,
out MemberInfo[] memberInfos,
out DataMemberContract[] contracts,
out IMessagePackSerializer[] serializers )
{
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 )
{
#if UNITY
contracts[ i ] = DataMemberContract.Null;
#endif // UNITY
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, "member.Member is PropertyInfo" );
#endif // DEBUG && !UNITY
getters[ i ] = target => property.GetGetMethod( true ).InvokePreservingExceptionType( target, null );
var setter = property.GetSetMethod( true );
if ( setter != null )
{
setters[ i ] = ( target, value ) => setter.InvokePreservingExceptionType( target, new[] { value } );
}
}
memberInfos[ i ] = member.Member;
#if !UNITY
contracts[ i ] = member.Contract;
#else
contracts[ i ] = member.Contract ?? DataMemberContract.Null;
#endif // !UNITY
var memberType = member.Member.GetMemberValueType();
if ( memberType.GetIsEnum() )
{
serializers[ i ] =
context.GetSerializer(
memberType,
EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod(
context,
memberType,
member.GetEnumMemberSerializationMethod()
)
);
}
else if ( DateTimeMessagePackSerializerHelpers.IsDateTime( memberType ) )
{
serializers[ i ] =
context.GetSerializer(
memberType,
DateTimeMessagePackSerializerHelpers.DetermineDateTimeConversionMethod(
context,
member.GetDateTimeMemberConversionMethod()
)
);
}
else
{
serializers[ i ] = context.GetSerializer( memberType, PolymorphismSchema.Create( context, memberType, member ) );
}
}
}
#if !UNITY
public static Func<int, T> CreateCollectionInstanceFactory<T, TKey>( Type targetType )
#else
public static Func<int, object> CreateCollectionInstanceFactory( Type abstractType, Type targetType, Type comparisonType )
#endif // !UNITY
{
var constructor = UnpackHelpers.GetCollectionConstructor( targetType );
var parameters = constructor.GetParameters();
switch ( parameters.Length )
{
case 0:
{
return _ =>
#if !UNITY
( T )
#endif // !UNITY
constructor.InvokePreservingExceptionType();
}
case 1:
{
if ( parameters[ 0 ].ParameterType == typeof( int ) )
{
return capacity =>
#if !UNITY
( T )
#endif // !UNITY
constructor.InvokePreservingExceptionType( capacity );
}
else if ( UnpackHelpers.IsIEqualityComparer( parameters[ 0 ].ParameterType ) )
{
var comparer =
#if !UNITY
EqualityComparer<TKey>.Default;
#else
UnpackHelpers.GetEqualityComparer( comparisonType );
#endif // !UNITY
return _ =>
#if !UNITY
( T )
#endif // !UNITY
constructor.InvokePreservingExceptionType( comparer );
}
break;
}
case 2:
{
var comparer =
#if !UNITY
EqualityComparer<TKey>.Default;
#else
UnpackHelpers.GetEqualityComparer( comparisonType );
#endif // !UNITY
if ( parameters[ 0 ].ParameterType == typeof( int )
&& UnpackHelpers.IsIEqualityComparer( parameters[ 1 ].ParameterType ) )
{
return capacity =>
#if !UNITY
( T )
#endif // !UNITY
constructor.InvokePreservingExceptionType( capacity, comparer );
}
else if ( UnpackHelpers.IsIEqualityComparer( parameters[ 0 ].ParameterType ) &&
parameters[ 0 ].ParameterType == typeof( int ) )
{
return capacity =>
#if !UNITY
( T )
#endif // !UNITY
constructor.InvokePreservingExceptionType( comparer, capacity );
}
break;
}
}
throw SerializationExceptions.NewTargetDoesNotHavePublicDefaultConstructorNorInitialCapacity(
#if !UNITY
typeof( T )
#else
abstractType
#endif // !UNITY
);
}
#if !UNITY
/// <summary>
/// Defines non-generic factory method for 'universal' serializers which use general collection features.
/// </summary>
private interface IVariantReflectionSerializerFactory
{
IMessagePackSingleObjectSerializer Create( SerializationContext context, Type targetType, PolymorphismSchema schema );
}
// ReSharper disable MemberHidesStaticFromOuterClass
private sealed class NonGenericEnumerableSerializerFactory<T> : IVariantReflectionSerializerFactory
where T : IEnumerable
{
public NonGenericEnumerableSerializerFactory() { }
public IMessagePackSingleObjectSerializer Create( SerializationContext context, Type targetType, PolymorphismSchema schema )
{
return new ReflectionNonGenericEnumerableMessagePackSerializer<T>( context, targetType, schema );
}
}
private sealed class NonGenericCollectionSerializerFactory<T> : IVariantReflectionSerializerFactory
where T : ICollection
{
public NonGenericCollectionSerializerFactory() { }
public IMessagePackSingleObjectSerializer Create( SerializationContext context, Type targetType, PolymorphismSchema schema )
{
return new ReflectionNonGenericCollectionMessagePackSerializer<T>( context, targetType, schema );
}
}
private sealed class NonGenericListSerializerFactory<T> : IVariantReflectionSerializerFactory
where T : IList
{
public NonGenericListSerializerFactory() { }
public IMessagePackSingleObjectSerializer Create( SerializationContext context, Type targetType, PolymorphismSchema schema )
{
return new ReflectionNonGenericListMessagePackSerializer<T>( context, targetType, schema );
}
}
private sealed class NonGenericDictionarySerializerFactory<T> : IVariantReflectionSerializerFactory
where T : IDictionary
{
public NonGenericDictionarySerializerFactory() { }
public IMessagePackSingleObjectSerializer Create( SerializationContext context, Type targetType, PolymorphismSchema schema )
{
return new ReflectionNonGenericDictionaryMessagePackSerializer<T>( context, targetType, schema );
}
}
private sealed class EnumerableSerializerFactory<TCollection, TItem> : IVariantReflectionSerializerFactory
where TCollection : IEnumerable<TItem>
{
public EnumerableSerializerFactory() { }
public IMessagePackSingleObjectSerializer Create( SerializationContext context, Type targetType, PolymorphismSchema schema )
{
var itemSchema = schema ?? PolymorphismSchema.Default;
return new ReflectionEnumerableMessagePackSerializer<TCollection, TItem>( context, targetType, itemSchema );
}
}
private sealed class CollectionSerializerFactory<TCollection, TItem> : IVariantReflectionSerializerFactory
where TCollection : ICollection<TItem>
{
public CollectionSerializerFactory() { }
public IMessagePackSingleObjectSerializer Create( SerializationContext context, Type targetType, PolymorphismSchema schema )
{
var itemSchema = schema ?? PolymorphismSchema.Default;
return new ReflectionCollectionMessagePackSerializer<TCollection, TItem>( context, targetType, itemSchema );
}
}
private sealed class DictionarySerializerFactory<TDictionary, TKey, TValue> : IVariantReflectionSerializerFactory
where TDictionary : IDictionary<TKey, TValue>
{
public DictionarySerializerFactory() { }
public IMessagePackSingleObjectSerializer Create( SerializationContext context, Type targetType, PolymorphismSchema schema )
{
return new ReflectionDictionaryMessagePackSerializer<TDictionary, TKey, TValue>( context, targetType, schema );
}
}
// ReSharper restore MemberHidesStaticFromOuterClass
#endif // !UNITY
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using gagr = Google.Api.Gax.ResourceNames;
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.Monitoring.V3.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedGroupServiceClientTest
{
[xunit::FactAttribute]
public void GetGroupRequestObject()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
GetGroupRequest request = new GetGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.GetGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.GetGroup(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGroupRequestObjectAsync()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
GetGroupRequest request = new GetGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.GetGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.GetGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.GetGroupAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGroup()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
GetGroupRequest request = new GetGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.GetGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.GetGroup(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGroupAsync()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
GetGroupRequest request = new GetGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.GetGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.GetGroupAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.GetGroupAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGroupResourceNames1()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
GetGroupRequest request = new GetGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.GetGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.GetGroup(request.GroupName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGroupResourceNames1Async()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
GetGroupRequest request = new GetGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.GetGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.GetGroupAsync(request.GroupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.GetGroupAsync(request.GroupName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGroupResourceNames2()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
GetGroupRequest request = new GetGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.GetGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.GetGroup(request.ResourceName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGroupResourceNames2Async()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
GetGroupRequest request = new GetGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.GetGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.GetGroupAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.GetGroupAsync(request.ResourceName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateGroupRequestObject()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ValidateOnly = true,
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.CreateGroup(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateGroupRequestObjectAsync()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ValidateOnly = true,
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.CreateGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.CreateGroupAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateGroup()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.CreateGroup(request.Name, request.Group);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateGroupAsync()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.CreateGroupAsync(request.Name, request.Group, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.CreateGroupAsync(request.Name, request.Group, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateGroupResourceNames1()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.CreateGroup(request.ProjectName, request.Group);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateGroupResourceNames1Async()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.CreateGroupAsync(request.ProjectName, request.Group, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.CreateGroupAsync(request.ProjectName, request.Group, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateGroupResourceNames2()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.CreateGroup(request.OrganizationName, request.Group);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateGroupResourceNames2Async()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.CreateGroupAsync(request.OrganizationName, request.Group, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.CreateGroupAsync(request.OrganizationName, request.Group, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateGroupResourceNames3()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.CreateGroup(request.FolderName, request.Group);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateGroupResourceNames3Async()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.CreateGroupAsync(request.FolderName, request.Group, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.CreateGroupAsync(request.FolderName, request.Group, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateGroupResourceNames4()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.CreateGroup(request.ResourceName, request.Group);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateGroupResourceNames4Async()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
CreateGroupRequest request = new CreateGroupRequest
{
Group = new Group(),
ProjectName = gagr::ProjectName.FromProject("[PROJECT]"),
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.CreateGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.CreateGroupAsync(request.ResourceName, request.Group, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.CreateGroupAsync(request.ResourceName, request.Group, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateGroupRequestObject()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
UpdateGroupRequest request = new UpdateGroupRequest
{
Group = new Group(),
ValidateOnly = true,
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.UpdateGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.UpdateGroup(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateGroupRequestObjectAsync()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
UpdateGroupRequest request = new UpdateGroupRequest
{
Group = new Group(),
ValidateOnly = true,
};
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.UpdateGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.UpdateGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.UpdateGroupAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateGroup()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
UpdateGroupRequest request = new UpdateGroupRequest { Group = new Group(), };
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.UpdateGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group response = client.UpdateGroup(request.Group);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateGroupAsync()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
UpdateGroupRequest request = new UpdateGroupRequest { Group = new Group(), };
Group expectedResponse = new Group
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
DisplayName = "display_name137f65c2",
ParentName = "parent_name91315215",
Filter = "filtere47ac9b2",
IsCluster = true,
};
mockGrpcClient.Setup(x => x.UpdateGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Group>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
Group responseCallSettings = await client.UpdateGroupAsync(request.Group, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Group responseCancellationToken = await client.UpdateGroupAsync(request.Group, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteGroupRequestObject()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
DeleteGroupRequest request = new DeleteGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
Recursive = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteGroup(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteGroupRequestObjectAsync()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
DeleteGroupRequest request = new DeleteGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
Recursive = true,
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteGroupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteGroupAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteGroup()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
DeleteGroupRequest request = new DeleteGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteGroup(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteGroupAsync()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
DeleteGroupRequest request = new DeleteGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteGroupAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteGroupAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteGroupResourceNames1()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
DeleteGroupRequest request = new DeleteGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteGroup(request.GroupName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteGroupResourceNames1Async()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
DeleteGroupRequest request = new DeleteGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteGroupAsync(request.GroupName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteGroupAsync(request.GroupName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteGroupResourceNames2()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
DeleteGroupRequest request = new DeleteGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteGroup(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
client.DeleteGroup(request.ResourceName);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteGroupResourceNames2Async()
{
moq::Mock<GroupService.GroupServiceClient> mockGrpcClient = new moq::Mock<GroupService.GroupServiceClient>(moq::MockBehavior.Strict);
DeleteGroupRequest request = new DeleteGroupRequest
{
GroupName = GroupName.FromProjectGroup("[PROJECT]", "[GROUP]"),
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteGroupAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GroupServiceClient client = new GroupServiceClientImpl(mockGrpcClient.Object, null);
await client.DeleteGroupAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteGroupAsync(request.ResourceName, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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.Xml;
using Microsoft.Test.ModuleCore;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
//[TestCase(Name = "ReadToNextSibling", Desc = "ReadToNextSibling")]
public partial class TCReadToNextSibling : BridgeHelpers
{
#region XMLSTR
private string _xmlStr = @"<?xml version='1.0'?>
<root><!--Comment-->
<elem>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah
<child4/>
</child2>
<?pi target1?>
</child1>
</elem>
<elem att='1'>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah
<child4/>
</child2>
<?pi target1?>
</child1>
</elem>
<elem xmlns='elem'>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah2
<child4/>
</child2>
</child1>
</elem>
<elem xmlns='elem' att='1'>
<child1 att='1'>
<child2 xmlns='child2'>
<child3/>
blahblahblah2
<child4/>
</child2>
</child1>
</elem>
<e:elem xmlns:e='elem2'>
<e:child1 att='1'>
<e:child2 xmlns='child2'>
<e:child3/>
blahblahblah2
<e:child4/>
</e:child2>
</e:child1>
</e:elem>
<e:elem xmlns:e='elem2' att='1'>
<e:child1 att='1'>
<e:child2 xmlns='child2'>
<e:child3/>
blahblahblah2
<e:child4/>
</e:child2>
</e:child1>
</e:elem>
</root>";
#endregion
//[Variation("Simple positive test 1", Priority = 0, Params = new object[] { "NNS" })]
//[Variation("Simple positive test 2", Priority = 0, Params = new object[] { "DNS" })]
//[Variation("Simple positive test 3", Priority = 0, Params = new object[] { "NS" })]
public void v()
{
string type = Variation.Params[0].ToString();
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
switch (type)
{
case "NNS":
DataReader.ReadToDescendant("elem");
DataReader.ReadToNextSibling("elem");
if (DataReader.HasAttributes)
{
TestLog.Compare(DataReader.GetAttribute("att"), "1", "Not the expected attribute");
}
else
{
TestLog.WriteLine("Positioned on wrong element");
throw new TestException(TestResult.Failed, "");
}
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "DNS":
DataReader.ReadToDescendant("elem", "elem");
DataReader.ReadToNextSibling("elem", "elem");
if (DataReader.HasAttributes)
{
if (DataReader.GetAttribute("att") == null)
{
TestLog.WriteLine("Positioned on wrong element, not on DNS");
throw new TestException(TestResult.Failed, "");
}
}
else
{
TestLog.WriteLine("Positioned on wrong element");
throw new TestException(TestResult.Failed, "");
}
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "NS":
DataReader.ReadToDescendant("e:elem");
DataReader.ReadToNextSibling("e:elem");
if (DataReader.HasAttributes)
{
if (DataReader.GetAttribute("xmlns:e") == null)
{
TestLog.WriteLine("Positioned on wrong element, not on DNS");
throw new TestException(TestResult.Failed, "");
}
}
else
{
TestLog.WriteLine("Positioned on wrong element");
throw new TestException(TestResult.Failed, "");
}
while (DataReader.Read()) ;
DataReader.Dispose();
return;
default:
throw new TestFailedException("Error in Test type");
}
}
//[Variation("Read on a deep tree atleast more than 4K boundary", Priority = 2)]
public void v2()
{
ManagedNodeWriter mnw = new ManagedNodeWriter();
mnw.PutPattern("X");
int count = 0;
do
{
mnw.PutPattern("E/");
count++;
} while (mnw.GetNodes().Length < 4096);
mnw.PutText("<a/><b/>");
mnw.Finish();
XmlReader DataReader = GetReader(new StringReader(mnw.GetNodes()));
PositionOnElement(DataReader, "ELEMENT_1");
TestLog.Compare(DataReader.ReadToDescendant("a"), true, "Couldnt go to Descendant");
int depth = DataReader.Depth;
TestLog.Compare(DataReader.ReadToNextSibling("b"), true, "Couldnt go to NextSibling");
TestLog.Compare(DataReader.Depth, depth, "Depth is not correct");
TestLog.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Read to next sibling with same names 1", Priority = 1, Params = new object[] { "NNS", "<root><a att='1'/><a att='2'/><a att='3'/></root>" })]
//[Variation("Read on next sibling with same names 2", Priority = 1, Params = new object[] { "DNS", "<root xmlns='a'><a att='1'/><a att='2'/><a att='3'/></root>" })]
//[Variation("Read on next sibling with same names 3", Priority = 1, Params = new object[] { "NS", "<root xmlns:a='a'><a:a att='1'/><a:a att='2'/><a:a att='3'/></root>" })]
public void v3()
{
string type = Variation.Params[0].ToString();
string xml = Variation.Params[1].ToString();
XmlReader DataReader = GetReader(new StringReader(xml));
DataReader.Read();
// Doing a sequential read.
switch (type)
{
case "NNS":
DataReader.ReadToDescendant("a");
DataReader.ReadToNextSibling("a");
DataReader.ReadToNextSibling("a");
TestLog.Compare(DataReader.GetAttribute("att"), "3", "Wrong node");
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "DNS":
DataReader.ReadToDescendant("a", "a");
DataReader.ReadToNextSibling("a", "a");
DataReader.ReadToNextSibling("a", "a");
TestLog.Compare(DataReader.GetAttribute("att"), "3", "Wrong node");
while (DataReader.Read()) ;
DataReader.Dispose();
return;
case "NS":
DataReader.ReadToDescendant("a:a");
DataReader.ReadToNextSibling("a:a");
DataReader.ReadToNextSibling("a:a");
TestLog.Compare(DataReader.GetAttribute("att"), "3", "Wrong node");
while (DataReader.Read()) ;
DataReader.Dispose();
return;
default:
throw new TestFailedException("Error in Test type");
}
}
//[Variation("If name not found, stop at end element of the subtree", Priority = 1)]
public void v4()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "elem");
int depth = DataReader.Depth;
TestLog.Compare(DataReader.ReadToNextSibling("abc"), false, "Reader returned true for an invalid name");
TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type");
TestLog.Compare(DataReader.Depth, depth - 1, "Wrong Depth");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Positioning on a level and try to find the name which is on a level higher", Priority = 1)]
public void v5()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "child3");
TestLog.Compare(DataReader.ReadToNextSibling("child1"), false, "Reader returned true for an invalid name");
TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type");
PositionOnElement(DataReader, "child3");
TestLog.Compare(DataReader.ReadToNextSibling("child2", "child2"), false, "Reader returned true for an invalid name,ns");
TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type for name,ns");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Read to next sibling on one level and again to level below it", Priority = 1)]
public void v6()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
PositionOnElement(DataReader, "root");
TestLog.Compare(DataReader.ReadToDescendant("elem"), true, "Cant find elem");
TestLog.Compare(DataReader.ReadToNextSibling("elem", "elem"), true, "Cant find elem,elem");
TestLog.Compare(DataReader.ReadToNextSibling("e:elem"), true, "Cant find e:elem");
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Call from different nodetypes", Priority = 1)]
public void v12()
{
XmlReader DataReader = GetReader(new StringReader(_xmlStr));
while (DataReader.Read())
{
if (DataReader.NodeType != XmlNodeType.Element)
{
TestLog.Compare(DataReader.ReadToNextSibling("abc"), false, "Fails on node");
}
else
{
if (DataReader.HasAttributes)
{
while (DataReader.MoveToNextAttribute())
{
TestLog.Compare(DataReader.ReadToNextSibling("abc"), false, "Fails on attribute node");
}
}
}
}
DataReader.Dispose();
}
//[Variation("Pass null to both arguments throws ArgumentException", Priority = 2)]
public void v16()
{
XmlReader DataReader = GetReader(new StringReader("<root><e/></root>"));
DataReader.Read();
try
{
DataReader.ReadToNextSibling(null);
}
catch (ArgumentNullException)
{
}
try
{
DataReader.ReadToNextSibling("e", null);
}
catch (ArgumentNullException)
{
}
while (DataReader.Read()) ;
DataReader.Dispose();
}
//[Variation("Different names, same uri works correctly", Priority = 2)]
public void v17()
{
XmlReader DataReader = GetReader(new StringReader("<root><child1 xmlns='foo'/>blah<child1 xmlns='bar'>blah</child1></root>"));
DataReader.Read();
DataReader.ReadToDescendant("child1", "foo");
DataReader.ReadToNextSibling("child1", "bar");
TestLog.Compare(DataReader.IsEmptyElement, false, "Not on the correct node");
while (DataReader.Read()) ;
DataReader.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Rocks;
namespace Xamarin.Forms.Build.Tasks
{
class TypeRefComparer : IEqualityComparer<TypeReference>
{
static string GetAssembly(TypeReference typeRef)
{
var md = typeRef.Scope as ModuleDefinition;
if (md != null)
return md.Assembly.FullName;
var anr = typeRef.Scope as AssemblyNameReference;
if (anr != null)
return anr.FullName;
throw new ArgumentOutOfRangeException(nameof(typeRef));
}
public bool Equals(TypeReference x, TypeReference y)
{
if (x.FullName != y.FullName)
return false;
var xasm = GetAssembly(x);
if (xasm.StartsWith("System.Runtime", StringComparison.Ordinal) || xasm.StartsWith("mscorlib", StringComparison.Ordinal))
xasm = "mscorlib";
var yasm = GetAssembly(y);
if (yasm.StartsWith("System.Runtime", StringComparison.Ordinal) || yasm.StartsWith("mscorlib", StringComparison.Ordinal))
yasm = "mscorlib";
return xasm == yasm;
}
public int GetHashCode(TypeReference obj)
{
return $"{GetAssembly(obj)}//{obj.FullName}".GetHashCode();
}
static TypeRefComparer s_default;
public static TypeRefComparer Default => s_default ?? (s_default = new TypeRefComparer());
}
static class TypeReferenceExtensions
{
public static PropertyDefinition GetProperty(this TypeReference typeRef, Func<PropertyDefinition, bool> predicate,
out TypeReference declaringTypeRef)
{
declaringTypeRef = typeRef;
var typeDef = typeRef.Resolve();
var properties = typeDef.Properties.Where(predicate);
if (properties.Any())
return properties.Single();
if (typeDef.BaseType == null || typeDef.BaseType.FullName == "System.Object")
return null;
return typeDef.BaseType.GetProperty(predicate, out declaringTypeRef);
}
public static EventDefinition GetEvent(this TypeReference typeRef, Func<EventDefinition, bool> predicate)
{
var typeDef = typeRef.Resolve();
var events = typeDef.Events.Where(predicate);
if (events.Any())
return events.Single();
if (typeDef.BaseType == null || typeDef.BaseType.FullName == "System.Object")
return null;
return typeDef.BaseType.GetEvent(predicate);
}
public static FieldDefinition GetField(this TypeReference typeRef, Func<FieldDefinition, bool> predicate,
out TypeReference declaringTypeRef)
{
declaringTypeRef = typeRef;
var typeDef = typeRef.Resolve();
var bp = typeDef.Fields.Where
(predicate);
if (bp.Any())
return bp.Single();
if (typeDef.BaseType == null || typeDef.BaseType.FullName == "System.Object")
return null;
var basetype = typeDef.BaseType.ResolveGenericParameters(typeRef);
return basetype.GetField(predicate, out declaringTypeRef);
}
public static bool ImplementsInterface(this TypeReference typeRef, TypeReference @interface)
{
var typeDef = typeRef.Resolve();
if (typeDef.Interfaces.Any(tr => tr.InterfaceType.FullName == @interface.FullName))
return true;
var baseTypeRef = typeDef.BaseType;
if (baseTypeRef != null && baseTypeRef.FullName != "System.Object")
return baseTypeRef.ImplementsInterface(@interface);
return false;
}
public static bool ImplementsGenericInterface(this TypeReference typeRef, string @interface,
out GenericInstanceType interfaceReference, out IList<TypeReference> genericArguments)
{
interfaceReference = null;
genericArguments = null;
var typeDef = typeRef.Resolve();
InterfaceImplementation iface;
if ((iface = typeDef.Interfaces.FirstOrDefault(tr =>
tr.InterfaceType.FullName.StartsWith(@interface, StringComparison.Ordinal) &&
tr.InterfaceType.IsGenericInstance && (tr.InterfaceType as GenericInstanceType).HasGenericArguments)) != null)
{
interfaceReference = iface.InterfaceType as GenericInstanceType;
genericArguments = (iface.InterfaceType as GenericInstanceType).GenericArguments;
return true;
}
var baseTypeRef = typeDef.BaseType;
if (baseTypeRef != null && baseTypeRef.FullName != "System.Object")
return baseTypeRef.ImplementsGenericInterface(@interface, out interfaceReference, out genericArguments);
return false;
}
static readonly string[] arrayInterfaces = {
"System.ICloneable",
"System.Collections.IEnumerable",
"System.Collections.IList",
"System.Collections.ICollection",
"System.Collections.IStructuralComparable",
"System.Collections.IStructuralEquatable",
};
static readonly string[] arrayGenericInterfaces = {
"System.Collections.Generic.IEnumerable`1",
"System.Collections.Generic.IList`1",
"System.Collections.Generic.ICollection`1",
"System.Collections.Generic.IReadOnlyCollection`1",
"System.Collections.Generic.IReadOnlyList`1",
};
public static bool InheritsFromOrImplements(this TypeReference typeRef, TypeReference baseClass)
{
if (TypeRefComparer.Default.Equals(typeRef, baseClass))
return true;
if (typeRef.IsValueType)
return false;
if (typeRef.IsArray) {
var array = (ArrayType)typeRef;
var arrayType = typeRef.Resolve();
if (arrayInterfaces.Contains(baseClass.FullName))
return true;
if (array.IsVector && //generic interfaces are not implemented on multidimensional arrays
arrayGenericInterfaces.Contains(baseClass.Resolve().FullName) &&
baseClass.IsGenericInstance &&
TypeRefComparer.Default.Equals((baseClass as GenericInstanceType).GenericArguments[0], arrayType))
return true;
return baseClass.FullName == "System.Object";
}
if (typeRef.FullName == "System.Object")
return false;
var typeDef = typeRef.Resolve();
if (TypeRefComparer.Default.Equals(typeDef, baseClass.Resolve()))
return true;
if (typeDef.Interfaces.Any(ir => TypeRefComparer.Default.Equals(ir.InterfaceType, baseClass)))
return true;
if (typeDef.BaseType == null)
return false;
typeRef = typeDef.BaseType.ResolveGenericParameters(typeRef);
return typeRef.InheritsFromOrImplements(baseClass);
}
public static CustomAttribute GetCustomAttribute(this TypeReference typeRef, TypeReference attribute)
{
var typeDef = typeRef.Resolve();
//FIXME: avoid string comparison. make sure the attribute TypeRef is the same one
var attr = typeDef.CustomAttributes.SingleOrDefault(ca => ca.AttributeType.FullName == attribute.FullName);
if (attr != null)
return attr;
var baseTypeRef = typeDef.BaseType;
if (baseTypeRef != null && baseTypeRef.FullName != "System.Object")
return baseTypeRef.GetCustomAttribute(attribute);
return null;
}
[Obsolete]
public static MethodDefinition GetMethod(this TypeReference typeRef, Func<MethodDefinition, bool> predicate)
{
TypeReference declaringTypeReference;
return typeRef.GetMethod(predicate, out declaringTypeReference);
}
[Obsolete]
public static MethodDefinition GetMethod(this TypeReference typeRef, Func<MethodDefinition, bool> predicate,
out TypeReference declaringTypeRef)
{
declaringTypeRef = typeRef;
var typeDef = typeRef.Resolve();
var methods = typeDef.Methods.Where(predicate);
if (methods.Any())
return methods.Single();
if (typeDef.BaseType != null && typeDef.BaseType.FullName == "System.Object")
return null;
if (typeDef.IsInterface)
{
foreach (var face in typeDef.Interfaces)
{
var m = face.InterfaceType.GetMethod(predicate);
if (m != null)
return m;
}
return null;
}
return typeDef.BaseType.GetMethod(predicate, out declaringTypeRef);
}
public static IEnumerable<Tuple<MethodDefinition, TypeReference>> GetMethods(this TypeReference typeRef,
Func<MethodDefinition, bool> predicate, ModuleDefinition module)
{
return typeRef.GetMethods((md, tr) => predicate(md), module);
}
public static IEnumerable<Tuple<MethodDefinition, TypeReference>> GetMethods(this TypeReference typeRef,
Func<MethodDefinition, TypeReference, bool> predicate, ModuleDefinition module)
{
var typeDef = typeRef.Resolve();
foreach (var method in typeDef.Methods.Where(md => predicate(md, typeRef)))
yield return new Tuple<MethodDefinition, TypeReference>(method, typeRef);
if (typeDef.IsInterface)
{
foreach (var face in typeDef.Interfaces)
{
if (face.InterfaceType.IsGenericInstance && typeRef is GenericInstanceType)
{
int i = 0;
foreach (var arg in ((GenericInstanceType)typeRef).GenericArguments)
((GenericInstanceType)face.InterfaceType).GenericArguments[i++] = module.ImportReference(arg);
}
foreach (var tuple in face.InterfaceType.GetMethods(predicate, module))
yield return tuple;
}
yield break;
}
if (typeDef.BaseType == null || typeDef.BaseType.FullName == "System.Object")
yield break;
var baseType = typeDef.BaseType.ResolveGenericParameters(typeRef);
foreach (var tuple in baseType.GetMethods(predicate, module))
yield return tuple;
}
public static MethodReference GetImplicitOperatorTo(this TypeReference fromType, TypeReference toType, ModuleDefinition module)
{
var implicitOperatorsOnFromType = fromType.GetMethods(md => md.IsPublic && md.IsStatic && md.IsSpecialName && md.Name == "op_Implicit", module);
var implicitOperatorsOnToType = toType.GetMethods(md => md.IsPublic && md.IsStatic && md.IsSpecialName && md.Name == "op_Implicit", module);
var implicitOperators = implicitOperatorsOnFromType.Concat(implicitOperatorsOnToType).ToList();
if (implicitOperators.Any()) {
foreach (var op in implicitOperators) {
var cast = op.Item1;
var opDeclTypeRef = op.Item2;
var castDef = module.ImportReference(cast).ResolveGenericParameters(opDeclTypeRef, module);
var returnType = castDef.ReturnType;
if (returnType.IsGenericParameter)
returnType = ((GenericInstanceType)opDeclTypeRef).GenericArguments [((GenericParameter)returnType).Position];
if (returnType.FullName == toType.FullName &&
cast.Parameters [0].ParameterType.Name == fromType.Name) {
return castDef;
}
}
}
return null;
}
public static TypeReference ResolveGenericParameters(this TypeReference self, TypeReference declaringTypeReference)
{
var genericself = self as GenericInstanceType;
if (genericself == null)
return self;
var genericdeclType = declaringTypeReference as GenericInstanceType;
if (genericdeclType == null)
return self;
if (!genericself.GenericArguments.Any(arg => arg.IsGenericParameter))
return self;
List<TypeReference> args = new List<TypeReference>();
for (var i = 0; i < genericself.GenericArguments.Count; i++)
args.Add(genericdeclType.GenericArguments[(genericself.GenericArguments[i] as GenericParameter).Position]);
return self.GetElementType().MakeGenericInstanceType(args.ToArray());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#if FEATURE_CTYPES
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Modules {
/// <summary>
/// Provides support for interop with native code from Python code.
/// </summary>
public static partial class CTypes {
[PythonType("CFuncPtr")]
public abstract class _CFuncPtr : CData, IDynamicMetaObjectProvider, ICodeFormattable {
private readonly Delegate _delegate;
private readonly int _comInterfaceIndex = -1;
private object _errcheck, _restype = _noResType;
private IList<object> _argtypes;
private int _id;
private static int _curId = 0;
internal static object _noResType = new object();
// __nonzero__
/// <summary>
/// Creates a new CFuncPtr object from a tuple. The 1st element of the
/// tuple is the ordinal or function name. The second is an object with
/// a _handle property. The _handle property is the handle of the module
/// from which the function will be loaded.
/// </summary>
public _CFuncPtr(PythonTuple args) {
if (args == null) {
throw PythonOps.TypeError("expected sequence, got None");
} else if (args.Count != 2) {
throw PythonOps.TypeError($"argument 1 must be a sequence of length 2, not {args.Count}");
}
object nameOrOrdinal = args[0];
object dll = args[1];
IntPtr intPtrHandle = GetHandleFromObject(dll, "the _handle attribute of the second element must be an integer");
IntPtr tmpAddr;
string funcName = args[0] as string;
if (funcName != null) {
tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, funcName);
} else {
tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, new IntPtr((int)nameOrOrdinal));
}
if (tmpAddr == IntPtr.Zero) {
if (CallingConvention == CallingConvention.StdCall && funcName != null) {
// apply std call name mangling - prepend a _, append @bytes where
// bytes is the number of bytes of the argument list.
string mangled = "_" + funcName + "@";
for (int i = 0; i < 128 && tmpAddr == IntPtr.Zero; i += 4) {
tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, mangled + i);
}
}
if (tmpAddr == IntPtr.Zero) {
throw PythonOps.AttributeError($"function {args[0]} is not defined");
}
}
_memHolder = new MemoryHolder(IntPtr.Size);
addr = tmpAddr;
_id = Interlocked.Increment(ref _curId);
}
public _CFuncPtr() {
_id = Interlocked.Increment(ref _curId);
_memHolder = new MemoryHolder(IntPtr.Size);
}
public _CFuncPtr(CodeContext context, object function) {
_memHolder = new MemoryHolder(IntPtr.Size);
if (function != null) {
if (!PythonOps.IsCallable(context, function)) {
throw PythonOps.TypeError("argument must be called or address of function");
}
_delegate = ((CFuncPtrType)DynamicHelpers.GetPythonType(this)).MakeReverseDelegate(context, function);
addr = Marshal.GetFunctionPointerForDelegate(_delegate);
CFuncPtrType myType = (CFuncPtrType)NativeType;
PythonType resType = myType._restype;
if (resType != null) {
if (!(resType is INativeType) || resType is PointerType) {
throw PythonOps.TypeError($"invalid result type {resType.Name} for callback function");
}
}
}
_id = Interlocked.Increment(ref _curId);
}
/// <summary>
/// Creates a new CFuncPtr which calls a COM method.
/// </summary>
public _CFuncPtr(int index, string name) {
_memHolder = new MemoryHolder(IntPtr.Size);
_comInterfaceIndex = index;
_id = Interlocked.Increment(ref _curId);
}
/// <summary>
/// Creates a new CFuncPtr with the specfied address.
/// </summary>
public _CFuncPtr(int handle) {
_memHolder = new MemoryHolder(IntPtr.Size);
addr = new IntPtr(handle);
_id = Interlocked.Increment(ref _curId);
}
/// <summary>
/// Creates a new CFuncPtr with the specfied address.
/// </summary>
public _CFuncPtr([NotNull]BigInteger handle) {
_memHolder = new MemoryHolder(IntPtr.Size);
addr = new IntPtr((long)handle);
_id = Interlocked.Increment(ref _curId);
}
public _CFuncPtr(IntPtr handle) {
_memHolder = new MemoryHolder(IntPtr.Size);
addr = handle;
_id = Interlocked.Increment(ref _curId);
}
public bool __nonzero__() {
return addr != IntPtr.Zero;
}
#region Public APIs
[SpecialName, PropertyMethod]
public object Geterrcheck() {
return _errcheck;
}
[SpecialName, PropertyMethod]
public void Seterrcheck(object value) {
_errcheck = value;
}
[SpecialName, PropertyMethod]
public void Deleteerrcheck() {
_errcheck = null;
_id = Interlocked.Increment(ref _curId);
}
[PropertyMethod, SpecialName]
public object Getrestype() {
if (_restype == _noResType) {
return ((CFuncPtrType)NativeType)._restype;
}
return _restype;
}
[PropertyMethod, SpecialName]
public void Setrestype(object value) {
INativeType nt = value as INativeType;
if (nt != null || value == null || PythonOps.IsCallable(((PythonType)NativeType).Context.SharedContext, value)) {
_restype = value;
_id = Interlocked.Increment(ref _curId);
} else {
throw PythonOps.TypeError("restype must be a type, a callable, or None");
}
}
[SpecialName, PropertyMethod]
public void Deleterestype() {
_restype = _noResType;
_id = Interlocked.Increment(ref _curId);
}
public object argtypes {
get {
if (_argtypes != null) {
return _argtypes;
}
if (((CFuncPtrType)NativeType)._argtypes != null) {
return PythonTuple.MakeTuple(((CFuncPtrType)NativeType)._argtypes);
}
return null;
}
set {
if (value != null) {
IList<object> argValues = value as IList<object>;
if (argValues == null) {
throw PythonOps.TypeErrorForTypeMismatch("sequence", value);
}
foreach (object o in argValues) {
if (!(o is INativeType)) {
if (!PythonOps.HasAttr(DefaultContext.Default, o, "from_param")) {
throw PythonOps.TypeErrorForTypeMismatch("ctype or object with from_param", o);
}
}
}
_argtypes = argValues;
} else {
_argtypes = null;
}
_id = Interlocked.Increment(ref _curId);
}
}
#endregion
#region Internal APIs
internal CallingConvention CallingConvention {
get {
return ((CFuncPtrType)DynamicHelpers.GetPythonType(this)).CallingConvention;
}
}
internal int Flags {
get {
return ((CFuncPtrType)DynamicHelpers.GetPythonType(this))._flags;
}
}
// TODO: access via PythonOps
public IntPtr addr {
[PythonHidden]
get {
return _memHolder.ReadIntPtr(0);
}
[PythonHidden]
set {
_memHolder.WriteIntPtr(0, value);
}
}
internal int Id {
get {
return _id;
}
}
#endregion
#region IDynamicObject Members
// needs to be public so that derived base classes can call it.
[PythonHidden]
public DynamicMetaObject GetMetaObject(Expression parameter) {
return new Meta(parameter, this);
}
#endregion
#region MetaObject
private class Meta : MetaPythonObject {
public Meta(Expression parameter, _CFuncPtr func)
: base(parameter, BindingRestrictions.Empty, func) {
}
public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) {
CodeContext context = PythonContext.GetPythonContext(binder).SharedContext;
ArgumentMarshaller[] signature = GetArgumentMarshallers(args);
BindingRestrictions restrictions = BindingRestrictions.GetTypeRestriction(
Expression,
Value.GetType()
).Merge(
BindingRestrictions.GetExpressionRestriction(
Expression.Call(
typeof(ModuleOps).GetMethod("CheckFunctionId"),
Expression.Convert(Expression, typeof(_CFuncPtr)),
Expression.Constant(Value.Id)
)
)
);
foreach (var arg in signature) {
restrictions = restrictions.Merge(arg.GetRestrictions());
}
int argCount = args.Length;
if (Value._comInterfaceIndex != -1) {
argCount--;
}
// need to verify we have the correct # of args
if (Value._argtypes != null) {
if (argCount < Value._argtypes.Count || (Value.CallingConvention != CallingConvention.Cdecl && argCount > Value._argtypes.Count)) {
return IncorrectArgCount(binder, restrictions, Value._argtypes.Count, argCount);
}
} else {
CFuncPtrType funcType = ((CFuncPtrType)Value.NativeType);
if (funcType._argtypes != null &&
(argCount < funcType._argtypes.Length || (Value.CallingConvention != CallingConvention.Cdecl && argCount > funcType._argtypes.Length))) {
return IncorrectArgCount(binder, restrictions, funcType._argtypes.Length, argCount);
}
}
if (Value._comInterfaceIndex != -1 && args.Length == 0) {
return NoThisParam(binder, restrictions);
}
Expression call = MakeCall(signature, GetNativeReturnType(), Value.Getrestype() == null, GetFunctionAddress(args));
List<Expression> block = new List<Expression>();
Expression res;
if (call.Type != typeof(void)) {
ParameterExpression tmp = Expression.Parameter(call.Type, "ret");
block.Add(Expression.Assign(tmp, call));
AddKeepAlives(signature, block);
block.Add(tmp);
res = Expression.Block(new[] { tmp }, block);
} else {
block.Add(call);
AddKeepAlives(signature, block);
res = Expression.Block(block);
}
res = AddReturnChecks(context, args, res);
return new DynamicMetaObject(Utils.Convert(res, typeof(object)), restrictions);
}
private Expression AddReturnChecks(CodeContext context, DynamicMetaObject[] args, Expression res) {
PythonContext ctx = context.LanguageContext;
object resType = Value.Getrestype();
if (resType != null) {
// res type can be callable, a type with _check_retval_, or
// it can be just be a type which doesn't require post-processing.
INativeType nativeResType = resType as INativeType;
object checkRetVal = null;
if (nativeResType == null) {
checkRetVal = resType;
} else if (!PythonOps.TryGetBoundAttr(context, nativeResType, "_check_retval_", out checkRetVal)) {
// we just wanted to try and get the value, don't need to do anything here.
checkRetVal = null;
}
if (checkRetVal != null) {
res = Expression.Dynamic(
ctx.CompatInvoke(new CallInfo(1)),
typeof(object),
Expression.Constant(checkRetVal),
res
);
}
}
object errCheck = Value.Geterrcheck();
if (errCheck != null) {
res = Expression.Dynamic(
ctx.CompatInvoke(new CallInfo(3)),
typeof(object),
Expression.Constant(errCheck),
res,
Expression,
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.MakeTuple)),
Expression.NewArrayInit(
typeof(object),
Microsoft.Scripting.Utils.ArrayUtils.ConvertAll(args, x => Utils.Convert(x.Expression, typeof(object)))
)
)
);
}
return res;
}
private static DynamicMetaObject IncorrectArgCount(DynamicMetaObjectBinder binder, BindingRestrictions restrictions, int expected, int got) {
return new DynamicMetaObject(
binder.Throw(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.TypeError)),
Expression.Constant(String.Format("this function takes {0} arguments ({1} given)", expected, got)),
Expression.NewArrayInit(typeof(object))
),
typeof(object)
),
restrictions
);
}
private static DynamicMetaObject NoThisParam(DynamicMetaObjectBinder binder, BindingRestrictions restrictions) {
return new DynamicMetaObject(
binder.Throw(
Expression.Call(
typeof(PythonOps).GetMethod(nameof(PythonOps.ValueError)),
Expression.Constant("native com method call without 'this' parameter"),
Expression.NewArrayInit(typeof(object))
),
typeof(object)
),
restrictions
);
}
/// <summary>
/// we need to keep alive any methods which have arguments for the duration of the
/// call. Otherwise they could be collected on the finalizer thread before we come back.
/// </summary>
private void AddKeepAlives(ArgumentMarshaller[] signature, List<Expression> block) {
foreach (ArgumentMarshaller marshaller in signature) {
Expression keepAlive = marshaller.GetKeepAlive();
if (keepAlive != null) {
block.Add(keepAlive);
}
}
}
private Expression MakeCall(ArgumentMarshaller[] signature, INativeType nativeRetType, bool retVoid, Expression address) {
List<object> constantPool = new List<object>();
MethodInfo interopInvoker = CreateInteropInvoker(
GetCallingConvention(),
signature,
nativeRetType,
retVoid,
constantPool
);
// build the args - IntPtr, user Args, constant pool
Expression[] callArgs = new Expression[signature.Length + 2];
callArgs[0] = address;
for (int i = 0; i < signature.Length; i++) {
callArgs[i + 1] = signature[i].ArgumentExpression;
}
callArgs[callArgs.Length - 1] = Expression.Constant(constantPool.ToArray());
return Expression.Call(interopInvoker, callArgs);
}
private Expression GetFunctionAddress(DynamicMetaObject[] args) {
Expression address;
if (Value._comInterfaceIndex != -1) {
Debug.Assert(args.Length != 0); // checked earlier
address = Expression.Call(
typeof(ModuleOps).GetMethod("GetInterfacePointer"),
Expression.Call(
typeof(ModuleOps).GetMethod("GetPointer"),
args[0].Expression
),
Expression.Constant(Value._comInterfaceIndex)
);
} else {
address = Expression.Property(
Expression.Convert(Expression, typeof(_CFuncPtr)),
"addr"
);
}
return address;
}
private CallingConvention GetCallingConvention() {
return Value.CallingConvention;
}
private INativeType GetNativeReturnType() {
return Value.Getrestype() as INativeType;
}
private ArgumentMarshaller/*!*/[]/*!*/ GetArgumentMarshallers(DynamicMetaObject/*!*/[]/*!*/ args) {
CFuncPtrType funcType = ((CFuncPtrType)Value.NativeType);
ArgumentMarshaller[] res = new ArgumentMarshaller[args.Length];
// first arg is taken by self if we're a com method
for (int i = 0; i < args.Length; i++) {
DynamicMetaObject mo = args[i];
object argType = null;
if (Value._comInterfaceIndex == -1 || i != 0) {
int argtypeIndex = Value._comInterfaceIndex == -1 ? i : i - 1;
if (Value._argtypes != null && argtypeIndex < Value._argtypes.Count) {
argType = Value._argtypes[argtypeIndex];
} else if (funcType._argtypes != null && argtypeIndex < funcType._argtypes.Length) {
argType = funcType._argtypes[argtypeIndex];
}
}
res[i] = GetMarshaller(mo.Expression, mo.Value, i, argType);
}
return res;
}
private ArgumentMarshaller/*!*/ GetMarshaller(Expression/*!*/ expr, object value, int index, object nativeType) {
if (nativeType != null) {
if (nativeType is INativeType nt) {
return new CDataMarshaller(expr, CompilerHelpers.GetType(value), nt);
}
return new FromParamMarshaller(expr);
}
if (value is CData data) {
return new CDataMarshaller(expr, CompilerHelpers.GetType(value), data.NativeType);
}
if (value is NativeArgument arg) {
return new NativeArgumentMarshaller(expr);
}
if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out object val)) {
throw new NotImplementedException("_as_parameter");
//return new UserDefinedMarshaller(GetMarshaller(..., value, index));
}
// Marshalling primitive or an object
return new PrimitiveMarshaller(expr, CompilerHelpers.GetType(value));
}
public new _CFuncPtr/*!*/ Value {
get {
return (_CFuncPtr)base.Value;
}
}
/// <summary>
/// Creates a method for calling with the specified signature. The returned method has a signature
/// of the form:
///
/// (IntPtr funcAddress, arg0, arg1, ..., object[] constantPool)
///
/// where IntPtr is the address of the function to be called. The arguments types are based upon
/// the types that the ArgumentMarshaller requires.
/// </summary>
private static MethodInfo/*!*/ CreateInteropInvoker(CallingConvention convention, ArgumentMarshaller/*!*/[]/*!*/ sig, INativeType nativeRetType, bool retVoid, List<object> constantPool) {
Type[] sigTypes = new Type[sig.Length + 2];
sigTypes[0] = typeof(IntPtr);
for (int i = 0; i < sig.Length; i++) {
sigTypes[i + 1] = sig[i].ArgumentExpression.Type;
}
sigTypes[sigTypes.Length - 1] = typeof(object[]);
Type retType = retVoid ? typeof(void) :
nativeRetType != null ? nativeRetType.GetPythonType() : typeof(int);
Type calliRetType = retVoid ? typeof(void) :
nativeRetType != null ? nativeRetType.GetNativeType() : typeof(int);
#if !CTYPES_USE_SNIPPETS
DynamicMethod dm = new DynamicMethod("InteropInvoker", retType, sigTypes, DynamicModule);
#else
TypeGen tg = Snippets.Shared.DefineType("InteropInvoker", typeof(object), false, false);
MethodBuilder dm = tg.TypeBuilder.DefineMethod("InteropInvoker", CompilerHelpers.PublicStatic, retType, sigTypes);
#endif
ILGenerator method = dm.GetILGenerator();
LocalBuilder calliRetTmp = null, finalRetValue = null;
if (dm.ReturnType != typeof(void)) {
calliRetTmp = method.DeclareLocal(calliRetType);
finalRetValue = method.DeclareLocal(dm.ReturnType);
}
// try {
// emit all of the arguments, save their cleanups
method.BeginExceptionBlock();
List<MarshalCleanup> cleanups = null;
for (int i = 0; i < sig.Length; i++) {
#if DEBUG
method.Emit(OpCodes.Ldstr, String.Format("Argument #{0}, Marshaller: {1}, Native Type: {2}", i, sig[i], sig[i].NativeType));
method.Emit(OpCodes.Pop);
#endif
MarshalCleanup cleanup = sig[i].EmitCallStubArgument(method, i + 1, constantPool, sigTypes.Length - 1);
if (cleanup != null) {
if (cleanups == null) {
cleanups = new List<MarshalCleanup>();
}
cleanups.Add(cleanup);
}
}
// emit the target function pointer and the calli
#if DEBUG
method.Emit(OpCodes.Ldstr, "!!! CALLI !!!");
method.Emit(OpCodes.Pop);
#endif
method.Emit(OpCodes.Ldarg_0);
method.EmitCalli(OpCodes.Calli, convention, calliRetType, sig.Select(x => x.NativeType).ToArray());
// if we have a return value we need to store it and marshal to Python
// before we run any cleanup code.
if (retType != typeof(void)) {
#if DEBUG
method.Emit(OpCodes.Ldstr, "!!! Return !!!");
method.Emit(OpCodes.Pop);
#endif
if (nativeRetType != null) {
method.Emit(OpCodes.Stloc, calliRetTmp);
nativeRetType.EmitReverseMarshalling(method, new Local(calliRetTmp), constantPool, sig.Length + 1);
method.Emit(OpCodes.Stloc, finalRetValue);
} else {
Debug.Assert(retType == typeof(int));
// no marshalling necessary
method.Emit(OpCodes.Stloc, finalRetValue);
}
}
// } finally {
// emit the cleanup code
method.BeginFinallyBlock();
if (cleanups != null) {
foreach (MarshalCleanup mc in cleanups) {
mc.Cleanup(method);
}
}
method.EndExceptionBlock();
// }
// load the temporary value and return it.
if (retType != typeof(void)) {
method.Emit(OpCodes.Ldloc, finalRetValue);
}
method.Emit(OpCodes.Ret);
#if CTYPES_USE_SNIPPETS
return tg.TypeBuilder.CreateType().GetMethod("InteropInvoker");
#else
return dm;
#endif
}
private static SignatureHelper GetMethodSigHelper(CallingConvention convention, Type calliRetType) {
#if FEATURE_REFEMIT_FULL
return SignatureHelper.GetMethodSigHelper(convention, calliRetType);
#else
var helper = typeof(SignatureHelper).GetMethod("GetMethodSigHelper", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(CallingConvention), typeof(Type) }, null);
return (SignatureHelper)helper.Invoke(null, new object[] { convention, calliRetType });
#endif
}
private static SignatureHelper GetCalliSignature(CallingConvention convention, ArgumentMarshaller/*!*/[] sig, Type calliRetType) {
SignatureHelper signature = GetMethodSigHelper(convention, calliRetType);
foreach (ArgumentMarshaller argMarshaller in sig) {
signature.AddArgument(argMarshaller.NativeType);
}
return signature;
}
#region Argument Marshalling
/// <summary>
/// Base class for marshalling arguments from the user provided value to the
/// call stub. This class provides the logic for creating the call stub and
/// calling it.
/// </summary>
abstract class ArgumentMarshaller {
private readonly Expression/*!*/ _argExpr;
public ArgumentMarshaller(Expression/*!*/ container) {
_argExpr = container;
}
/// <summary>
/// Emits the IL to get the argument for the call stub generated into
/// a dynamic method.
/// </summary>
public abstract MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument);
public abstract Type/*!*/ NativeType {
get;
}
/// <summary>
/// Gets the expression used to provide the argument. This is the expression
/// from an incoming DynamicMetaObject.
/// </summary>
public Expression/*!*/ ArgumentExpression {
get {
return _argExpr;
}
}
/// <summary>
/// Gets an expression which keeps alive the argument for the duration of the call.
///
/// Returns null if a keep alive is not necessary.
/// </summary>
public virtual Expression GetKeepAlive() {
return null;
}
public virtual BindingRestrictions GetRestrictions() {
return BindingRestrictions.Empty;
}
}
/// <summary>
/// Provides marshalling of primitive values when the function type
/// has no type information or when the user has provided us with
/// an explicit cdata instance.
/// </summary>
class PrimitiveMarshaller : ArgumentMarshaller {
private readonly Type/*!*/ _type;
private static MethodInfo _bigIntToInt32;
private static MethodInfo BigIntToInt32 {
get {
if (_bigIntToInt32 == null) {
MemberInfo[] mis = typeof(BigInteger).GetMember(
"op_Explicit",
MemberTypes.Method,
BindingFlags.Public | BindingFlags.Static
);
foreach (MethodInfo mi in mis) {
if (mi.ReturnType == typeof(int)) {
_bigIntToInt32 = mi;
break;
}
}
Debug.Assert(_bigIntToInt32 != null);
}
return _bigIntToInt32;
}
}
public PrimitiveMarshaller(Expression/*!*/ container, Type/*!*/ type)
: base(container) {
_type = type;
}
private static readonly MethodInfo StringGetPinnableReference = typeof(string).GetMethod("GetPinnableReference");
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
if (_type == typeof(DynamicNull)) {
generator.Emit(OpCodes.Ldc_I4_0);
generator.Emit(OpCodes.Conv_I);
return null;
}
generator.Emit(OpCodes.Ldarg, argIndex);
if (ArgumentExpression.Type != _type) {
generator.Emit(OpCodes.Unbox_Any, _type);
}
if (_type == typeof(string)) {
// pin the string and convert to a wchar*. We could let the CLR do this
// but we need the string to be pinned longer than the duration of the the CLR's
// p/invoke. This is because the function could return the same pointer back
// to us and we need to create a new string from it.
if (StringGetPinnableReference is null) {
LocalBuilder lb = generator.DeclareLocal(typeof(string), true);
generator.Emit(OpCodes.Stloc, lb);
generator.Emit(OpCodes.Ldloc, lb);
generator.Emit(OpCodes.Conv_I);
#pragma warning disable CS0618 // Type or member is obsolete
generator.Emit(OpCodes.Ldc_I4, RuntimeHelpers.OffsetToStringData);
#pragma warning restore CS0618 // Type or member is obsolete
generator.Emit(OpCodes.Add);
} else {
generator.Emit(OpCodes.Call, StringGetPinnableReference);
}
} else if (_type == typeof(Bytes)) {
LocalBuilder lb = generator.DeclareLocal(typeof(byte).MakeByRefType(), true);
generator.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("GetBytes"));
generator.Emit(OpCodes.Ldc_I4_0);
generator.Emit(OpCodes.Ldelema, typeof(Byte));
generator.Emit(OpCodes.Stloc, lb);
generator.Emit(OpCodes.Ldloc, lb);
} else if (_type == typeof(BigInteger)) {
generator.Emit(OpCodes.Call, BigIntToInt32);
} else if (!_type.IsValueType) {
generator.Emit(OpCodes.Call, typeof(CTypes).GetMethod("PyObj_ToPtr"));
}
return null;
}
public override Type NativeType {
get {
if (_type == typeof(BigInteger)) {
return typeof(int);
} else if (!_type.IsValueType) {
return typeof(IntPtr);
}
return _type;
}
}
public override BindingRestrictions GetRestrictions() {
if (_type == typeof(DynamicNull)) {
return BindingRestrictions.GetExpressionRestriction(Expression.Equal(ArgumentExpression, Expression.Constant(null)));
}
return BindingRestrictions.GetTypeRestriction(ArgumentExpression, _type);
}
}
class FromParamMarshaller : ArgumentMarshaller {
public FromParamMarshaller(Expression/*!*/ container)
: base(container) {
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator generator, int argIndex, List<object> constantPool, int constantPoolArgument) {
throw new NotImplementedException();
}
public override Type NativeType {
get { throw new NotImplementedException(); }
}
}
/// <summary>
/// Provides marshalling for when the function type provide argument information.
/// </summary>
class CDataMarshaller : ArgumentMarshaller {
private readonly Type/*!*/ _type;
private readonly INativeType/*!*/ _cdataType;
public CDataMarshaller(Expression/*!*/ container, Type/*!*/ type, INativeType/*!*/cdataType)
: base(container) {
_type = type;
_cdataType = cdataType;
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
return _cdataType.EmitMarshalling(generator, new Arg(argIndex, ArgumentExpression.Type), constantPool, constantPoolArgument);
}
public override Type NativeType {
get {
return _cdataType.GetNativeType();
}
}
public override Expression GetKeepAlive() {
// Future possible optimization - we could just keep alive the MemoryHolder
if (_type.IsValueType) {
return null;
}
return Expression.Call(
typeof(GC).GetMethod("KeepAlive"),
ArgumentExpression
);
}
public override BindingRestrictions GetRestrictions() {
// we base this off of the type marshalling which can handle anything.
return BindingRestrictions.Empty;
}
}
/// <summary>
/// Provides marshalling for when the user provides a native argument object
/// (usually gotten by byref or pointer) and the function type has no type information.
/// </summary>
class NativeArgumentMarshaller : ArgumentMarshaller {
public NativeArgumentMarshaller(Expression/*!*/ container)
: base(container) {
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
// We access UnsafeAddress here but ensure the object is kept
// alive via the expression returned in GetKeepAlive.
generator.Emit(OpCodes.Ldarg, argIndex);
generator.Emit(OpCodes.Castclass, typeof(NativeArgument));
generator.Emit(OpCodes.Call, typeof(NativeArgument).GetMethod("get__obj"));
generator.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress"));
return null;
}
public override Type/*!*/ NativeType {
get {
return typeof(IntPtr);
}
}
public override Expression GetKeepAlive() {
// Future possible optimization - we could just keep alive the MemoryHolder
return Expression.Call(
typeof(GC).GetMethod("KeepAlive"),
ArgumentExpression
);
}
public override BindingRestrictions GetRestrictions() {
return BindingRestrictions.GetTypeRestriction(ArgumentExpression, typeof(NativeArgument));
}
}
#if FALSE // TODO: not implemented yet
/// <summary>
/// Provides the marshalling for a user defined object which has an _as_parameter_
/// value.
/// </summary>
class UserDefinedMarshaller : ArgumentMarshaller {
private readonly ArgumentMarshaller/*!*/ _marshaller;
public UserDefinedMarshaller(Expression/*!*/ container, ArgumentMarshaller/*!*/ marshaller)
: base(container) {
_marshaller = marshaller;
}
public override Type NativeType {
get { throw new NotImplementedException("user defined marshaller sig type"); }
}
public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) {
throw new NotImplementedException("user defined marshaller");
}
}
#endif
#endregion
}
#endregion
public string __repr__(CodeContext context) {
if (_comInterfaceIndex != -1) {
return string.Format("<COM method offset {0}: {1} at {2}>", _comInterfaceIndex, DynamicHelpers.GetPythonType(this).Name, _id);
}
return ObjectOps.__repr__(this);
}
}
}
#if NETSTANDARD2_0
#nullable enable
internal static class ILGeneratorExtensions {
private static MethodInfo? EmitCalliMethodInfo = typeof(ILGenerator).GetMethod("EmitCalli", new Type[] { typeof(OpCode), typeof(CallingConvention), typeof(Type), typeof(Type[]) });
public static void EmitCalli(this ILGenerator ilgen, OpCode opcode, CallingConvention unmanagedCallConv, Type? returnType, Type[]? parameterTypes) {
// should exist in runtimes of interest, but just in case, let it throw if the method doesn't exist...
EmitCalliMethodInfo!.Invoke(ilgen, new object[] { opcode, unmanagedCallConv, returnType!, parameterTypes! });
}
}
#nullable restore
#endif
}
#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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents creating a new array and possibly initializing the elements of the new array.
/// </summary>
[DebuggerTypeProxy(typeof(NewArrayExpressionProxy))]
public class NewArrayExpression : Expression
{
internal NewArrayExpression(Type type, ReadOnlyCollection<Expression> expressions)
{
Expressions = expressions;
Type = type;
}
internal static NewArrayExpression Make(ExpressionType nodeType, Type type, ReadOnlyCollection<Expression> expressions)
{
Debug.Assert(type.IsArray);
if (nodeType == ExpressionType.NewArrayInit)
{
return new NewArrayInitExpression(type, expressions);
}
else
{
return new NewArrayBoundsExpression(type, expressions);
}
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type { get; }
/// <summary>
/// Gets the bounds of the array if the value of the <see cref="ExpressionType"/> property is NewArrayBounds, or the values to initialize the elements of the new array if the value of the <see cref="Expression.NodeType"/> property is NewArrayInit.
/// </summary>
public ReadOnlyCollection<Expression> Expressions { get; }
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitNewArray(this);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="expressions">The <see cref="Expressions"/> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public NewArrayExpression Update(IEnumerable<Expression> expressions)
{
// Explicit null check here as otherwise wrong parameter name will be used.
ContractUtils.RequiresNotNull(expressions, nameof(expressions));
if (ExpressionUtils.SameElements(ref expressions, Expressions))
{
return this;
}
return NodeType == ExpressionType.NewArrayInit
? NewArrayInit(Type.GetElementType(), expressions)
: NewArrayBounds(Type.GetElementType(), expressions);
}
}
internal sealed class NewArrayInitExpression : NewArrayExpression
{
internal NewArrayInitExpression(Type type, ReadOnlyCollection<Expression> expressions)
: base(type, expressions)
{
}
/// <summary>
/// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType => ExpressionType.NewArrayInit;
}
internal sealed class NewArrayBoundsExpression : NewArrayExpression
{
internal NewArrayBoundsExpression(Type type, ReadOnlyCollection<Expression> expressions)
: base(type, expressions)
{
}
/// <summary>
/// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType => ExpressionType.NewArrayBounds;
}
public partial class Expression
{
#region NewArrayInit
/// <summary>
/// Creates a <see cref="NewArrayExpression"/> of the specified type from the provided initializers.
/// </summary>
/// <param name="type">A Type that represents the element type of the array.</param>
/// <param name="initializers">The expressions used to create the array elements.</param>
/// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayInit"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns>
public static NewArrayExpression NewArrayInit(Type type, params Expression[] initializers)
{
return NewArrayInit(type, (IEnumerable<Expression>)initializers);
}
/// <summary>
/// Creates a <see cref="NewArrayExpression"/> of the specified type from the provided initializers.
/// </summary>
/// <param name="type">A Type that represents the element type of the array.</param>
/// <param name="initializers">The expressions used to create the array elements.</param>
/// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayInit"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns>
public static NewArrayExpression NewArrayInit(Type type, IEnumerable<Expression> initializers)
{
ContractUtils.RequiresNotNull(type, nameof(type));
ContractUtils.RequiresNotNull(initializers, nameof(initializers));
if (type == typeof(void))
{
throw Error.ArgumentCannotBeOfTypeVoid(nameof(type));
}
TypeUtils.ValidateType(type, nameof(type));
if (type.IsByRef)
{
throw Error.TypeMustNotBeByRef(nameof(type));
}
if (type.IsPointer)
{
throw Error.TypeMustNotBePointer(nameof(type));
}
ReadOnlyCollection<Expression> initializerList = initializers.ToReadOnly();
Expression[] newList = null;
for (int i = 0, n = initializerList.Count; i < n; i++)
{
Expression expr = initializerList[i];
ExpressionUtils.RequiresCanRead(expr, nameof(initializers), i);
if (!TypeUtils.AreReferenceAssignable(type, expr.Type))
{
if (!TryQuote(type, ref expr))
{
throw Error.ExpressionTypeCannotInitializeArrayType(expr.Type, type);
}
if (newList == null)
{
newList = new Expression[initializerList.Count];
for (int j = 0; j < i; j++)
{
newList[j] = initializerList[j];
}
}
}
if (newList != null)
{
newList[i] = expr;
}
}
if (newList != null)
{
initializerList = new TrueReadOnlyCollection<Expression>(newList);
}
return NewArrayExpression.Make(ExpressionType.NewArrayInit, type.MakeArrayType(), initializerList);
}
#endregion
#region NewArrayBounds
/// <summary>
/// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank.
/// </summary>
/// <param name="type">A <see cref="System.Type"/> that represents the element type of the array.</param>
/// <param name="bounds">An array that contains Expression objects to use to populate the <see cref="NewArrayExpression.Expressions"/> collection.</param>
/// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayBounds"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns>
public static NewArrayExpression NewArrayBounds(Type type, params Expression[] bounds)
{
return NewArrayBounds(type, (IEnumerable<Expression>)bounds);
}
/// <summary>
/// Creates a <see cref="NewArrayExpression"/> that represents creating an array that has a specified rank.
/// </summary>
/// <param name="type">A <see cref="System.Type"/> that represents the element type of the array.</param>
/// <param name="bounds">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the <see cref="NewArrayExpression.Expressions"/> collection.</param>
/// <returns>A <see cref="NewArrayExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.NewArrayBounds"/> and the <see cref="NewArrayExpression.Expressions"/> property set to the specified value.</returns>
public static NewArrayExpression NewArrayBounds(Type type, IEnumerable<Expression> bounds)
{
ContractUtils.RequiresNotNull(type, nameof(type));
ContractUtils.RequiresNotNull(bounds, nameof(bounds));
if (type == typeof(void))
{
throw Error.ArgumentCannotBeOfTypeVoid(nameof(type));
}
TypeUtils.ValidateType(type, nameof(type));
if (type.IsByRef)
{
throw Error.TypeMustNotBeByRef(nameof(type));
}
if (type.IsPointer)
{
throw Error.TypeMustNotBePointer(nameof(type));
}
ReadOnlyCollection<Expression> boundsList = bounds.ToReadOnly();
int dimensions = boundsList.Count;
if (dimensions <= 0) throw Error.BoundsCannotBeLessThanOne(nameof(bounds));
for (int i = 0; i < dimensions; i++)
{
Expression expr = boundsList[i];
ExpressionUtils.RequiresCanRead(expr, nameof(bounds), i);
if (!expr.Type.IsInteger())
{
throw Error.ArgumentMustBeInteger(nameof(bounds), i);
}
}
Type arrayType;
if (dimensions == 1)
{
//To get a vector, need call Type.MakeArrayType().
//Type.MakeArrayType(1) gives a non-vector array, which will cause type check error.
arrayType = type.MakeArrayType();
}
else
{
arrayType = type.MakeArrayType(dimensions);
}
return NewArrayExpression.Make(ExpressionType.NewArrayBounds, arrayType, boundsList);
}
#endregion
}
}
| |
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using System.Net;
using System.Collections.Generic;
using GoogleMapsApi;
using GoogleMapsApi.Entities.Common;
using GoogleMapsApi.Entities.Directions.Request;
using GoogleMapsApi.Entities.Directions.Response;
using GoogleMapsApi.Entities.Geocoding.Request;
using GoogleMapsApi.Entities.Geocoding.Response;
using GoogleMapsApi.StaticMaps;
using GoogleMapsApi.StaticMaps.Entities;
using System.Linq;
using Android.Graphics;
using System.Threading;
using System.Threading.Tasks;
using InstaPool.DataModels;
using Newtonsoft.Json;
using GMarker = Android.Gms.Maps.Model.Marker;
namespace InstaPool
{
[Activity(Label = "UserHome")]
public class UserHome : Activity, IOnMapReadyCallback, GoogleMap.IInfoWindowAdapter, GoogleMap.IOnInfoWindowClickListener
{
public enum CommuteUserState
{
Commuter_Init,
Commuter_Show_Location,
Commuter_Show_Poolers,
Commuter_Choose_Pickup,
Commuter_Select_Pooler,
Commuter_Pool_Requested
};
private GoogleMap gMap;
private MapFragment _mapFragment;
private CommuteUserState PrevUserState = CommuteUserState.Commuter_Init;
private CommuteUserState CurrentUserState = CommuteUserState.Commuter_Show_Location;
private Button FindPoolButton;
private Button RequestPoolButton;
private LatLng CommuterDestination;
private LatLng CommuterSource;
private GMarker CommuterSourceMarker;
private GMarker CommuterPickupMarker;
private Dictionary<GMarker, int> CommuterHashMap;
private WebClient _webClient;
private Uri _uri;
private string _validateCredsUri = "http://niting-wrk.fareast.corp.microsoft.com:5858/user/login/";
private User _user;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.UserHome);
_webClient = new WebClient();
_mapFragment = MapFragment.NewInstance();
FragmentTransaction tx = FragmentManager.BeginTransaction();
tx.Add(Resource.Id.map_layout, _mapFragment);
tx.Commit();
_mapFragment.GetMapAsync(this);
FindPoolButton = FindViewById<Button>(Resource.Id.FindPoolButton);
FindPoolButton.Click += delegate
{
CurrentUserState = CommuteUserState.Commuter_Show_Poolers;
};
RequestPoolButton = FindViewById<Button>(Resource.Id.RequestPoolButton);
RequestPoolButton.Click += delegate
{
Dialog dd = new Dialog(this);
dd.SetContentView(Resource.Layout.pool_requested);
/*
FragmentTransaction trans = FragmentManager.BeginTransaction();
var okDialog = new dialog_pool_requested();
okDialog.Show(trans ,"my_tag");*/
dd.Show();
Button bb = dd.FindViewById<Button>(Resource.Id.pool_request_ok_button);
bb.Click += delegate
{
dd.Dismiss();
CurrentUserState = CommuteUserState.Commuter_Pool_Requested;
};
};
_user = JsonConvert.DeserializeObject<User>(Intent.GetStringExtra("UserJson"));
var destCoordinates = _user.Commute.Destination.Split(',');
CommuterDestination = new LatLng(double.Parse(destCoordinates[0]), double.Parse(destCoordinates[1]));
var srcCoordinates = _user.Commute.Source.Split(',');
CommuterSource = new LatLng(double.Parse(srcCoordinates[0]), double.Parse(srcCoordinates[1]));
CommuterHashMap = new Dictionary<GMarker, int>();
MapWorker();
}
public void OnMapReady(GoogleMap googMap)
{
gMap = googMap;
gMap.UiSettings.ZoomControlsEnabled = true;
gMap.SetInfoWindowAdapter(this);
gMap.SetOnInfoWindowClickListener(this);
}
async void MapWorker()
{
while (true)
{
if (CurrentUserState != PrevUserState && gMap != null)
{
gMap.Clear();
switch (CurrentUserState)
{
case CommuteUserState.Commuter_Show_Location:
ShowMyLocation();
break;
case CommuteUserState.Commuter_Show_Poolers:
ShowPools();
break;
case CommuteUserState.Commuter_Choose_Pickup:
ShowPickupOption();
break;
case CommuteUserState.Commuter_Select_Pooler:
ShowSelectPooler();
break;
case CommuteUserState.Commuter_Pool_Requested:
ShowPoolRequested();
break;
default:
Console.WriteLine("NO OP!!!");
break;
}
PrevUserState = CurrentUserState;
}
await Task.Delay(500);
}
}
void ShowPoolRequested()
{
SetPoolButtonVisibility(false);
ContractMapView();
SetRequestButtonVisibility(false);
SetRequestTextVisibility(true);
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(CommuterSource, 17);
gMap.MoveCamera(camera);
MarkerOptions markerOpt1 = new MarkerOptions()
.SetPosition(CommuterSource)
.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueGreen));
CommuterSourceMarker = gMap.AddMarker(markerOpt1);
var colorArray = new Color[4];
colorArray[0] = Color.Green;
colorArray[1] = Color.Red;
colorArray[2] = Color.Tomato;
colorArray[3] = Color.Orange;
int i = 0;
var routes = GetAllRoutes();
ShowPoolerLocation(routes.First(), colorArray[i % 4], true);
}
void ShowSelectPooler()
{
SetPoolButtonVisibility(false);
ContractMapView();
SetRequestButtonVisibility(true);
SetRequestTextVisibility(false);
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(CommuterSource, 17);
gMap.MoveCamera(camera);
MarkerOptions markerOpt1 = new MarkerOptions()
.SetPosition(CommuterSource)
.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueGreen));
CommuterSourceMarker = gMap.AddMarker(markerOpt1);
var colorArray = new Color[4];
colorArray[0] = Color.Green;
colorArray[1] = Color.Red;
colorArray[2] = Color.Tomato;
colorArray[3] = Color.Orange;
int i = 0;
var routes = GetAllRoutes();
ShowPoolerLocation(routes.First(), colorArray[i % 4], true);
}
void ShowPickupOption()
{
SetPoolButtonVisibility(true);
ContractMapView();
SetRequestButtonVisibility(false);
SetRequestTextVisibility(false);
var routes = GetAllRoutes();
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(CommuterSource, 14);
gMap.MoveCamera(camera);
MarkerOptions markerOpt1 = new MarkerOptions()
.SetPosition(CommuterSource)
.Draggable(true)
.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueGreen));
CommuterPickupMarker = gMap.AddMarker(markerOpt1);
MarkerOptions markerOpt = new MarkerOptions()
.SetPosition(new LatLng(17.439683, 78.34877))
.Draggable(true)
.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueGreen));
gMap.AddMarker(markerOpt);
MarkerOptions markerOpt2 = new MarkerOptions()
.SetPosition(new LatLng(17.436318, 78.3471047))
.Draggable(true)
.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueGreen));
gMap.AddMarker(markerOpt2);
// might be unneceaasry
CommuterHashMap[CommuterPickupMarker] = 10;
ShowPoolerLocation(routes.First(), Color.Orange);
}
void add(LatLng ll, float c)
{
MarkerOptions markerOpt2 = new MarkerOptions()
.SetPosition(ll)
.SetIcon(BitmapDescriptorFactory.DefaultMarker(c));
gMap.AddMarker(markerOpt2);
}
void ShowMyLocation()
{
/*
add(new LatLng(17.452486, 78.3437004), BitmapDescriptorFactory.HueGreen);
add(new LatLng(17.440173, 78.3614254), BitmapDescriptorFactory.HueAzure);
add(new LatLng(17.4438644, 78.3541745), BitmapDescriptorFactory.HueAzure);
*/
MarkerOptions markerOpt1 = new MarkerOptions()
.SetPosition(CommuterSource)
.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueAzure));
gMap.AddMarker(markerOpt1);
MarkerOptions markerOpt2 = new MarkerOptions()
.SetPosition(CommuterDestination);
gMap.AddMarker(markerOpt2);
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(CommuterSource, 12);
gMap.MoveCamera(camera);
}
void ShowPools()
{
SetPoolButtonVisibility(false);
ExpandMapView();
SetRequestButtonVisibility(false);
SetRequestTextVisibility(false);
CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(CommuterSource, 17);
gMap.MoveCamera(camera);
MarkerOptions markerOpt1 = new MarkerOptions()
.SetPosition(CommuterSource)
.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueGreen));
CommuterSourceMarker = gMap.AddMarker(markerOpt1);
var colorArray = new Color[4];
colorArray[0] = Color.Green;
colorArray[1] = Color.Red;
colorArray[2] = Color.Tomato;
colorArray[3] = Color.Orange;
int i = 0;
var routes = GetAllRoutes();
foreach (var route in routes)
{
ShowPoolerLocation(route, colorArray[i % 4]);
i++;
}
}
void SetRequestTextVisibility(bool isVisible)
{
var RequestTextLayout = FindViewById<LinearLayout>(Resource.Id.request_text_layout);
RequestTextLayout.Visibility = (isVisible ? ViewStates.Visible : ViewStates.Gone);
}
void SetRequestButtonVisibility(bool isVisible)
{
var RequestButton = FindViewById<Button>(Resource.Id.RequestPoolButton);
RequestButton.Visibility = (isVisible ? ViewStates.Visible : ViewStates.Gone);
}
void SetPoolButtonVisibility(bool isVisible)
{
var PoolButton = FindViewById<Button>(Resource.Id.FindPoolButton);
PoolButton.Visibility = (isVisible ? ViewStates.Visible : ViewStates.Gone);
}
void ExpandMapView()
{
var MapLayout = FindViewById<LinearLayout>(Resource.Id.map_layout);
var ll = MapLayout.LayoutParameters;
MapLayout.LayoutParameters = new LinearLayout.LayoutParams(ll.Width, ll.Height, 85);
}
void ContractMapView()
{
var MapLayout = FindViewById<LinearLayout>(Resource.Id.map_layout);
var ll = MapLayout.LayoutParameters;
MapLayout.LayoutParameters = new LinearLayout.LayoutParams(ll.Width, ll.Height, 75);
}
private void ShowPoolerLocation(RouteInfo routeInfo, Color color, bool drawRoute = false)
{
MarkerOptions markerOpt1 = new MarkerOptions()
.SetPosition(routeInfo.Source)
.SetTitle(routeInfo.UserId.ToString())
.SetSnippet("Price: " + routeInfo.Price)
.SetIcon(BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueAzure));
gMap.AddMarker(markerOpt1);
MarkerOptions markerOpt2 = new MarkerOptions()
.SetPosition(routeInfo.Destination);
gMap.AddMarker(markerOpt2);
if (drawRoute)
{
var path = GetPath(routeInfo);
var polylineoption = new PolylineOptions();
polylineoption.InvokeColor(color);
polylineoption.Geodesic(true);
polylineoption.Add(path.ToArray());
gMap.AddPolyline(polylineoption);
}
}
private List<LatLng> GetPath(RouteInfo routeInfo)
{
DirectionsRequest directionsRequest = new DirectionsRequest()
{
Origin = GetLatLngStr(routeInfo.Source),
Destination = GetLatLngStr(routeInfo.Destination)
};
DirectionsResponse directions = GoogleMaps.Directions.Query(directionsRequest);
var latLngList = new List<LatLng>();
var route = directions.Routes.First();
foreach (var leg in route.Legs)
{
foreach (var step in leg.Steps)
{
var pLine = step.PolyLine;
foreach (var point in pLine.Points)
{
latLngList.Add(new LatLng(point.Latitude, point.Longitude));
}
}
}
return latLngList;
}
private string GetLatLngStr(LatLng latLng)
{
return latLng.Latitude + "," + latLng.Longitude;
}
private List<RouteInfo> GetAllRoutes()
{
var tripInfo = GetAvailableTrips();
var routeInfo = new List<RouteInfo>();
foreach (var trip in tripInfo)
{
var tripDestCoordinates = trip.Commute.Destination.Split(',');
var tripDest = new LatLng(double.Parse(tripDestCoordinates[0]), double.Parse(tripDestCoordinates[1]));
var tripSrcCoordinates = trip.Commute.Source.Split(',');
var tripSrc = new LatLng(double.Parse(tripSrcCoordinates[0]), double.Parse(tripSrcCoordinates[1]));
routeInfo.Add(new RouteInfo() { Source = tripSrc, Destination = tripDest, UserId = trip.UserId, Price = trip.Price });
}
return routeInfo;
}
public List<Trip> GetAvailableTrips()
{
var availableTrips = new List<Trip>();
var userSrcCoordinates = _user.Commute.Source.Split(',');
var userDestCoordinates = _user.Commute.Destination.Split(',');
_uri = new Uri(
"http://niting-wrk.fareast.corp.microsoft.com:9090/pool-match-service/match/pools?"
+ "userLocation=" + userSrcCoordinates[0] + "," + userSrcCoordinates[1]
+ "&userDestination=" + userDestCoordinates[0] + "," + userDestCoordinates[1]);
//_webClient.Headers.Add(HttpRequestHeader.ContentType, "application/json");
var responseString = _webClient.DownloadString(_uri);
availableTrips = JsonConvert.DeserializeObject<List<Trip>>(responseString);
return availableTrips;
}
public View GetInfoContents(Android.Gms.Maps.Model.Marker marker)
{
return null;
}
public View GetInfoWindow(Android.Gms.Maps.Model.Marker marker)
{
if (!marker.Equals(CommuterSourceMarker))
{
return LayoutInflater.Inflate(Resource.Layout.info_window, null, false);
}
return null;
}
public void OnInfoWindowClick(GMarker marker)
{
// get user id from hashmap with marker info
CurrentUserState = CommuteUserState.Commuter_Select_Pooler;
}
}
internal class RouteInfo
{
public LatLng Source, Destination;
internal List<LatLng> WayPoints;
internal int UserId;
internal double Price;
}
}
| |
namespace Fixtures.SwaggerBatHttp
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial interface IHttpSuccess
{
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Head200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get 200 success
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse<bool?>> Get200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put boolean value true returning 200 success
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Put200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returning 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Patch200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post bollean value true in request that returns a 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Post200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete simple boolean value true returns 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Delete200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 201
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Put201WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 201 (Created)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Post201WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Put202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returns 202
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Patch202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Post202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete true Boolean value in request returns 202 (accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Delete202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Put204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Patch204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Post204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Delete204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 404 status code
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
Task<HttpOperationResponse> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// 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.Concurrent;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class HttpClientTest
{
[Fact]
public void Dispose_MultipleTimes_Success()
{
var client = new HttpClient();
client.Dispose();
client.Dispose();
}
[Fact]
public void DefaultRequestHeaders_Idempotent()
{
using (var client = new HttpClient())
{
Assert.NotNull(client.DefaultRequestHeaders);
Assert.Same(client.DefaultRequestHeaders, client.DefaultRequestHeaders);
}
}
[Fact]
public void BaseAddress_Roundtrip_Equal()
{
using (var client = new HttpClient())
{
Assert.Null(client.BaseAddress);
Uri uri = new Uri(CreateFakeUri());
client.BaseAddress = uri;
Assert.Equal(uri, client.BaseAddress);
client.BaseAddress = null;
Assert.Null(client.BaseAddress);
}
}
[Fact]
public void BaseAddress_InvalidUri_Throws()
{
using (var client = new HttpClient())
{
Assert.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("ftp://onlyhttpsupported"));
Assert.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("/onlyabsolutesupported", UriKind.Relative));
}
}
[Fact]
public void Timeout_Roundtrip_Equal()
{
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
Assert.Equal(Timeout.InfiniteTimeSpan, client.Timeout);
client.Timeout = TimeSpan.FromSeconds(1);
Assert.Equal(TimeSpan.FromSeconds(1), client.Timeout);
}
}
[Fact]
public void Timeout_OutOfRange_Throws()
{
using (var client = new HttpClient())
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(-2));
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(0));
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(int.MaxValue));
}
}
[Fact]
public void MaxResponseContentBufferSize_Roundtrip_Equal()
{
using (var client = new HttpClient())
{
client.MaxResponseContentBufferSize = 1;
Assert.Equal(1, client.MaxResponseContentBufferSize);
client.MaxResponseContentBufferSize = int.MaxValue;
Assert.Equal(int.MaxValue, client.MaxResponseContentBufferSize);
}
}
[Fact]
public void MaxResponseContentBufferSize_OutOfRange_Throws()
{
using (var client = new HttpClient())
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = -1);
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 0);
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 1 + (long)int.MaxValue);
}
}
[Fact]
public async Task MaxResponseContentBufferSize_TooSmallForContent_Throws()
{
using (var client = new HttpClient())
{
client.MaxResponseContentBufferSize = 1;
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(Configuration.Http.RemoteEchoServer));
}
}
[Fact]
public async Task Properties_CantChangeAfterOperation_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
(await client.GetAsync(CreateFakeUri())).Dispose();
Assert.Throws<InvalidOperationException>(() => client.BaseAddress = null);
Assert.Throws<InvalidOperationException>(() => client.Timeout = TimeSpan.FromSeconds(1));
Assert.Throws<InvalidOperationException>(() => client.MaxResponseContentBufferSize = 1);
}
}
[Theory]
[InlineData(null)]
[InlineData("/something.html")]
public void GetAsync_NoBaseAddress_InvalidUri_ThrowsException(string uri)
{
using (var client = new HttpClient())
{
Assert.Throws<InvalidOperationException>(() => { client.GetAsync(uri == null ? null : new Uri(uri, UriKind.RelativeOrAbsolute)); });
}
}
[Theory]
[InlineData(null)]
[InlineData("/")]
public async Task GetAsync_BaseAddress_ValidUri_Success(string uri)
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
client.BaseAddress = new Uri(CreateFakeUri());
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GetContentAsync_ErrorStatusCode_ExpectedExceptionThrown(bool withResponseContent)
{
using (var client = new HttpClient(new CustomResponseHandler(
(r,c) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = withResponseContent ? new ByteArrayContent(new byte[1]) : null
}))))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetByteArrayAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponse_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => client.GetStringAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponseContent_ReturnsDefaultValue()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage() { Content = null }))))
{
Assert.Same(string.Empty, await client.GetStringAsync(CreateFakeUri()));
Assert.Same(Array.Empty<byte>(), await client.GetByteArrayAsync(CreateFakeUri()));
Assert.Same(Stream.Null, await client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Synchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => { throw e; }) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Asynchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => Task.FromException(e)) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetAsync_InvalidUrl_ExpectedExceptionThrown()
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Canceled_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
var content = new ByteArrayContent(new byte[1]);
var cts = new CancellationTokenSource();
Task t1 = client.GetAsync(CreateFakeUri(), cts.Token);
Task t2 = client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, cts.Token);
Task t3 = client.PostAsync(CreateFakeUri(), content, cts.Token);
Task t4 = client.PutAsync(CreateFakeUri(), content, cts.Token);
Task t5 = client.DeleteAsync(CreateFakeUri(), cts.Token);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t1);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t2);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t3);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t4);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t5);
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Success()
{
Action<HttpResponseMessage> verify = message => { using (message) Assert.Equal(HttpStatusCode.OK, message.StatusCode); };
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
verify(await client.GetAsync(CreateFakeUri()));
verify(await client.GetAsync(CreateFakeUri(), CancellationToken.None));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, CancellationToken.None));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.DeleteAsync(CreateFakeUri()));
verify(await client.DeleteAsync(CreateFakeUri(), CancellationToken.None));
}
}
[Fact]
public void GetAsync_CustomException_Synchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => { throw e; })))
{
FormatException thrown = Assert.Throws<FormatException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Same(e, thrown);
}
}
[Fact]
public async Task GetAsync_CustomException_Asynchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromException<HttpResponseMessage>(e))))
{
FormatException thrown = await Assert.ThrowsAsync<FormatException>(() => client.GetAsync(CreateFakeUri()));
Assert.Same(e, thrown);
}
}
[Fact]
public void SendAsync_NullRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
Assert.Throws<ArgumentNullException>("request", () => { client.SendAsync(null); });
}
}
[Fact]
public async Task SendAsync_DuplicateRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()))
{
(await client.SendAsync(request)).Dispose();
Assert.Throws<InvalidOperationException>(() => { client.SendAsync(request); });
}
}
[Fact]
public async Task SendAsync_RequestContentDisposed()
{
var content = new ByteArrayContent(new byte[1]);
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()) { Content = content })
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
await client.SendAsync(request);
Assert.Throws<ObjectDisposedException>(() => { content.ReadAsStringAsync(); });
}
}
[Fact]
public void Dispose_UseAfterDispose_Throws()
{
var client = new HttpClient();
client.Dispose();
Assert.Throws<ObjectDisposedException>(() => client.BaseAddress = null);
Assert.Throws<ObjectDisposedException>(() => client.CancelPendingRequests());
Assert.Throws<ObjectDisposedException>(() => { client.DeleteAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetByteArrayAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStreamAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStringAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.SendAsync(new HttpRequestMessage(HttpMethod.Get, CreateFakeUri())); });
Assert.Throws<ObjectDisposedException>(() => { client.Timeout = TimeSpan.FromSeconds(1); });
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void CancelAllPending_AllPendingOperationsCanceled(bool withInfiniteTimeout)
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
if (withInfiniteTimeout)
{
client.Timeout = Timeout.InfiniteTimeSpan;
}
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
client.CancelPendingRequests();
Assert.All(tasks, task => Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
public void Timeout_TooShort_AllPendingOperationsCanceled()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
client.Timeout = TimeSpan.FromMilliseconds(1);
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
Assert.All(tasks, task => Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
[OuterLoop("One second delay in getting server's response")]
public async Task Timeout_SetTo30AndGetResponseFromLoopbackQuickly_Success()
{
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) })
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task getTask = client.GetStringAsync(url);
await Task.Delay(TimeSpan.FromSeconds(.5));
await TestHelper.WhenAllCompletedOrAnyFailed(
getTask,
LoopbackServer.ReadRequestAndSendResponseAsync(server));
});
}
}
private static string CreateFakeUri() => $"http://{Guid.NewGuid().ToString("N")}";
private static async Task<T> WhenCanceled<T>(CancellationToken cancellationToken)
{
await Task.Delay(-1, cancellationToken).ConfigureAwait(false);
return default(T);
}
private sealed class CustomResponseHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _func;
public CustomResponseHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> func) { _func = func; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return _func(request, cancellationToken);
}
}
private sealed class CustomContent : HttpContent
{
private readonly Func<Stream, Task> _func;
public CustomContent(Func<Stream, Task> func) { _func = func; }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _func(stream);
}
protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for PropertyOperations.
/// </summary>
public static partial class PropertyOperationsExtensions
{
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-properties" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
public static IPage<PropertyContract> ListByService(this IPropertyOperations operations, string resourceGroupName, string serviceName, ODataQuery<PropertyContract> odataQuery = default(ODataQuery<PropertyContract>))
{
return ((IPropertyOperations)operations).ListByServiceAsync(resourceGroupName, serviceName, odataQuery).GetAwaiter().GetResult();
}
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-properties" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PropertyContract>> ListByServiceAsync(this IPropertyOperations operations, string resourceGroupName, string serviceName, ODataQuery<PropertyContract> odataQuery = default(ODataQuery<PropertyContract>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceWithHttpMessagesAsync(resourceGroupName, serviceName, odataQuery, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the details of the property specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
public static PropertyContract Get(this IPropertyOperations operations, string resourceGroupName, string serviceName, string propId)
{
return operations.GetAsync(resourceGroupName, serviceName, propId).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the details of the property specified by its identifier.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PropertyContract> GetAsync(this IPropertyOperations operations, string resourceGroupName, string serviceName, string propId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serviceName, propId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a property.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
public static PropertyContract CreateOrUpdate(this IPropertyOperations operations, string resourceGroupName, string serviceName, string propId, PropertyContract parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serviceName, propId, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a property.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<PropertyContract> CreateOrUpdateAsync(this IPropertyOperations operations, string resourceGroupName, string serviceName, string propId, PropertyContract parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serviceName, propId, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the specific property.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the property to update. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
public static void Update(this IPropertyOperations operations, string resourceGroupName, string serviceName, string propId, PropertyUpdateParameters parameters, string ifMatch)
{
operations.UpdateAsync(resourceGroupName, serviceName, propId, parameters, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Updates the specific property.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the property to update. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this IPropertyOperations operations, string resourceGroupName, string serviceName, string propId, PropertyUpdateParameters parameters, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(resourceGroupName, serviceName, propId, parameters, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Deletes specific property from the the API Management service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the property to delete. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
public static void Delete(this IPropertyOperations operations, string resourceGroupName, string serviceName, string propId, string ifMatch)
{
operations.DeleteAsync(resourceGroupName, serviceName, propId, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes specific property from the the API Management service instance.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='propId'>
/// Identifier of the property.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the property to delete. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IPropertyOperations operations, string resourceGroupName, string serviceName, string propId, string ifMatch, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serviceName, propId, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-properties" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<PropertyContract> ListByServiceNext(this IPropertyOperations operations, string nextPageLink)
{
return operations.ListByServiceNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists a collection of properties defined within a service instance.
/// <see href="https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-properties" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<PropertyContract>> ListByServiceNextAsync(this IPropertyOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServiceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.